comment-lens-scanner 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ """Local, non-executing source comment inventory scanner."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .core import scan_repository
6
+
7
+ __all__ = ["scan_repository", "__version__"]
@@ -0,0 +1,4 @@
1
+ from .core import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,55 @@
1
+ """Minimal repository-owned baselines for deterministic findings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ from .policy import ConfigError
9
+
10
+ BASELINE_VERSION = 1
11
+
12
+
13
+ def create_baseline(report: dict[str, object]) -> dict[str, object]:
14
+ return {
15
+ "baselineVersion": BASELINE_VERSION,
16
+ "repository": report["repository"],
17
+ "findings": [
18
+ {"findingId": item["findingId"], "ruleId": item["ruleId"], "path": item["path"]}
19
+ for item in sorted(report["findings"], key=lambda finding: finding["findingId"])
20
+ ],
21
+ }
22
+
23
+
24
+ def load_baseline(path: Path, repository: str) -> dict[str, object]:
25
+ try:
26
+ baseline = json.loads(path.read_text(encoding="utf-8"))
27
+ except (OSError, UnicodeError, json.JSONDecodeError) as error:
28
+ raise ConfigError(f"cannot read baseline {path}: {error}") from error
29
+ if not isinstance(baseline, dict) or type(baseline.get("baselineVersion")) is not int or baseline["baselineVersion"] != BASELINE_VERSION:
30
+ raise ConfigError("unsupported baseline version")
31
+ if baseline.get("repository") != repository:
32
+ raise ConfigError("baseline repository does not match this scan")
33
+ findings = baseline.get("findings")
34
+ if not isinstance(findings, list):
35
+ raise ConfigError("baseline findings must be a list")
36
+ seen: set[str] = set()
37
+ for item in findings:
38
+ if not isinstance(item, dict) or set(item) != {"findingId", "ruleId", "path"}:
39
+ raise ConfigError("baseline contains an invalid finding")
40
+ if any(not isinstance(item[key], str) or not item[key] for key in ("findingId", "ruleId", "path")):
41
+ raise ConfigError("baseline contains an invalid finding")
42
+ if item["findingId"] in seen:
43
+ raise ConfigError("baseline contains duplicate finding IDs")
44
+ seen.add(item["findingId"])
45
+ return baseline
46
+
47
+
48
+ def write_baseline(path: Path, baseline: dict[str, object], *, force: bool = False) -> None:
49
+ if path.exists() and not force:
50
+ raise ConfigError(f"baseline already exists: {path}; pass --force to replace it")
51
+ path.parent.mkdir(parents=True, exist_ok=True)
52
+ mode = "w" if force else "x"
53
+ with path.open(mode, encoding="utf-8") as stream:
54
+ json.dump(baseline, stream, indent=2, ensure_ascii=False)
55
+ stream.write("\n")
@@ -0,0 +1,332 @@
1
+ """Local, offline command-line interface for Comment Lens."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import re
8
+ import sys
9
+ from pathlib import Path, PureWindowsPath
10
+ from urllib.parse import urlsplit
11
+
12
+ from .baseline import create_baseline, load_baseline, write_baseline
13
+ from .core import DEFAULT_EXCLUSIONS, _git, scan_repository, write_output
14
+ from .github_annotations import annotations
15
+ from .history import load_report, render_summary, summarize_reports
16
+ from .policy import ConfigError, build_report, load_policy, render_report
17
+
18
+ HUNK = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")
19
+
20
+
21
+ class ScanError(ValueError):
22
+ """The requested local scan cannot produce trustworthy results."""
23
+
24
+
25
+ def _git_output(root: Path, args: list[str]) -> str:
26
+ output, error = _git(root, args)
27
+ if error is not None:
28
+ raise ScanError(f"Git operation failed: {error}")
29
+ return output
30
+
31
+
32
+ def _repository_id(root: Path, override: str | None) -> str:
33
+ if override:
34
+ return override
35
+ remote, error = _git(root, ["remote", "get-url", "origin"])
36
+ if error is not None:
37
+ return root.name
38
+ value = remote.strip()
39
+ if value.startswith("git@github.com:"):
40
+ path = value.removeprefix("git@github.com:")
41
+ else:
42
+ parsed = urlsplit(value)
43
+ if parsed.hostname != "github.com":
44
+ return root.name
45
+ path = parsed.path.lstrip("/")
46
+ parts = path.removesuffix(".git").split("/")
47
+ return "/".join(parts) if len(parts) == 2 and all(parts) else root.name
48
+
49
+
50
+ def changed_selection(root: Path, revision: str) -> tuple[set[str], dict[str, list[tuple[int, int]]]]:
51
+ if not revision or revision.startswith("-") or any(character.isspace() for character in revision) or "\0" in revision:
52
+ raise ConfigError("changed revision must be a Git ref or range")
53
+ options = ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--ignore-submodules=all"]
54
+ names = _git_output(root, [*options, "--diff-filter=AM", "--name-only", "-z", revision, "--"])
55
+ paths = {path for path in names.split("\0") if path}
56
+ if ".." in revision:
57
+ right = revision.split("...")[-1] if "..." in revision else revision.split("..")[-1]
58
+ if not right:
59
+ raise ConfigError("changed range must end at the checked-out HEAD")
60
+ endpoint = _git_output(root, ["rev-parse", "--verify", f"{right}^{{commit}}"]).strip()
61
+ head = _git_output(root, ["rev-parse", "HEAD"]).strip()
62
+ if endpoint != head:
63
+ raise ConfigError("changed range must end at the checked-out HEAD")
64
+ if paths and _git_output(root, ["diff", "--name-only", "-z", "HEAD", "--", *sorted(paths)]):
65
+ raise ConfigError("changed files differ from HEAD; use a single base ref to include working-tree changes")
66
+
67
+ ranges: dict[str, list[tuple[int, int]]] = {}
68
+ for path in sorted(paths):
69
+ patch = _git_output(root, [*options, "--unified=0", "--no-color", revision, "--", path])
70
+ spans = []
71
+ for line in patch.splitlines():
72
+ match = HUNK.match(line)
73
+ if match is None:
74
+ continue
75
+ first = int(match.group(1))
76
+ count = int(match.group(2) or "1")
77
+ if count:
78
+ spans.append((first, first + count - 1))
79
+ ranges[path] = spans
80
+ return paths, ranges
81
+
82
+
83
+ def _failed(scan: dict[str, object]) -> bool:
84
+ return any(item["severity"] == "error" for item in scan["diagnostics"]) or any(
85
+ item["status"] == "failed" for item in scan["files"]
86
+ )
87
+
88
+
89
+ def _write_text(output: Path | None, content: str) -> None:
90
+ if output is None:
91
+ sys.stdout.write(content)
92
+ return
93
+ output.parent.mkdir(parents=True, exist_ok=True)
94
+ output.write_text(content, encoding="utf-8")
95
+
96
+
97
+ def _load_artifacts(directory: Path) -> dict[str, object]:
98
+ manifest = json.loads((directory / "scan.json").read_text(encoding="utf-8"))
99
+ if not isinstance(manifest, dict) or not isinstance(manifest.get("scanId"), str):
100
+ raise ScanError("scan.json is not a Comment Lens manifest")
101
+ comments = []
102
+ with (directory / "comments.ndjson").open(encoding="utf-8") as stream:
103
+ for line in stream:
104
+ if not line.strip():
105
+ continue
106
+ comment = json.loads(line)
107
+ if not isinstance(comment, dict) or comment.get("scanId") != manifest["scanId"]:
108
+ raise ScanError("comments.ndjson does not match scan.json")
109
+ comments.append(comment)
110
+ manifest["_comments"] = comments
111
+ return manifest
112
+
113
+
114
+ def _common(parser: argparse.ArgumentParser) -> None:
115
+ parser.add_argument("root", nargs="?", type=Path, default=Path("."), help="Repository root")
116
+ parser.add_argument("--config", type=Path, help="Policy file, relative to the repository root")
117
+ parser.add_argument("--exclude", action="append", default=[], help="Additional repository-relative path to exclude")
118
+
119
+
120
+ def _baseline_path(root: Path, explicit: Path | None, configured: str | None, *, required: bool) -> Path | None:
121
+ chosen = explicit or (Path(configured) if configured else None)
122
+ if chosen is None and required:
123
+ chosen = Path(".comment-lens-baseline.json")
124
+ return chosen if chosen is None or chosen.is_absolute() else root / chosen
125
+
126
+
127
+ def _check_options(parser: argparse.ArgumentParser) -> None:
128
+ _common(parser)
129
+ parser.add_argument("--path", action="append", help="Scan one repository-relative file; repeat for more files")
130
+ parser.add_argument("--changed", help="Select changes from a Git ref or range")
131
+ parser.add_argument("--scope", choices=("comments", "files"), default="comments", help="Use changed comment lines or all comments in changed files")
132
+ parser.add_argument("--include-untracked", action="store_true")
133
+ parser.add_argument("--repository-id", help="Stable owner/name identity; inferred from a GitHub origin by default")
134
+ parser.add_argument("--baseline", type=Path, help="Baseline file; overrides baseline.path")
135
+ parser.add_argument("--fail-on", choices=("none", "low", "review", "high"), help="Opt into a blocking severity")
136
+ parser.add_argument("--format", choices=("markdown", "json", "sarif"), default="markdown")
137
+ parser.add_argument("--source", choices=("local", "ci"), default="local", help="Label this report's origin")
138
+ parser.add_argument("--output", type=Path, help="Write the report to a file instead of standard output")
139
+
140
+
141
+ def _scan(args: argparse.Namespace) -> int:
142
+ root = args.root.resolve()
143
+ policy = load_policy(root, args.config, excludes=tuple(args.exclude))
144
+ selection = changed_selection(root, args.changed)[0] if args.changed else None
145
+ if args.changed and args.include_untracked:
146
+ raise ConfigError("--include-untracked cannot be combined with --changed")
147
+ result = scan_repository(
148
+ root,
149
+ include_untracked=args.include_untracked,
150
+ exclusions=(*DEFAULT_EXCLUSIONS, *policy.exclusions),
151
+ repository_id=_repository_id(root, args.repository_id),
152
+ selected_paths=selection,
153
+ offline=True,
154
+ )
155
+ output = args.output if args.output.is_absolute() else root / args.output
156
+ write_output(result, output / "scan.json", output / "comments.ndjson")
157
+ print(json.dumps({
158
+ "scanId": result["scanId"],
159
+ "files": len(result["files"]),
160
+ "comments": len(result["_comments"]),
161
+ "diagnostics": len(result["diagnostics"]),
162
+ "output": str(output),
163
+ }))
164
+ return 2 if _failed(result) else 0
165
+
166
+
167
+ def _check(args: argparse.Namespace) -> int:
168
+ root = args.root.resolve()
169
+ policy = load_policy(root, args.config, excludes=tuple(args.exclude), fail_on=args.fail_on)
170
+ if args.changed and args.include_untracked:
171
+ raise ConfigError("--include-untracked cannot be combined with --changed")
172
+ if args.changed and args.path:
173
+ raise ConfigError("--path cannot be combined with --changed")
174
+ if args.path and any(
175
+ not path
176
+ or path.startswith("/")
177
+ or PureWindowsPath(path).drive
178
+ or "\\" in path
179
+ or any(part in ("", ".", "..") for part in path.split("/"))
180
+ for path in args.path
181
+ ):
182
+ raise ConfigError("--path must name a repository-relative file")
183
+ paths, ranges = changed_selection(root, args.changed) if args.changed else (None, None)
184
+ if args.path:
185
+ paths = set(args.path)
186
+ result = scan_repository(
187
+ root,
188
+ include_untracked=args.include_untracked,
189
+ exclusions=(*DEFAULT_EXCLUSIONS, *policy.exclusions),
190
+ repository_id=_repository_id(root, args.repository_id),
191
+ selected_paths=paths,
192
+ offline=True,
193
+ )
194
+ baseline_path = _baseline_path(root, args.baseline, policy.baseline_path, required=args.command == "compare")
195
+ baseline = load_baseline(baseline_path, result["repoId"]) if baseline_path is not None else None
196
+ report = build_report(
197
+ result,
198
+ policy,
199
+ selection=f"{args.scope} changed in {args.changed}" if args.changed else "selected files" if args.path else "all tracked files",
200
+ ranges=ranges if args.changed and args.scope == "comments" else None,
201
+ baseline=baseline,
202
+ full_scan=args.changed is None and not args.path,
203
+ root=root,
204
+ source=args.source,
205
+ )
206
+ output = args.output if args.output is None or args.output.is_absolute() else root / args.output
207
+ _write_text(output, render_report(report, args.format))
208
+ if _failed(result):
209
+ return 2
210
+ return 1 if report["summary"]["blocking"] else 0
211
+
212
+
213
+ def _baseline_create(args: argparse.Namespace) -> int:
214
+ root = args.root.resolve()
215
+ policy = load_policy(root, args.config, excludes=tuple(args.exclude))
216
+ result = scan_repository(
217
+ root,
218
+ exclusions=(*DEFAULT_EXCLUSIONS, *policy.exclusions),
219
+ repository_id=_repository_id(root, args.repository_id),
220
+ offline=True,
221
+ )
222
+ if _failed(result):
223
+ raise ScanError("scan failed; baseline was not written")
224
+ report = build_report(result, policy, root=root)
225
+ path = _baseline_path(root, args.output, policy.baseline_path, required=True)
226
+ write_baseline(path, create_baseline(report), force=args.force)
227
+ print(json.dumps({"baseline": str(path), "findings": report["summary"]["findings"]}))
228
+ return 0
229
+
230
+
231
+ def _export(args: argparse.Namespace) -> int:
232
+ root = args.root.resolve()
233
+ policy = load_policy(root, args.config, excludes=tuple(args.exclude), fail_on=args.fail_on)
234
+ directory = args.input if args.input.is_absolute() else root / args.input
235
+ scan = _load_artifacts(directory)
236
+ baseline_path = _baseline_path(root, args.baseline, policy.baseline_path, required=False)
237
+ baseline = load_baseline(baseline_path, scan["repoId"]) if baseline_path is not None else None
238
+ report = build_report(scan, policy, baseline=baseline, full_scan=False, source=args.source)
239
+ output = args.output if args.output is None or args.output.is_absolute() else root / args.output
240
+ _write_text(output, render_report(report, args.format))
241
+ if _failed(scan):
242
+ return 2
243
+ return 1 if report["summary"]["blocking"] else 0
244
+
245
+
246
+ def _annotate(args: argparse.Namespace) -> int:
247
+ if args.limit < 1:
248
+ raise ConfigError("annotation limit must be positive")
249
+ sys.stdout.write(annotations(args.input, limit=args.limit))
250
+ return 0
251
+
252
+
253
+ def _render(args: argparse.Namespace) -> int:
254
+ report = load_report(args.input, require_date=False)
255
+ _write_text(args.output, render_report(report, args.format))
256
+ if report.get("scanFailed"):
257
+ return 2
258
+ return 1 if report["summary"].get("blocking") else 0
259
+
260
+
261
+ def _summary(args: argparse.Namespace) -> int:
262
+ reports = [load_report(path) for path in args.report]
263
+ _write_text(args.output, render_summary(summarize_reports(reports), args.format))
264
+ return 0
265
+
266
+
267
+ def main(argv: list[str] | None = None) -> int:
268
+ parser = argparse.ArgumentParser(prog="comment-lens", description="Inspect repository comments locally without uploading source code.")
269
+ commands = parser.add_subparsers(dest="command", required=True)
270
+
271
+ scan = commands.add_parser("scan", help="Write compatible scan.json and comments.ndjson artifacts")
272
+ _common(scan)
273
+ scan.add_argument("--changed", help="Limit the scan to files changed from a Git ref or range")
274
+ scan.add_argument("--include-untracked", action="store_true")
275
+ scan.add_argument("--repository-id", help="Stable owner/name identity; inferred from a GitHub origin by default")
276
+ scan.add_argument("--output", type=Path, default=Path(".comment-lens"), help="Artifact directory")
277
+ scan.set_defaults(run=_scan)
278
+
279
+ check = commands.add_parser("check", help="Report deterministic maintenance findings")
280
+ _check_options(check)
281
+ check.set_defaults(run=_check)
282
+
283
+ baseline = commands.add_parser("baseline", help="Create a repository-owned baseline")
284
+ baseline_commands = baseline.add_subparsers(dest="baseline_command", required=True)
285
+ create = baseline_commands.add_parser("create", help="Capture findings from a full tracked-file scan")
286
+ _common(create)
287
+ create.add_argument("--repository-id", help="Stable owner/name identity; inferred from a GitHub origin by default")
288
+ create.add_argument("--output", type=Path, help="Baseline file; defaults to baseline.path or .comment-lens-baseline.json")
289
+ create.add_argument("--force", action="store_true", help="Replace an existing baseline")
290
+ create.set_defaults(run=_baseline_create)
291
+
292
+ compare = commands.add_parser("compare", help="Compare current findings with a baseline")
293
+ _check_options(compare)
294
+ compare.set_defaults(run=_check)
295
+
296
+ export = commands.add_parser("export", help="Render findings from an existing local scan")
297
+ _common(export)
298
+ export.add_argument("--input", type=Path, default=Path(".comment-lens"), help="Directory containing scan.json and comments.ndjson")
299
+ export.add_argument("--baseline", type=Path, help="Compare with a baseline file")
300
+ export.add_argument("--fail-on", choices=("none", "low", "review", "high"), help="Opt into a blocking severity")
301
+ export.add_argument("--format", choices=("markdown", "json", "sarif"), default="json")
302
+ export.add_argument("--source", choices=("local", "ci"), default="local", help="Label this report's origin")
303
+ export.add_argument("--output", type=Path, help="Write the report to a file instead of standard output")
304
+ export.set_defaults(run=_export)
305
+
306
+ annotate = commands.add_parser("annotate", help="Emit GitHub Actions annotations from a SARIF report")
307
+ annotate.add_argument("--input", type=Path, required=True, help="SARIF file produced by check or compare")
308
+ annotate.add_argument("--limit", type=int, default=50, help="Maximum number of annotations")
309
+ annotate.set_defaults(run=_annotate)
310
+
311
+ render = commands.add_parser("render", help="Render a saved JSON report without rescanning")
312
+ render.add_argument("--input", type=Path, required=True, help="JSON report from check or compare")
313
+ render.add_argument("--format", choices=("markdown", "sarif"), required=True)
314
+ render.add_argument("--output", type=Path)
315
+ render.set_defaults(run=_render)
316
+
317
+ summary = commands.add_parser("summary", help="Summarize saved local and CI JSON reports")
318
+ summary.add_argument("--report", type=Path, action="append", required=True, help="Saved JSON report; repeat for each scan")
319
+ summary.add_argument("--format", choices=("json", "markdown"), default="markdown")
320
+ summary.add_argument("--output", type=Path)
321
+ summary.set_defaults(run=_summary)
322
+
323
+ args = parser.parse_args(argv)
324
+ try:
325
+ return args.run(args)
326
+ except (ConfigError, ScanError, OSError, UnicodeError, ValueError, KeyError, TypeError) as error:
327
+ print(f"comment-lens: {error}", file=sys.stderr)
328
+ return 2
329
+
330
+
331
+ if __name__ == "__main__":
332
+ raise SystemExit(main())