Last active
August 29, 2015 14:18
-
-
Save asfaltboy/08acf3086db9ebff3328 to your computer and use it in GitHub Desktop.
Allow generating TOC for [POSA-15 MOOC](https://github.com/douglascraigschmidt/POSA-15/wiki/POSA-15-FAQ)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Parse markdown list items (such as FAQ) into a TOC | |
Usage: | |
python list_toc_generator.py <markdown_file, markdow_file...> | |
""" | |
import re | |
import sys | |
item_pattern = re.compile('^(^\d+)\.\s+<a name="\w+"></a>\*\*(.*)\*\*$') | |
content_pattern = re.compile('^## FAQ$') | |
def get_links(path): | |
links = [] | |
in_content = True | |
with open(path) as f: | |
for line in f: | |
if line.startswith('**Table of Contents**'): | |
in_content = False | |
elif not in_content: | |
if re.match(content_pattern, line): | |
in_content = True | |
else: | |
match = re.match(item_pattern, line) | |
if not match: | |
continue | |
links.append(match.groups()) | |
return links | |
def generate_toc(links): | |
TOC = '## Table of Contents\n\n' | |
FOOTER = '\n\n## FAQ' | |
return TOC + '\n'.join('{i}. [{t}](#{i})'.format(i=item, t=title) | |
for item, title in links) + FOOTER | |
if __name__ == '__main__': | |
if len(sys.argv) < 2: | |
sys.exit('Please pass a path to a markdown file as argument') | |
for fpath in sys.argv[1:]: | |
links = get_links(fpath) | |
print(generate_toc(links)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment