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.

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