Created
March 19, 2019 16:37
-
-
Save SureshKL/4b378af6fb0ae900175000a5c44da9b8 to your computer and use it in GitHub Desktop.
[Utility] Git commands TOC Generator
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
import re | |
readme_path = r'Useful Git Commands.md' | |
skip_rules = ('# Useful Git commands', | |
'# Table of Contents:', | |
) | |
def generate_toc(headers): | |
# Syntax: [git init](#git-init) | |
special_chars_pat = re.compile(r'[:(),"\']') | |
for header in headers: | |
ref = special_chars_pat.sub('', header.strip('# ')).replace(' ', | |
'-').lower() | |
link_text = header.strip("# ") | |
print(f'- [{link_text}](#{ref})') | |
def read_file(): | |
with open(readme_path) as f: | |
return f.read() | |
def get_headers(data: str, skip_rules: tuple): | |
lines = list(filter(lambda l: l not in skip_rules, data.splitlines())) | |
headers = [] | |
header_pat = re.compile('^#\s+.*') | |
skip = False | |
for line in lines: | |
if '```' in line: | |
skip = False if skip is True else True # Second occurrence | |
continue | |
if not skip and header_pat.search(line): | |
headers.append(line) | |
return headers | |
if __name__ == '__main__': | |
data = read_file() | |
headers = get_headers(data, skip_rules=skip_rules) | |
generate_toc(headers) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment