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.

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