def generate_html(markdown_files): """ Generate HTML from a given markdown file :type markdown_files: [MarkdownFile] :param markdown_files: List of MarkdownFile object """ env = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(os.path.dirname(__file__), 'templates'))) template = env.get_template('markdown-template.html') for markdown_file in markdown_files: logger.debug( 'Generating HTML for {}..'.format(markdown_file.source_file)) # Ensure that the output directory exists try: os.makedirs(markdown_file.destination_dir) except OSError as (errno, errmsg): if errno == 17: # Code 17 == File exists pass else: raise with open(markdown_file.source_file, 'r') as file_handle: try: text = file_handle.read().decode('utf-8') except UnicodeError: logger.warning('UnicodeError when reading {}. Skipping.'.format( markdown_file.source_file)) pass with open(markdown_file.destination_file, 'w') as file_handle: markdown_object = markdown.Markdown( extensions=[ 'meta', 'toc', 'tables', 'codehilite(linenums=False)']) markdown_html = markdown_object.convert(text) # Update the title, if the title attribute is in the parsed metadata if 'title' in markdown_object.Meta: markdown_file.set_metadata( 'title', markdown_object.Meta['title'][0]) html = template.render( { 'title': markdown_file.get_metadata('title'), 'destination_root_dir': markdown_file.destination_root_dir, 'markdown_html': markdown_html, 'generation_timestamp': datetime.datetime.utcnow().strftime( '%Y-%m-%d %H:%M') }) file_handle.write(html.encode('utf-8')) logger.debug('Wrote {}'.format(markdown_file.destination_file))
def generate_index_page(markdown_files): """ Generate the index page :type markdown_files: list :param markdown_files: List of MarkdownFile objects to print to the index """ logger.debug('Generating index page..') env = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(os.path.dirname(__file__), 'templates'))) template = env.get_template('index.html') markdown_metadata = [] for markdown_file in markdown_files: markdown_metadata.append(markdown_file.metadata) index_path = os.path.join(markdown_file.destination_root_dir, 'index.html') with open(index_path, 'w') as file_handle: file_handle.write(template.render( { 'markdown_metadata': markdown_metadata, 'generation_timestamp': datetime.datetime.utcnow().strftime( '%Y-%m-%d %H:%M') }))
def main(): """ Main function """ parser = argparse.ArgumentParser( description='markdown-docs markdown documentation generator') parser.add_argument('-d', '--directory', help='Root directory to parse from (default: current dir)') parser.add_argument('-o', '--output', help='Output directory to store HTML files in') parser.add_argument('--version', action='store_true', help='Print version information') parser.add_argument('generate', nargs='?', default=False, help='Generate HTML') parser.add_argument('serve', nargs='?', default=True, help='Start a local web server to serve the documentation') args = parser.parse_args() if args.version: print_version() sys.exit(0) if args.directory: source_dir = os.path.expandvars(os.path.expanduser(args.directory)) if not os.path.exists(source_dir): logger.error('{} does not exist'.format(source_dir)) sys.exit(1) elif not os.path.isdir(source_dir): logger.error('{} is not a directory'.format(source_dir)) sys.exit(1) else: source_dir = os.path.realpath(os.path.curdir) temp_dir_used = False if args.output: destination_root_dir = os.path.expandvars( os.path.expanduser(args.output)) try: os.makedirs(destination_root_dir) except OSError as (errno, errmsg): if errno == 17: # Code 17 == File exists pass else: logger.error('Error creating {}: {}'.format( destination_root_dir, errmsg)) sys.exit(1)
destination_root_dir = os.path.expandvars( os.path.expanduser(args.output)) try: os.makedirs(destination_root_dir) except OSError as (errno, errmsg): if errno == 17: # Code 17 == File exists pass else: logger.error('Error creating {}: {}'.format( destination_root_dir, errmsg)) sys.exit(1) else: destination_root_dir = tempfile.mkdtemp(prefix='markdown-docs') logger.debug('Using temporary folder: {}'.format(destination_root_dir)) if not args.generate: temp_dir_used = True try: markdown_files = find_markdown_files(source_dir, destination_root_dir) logger.info('Generating documentation for {:d} markdown files..'.format( len(markdown_files))) markdowndocs.generator.generate_html(markdown_files) markdowndocs.generator.generate_index_page(markdown_files) markdowndocs.generator.import_static_files(destination_root_dir) logger.info('Done with documentation generation!') if args.serve and not args.generate: markdowndocs.web_server.run_webserver(destination_root_dir) if args.generate: