|
| 1 | +import logging |
| 2 | +import os |
| 3 | +from itertools import takewhile |
| 4 | +from typing import List |
| 5 | + |
| 6 | +import markdown |
| 7 | +import yaml |
| 8 | +from flask import Flask |
| 9 | + |
| 10 | +BASE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../') |
| 11 | + |
| 12 | +config = { |
| 13 | + 'root': os.path.join(BASE_DIR, 'pages'), |
| 14 | + 'encoding': 'utf-8', |
| 15 | + 'extension': '.md', |
| 16 | + 'html_renderer': markdown, |
| 17 | +} |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | +def discover_pages(app: Flask) -> List[dict]: |
| 22 | + """ |
| 23 | + Walk the flatpage directory, finding, parsing, and |
| 24 | + storing all pages in an index |
| 25 | + """ |
| 26 | + page_index = {} |
| 27 | + for current_path, _, file_list in os.walk(config['root']): |
| 28 | + relative_path = current_path.replace(config['root'], '').lstrip(os.sep) |
| 29 | + |
| 30 | + for name in file_list: |
| 31 | + if not name.endswith(config['extension']): |
| 32 | + continue |
| 33 | + |
| 34 | + name_without_extension = os.path.splitext(name)[0] |
| 35 | + full_path = os.path.join(relative_path, name_without_extension) |
| 36 | + |
| 37 | + page = get_page(full_path) |
| 38 | + page_index[full_path] = page |
| 39 | + |
| 40 | + # If the file name is index, strip the name and add a pointer |
| 41 | + # from the base directory to the full content. |
| 42 | + if name_without_extension == 'index': |
| 43 | + page_index[full_path.rsplit('/', 1)[0]] = page |
| 44 | + |
| 45 | + app.page_index = page_index |
| 46 | + return app |
| 47 | + |
| 48 | +def parse_page(content: str) -> dict: |
| 49 | + """ |
| 50 | + Given the contents of a Markdown file, parse |
| 51 | + the YAML config and HTML content |
| 52 | + """ |
| 53 | + lines = iter(content.split('\n')) |
| 54 | + |
| 55 | + # Read lines until we hit the empty line |
| 56 | + meta = '\n'.join(takewhile(lambda l: l != '---', lines)) |
| 57 | + meta = yaml.safe_load(meta) |
| 58 | + content = '\n'.join(lines) |
| 59 | + |
| 60 | + # Render the Markdown content as HTML |
| 61 | + html = markdown.markdown(content) |
| 62 | + |
| 63 | + return dict( |
| 64 | + **meta, |
| 65 | + **{'html': html}, |
| 66 | + ) |
| 67 | + |
| 68 | +def get_page(path: str, encoding: str=None) -> dict: |
| 69 | + """ |
| 70 | + Accept a path in the vein of the blog, open it |
| 71 | + within the filesystem, and parse its contents |
| 72 | + """ |
| 73 | + logger.debug("Getting %s", path) |
| 74 | + if encoding is None: |
| 75 | + encoding = config['encoding'] |
| 76 | + |
| 77 | + path = os.path.join(config['root'], path + ".md") |
| 78 | + |
| 79 | + with open(path, encoding=encoding) as file: |
| 80 | + content = file.read() |
| 81 | + return parse_page(content) |
0 commit comments