|
| 1 | +#!/usr/bin/env python |
| 2 | +import argparse |
| 3 | +import json |
| 4 | +import os |
| 5 | +import re |
| 6 | +import sys |
| 7 | +import toml |
| 8 | +import logging |
| 9 | + |
| 10 | +logger = logging.getLogger('genindex') |
| 11 | +PAT_HEADMATTER = re.compile(r'^\+\+\+\n(.+)\n\+\+\+', re.DOTALL) |
| 12 | + |
| 13 | + |
| 14 | +def process_file(path): |
| 15 | + with open(path, 'r') as f: |
| 16 | + rawdata = f.read() |
| 17 | + |
| 18 | + match = PAT_HEADMATTER.match(rawdata) |
| 19 | + if not match: |
| 20 | + raise ValueError('Couldn\'t find headmatter') |
| 21 | + |
| 22 | + data = toml.loads(match.group(1)) |
| 23 | + title = data['title'] |
| 24 | + slug = data.get('slug', os.path.splitext(os.path.basename(path))[0]) |
| 25 | + tags = data['tags'] |
| 26 | + |
| 27 | + return (slug, title, tags) |
| 28 | + |
| 29 | + |
| 30 | +def main(args): |
| 31 | + parser = argparse.ArgumentParser(description=__doc__) |
| 32 | + parser.add_argument('source', help='Source directory under which to find pages.') |
| 33 | + parser.add_argument('--out', metavar='PATH', help='Path in which to save the tag index.') |
| 34 | + parser.add_argument('--config', metavar='PATH', help='Path to the project configuration file.') |
| 35 | + args = parser.parse_args() |
| 36 | + |
| 37 | + logging.basicConfig() |
| 38 | + data = [] |
| 39 | + |
| 40 | + with open(args.config, 'r') as f: |
| 41 | + tag_manifest = toml.load(f).get('tags', {}) |
| 42 | + |
| 43 | + error = False |
| 44 | + for root, _, files in os.walk(args.source): |
| 45 | + for filename in files: |
| 46 | + filename = os.path.join(root, filename) |
| 47 | + try: |
| 48 | + slug, title, tags = process_file(filename) |
| 49 | + except ValueError: |
| 50 | + logger.exception('Error processing %s', filename) |
| 51 | + continue |
| 52 | + |
| 53 | + for tag in tags: |
| 54 | + if not tag in tag_manifest: |
| 55 | + logger.fatal('Unknown tag "%s" in %s', tag, filename) |
| 56 | + error = True |
| 57 | + |
| 58 | + data.append((slug, title, tags)) |
| 59 | + |
| 60 | + if error: |
| 61 | + sys.exit(1) |
| 62 | + |
| 63 | + with open(args.out, 'w') as f: |
| 64 | + json.dump({ |
| 65 | + 'tags': tag_manifest, |
| 66 | + 'pages': data |
| 67 | + }, f) |
| 68 | + |
| 69 | +if __name__ == '__main__': |
| 70 | + main(sys.argv) |
0 commit comments