You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

245 lines
6.8 KiB

3 years ago
  1. #!/usr/bin/env python3
  2. # Assumes that there's a directory named ~/src/www-home which is a git repo
  3. # that the contents of output/ can be copied to, committed, & pushed to the
  4. # production server.
  5. # TODO: replace gallery.tinyletterapp.com images with locally hosted content.
  6. # TODO: in template.html, add apple touch icon, maybe other favicon sizes.
  7. # TODO: local mirrors of all papers in publications.html
  8. # TODO: just put the whole HTML content in the Atom feed?
  9. # TODO: atom feed logo in the top-right.
  10. # Requirements:
  11. # sudo apt install python3-markdown
  12. # sudo apt install python3-smartypants
  13. # sudo apt install python3-bs4
  14. import argparse
  15. from bs4 import BeautifulSoup
  16. import glob
  17. import html
  18. from io import StringIO
  19. import markdown
  20. import operator
  21. import os
  22. import re
  23. import shutil
  24. input_directory = 'content'
  25. static_directory = 'static'
  26. output_directory = 'output'
  27. deploy_directory = '~/src/www-home'
  28. md_extensions = [
  29. 'fenced_code', 'codehilite', 'nl2br', 'toc', 'smarty', 'tables', 'linkify']
  30. blog_entries = []
  31. def print_file(in_file, out_file):
  32. print('%-62s -> %s' % (in_file, out_file))
  33. def copy_static_files():
  34. for (dirpath, _, filenames) in os.walk(static_directory):
  35. for filename in filenames:
  36. source = os.path.join(dirpath, filename)
  37. out_path = dirpath.replace(static_directory, '', 1)
  38. out_path = out_path.lstrip('/')
  39. dest_dir = os.path.join(output_directory, out_path)
  40. os.makedirs(dest_dir, exist_ok=True)
  41. dest = os.path.join(dest_dir, filename)
  42. print_file(source, dest)
  43. shutil.copy2(source, dest)
  44. def find_update_date(text):
  45. match = re.search(r'^\*?Posted (\d{4}-\d{2}-\d{2})', text, re.MULTILINE)
  46. if not match:
  47. return None
  48. return match.group(1)
  49. def find_summary(html_content):
  50. text = BeautifulSoup(html_content, features='lxml').get_text()
  51. lines = text.split('\n')
  52. result = ' '.join(lines[2:4])
  53. return html.escape(result, quote=False)
  54. def process_markdown_files():
  55. template = open('template.html').read()
  56. for (dirpath, _, filenames) in os.walk(input_directory):
  57. for filename in filenames:
  58. markdown_filename = os.path.join(dirpath, filename)
  59. if not markdown_filename.endswith('.md'):
  60. continue
  61. blog_entry = {}
  62. markdown_file = open(markdown_filename)
  63. text = markdown_file.read()
  64. markdown_file.close()
  65. if not text.startswith('# '):
  66. text = '# ' + text
  67. match = re.match(r'^(.*?)\n', text)
  68. if match:
  69. title = match.group(1).lstrip('# ')
  70. else:
  71. title = text
  72. blog_entry['title'] = html.escape(title, quote=False)
  73. title += ' | Colin McMillen'
  74. if markdown_filename == os.path.join(input_directory, 'index.md'):
  75. title = 'Colin McMillen'
  76. out_filename = os.path.basename(markdown_filename).replace('.md', '.html')
  77. out_dirpath = os.path.join(output_directory, dirpath)
  78. out_dirpath = out_dirpath.replace('/content', '', 1)
  79. out_fullpath = os.path.join(out_dirpath, out_filename)
  80. page_url = out_fullpath.replace('output/', '', 1)
  81. if page_url.endswith('index.html'): # strip off index.html
  82. page_url = page_url[:-len('index.html')]
  83. html_content = markdown.markdown(
  84. text, extensions=md_extensions, output_format='html5')
  85. output = template.format(
  86. title=title, content=html_content, page_url=page_url)
  87. update_date = find_update_date(text)
  88. if update_date:
  89. blog_entry['url'] = 'https://www.mcmillen.dev/' + page_url
  90. blog_entry['date'] = update_date
  91. blog_entry['summary'] = find_summary(html_content)
  92. blog_entries.append(blog_entry)
  93. os.makedirs(out_dirpath, exist_ok=True)
  94. print_file(markdown_filename, out_fullpath)
  95. out_file = open(out_fullpath, 'w')
  96. out_file.write(output)
  97. out_file.close()
  98. def make_sitemap():
  99. sitemap_command = ' '.join("""
  100. find output -regextype posix-extended -regex '.*.(html|pdf)$' |
  101. grep -v ^output/google |
  102. grep -v ^output/drafts |
  103. perl -pe 's|output|https://www.mcmillen.dev|'
  104. > output/sitemap.txt""".split('\n'))
  105. print_file('', 'output/sitemap.txt')
  106. os.system(sitemap_command)
  107. def make_atom_feed():
  108. atom_template = '''<?xml version="1.0" encoding="utf-8"?>
  109. <feed xmlns="http://www.w3.org/2005/Atom">
  110. <title>Colin McMillen's Blog</title>
  111. <link href="https://www.mcmillen.dev"/>
  112. <link rel="self" href="https://www.mcmillen.dev/atom.xml"/>
  113. <updated>{last_update}</updated>
  114. <author>
  115. <name>Colin McMillen</name>
  116. </author>
  117. <id>https://www.mcmillen.dev/</id>
  118. {entries}
  119. </feed>
  120. '''
  121. entry_template = '''
  122. <entry>
  123. <title>{title}</title>
  124. <id>{url}</id>
  125. <link rel="alternate" href="{url}"/>
  126. <content type="text/html" src="{url}"/>
  127. <updated>{updated}</updated>
  128. <summary>{summary} (...)</summary>
  129. </entry>
  130. '''
  131. blog_entries.sort(key=operator.itemgetter('date'))
  132. entries_io = StringIO()
  133. last_update = None
  134. for entry in blog_entries:
  135. # We lie and pretend that all entries were written at noon EST.
  136. update_date = entry['date'] + 'T12:00:00-04:00'
  137. last_update = update_date
  138. entries_io.write(entry_template.format(
  139. url=entry['url'],
  140. title=entry['title'],
  141. updated=update_date,
  142. summary=entry['summary']))
  143. entries_text = entries_io.getvalue()
  144. atom_feed = atom_template.format(
  145. last_update=last_update,
  146. entries=entries_io.getvalue())
  147. entries_io.close()
  148. atom_filename = os.path.join(output_directory, 'atom.xml')
  149. print_file('', atom_filename)
  150. atom_file = open(atom_filename, 'w')
  151. atom_file.write(atom_feed)
  152. atom_file.close()
  153. def copy_site():
  154. os.system('cp -r output/* %s' % deploy_directory)
  155. def deploy_site():
  156. copy_site()
  157. os.chdir(os.path.expanduser(deploy_directory))
  158. os.system('git add .')
  159. os.system('git commit -m "automated update from build.py"')
  160. os.system('git push')
  161. def main():
  162. parser = argparse.ArgumentParser()
  163. parser.add_argument(
  164. '--clean', action='store_true',
  165. help='wipe the output directory before running')
  166. parser.add_argument(
  167. '--fast', action='store_true',
  168. help='only rebuild content files')
  169. parser.add_argument(
  170. '--copy', action='store_true',
  171. help='copy output files to www-home git repo')
  172. parser.add_argument(
  173. '--deploy', action='store_true',
  174. help='deploy the site by pushing the www-home git repo to production')
  175. args = parser.parse_args()
  176. if args.clean:
  177. shutil.rmtree(output_directory)
  178. os.makedirs(output_directory, exist_ok=True)
  179. if not args.fast:
  180. copy_static_files()
  181. process_markdown_files()
  182. make_sitemap()
  183. make_atom_feed()
  184. if args.copy and not args.deploy:
  185. copy_site()
  186. if args.deploy:
  187. if args.fast:
  188. print('cowardly refusing to deploy a site that was built with --fast')
  189. else:
  190. deploy_site()
  191. if __name__ == '__main__':
  192. main()