Exemple #1
0
def main(args, configs):
    if args.source:
        if not file_exists(args.source):
            log.warn('File ' + args.source + ' does not exist.')
            exit(1)
        elif not os.path.isfile(args.source):
            log.warn(args.source + ' is not a valid file')
            exit(1)
        result = link.link(args.source)
        if args.markdown:
            markdown_obj = Markdown(result)
            for k, v in markdown_obj.variables.items():
                configs['VARIABLES'][k] = v
            result = markdown_obj.text
        result = link.substitutions(result,
                                    configs.get('SUBSTITUTIONS', []),
                                    args)
        result, cache = link.retrieve_blocks(result)
        if 'TOC_BUILDER' in configs:
            configs['VARIABLES']['table-of-contents'] = link.scrape_headers(result, configs['TOC_BUILDER'])
            for import_stmt in (
                    'from datetime import datetime',
                    ):
                exec(import_stmt, configs)
        for k, v in cache.items():
            configs['VARIABLES'][k] = v

    result = compile(args.template, configs)
    if not args.destination:
        log.log(result)
        return
    file_write(args.destination, result)
    log.info('Result can be found at ' + args.destination)
Exemple #2
0
def main(args, configs):
    if args.source:
        if not file_exists(args.source):
            log.warn('File ' + args.source + ' does not exist.')
            exit(1)
        elif not os.path.isfile(args.source):
            log.warn(args.source + ' is not a valid file')
            exit(1)
        result = link.link(args.source)
        if args.markdown:
            markdown_obj = Markdown(result)
            for k, v in markdown_obj.variables.items():
                configs['VARIABLES'][k] = v
            result = markdown_obj.text
        result = link.substitutions(result, configs.get('SUBSTITUTIONS', []),
                                    args)
        result, cache = link.retrieve_blocks(result)
        if 'TOC_BUILDER' in configs:
            configs['VARIABLES']['table-of-contents'] = link.scrape_headers(
                result, configs['TOC_BUILDER'])
            for import_stmt in ('from datetime import datetime', ):
                exec(import_stmt, configs)
        for k, v in cache.items():
            configs['VARIABLES'][k] = v

    result = compile(args.template, configs)
    if not args.destination:
        log.log(result)
        return
    file_write(args.destination, result)
    log.info('Result can be found at ' + args.destination)
Exemple #3
0
 def sub(match):
     is_img = match.group(1) != ''
     content = match.group(2)
     ref = match.group(3).strip().lower()
     if not ref:
         ref = content.strip().lower()
     ref = ref.replace('\n', ' ')
     if ref not in markdown_obj.references:
         link, title = '', ''
         log.warn(
             'While parsing Markdown, encountered undefined reference: {}'.
             format(ref))
     else:
         link, title = markdown_obj.references[ref]
     if title:
         title = ' title="{0}"'.format(title)
     if is_img:
         result = '<img src="{0}" alt="{1}"{2}>'.format(
             link, content, title)
     else:
         result = '<a href="{0}"{2}>{1}</a>'.format(
             link,
             markdown_obj.convert(content).replace('<p>',
                                                   '').replace('</p>',
                                                               '').strip(),
             title)
     hashed = hash_text(result, 'link')
     hashes[hashed] = result
     return hashed
Exemple #4
0
 def call_sub(match):
     macro, arguments = match.groups()
     arguments = expr_re.findall(arguments)
     if macro not in macros:
         log.warn('The macro "' + macro + '" is not defined.')
         return ''
     variables, body = macros[macro]
     new_frame = Frame(parent=attrs)
     for var, arg in zip(variables, arguments):
         new_frame[var] = evaluate(arg, attrs)
     return expr_re.sub(lambda m: eval_macro_body(m, new_frame), body.strip('\n'))
Exemple #5
0
def evaluate(expression, attrs):
    expression = expression.replace('\n', ' ').strip()
    if expression in attrs:
        return attrs[expression]
    else:
        try:
            return eval(expression, {}, attrs)
        except Exception as e:
            log.warn('"{}" caused {}: {}'.format(expression,
                e.__class__.__name__, e))
            traceback.print_exc()
            return ''
