-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtiltoc.py
More file actions
85 lines (69 loc) · 2.4 KB
/
tiltoc.py
File metadata and controls
85 lines (69 loc) · 2.4 KB
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
import os
from datetime import datetime
# Directory
root = os.getcwd()
# Exclude
excludes = (root, "drafts", "archive")
def relative(root, path):
return '/'.join(path.replace(root, '').split(os.path.sep)[1:])
def tils(root):
for (path, dirs, files) in os.walk(root):
dirs[:] = [d for d in dirs if d not in excludes and not d.startswith(".")]
paths = [os.path.join(path, f) for f in files if f.endswith(".md")]
if path != root:
yield relative(root, path), paths
def flat(tils):
for (relative, paths) in tils:
for path in paths:
yield relative, path
def recent(tils, limit):
modified = []
for relative, filename in tils:
date = os.path.getmtime(filename)
modified.append((date, filename))
modified.sort(key=lambda data: data[0], reverse=True)
return modified[:limit]
def link(root, path):
path = relative(root, path)
return f"[{title(path)}]({path})"
def total(root):
return len(list(flat(tils(root))))
def title(path):
with open(path, 'r', encoding='UTF-8') as f:
title = f.readline().strip()
if title.startswith('# '):
return title.replace('# ', '', 1)
else:
directory = path.split('/')[-2]
filename = path.split('/')[-1]
filename = filename.replace(directory+"-", '', 1)
return ' '.join(n.capitalize() for n in os.path.splitext(filename)[0].split('-'))
def readme():
lines = []
lines.append("# TIL\n")
lines.append("> Today I Learned\n")
# Recents
lines.append("## Recently Modified\n")
for date, filename in recent(flat(tils(root)), 15):
date = datetime.utcfromtimestamp(date).strftime("%Y-%m-%d")
l = link(root, filename)
lines.append(f"- *{date}* : {l}")
# Categories
lines.append("\n## Categories\n")
lines.append("Total `%s` TILs\n" % total(root))
for relative, paths in tils(root):
count = len(paths)
lines.append(f"- [{relative}](#{relative}) *({count})*")
# Links
for relative, paths in tils(root):
lines.append(f"\n### {relative}\n")
for path in paths:
l = link(root, path)
lines.append(f"- {l}")
return lines
output = open(os.path.join(root, "README.md"), 'w', encoding='UTF-8')
for line in readme():
output.write(line)
output.write('\n')
output.close()
print ("Total %s TILs\n" % total(root))