-
Notifications
You must be signed in to change notification settings - Fork 1
/
toc
executable file
·135 lines (104 loc) · 3.89 KB
/
toc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#! /usr/bin/env python3
""" Reads the files in current directory and creates a table-of-contents output to be
included in the README.md.
"""
__author__ = 'vivekrai'
__version__ = '1.0'
import os
import argparse
import sys
from collections import defaultdict
import operator
import json
__ignore = ['.git', '.pyc', '._DS_Store', '.github', '.files']
__categories = {
'misc': 'Miscellaneous',
'python': 'Python (lang)',
'R': 'R-lang',
'unix': 'GNU Unix | Command line',
'algorithms': 'Algorithms',
'productivity': 'Productivity',
'computing': 'Computing',
'writing': 'Writing',
'math': 'Statistics | Methods | Math',
'biology': 'Biology',
'lessons': 'Zen lessons',
'unclassified': 'Unclassified'
}
def scan_files(path):
tree = defaultdict(list)
for root, dirs, files in os.walk(path, followlinks=True):
root = os.path.basename(root)
if root in __ignore or (root.startswith('.') and path != '.'): # ignore blacklist
dirs[:], files[:] = [], []
elif root == '' or root == os.path.basename(path): # skip root
continue
else:
tree[root] = files
return tree
def get_title(filepath):
with open(filepath, 'r') as f:
title = f.readline()
return title.strip('#').strip()
def get_permalink(title):
fix_pipes = '--'.join([x.strip() for x in title.lower().split('|')])
return '-'.join(fix_pipes.split(' '))
def write_json(root):
files = scan_files(root)
out = []
for k, v in files.items():
for md in v:
out.append({ "Category": k, "TIL": md })
print(json.dumps(out, indent=4))
def write_entries(root, output, header, footer):
files = scan_files(root)
out = []
out.append(header)
out.append("**Count: {}**\n\n".format(sum([len(x) for x in files.values()])))
# write short-toc
out.append("## Table of Contents\n")
for k, v in sorted(files.items(), key=operator.itemgetter(0)):
if len(v) < 1: continue # skip entries with no notes
cleaned_title = __categories[k]
out.append("* [{}](#{})\n".format(cleaned_title,
get_permalink(cleaned_title)))
out.append("\n")
# write full-toc
for k, v in sorted(files.items(), key=operator.itemgetter(0)):
if len(v) < 1: continue # skip entries with no notes
out.append("### {}\n".format(__categories[k.strip('./')]))
for file_ in v:
path_ = os.path.join(k, file_)
out.append("* [{}]({})\n".format(get_title(path_), path_))
out.append("\n")
# write footer
out.append(footer)
output = sys.stdout if not output else open(output, 'w')
with output as f:
f.writelines(out)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="""
Prints a markdown listing of posts from the til directory to target file
(default: stdout). You may use the output whicever way you like.""")
parser.add_argument('-r', '--root',
help="Root directory to scan for files",
default='.')
parser.add_argument('-f', '--fmt',
help="Output format",
default='json')
parser.add_argument('-o', '--output',
help="Output file (default: stdout)")
args = parser.parse_args()
if (args.fmt == "json"):
write_json(args.root)
else:
header_path = os.path.join(args.root, 'HEADER')
footer_path = os.path.join(args.root, 'FOOTER')
__header, __footer = '', ''
if os.path.exists(header_path):
with open(os.path.join(args.root, 'HEADER'), 'r') as f:
__header = f.read()
if os.path.exists(footer_path):
with open(os.path.join(args.root, 'FOOTER'), 'r') as f:
__footer = f.read()
write_entries(args.root, args.output, header=__header, footer=__footer)