Exemplo n.º 1
0
def feed(args):
    """Makes a feed from an .md.in file."""

    path = args.path

    # Extract the metadata fields we need
    meta = getmeta(path)
    title = meta['rsstitle'] if 'rsstitle' in meta else None
    subtitle = meta['subtitle'] if 'subtitle' in meta else ''

    # Get the first ten RSS items from file listing at path
    lines = getcontent(path)
    items = [make_item(line.strip()) for line in lines \
             if line.strip().endswith('.md') and \
             os.path.isfile(line.strip())][:10]

    # Create the RSS
    rss = rss2.RSS2(generator=None,
                    docs=None,
                    title=title,
                    link=permalink(path[8:].replace('.md.in', '.html')),
                    description=subtitle,
                    lastBuildDate=datetime.datetime.now(),
                    items=items)

    # Write it out
    write(rss.to_xml())
Exemplo n.º 2
0
def compose(args):
    """Composes the .md.in file at path."""

    path = args.path

    assert path.startswith('markdown/') and path.endswith('.md.in')
    
    meta = getmeta(path)
    meta['no-social'] = 'True'
    meta['rss-url'] = path[8:].replace('.md.in', '.xml')
    writemeta(meta)

    # Read the lines of the .md.in file
    lines = getcontent(path)

    # Process the lines
    writer = content_writer()
    next(writer)
    for line in lines:
        # If a filename is given then write the file (subject to some
        # processing); otherwise, write the line as-is.
        if line.strip().endswith('.md') and os.path.isfile(line.strip()):
            writer.send(line.strip())
        else:
            write(line)
Exemplo n.º 3
0
def writefile(src, dest, hide=False, force=False):
    """Writes files from src package data to dest.

    hide - if True, prepends a dot to the filename
    force - if True, overwrites existing files
    """

    if hide:  # Prepend a dot to the filename to hide it
        head, tail = os.path.split(dest)
        dest = os.path.join(head, '.' + tail)

    # Bail out if the destination already exists
    if os.path.exists(dest) and not force:
        return

    # Read from package data
    content = resource_string('bassclef', src)

    # Create the directory structure
    try:
        if os.path.dirname(dest):
            os.makedirs(os.path.dirname(dest))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

    # Initialize the file
    write('Writing %s\n'%dest)
    with open(dest, 'wb') as f:
        f.write(content)
Exemplo n.º 4
0
def main():
    """Main program."""

    # Create a top-level parser
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    # 'test'
    subparser = subparsers.add_parser('test')
    subparser.set_defaults(func=test)

    # 'init'
    subparser = subparsers.add_parser('init')
    subparser.add_argument('--force', '-f', action='store_true')
    subparser.add_argument('--extras', '-e', action='store_true')
    subparser.set_defaults(func=init)

    # 'make'
    subparser = subparsers.add_parser('make')
    subparser.add_argument('target', nargs='*', default='')
    subparser.set_defaults(func=make)

    # 'preprocess'
    subparser = subparsers.add_parser('preprocess')
    subparser.add_argument('path')
    subparser.set_defaults(func=preprocess)

    # 'postprocess'
    subparser = subparsers.add_parser('postprocess')
    subparser.set_defaults(func=postprocess)

    # 'compose'
    subparser = subparsers.add_parser('compose')
    subparser.add_argument('path')
    subparser.set_defaults(func=compose)

    # 'feed'
    subparser = subparsers.add_parser('feed')
    subparser.add_argument('path')
    subparser.set_defaults(func=feed)

    # 'serve'
    subparser = subparsers.add_parser('serve')
    subparser.set_defaults(func=serve)

    # Parse the args and call whatever function was selected
    args, other_args = parser.parse_known_args()
    if hasattr(args, 'func'):
        if args.func.__name__ in ['make']:
            args.func(args, other_args)
        elif other_args:
            write('Unknown options: ' + ' '.join(other_args) + '\n')
        elif args.func.__name__ in ['test', 'postprocess', 'serve']:
            args.func()
        else:
            args.func(args)
    else:
        parser.print_help()