Exemple #6
0
def evaluate(expression, attrs):
    expression = expression.replace('\n', ' ').strip()
    if expression in attrs:
        return attrs[expression]
    else:
        try:
            return eval(expression, {}, attrs)
        except Exception as e:
            log.warn('"{}" caused {}: {}'.format(expression,
                                                 e.__class__.__name__, e))
            traceback.print_exc()
            return ''
Exemple #7
0
 def call_sub(match):
     macro, arguments = match.groups()
     arguments = expr_re.findall(arguments)
     if macro not in macros:
         log.warn('The macro "' + macro + '" is not defined.')
         return ''
     variables, body = macros[macro]
     new_frame = Frame(parent=attrs)
     for var, arg in zip(variables, arguments):
         new_frame[var] = evaluate(arg, attrs)
     return expr_re.sub(lambda m: eval_macro_body(m, new_frame),
                        body.strip('\n'))
Exemple #8
0
    def link_sub(match):
        filename = match.group(2)
        regex = match.group(3)
        if not file_exists(filename):
            filename = os.path.join(base_dir, filename)
            if not file_exists(filename):
                log.warn("Could not find file " + match.group(2) \
                        + " or " + filename)
                return ''

        text = retrieve_and_link(filename, cache)
        if not regex:
            result = cache[filename + ':all']
        else:
            result = resolve_include_regex(regex, cache, filename)
        return textwrap.indent(result, match.group(1))
Exemple #9
0
def config_main(args, configs=None):
    if args.path:
        path = args.path
    else:
        path = os.getcwd()
    dest = os.path.join(path, CONFIG_NAME)
    config = os.path.join(os.path.dirname(__file__), CONFIG_NAME)
    with open(config, 'r') as f:
        template = f.read()
    if os.path.exists(path) and (not os.path.exists(dest) \
            or 'y' in input('Remove existing {}? [y/n] '.format(CONFIG_NAME)).lower()):
        with open(dest, 'w') as f:
            f.write(template)
        log.info('Copied ' + CONFIG_NAME + ' to ' + dest)
        exit(0)
    else:
        log.warn(CONFIG_NAME + ' not copied')
        exit(1)
Exemple #10
0
def main(args, configs):
    if not os.path.exists(args.source):
        log.warn('File ' + args.source + ' does not exist.')
        exit(1)
    elif not os.path.isfile(args.source):
        log.warn(args.source + ' is not a valid file')
        exit(1)
    result = link(args.source)
    if args.markdown:
        result = convert(result)
    result = substitutions(result,
                           configs.get('SUBSTITUTIONS', []),
                           args)
    result, cache = retrieve_blocks(result)
    if args.destination:
        file_write(args.destination, result)
        log.info('Result can be found in ' + args.destination)
    else:
        log.log('--- BEGIN RESULT ---', args.quiet)
        log.log(result)
        log.log('--- END RESULT ---', args.quiet)
Exemple #11
0
def main(args=None):
    if not args:
        parser = argparse.ArgumentParser()
        cmd_options(parser)
        args = parser.parse_args()
    if not args.source:
        text = ''
        log.log('--- BEGIN MARKDOWN (type Ctrl-D to finish) ---')
        while True:
            try:
                text += input() + '\n'
            except EOFError:
                log.log('--- END MARKDOWN ---')
                break
            except KeyboardInterrupt:
                log.warn('Aborting script')
                exit(1)
    else:
        if not os.path.exists(args.source):
            log.warn('File ' + args.source + ' does not exist.')
            exit(1)
        elif not os.path.isfile(args.source):
            log.warn(args.source + ' is not a valid file')
            exit(1)
        with open(args.source, 'r') as f:
            text = f.read()
    result = convert(text)
    if args.destination:
        with open(args.destination, 'w') as f:
            f.write(result)
        log.info('Result can be found in ' + args.destination)
    else:
        log.log(result)
