|
| 1 | +import argparse |
| 2 | +import re |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import shutil |
| 6 | +import logging |
| 7 | +from typing import List, Optional |
| 8 | +from dataclasses import dataclass |
| 9 | + |
| 10 | + |
| 11 | +@dataclass |
| 12 | +class Snippet: |
| 13 | + name: str |
| 14 | + lines: List[str] |
| 15 | + |
| 16 | + |
| 17 | +def write_snippet(target_dir: os.PathLike, snippet: Snippet): |
| 18 | + assert os.path.exists(target_dir) and os.path.isdir(target_dir) |
| 19 | + |
| 20 | + file_name = f'{snippet.name}.h' |
| 21 | + with open(os.path.join(target_dir, file_name), 'w', encoding='utf-8') as f: |
| 22 | + f.writelines(snippet.lines) |
| 23 | + |
| 24 | + |
| 25 | +def extract_snippets(filepath: os.PathLike) -> List[Snippet]: |
| 26 | + with open(filepath, 'r', encoding='utf-8') as f: |
| 27 | + lines = f.readlines() |
| 28 | + |
| 29 | + snippets = [] |
| 30 | + |
| 31 | + snippet_start = re.compile(r"^```\{.cpp\s+file=(\S+)\}$") |
| 32 | + snippet_end = re.compile(r"^```$") |
| 33 | + |
| 34 | + snippet_start_line: Optional[int] = None |
| 35 | + snippet_name: Optional[str] = None |
| 36 | + |
| 37 | + for line_idx, line in enumerate(lines): |
| 38 | + match_snippet_start = snippet_start.match(line) |
| 39 | + match_snippet_end = snippet_end.match(line) |
| 40 | + assert not (match_snippet_start and match_snippet_end) |
| 41 | + |
| 42 | + if match_snippet_start: |
| 43 | + assert snippet_start_line is None |
| 44 | + assert snippet_name is None |
| 45 | + |
| 46 | + snippet_start_line = line_idx |
| 47 | + snippet_name = match_snippet_start.group(1) |
| 48 | + elif match_snippet_end: |
| 49 | + if snippet_start_line is not None: |
| 50 | + assert snippet_start_line is not None |
| 51 | + assert snippet_name is not None |
| 52 | + |
| 53 | + snippet = lines[snippet_start_line + 1: line_idx] |
| 54 | + |
| 55 | + snippets.append(Snippet(name=snippet_name, lines=snippet)) |
| 56 | + |
| 57 | + snippet_start_line = None |
| 58 | + snippet_name = None |
| 59 | + |
| 60 | + return snippets |
| 61 | + |
| 62 | + |
| 63 | +def main(args: argparse.Namespace) -> None: |
| 64 | + src_dir = args.src_dir |
| 65 | + target_dir = args.target_dir |
| 66 | + |
| 67 | + logging.info(f'--src-dir="{src_dir}"') |
| 68 | + logging.info(f'--target-dir="{target_dir}"') |
| 69 | + |
| 70 | + assert os.path.isdir(src_dir) |
| 71 | + |
| 72 | + if args.remove_prev_target_dir and os.path.exists(target_dir): |
| 73 | + logging.info(f'Script launched with --remove-prev-target-dir flag') |
| 74 | + logging.info(f'Removing --target-dir="{target_dir}"') |
| 75 | + shutil.rmtree(target_dir) |
| 76 | + |
| 77 | + if not os.path.exists(target_dir): |
| 78 | + logging.info( |
| 79 | + f'--target-dir="{target_dir}" does not exist, creating') |
| 80 | + os.makedirs(target_dir, exist_ok=False) |
| 81 | + assert os.path.isdir( |
| 82 | + target_dir), f'Failed to create --target-dir: "{target_dir}"' |
| 83 | + |
| 84 | + snippets = [] |
| 85 | + |
| 86 | + for subdir, _, files in os.walk(src_dir): |
| 87 | + for filename in files: |
| 88 | + if filename.lower().endswith('.md'): |
| 89 | + filepath = os.path.join(subdir, filename) |
| 90 | + logging.debug(f'Extracting snippets from {filename}') |
| 91 | + snippets.extend(extract_snippets(filepath)) |
| 92 | + |
| 93 | + n_snippets = len(snippets) |
| 94 | + for snippet_idx, snippet in enumerate(snippets, start=1): |
| 95 | + logging.debug( |
| 96 | + f'({snippet_idx}/{n_snippets}) writing snippet {snippet.name} to "{target_dir}"') |
| 97 | + write_snippet(target_dir, snippet) |
| 98 | + |
| 99 | + logging.info( |
| 100 | + f'All done, {n_snippets} snippets have been written to "{target_dir}"') |
| 101 | + |
| 102 | + |
| 103 | +if __name__ == '__main__': |
| 104 | + parser = argparse.ArgumentParser( |
| 105 | + description='Recursively extracts specially annotation cpp code snippets from src dir with .md files') |
| 106 | + |
| 107 | + parser.add_argument('--src-dir', type=str, required=True, |
| 108 | + help='path to the directory with .md source to recursively look for cpp snippets with {.cpp file=...} annotation') |
| 109 | + parser.add_argument('--target-dir', type=str, required=True, |
| 110 | + help='path to the resulting directory with .h snippets extracted from src-dir') |
| 111 | + parser.add_argument('--remove-prev-target-dir', action='store_true', |
| 112 | + help='remove --target-dir prior to generating snippets') |
| 113 | + |
| 114 | + logging_level_names = list(logging.getLevelNamesMapping().keys()) |
| 115 | + assert 'INFO' in logging_level_names |
| 116 | + parser.add_argument('--logging-level', type=str, choices=logging_level_names, |
| 117 | + default='INFO', help='script logging level') |
| 118 | + |
| 119 | + args = parser.parse_args() |
| 120 | + |
| 121 | + logging.basicConfig( |
| 122 | + stream=sys.stdout, |
| 123 | + format='%(asctime)s %(module)-15s - [%(levelname)-6s] - %(message)s', |
| 124 | + datefmt='%H:%M:%S', |
| 125 | + level=args.logging_level |
| 126 | + ) |
| 127 | + |
| 128 | + main(args) |
0 commit comments