comment-lens-scanner 0.1.0__tar.gz
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.
- comment_lens_scanner-0.1.0/LICENSE +21 -0
- comment_lens_scanner-0.1.0/PKG-INFO +97 -0
- comment_lens_scanner-0.1.0/README.md +74 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner/__init__.py +7 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner/__main__.py +4 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner/baseline.py +55 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner/cli.py +332 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner/core.py +342 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner/github_annotations.py +44 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner/history.py +134 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner/maintenance.py +95 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner/policy.py +334 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner.egg-info/PKG-INFO +97 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner.egg-info/SOURCES.txt +20 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner.egg-info/dependency_links.txt +1 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner.egg-info/entry_points.txt +3 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner.egg-info/requires.txt +2 -0
- comment_lens_scanner-0.1.0/comment_lens_scanner.egg-info/top_level.txt +1 -0
- comment_lens_scanner-0.1.0/pyproject.toml +55 -0
- comment_lens_scanner-0.1.0/setup.cfg +4 -0
- comment_lens_scanner-0.1.0/tests/test_cli.py +183 -0
- comment_lens_scanner-0.1.0/tests/test_core.py +394 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Olayinka Vaughan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: comment-lens-scanner
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Deterministic source comment maintenance and quality scanner
|
|
5
|
+
Author: Olayinka Vaughan
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Builder106/comment-lens
|
|
8
|
+
Project-URL: Repository, https://github.com/Builder106/comment-lens
|
|
9
|
+
Project-URL: Issues, https://github.com/Builder106/comment-lens/issues
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
17
|
+
Requires-Python: >=3.12
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: pygments<3,>=2.17
|
|
21
|
+
Requires-Dist: tree-sitter-language-pack<2,>=1
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# Comment Lens Scanner
|
|
25
|
+
|
|
26
|
+
Comment Lens extracts code comments and keeps them useful over time. The local command-line interface finds comments that deserve attention before they become maintenance debt, explains why with deterministic rule evidence, and helps teams maintain high comment quality without modifying repository files.
|
|
27
|
+
|
|
28
|
+
## Features
|
|
29
|
+
|
|
30
|
+
- **AST-Aware Parsing**: Uses Tree-sitter grammars (with Pygments fallback) to distinguish docstrings, line comments, inline notes, and header blocks across major languages.
|
|
31
|
+
- **Maintenance Signals**: Flags unresolved `TODO`/`FIXME`/`HACK` directives, symbol duplication, stale comments on changed code, and broken local file links.
|
|
32
|
+
- **Git Differential Checks**: Fast pre-commit and CI checks using `--changed` to focus only on comments added or modified in the current branch.
|
|
33
|
+
- **Multi-Format Export**: Emits findings in JSON, NDJSON, Markdown, and SARIF for GitHub Actions PR annotations.
|
|
34
|
+
- **Zero-Network Default**: Fully local execution; code is inspected without being executed or transmitted to external servers.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install comment-lens-scanner
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Requires Python 3.12 or newer.
|
|
43
|
+
|
|
44
|
+
## Usage
|
|
45
|
+
|
|
46
|
+
### Scan a Repository
|
|
47
|
+
|
|
48
|
+
Scan the current repository and generate local finding manifests (`.comment-lens/scan.json` and `.comment-lens/comments.ndjson`):
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
comment-lens scan .
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### Check Changed Comments (Pre-Commit or CI)
|
|
55
|
+
|
|
56
|
+
Check only comments touching lines changed between `origin/main` and `HEAD`, failing if any high-severity findings are introduced:
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
comment-lens check . --changed origin/main...HEAD --fail-on high
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Generate SARIF output for CI integration:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
comment-lens check . --changed HEAD --scope files --format sarif --output findings.sarif
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Export an Existing Scan
|
|
69
|
+
|
|
70
|
+
Convert an existing scan artifact into Markdown or JSON:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
comment-lens export . --format markdown
|
|
74
|
+
comment-lens export . --format json
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Configuration
|
|
78
|
+
|
|
79
|
+
Place a `.comment-lens.toml` file at your repository root to configure exclusions and rule policies:
|
|
80
|
+
|
|
81
|
+
```toml
|
|
82
|
+
version = 1
|
|
83
|
+
exclude = ["fixtures", "legacy"]
|
|
84
|
+
|
|
85
|
+
[policy]
|
|
86
|
+
fail_on = "none"
|
|
87
|
+
|
|
88
|
+
[policy.rules]
|
|
89
|
+
todo = "review"
|
|
90
|
+
fixme = "high"
|
|
91
|
+
symbol_duplication = "review"
|
|
92
|
+
missing_local_reference = "high"
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## License
|
|
96
|
+
|
|
97
|
+
MIT License. See [LICENSE](https://github.com/Builder106/comment-lens/blob/main/LICENSE) for details.
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# Comment Lens Scanner
|
|
2
|
+
|
|
3
|
+
Comment Lens extracts code comments and keeps them useful over time. The local command-line interface finds comments that deserve attention before they become maintenance debt, explains why with deterministic rule evidence, and helps teams maintain high comment quality without modifying repository files.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **AST-Aware Parsing**: Uses Tree-sitter grammars (with Pygments fallback) to distinguish docstrings, line comments, inline notes, and header blocks across major languages.
|
|
8
|
+
- **Maintenance Signals**: Flags unresolved `TODO`/`FIXME`/`HACK` directives, symbol duplication, stale comments on changed code, and broken local file links.
|
|
9
|
+
- **Git Differential Checks**: Fast pre-commit and CI checks using `--changed` to focus only on comments added or modified in the current branch.
|
|
10
|
+
- **Multi-Format Export**: Emits findings in JSON, NDJSON, Markdown, and SARIF for GitHub Actions PR annotations.
|
|
11
|
+
- **Zero-Network Default**: Fully local execution; code is inspected without being executed or transmitted to external servers.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install comment-lens-scanner
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Requires Python 3.12 or newer.
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
### Scan a Repository
|
|
24
|
+
|
|
25
|
+
Scan the current repository and generate local finding manifests (`.comment-lens/scan.json` and `.comment-lens/comments.ndjson`):
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
comment-lens scan .
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### Check Changed Comments (Pre-Commit or CI)
|
|
32
|
+
|
|
33
|
+
Check only comments touching lines changed between `origin/main` and `HEAD`, failing if any high-severity findings are introduced:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
comment-lens check . --changed origin/main...HEAD --fail-on high
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Generate SARIF output for CI integration:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
comment-lens check . --changed HEAD --scope files --format sarif --output findings.sarif
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Export an Existing Scan
|
|
46
|
+
|
|
47
|
+
Convert an existing scan artifact into Markdown or JSON:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
comment-lens export . --format markdown
|
|
51
|
+
comment-lens export . --format json
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Configuration
|
|
55
|
+
|
|
56
|
+
Place a `.comment-lens.toml` file at your repository root to configure exclusions and rule policies:
|
|
57
|
+
|
|
58
|
+
```toml
|
|
59
|
+
version = 1
|
|
60
|
+
exclude = ["fixtures", "legacy"]
|
|
61
|
+
|
|
62
|
+
[policy]
|
|
63
|
+
fail_on = "none"
|
|
64
|
+
|
|
65
|
+
[policy.rules]
|
|
66
|
+
todo = "review"
|
|
67
|
+
fixme = "high"
|
|
68
|
+
symbol_duplication = "review"
|
|
69
|
+
missing_local_reference = "high"
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## License
|
|
73
|
+
|
|
74
|
+
MIT License. See [LICENSE](https://github.com/Builder106/comment-lens/blob/main/LICENSE) for details.
|
|
@@ -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())
|