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.

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