main.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. #!/usr/bin/env python3
  2. from dataclasses import dataclass
  3. import datetime
  4. import os
  5. import markdown
  6. import pystache
  7. import shutil
  8. import sys
  9. import tempfile
  10. import yaml
  11. class Datum:
  12. @classmethod
  13. def from_yaml(cls, data):
  14. return cls(**data)
  15. @classmethod
  16. def from_file(cls, path):
  17. with open(path) as f:
  18. data = yaml.safe_load(f)
  19. return cls.from_yaml(data)
  20. @dataclass
  21. class Quote(Datum):
  22. id: str
  23. content: str
  24. author: str
  25. @dataclass
  26. class Quip(Datum):
  27. id: str
  28. content: str
  29. @dataclass
  30. class Work:
  31. slug: str
  32. category: str
  33. title: str
  34. date: str
  35. contents: str
  36. class Path:
  37. OUTDIR=tempfile.TemporaryDirectory()
  38. @classmethod
  39. def data(cls, *paths):
  40. tgt = os.path.join(*paths)
  41. for path in sys.argv[2:]:
  42. if path.endswith(os.path.join(tgt)):
  43. return path
  44. raise Exception(f"Could not find {tgt}")
  45. @classmethod
  46. def out(cls, *paths):
  47. return os.path.join(cls.OUTDIR.name, *paths)
  48. @classmethod
  49. def write(cls, *paths):
  50. if len(paths) > 1:
  51. os.makedirs(cls.out(*paths[:-1]), exist_ok=True)
  52. return open(cls.out(*paths), 'w')
  53. @classmethod
  54. def read(cls, *paths):
  55. with open(cls.data(*paths)) as f:
  56. return f.read()
  57. @classmethod
  58. def list(cls, *paths):
  59. stuff = []
  60. tgt = f'{os.path.join(*paths)}/'
  61. for path in sys.argv[2:]:
  62. if tgt in path:
  63. chunks = path.split('/')
  64. idx = chunks.index(paths[-1])
  65. stuff.append(chunks[idx +1])
  66. return stuff
  67. class Template:
  68. renderer = pystache.Renderer(search_dirs="templates")
  69. def load_template(name):
  70. with open(f"templates/{name}.mustache") as f:
  71. parsed = pystache.parse(f.read())
  72. return lambda stuff: Template.renderer.render(parsed, stuff)
  73. main = load_template("main")
  74. quote = load_template("quote")
  75. list = load_template("list")
  76. def main():
  77. out_file = sys.argv[1]
  78. year = datetime.datetime.now().year
  79. std_copy = f'© Getty Ritter {year}'
  80. no_copy = 'all rights reversed'
  81. # gather the quips and make their individual pages
  82. quips = []
  83. for uuid in Path.list('quips'):
  84. q = Quip.from_file(Path.data('quips', uuid))
  85. quips.append(q)
  86. with Path.write('quips', uuid, 'index.html') as f:
  87. f.write(Template.main({
  88. 'title': f"Quip {uuid}",
  89. 'contents': Template.quote({'quotelist': [q]}),
  90. 'copy': no_copy,
  91. }))
  92. # sort 'em and make the combined page
  93. quips.sort(key=lambda q: q.id)
  94. with Path.write('quips', 'index.html') as f:
  95. f.write(Template.main({
  96. 'title': "Quips",
  97. 'contents': Template.quote({'quotelist': quips}),
  98. 'copy': no_copy,
  99. }))
  100. # gather the quotes and make their individual pages
  101. quotes = []
  102. for uuid in Path.list('quotes'):
  103. q = Quote.from_file(Path.data('quotes', uuid))
  104. quotes.append(q)
  105. with Path.write('quotes', uuid, 'index.html') as f:
  106. f.write(Template.main({
  107. 'title': f"Quote {uuid}",
  108. 'contents': Template.quote({'quotelist': [q]}),
  109. 'copy': no_copy,
  110. }))
  111. # sort 'em and make their combined page
  112. quotes.sort(key=lambda q: q.id)
  113. with Path.write('quotes', 'index.html') as f:
  114. f.write(Template.main({
  115. 'title': "Quotes",
  116. 'contents': Template.quote({'quotelist': quotes}),
  117. 'copy': no_copy,
  118. }))
  119. # figure out what categories we've got
  120. with open(Path.data('works.json')) as f:
  121. categories = yaml.safe_load(f)
  122. # make an index page for each category
  123. with Path.write('category', 'index.html') as f:
  124. f.write(Template.main({
  125. 'title': 'Categories',
  126. 'contents': Template.list({
  127. 'works': [
  128. {'slug': f'category/{c["slug"]}', 'title': c['category']}
  129. for c in categories
  130. ]
  131. }),
  132. 'copy': 'whatever',
  133. }))
  134. # create each category page
  135. for slug in Path.list('works'):
  136. # we need to know what works exist in the category
  137. works = []
  138. for work in Path.list('works', slug):
  139. # grab the metadata for this work
  140. with open(Path.data('works', slug, work, 'metadata.yaml')) as f:
  141. meta = yaml.safe_load(f)
  142. with open(Path.data('works', slug, work, 'text')) as f:
  143. text = markdown.markdown(f.read())
  144. w = Work(
  145. slug=meta.get('slug', work),
  146. category=meta.get('category', slug),
  147. title=meta['name'],
  148. date=meta['date'],
  149. contents=text,
  150. )
  151. if slug == 'pages':
  152. # always keep index/about up-to-date
  153. copy = std_copy
  154. else:
  155. # report other works in their own year
  156. copy = f'© Getty Ritter {w.date}'
  157. with Path.write(w.slug, 'index.html') as f:
  158. f.write(Template.main({
  159. 'title': w.title,
  160. 'contents': text,
  161. 'copy': copy,
  162. }))
  163. works.append(w)
  164. works.sort(key=lambda w: w.slug)
  165. # not every on-disk category should be shown: we should find
  166. # it in the categories list first
  167. category_metadata = [c for c in categories if c['slug'] == slug]
  168. if not category_metadata:
  169. continue
  170. with Path.write('category', slug, 'index.html') as f:
  171. f.write(Template.main({
  172. 'title': category_metadata[0]['category'],
  173. 'contents': Template.list({
  174. 'works': works,
  175. }),
  176. 'copy': std_copy,
  177. }))
  178. shutil.copy(Path.out('index', 'index.html'), Path.out('index.html'))
  179. os.makedirs(Path.out('static'), exist_ok=True)
  180. shutil.copy('static/main.css', Path.out('static', 'main.css'))
  181. shutil.copy('static/icon.png', Path.out('static', 'icon.png'))
  182. shutil.make_archive('output', 'zip', Path.OUTDIR.name)
  183. shutil.move('output.zip', out_file)
  184. Path.OUTDIR.cleanup()
  185. if __name__ == '__main__':
  186. main()