Debian Codegraph @

test/sanity/code-smell/pymarkdown.py

raw
1 """Sanity test for Markdown files."""
2
3 from __future__ import annotations
4
5 import pathlib
6 import re
7 import subprocess
8 import sys
9
10 import yaml
11
12 try:
13 from yaml import CSafeLoader as SafeLoader
14 except ImportError:
15 from yaml import SafeLoader
16
17 import typing as t
18
19
20 def main() -> None:
21 paths = sys.argv[1:] or sys.stdin.read().splitlines()
22
23 self_dir = pathlib.Path(__file__).parent
24 base_dir = self_dir.parent.parent.parent
25 config_path = self_dir / 'pymarkdown.config.json'
26
27 # This regex is intentionally a very loose check for potential frontmatter.
28 # There's no good reason for a non-frontmatter containing file to match this pattern.
29 frontmatter_pattern = re.compile(r'^\s*--')
30
31 frontmatter_allowed_prefixes = [
32 ".claude/",
33 ".github/",
34 ]
35
36 frontmatter_paths = []
37 other_paths = []
38 results = []
39
40 for path in paths:
41 content = pathlib.Path(path).read_text()
42 has_frontmatter = frontmatter_pattern.search(content)
43 allow_frontmatter = any(path.startswith(prefix) for prefix in frontmatter_allowed_prefixes)
44
45 # When potential frontmatter is detected, check it before running the document through pymarkdown.
46 # This avoids treating frontmatter issues as Markdown issues, which would otherwise lead to confusing error messages.
47
48 if allow_frontmatter:
49 if has_frontmatter and (issues := check_frontmatter(path, content)):
50 results.extend(issues)
51 else:
52 frontmatter_paths.append(path)
53 else:
54 if has_frontmatter:
55 results.append(f'{path}:1:1: frontmatter-not-allowed: frontmatter is not allowed in this document')
56 else:
57 other_paths.append(path)
58
59 results.extend(run_pymarkdown(frontmatter_paths, config_path, base_dir, enable_frontmatter=True))
60 results.extend(run_pymarkdown(other_paths, config_path, base_dir, enable_frontmatter=False))
61
62 if results:
63 print('\n'.join(results))
64
65
66 def check_frontmatter(path: str, content: str) -> list[str]:
67 """
68 Check frontmatter formatting.
69 Use only after detecting signs of frontmatter usage.
70 This supplements the frontmatter support in pymarkdown, which is less aggressive about detecting potential frontmatter.
71 """
72 match = re.search(r"^(?P<content>---\n.*?)\n---\n", content, flags=re.DOTALL)
73
74 if not match:
75 return [f"{path}:1:1: malformed-frontmatter: document appears to start with malformed frontmatter"]
76
77 yaml_content = match.group('content')
78
79 try:
80 yaml.load(yaml_content, Loader=SafeLoader)
81 except yaml.MarkedYAMLError as ex:
82 message = ' '.join(filter(None, (ex.context, ex.problem, ex.note))).strip()
83
84 return [f"{path}:{ex.problem_mark.line}:{ex.problem_mark.column}: frontmatter-yaml: {message}"]
85 except yaml.YAMLError as ex:
86 return [f"{path}:1:1: frontmatter-yaml: {ex}"]
87
88 return []
89
90
91 def run_pymarkdown(paths: list[str], config_path: pathlib.Path, base_dir: pathlib.Path, enable_frontmatter: bool) -> list[str]:
92 """Run pymarkdown on the given paths and return a list of results."""
93
94 if not paths:
95 return []
96
97 extensions: list[str] = []
98
99 if enable_frontmatter:
100 extensions.append('front-matter')
101
102 cmd = [
103 sys.executable,
104 '-m',
105 'pymarkdown',
106 '--config',
107 config_path,
108 '--strict-config',
109 '--enable-extensions',
110 ','.join(extensions),
111 'scan',
112 ] + paths
113
114 process = subprocess.run(
115 cmd,
116 stdin=subprocess.DEVNULL,
117 capture_output=True,
118 check=False,
119 text=True,
120 )
121
122 if process.stderr:
123 print(process.stderr.strip(), file=sys.stderr)
124 sys.exit(1)
125
126 if not (stdout := process.stdout.strip()):
127 return []
128
129 pattern = re.compile(r'^(?P<path>[^:]*):(?P<line>[0-9]+):(?P<column>[0-9]+): (?P<code>[^:]*): (?P<message>.*) \((?P<aliases>.*)\)$')
130 matches = parse_to_list_of_dict(pattern, stdout)
131
132 for match in matches:
133 match['path'] = str(pathlib.Path(match['path']).relative_to(base_dir))
134
135 results = [f"{match['path']}:{match['line']}:{match['column']}: {match['aliases'].split(', ')[0]}: {match['message']}" for match in matches]
136
137 return results
138
139
140 def parse_to_list_of_dict(pattern: re.Pattern, value: str) -> list[dict[str, t.Any]]:
141 matched = []
142 unmatched = []
143
144 for line in value.splitlines():
145 match = re.search(pattern, line)
146
147 if match:
148 matched.append(match.groupdict())
149 else:
150 unmatched.append(line)
151
152 if unmatched:
153 raise Exception(f'Pattern {pattern!r} did not match values:\n' + '\n'.join(unmatched))
154
155 return matched
156
157
158 if __name__ == '__main__':
159 main()