Exemple #12
0
def main(args=None):
    if not args:
        parser = argparse.ArgumentParser()
        cmd_options(parser)
        args = parser.parse_args()
    if not args.source:
        text = ''
        log.log('--- BEGIN MARKDOWN (type Ctrl-D to finish) ---')
        while True:
            try:
                text += input() + '\n'
            except EOFError:
                log.log('--- END MARKDOWN ---')
                break
            except KeyboardInterrupt:
                log.warn('Aborting script')
                exit(1)
    else:
        if not os.path.exists(args.source):
            log.warn('File ' + args.source + ' does not exist.')
            exit(1)
        elif not os.path.isfile(args.source):
            log.warn(args.source + ' is not a valid file')
            exit(1)
        with open(args.source, 'r') as f:
            text = f.read()
    result = convert(text)
    if args.destination:
        with open(args.destination, 'w') as f:
            f.write(result)
        log.info('Result can be found in ' + args.destination)
    else:
        log.log(result)
Exemple #13
0
def get_template(filename, template_dirs):
    """Return the contents of `filename` as a string.

    PARAMETERS:
    filename -- string: name of template file relative to a 'template'
                directory

    BEHAVIOR:
    `filename` should be of the format:

        [<app>:]<filepath>

    The filepath is expected to be a relative path to a template file
    (usually an html template). If <app> is provided, `get_template`
    will look only in that app's template directory. Otherwise,
    `get_template` will look through the list TEMPLATE_DIRS in order,
    and search in a directory called 'templates' in each of them for
    `filename`.

    By default, the repo home directory is searched first,
    before any app directories.

    If no such `filename` is found, the program exits with status 1.
    """
    if ':' in filename:
        app, filename = filename.split(':')
        dirs = [path for path in template_dirs if app in path]
    else:
        dirs = template_dirs
    for path in dirs:
        template = os.path.join(path, 'templates', filename)
        if file_exists(template):
            return file_read(template)
    log.warn('The template "' + filename \
            + '" could not be found in these directories:')
    for path in dirs:
        log.log(os.path.join(path, 'templates'))
    exit(1)
Exemple #14
0
def get_template(filename, template_dirs):
    """Return the contents of `filename` as a string.

    PARAMETERS:
    filename -- string: name of template file relative to a 'template'
                directory

    BEHAVIOR:
    `filename` should be of the format:

        [<app>:]<filepath>

    The filepath is expected to be a relative path to a template file
    (usually an html template). If <app> is provided, `get_template`
    will look only in that app's template directory. Otherwise,
    `get_template` will look through the list TEMPLATE_DIRS in order,
    and search in a directory called 'templates' in each of them for
    `filename`.

    By default, the repo home directory is searched first,
    before any app directories.

    If no such `filename` is found, the program exits with status 1.
    """
    if ':' in filename:
        app, filename = filename.split(':')
        dirs = [path for path in template_dirs if app in path]
    else:
        dirs = template_dirs
    for path in dirs:
        template = os.path.join(path, 'templates', filename)
        if file_exists(template):
            return file_read(template)
    log.warn('The template "' + filename \
            + '" could not be found in these directories:')
    for path in dirs:
        log.log(os.path.join(path, 'templates'))
    exit(1)
Exemple #15
0
 def sub(match):
     is_img = match.group(1) != ''
     content = match.group(2)
     ref = match.group(3).strip().lower()
     if not ref:
         ref = content.strip().lower()
     ref = ref.replace('\n', ' ')
     if ref not in markdown_obj.references:
         link, title = '', ''
         log.warn('While parsing Markdown, encountered undefined reference: {}'.format(ref))
     else:
         link, title = markdown_obj.references[ref]
     if title:
         title = ' title="{0}"'.format(title)
     if is_img:
         result = '<img src="{0}" alt="{1}"{2}>'.format(
                 link, content, title)
     else:
         result = '<a href="{0}"{2}>{1}</a>'.format(link,
                 markdown_obj.convert(content).replace('<p>', '').replace('</p>', '').strip(),
                 title)
     hashed = hash_text(result, 'link')
     hashes[hashed] = result
     return hashed