makesite.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. #!/usr/bin/env python3
  2. # The MIT License (MIT)
  3. #
  4. # Copyright (c) 2018 Sunaina Pai
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining
  7. # a copy of this software and associated documentation files (the
  8. # "Software"), to deal in the Software without restriction, including
  9. # without limitation the rights to use, copy, modify, merge, publish,
  10. # distribute, sublicense, and/or sell copies of the Software, and to
  11. # permit persons to whom the Software is furnished to do so, subject to
  12. # the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be
  15. # included in all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  20. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  21. # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  22. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  23. # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  24. """Make static website/blog with Python."""
  25. import os
  26. import shutil
  27. import re
  28. import glob
  29. import sys
  30. import json
  31. import datetime
  32. def fread(filename):
  33. """Read file and close the file."""
  34. with open(filename, 'r') as f:
  35. return f.read()
  36. def fwrite(filename, text):
  37. """Write content to file and close the file."""
  38. basedir = os.path.dirname(filename)
  39. if not os.path.isdir(basedir):
  40. os.makedirs(basedir)
  41. with open(filename, 'w') as f:
  42. f.write(text)
  43. def log(msg, *args):
  44. """Log message with specified arguments."""
  45. sys.stderr.write(msg.format(*args) + '\n')
  46. def truncate(text, words=25):
  47. """Remove tags and truncate text to the specified number of words."""
  48. return ' '.join(re.sub('(?s)<.*?>', ' ', text).split()[:words])
  49. def read_headers(text):
  50. """Parse headers in text and yield (key, value, end-index) tuples."""
  51. for match in re.finditer(r'\s*<!--\s*(.+?)\s*:\s*(.+?)\s*-->\s*|.+', text):
  52. if not match.group(1):
  53. break
  54. yield match.group(1), match.group(2), match.end()
  55. def rfc_2822_format(date_str):
  56. """Convert yyyy-mm-dd date string to RFC 2822 format date string."""
  57. d = datetime.datetime.strptime(date_str, '%Y-%m-%d')
  58. return d.strftime('%a, %d %b %Y %H:%M:%S +0000')
  59. def read_content(filename):
  60. """Read content and metadata from file into a dictionary."""
  61. # Read file content.
  62. text = fread(filename)
  63. # Read metadata and save it in a dictionary.
  64. date_slug = os.path.basename(filename).split('.')[0]
  65. match = re.search(r'^(?:(\d\d\d\d-\d\d-\d\d)-)?(.+)$', date_slug)
  66. content = {
  67. 'date': match.group(1) or '1970-01-01',
  68. 'slug': match.group(2),
  69. }
  70. # Read headers.
  71. end = 0
  72. for key, val, end in read_headers(text):
  73. content[key] = val
  74. # Separate content from headers.
  75. text = text[end:]
  76. # Convert Markdown content to HTML.
  77. if filename.endswith(('.md', '.mkd', '.mkdn', '.mdown', '.markdown')):
  78. try:
  79. if _test == 'ImportError':
  80. raise ImportError('Error forced by test')
  81. #import commonmark
  82. #text = commonmark.commonmark(text)
  83. import markdown2
  84. text = markdown2.markdown(text, extras=["tables","fenced-code-blocks"])
  85. except ImportError as e:
  86. log('WARNING: Cannot render Markdown in {}: {}', filename, str(e))
  87. # Update the dictionary with content and RFC 2822 date.
  88. content.update({
  89. 'content': text,
  90. 'rfc_2822_date': rfc_2822_format(content['date'])
  91. })
  92. return content
  93. def render(template, **params):
  94. """Replace placeholders in template with values from params."""
  95. return re.sub(r'{{\s*([^}\s]+)\s*}}',
  96. lambda match: str(params.get(match.group(1), match.group(0))),
  97. template)
  98. def make_pages(src, dst, layout, **params):
  99. """Generate pages from page content."""
  100. items = []
  101. for src_path in glob.glob(src):
  102. content = read_content(src_path)
  103. page_params = dict(params, **content)
  104. # Populate placeholders in content if content-rendering is enabled.
  105. if page_params.get('render') == 'yes':
  106. rendered_content = render(page_params['content'], **page_params)
  107. page_params['content'] = rendered_content
  108. content['content'] = rendered_content
  109. items.append(content)
  110. dst_path = render(dst, **page_params)
  111. output = render(layout, **page_params)
  112. log('Rendering {} => {} ...', src_path, dst_path)
  113. fwrite(dst_path, output)
  114. return sorted(items, key=lambda x: x['date'], reverse=True)
  115. def make_list(posts, dst, list_layout, item_layout, **params):
  116. """Generate list page for a blog."""
  117. items = []
  118. for post in posts:
  119. item_params = dict(params, **post)
  120. item_params['summary'] = truncate(post['content'])
  121. item = render(item_layout, **item_params)
  122. items.append(item)
  123. params['content'] = ''.join(items)
  124. dst_path = render(dst, **params)
  125. output = render(list_layout, **params)
  126. log('Rendering list => {} ...', dst_path)
  127. fwrite(dst_path, output)
  128. def main():
  129. # Create a new _site directory from scratch.
  130. if os.path.isdir('_site'):
  131. shutil.rmtree('_site')
  132. shutil.copytree('static', '_site')
  133. # Default parameters.
  134. params = {
  135. 'base_path': '',
  136. 'subtitle': 'Milis Linux',
  137. 'author': 'Admin',
  138. 'site_url': 'http://localhost:8000',
  139. 'current_year': datetime.datetime.now().year
  140. }
  141. # If params.json exists, load it.
  142. if os.path.isfile('params.json'):
  143. params.update(json.loads(fread('params.json')))
  144. # Load layouts.
  145. page_layout = fread('layout/page.html')
  146. post_layout = fread('layout/post.html')
  147. list_layout = fread('layout/list.html')
  148. item_layout = fread('layout/item.html')
  149. feed_xml = fread('layout/feed.xml')
  150. item_xml = fread('layout/item.xml')
  151. # Combine layouts to form final layouts.
  152. post_layout = render(page_layout, content=post_layout)
  153. list_layout = render(page_layout, content=list_layout)
  154. # Create site pages.
  155. make_pages('content/_index.md', '_site/index.html',
  156. page_layout,title='Ana Sayfa', **params)
  157. make_pages('content/[!_]*.html', '_site/{{ slug }}/index.html',
  158. page_layout, **params)
  159. make_pages('content/[!_]*.md', '_site/{{ slug }}/index.html',
  160. page_layout, **params)
  161. # Create blogs.
  162. blog_posts = make_pages('content/blog/*.md',
  163. '_site/blog/{{ slug }}/index.html',
  164. post_layout, blog='blog', **params)
  165. doc_pages = make_pages('content/doc/*.md', '_site/doc/{{ slug }}/index.html', page_layout, **params)
  166. #news_posts = make_pages('content/news/*.html', '_site/news/{{ slug }}/index.html', post_layout, blog='news', **params)
  167. #doc_posts = make_pages('content/belge/*.md', '_site/belge/{{ slug }}/index.html', post_layout, blog='belgeler', **params)
  168. # Create blog list pages.
  169. make_list(blog_posts, '_site/blog/index.html',
  170. list_layout, item_layout, blog='blog', title='Blog', **params)
  171. #make_list(news_posts, '_site/news/index.html',list_layout, item_layout, blog='news', title='News', **params)
  172. #make_list(doc_posts, '_site/belge/index.html',list_layout, item_layout, blog='belge', title='Belgeler', **params)
  173. # Create RSS feeds.
  174. make_list(blog_posts, '_site/blog/rss.xml',
  175. feed_xml, item_xml, blog='blog', title='Blog', **params)
  176. #make_list(news_posts, '_site/news/rss.xml', feed_xml, item_xml, blog='news', title='News', **params)
  177. # Test parameter to be set temporarily by unit tests.
  178. _test = None
  179. if __name__ == '__main__':
  180. main()