Exemplo n.º 5
0
def serve():
    """Runs a test server."""

    os.chdir('www')

    # Set up the server
    http_request_handler = http.server.SimpleHTTPRequestHandler
    httpd = socketserver.TCPServer(('', PORT), http_request_handler)

    write('Serving at http://127.0.0.1:%d/ (^C to exit)...\n'%PORT)

    # Catch ^C and exit gracefully
    def signal_handler(sig, frame):  # pylint: disable=unused-argument
        """Exit handler."""
        write('\n')
        sys.exit(0)
    signal.signal(signal.SIGINT, signal_handler)

    httpd.serve_forever()
Exemplo n.º 6
0
 def signal_handler(sig, frame):  # pylint: disable=unused-argument
     """Exit handler."""
     write('\n')
     sys.exit(0)
Exemplo n.º 7
0
def content_writer():
    """Writes the processed content of a .md file to stdout.

    Use it this way:

      writer = content_writer()
      next(writer)
      writer.send('/path/to/file.md')

    Send as many paths as you want.

    The content is processed internally and by pandoc (via a system call).
    The output is html.  For any subsequent processing with pandoc, don't
    forget to turn off its markdown_in_html_blocks extension.
    """

    # Process the entry template with pandoc-tpp and write it to a
    # temporary file.  Remove leading spaces so that this can be written into
    # a markdown file.
    lines = pandoc_tpp.preprocess('templates/entry.html5')
    with tempfile.NamedTemporaryFile(mode='w+', suffix='.html5',
                                     delete=False) as f:
        template_path = f.name
        f.writelines(lines)

    # Keep track of the number of files processed
    n = 0

    while True:

        # Get the path to the next entry
        path = yield
        assert path.startswith('markdown/')

        # Get various types of links
        relurl = path[8:-3] + '.html'
        plink = permalink(relurl)
        quoted_plink = urllib.parse.quote(plink).replace('/', '%2F')

        # Renew the entry's metadata
        meta = getmeta(path)
        meta['rel-url'] = relurl
        meta['permalink'] = plink

        # Flag the first entry in the metadata
        if n == 0:
            meta['first-entry'] = 'True'
        elif 'first-entry' in meta:
            del meta['first-entry']

        # Process the entry's content
        lines = process(getcontent(path), meta, n)

        # Write the markdown to a temporary file
        with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f:
            tmppath1 = f.name
            writemeta(meta, f=f)
            writelines(lines, f=f)

        # Preprocess the temporary file if this is the first entry
        if n==0:
            with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f:
                tmppath2 = f.name
                subprocess.call(['bcms', 'preprocess', tmppath1], stdout=f)
        else:
            tmppath2 = tmppath1
        
        # Write a horizontal rule between files
        if n != 0:
            write('\n<hr />\n')

        # Start the new entry
        write('\n')
        write('<div id="entry-%d">\n'%n)

        # Process the markdown with pandoc, writing the output to stdout
        STDOUT.flush()
        assert path.startswith('markdown/') and path.endswith('.md')
        subprocess.call(['pandoc',  tmppath2,
                         '-s', '-S',
                         '-f', 'markdown+markdown_attribute',
                         '-t', 'html5',
                         '--email-obfuscation', 'none',
                         '--template', template_path,
                         '-M', 'permalink=' + plink,
                         '-M', 'quoted-permalink=' + quoted_plink])
        STDOUT.flush()

        write('</div> <!-- id="entry-%d" -->\n'%n)

        # Increment the counter
        n += 1
Exemplo n.º 8
0
def test():
    """Runs the tests."""

    write('Checking python... ')
    check_python()
    write('OK.\n')

    write('Checking make... ')
    check_make()
    write('OK.\n')

    write('Checking pandoc... ')
    check_pandoc()
    write('OK.\n')

    write('Checking convert... ')
    check_convert()
    write('OK.\n')