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.

243 lines
6.7 KiB

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