vetgate 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.
vetgate-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 vetgate contributors
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.
vetgate-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: vetgate
3
+ Version: 0.1.0
4
+ Summary: Fast local security & quality gate for LLM-generated code (C# first). Deterministic, explainable, millisecond diff mode.
5
+ License: MIT License
6
+
7
+ Copyright (c) 2026 vetgate contributors
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+
27
+ Project-URL: Homepage, https://github.com/stuckerbsas/vetgate
28
+ Project-URL: Issues, https://github.com/stuckerbsas/vetgate/issues
29
+ Keywords: security,sast,csharp,dotnet,llm,code-review,claude-code
30
+ Classifier: Development Status :: 4 - Beta
31
+ Classifier: License :: OSI Approved :: MIT License
32
+ Classifier: Programming Language :: Python :: 3
33
+ Classifier: Programming Language :: C#
34
+ Classifier: Topic :: Security
35
+ Classifier: Topic :: Software Development :: Quality Assurance
36
+ Requires-Python: >=3.10
37
+ Description-Content-Type: text/markdown
38
+ License-File: LICENSE
39
+ Requires-Dist: tree-sitter>=0.23
40
+ Requires-Dist: tree-sitter-c-sharp>=0.23
41
+ Dynamic: license-file
42
+
43
+ # vetgate
44
+
45
+ > **Beta.** C# only for now. Calibrated on a private 1,200-file .NET codebase and on public repos (eShop, nopCommerce, Bitwarden server, Jellyfin). Issues with false positives are very welcome.
46
+
47
+ A fast, local, low-noise security and quality vetgate for code written or changed by LLM coding agents.
48
+ C# / ASP.NET Core first; more languages plug into the same architecture.
49
+
50
+ - **Deterministic and explainable.** Every finding says where the data comes from (`source`), which control is
51
+ missing (`guard`), where it lands (`sink`) and why that is exploitable (`reason`).
52
+ - **Fast.** Milliseconds per file, no server, no model download. `--diff` scans only what changed.
53
+ - **Low noise by design.** Intra-procedural taint with guard recognition. The default vetgate is calibrated to
54
+ 0 medium+ findings on a large real-world .NET codebase (1,200+ files).
55
+ - **Built for agents.** A post-edit hook feeds findings back to the coding agent after every edit, and the
56
+ `compact` format uses one line per finding.
57
+
58
+ It is a pre-filter, not a full SAST: no cross-file flow, no business-logic or IDOR analysis. Use it to catch the
59
+ obvious things cheaply, and keep human or LLM review for what needs reasoning.
60
+
61
+ ## Install
62
+
63
+ ```bash
64
+ pip install vetgate # Python 3.10+; depends only on tree-sitter + tree-sitter-c-sharp
65
+ ```
66
+
67
+ ## Use
68
+
69
+ ```bash
70
+ vetgate src/ # security focus, blocks on medium+
71
+ vetgate src/ --focus all --format text # security + debug + quality + practices
72
+ vetgate . --diff # only files changed vs HEAD (+ untracked)
73
+ vetgate . --diff origin/main --format sarif > gate.sarif
74
+ git diff --name-only | vetgate --files-from -
75
+ ```
76
+
77
+ | Option | Meaning |
78
+ |---|---|
79
+ | `--focus security,debug,quality,practices,all` | which checks to run (default `security`) |
80
+ | `--min-severity low/medium/high` | default `medium` for security only, `low` otherwise |
81
+ | `--format json/text/compact/sarif` | SARIF works with GitHub code scanning |
82
+ | `--disable RULE,...` | skip rules |
83
+ | `--include-tests` | also scan test projects (skipped by default) |
84
+ | `--include-dapper` | C#: also check dynamic Dapper SQL |
85
+ | `--no-fail` | always exit 0 |
86
+
87
+ Exit code: `0` clean, `1` findings at or above the threshold, `2` error.
88
+
89
+ Suppress one finding: `// vetgate-ignore: RULE -- reason` on the line or the line above.
90
+
91
+ ## Rules (C#)
92
+
93
+ **security** (default gate): `SQL_INJ`, `CMD_INJ`, `PATH_TRAVERSAL`, `INSECURE_DESERIALIZATION`,
94
+ `HARDCODED_SECRET`, `ENDPOINT_NO_AUTH`, `WEAK_CRYPTO`, `SSRF`, `OPEN_REDIRECT`, `XSS_RAW_HTML`, `XXE`,
95
+ `CERT_VALIDATION_DISABLED`, `JWT_VALIDATION_DISABLED`, `INSECURE_RANDOM`, `CORS_PERMISSIVE`
96
+ (`ENDPOINT_NO_AUTH` is reported as low: many apps expose public endpoints without `[AllowAnonymous]`.)
97
+
98
+ **debug** (low): `DEBUG_CONSOLE_OUTPUT`, `SECURITY_BYPASS_TODO`, `TEST_STUB_LEAK`
99
+ **quality** (low): `ASYNC_NO_TRY_CATCH`, `EMPTY_CATCH_BLOCK`, `OVERLONG_METHOD`
100
+ **practices** (low): `ASYNC_VOID`, `SYNC_OVER_ASYNC`, `THREAD_SLEEP_IN_ASYNC`, `LOG_INTERPOLATION`,
101
+ `HTTPCLIENT_PER_CALL`, `THROW_EX_RESETS_STACK`
102
+
103
+ Full reference (what is flagged, what is not, how to fix): [docs/rules/csharp.md](docs/rules/csharp.md)
104
+
105
+ ## Example
106
+
107
+ ```
108
+ $ vetgate Controllers/ToolsController.cs --format text
109
+ Controllers/ToolsController.cs:19: [HIGH] CMD_INJ (deterministic, 1.0)
110
+ source: request parameter 'tool' ([FromQuery])
111
+ guard : no allowlist / argument escaping before process start
112
+ sink : process execution (executable: tool)
113
+ reason: Request-controlled text becomes part of the executable or its command line; ...
114
+ ```
115
+
116
+ ## Coding-agent integration
117
+
118
+ - **Post-edit hook (Claude Code):** the `vetgate-hook` command runs as a `PostToolUse` hook on `Edit|Write`.
119
+ It reports medium+ findings anywhere in the edited file and low findings only on lines changed vs git `HEAD`,
120
+ so legacy noise does not flood the context. It says nothing when the file is clean and never blocks the edit.
121
+ ```json
122
+ { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write|MultiEdit", "hooks": [
123
+ { "type": "command", "command": "vetgate-hook", "timeout": 30 } ] } ] } }
124
+ ```
125
+ - **Skill:** [SKILL.md](SKILL.md) tells an agent when to run the vetgate and how to act on the results.
126
+
127
+ ## Development
128
+
129
+ ```bash
130
+ python -m unittest discover -s tests # fixtures + core tests
131
+ python run_fixtures.py # fixtures + false-positive check on real codebases
132
+ ```
133
+
134
+ Each rule has a fixture in `fixtures/<lang>/` with a `FIXTURE-RULES: ...` header and an `EXPECT: RULE` marker on
135
+ every line that must be flagged. Vulnerable and safe cases sit side by side, and the reported set must match
136
+ exactly. Real-codebase false-positive targets come from `--fp-target`, `$VETGATE_FP_TARGETS` or a gitignored
137
+ `vetgate.local.json` (`{"fp_targets": ["..."]}`). They must give 0 medium+ findings.
138
+
139
+ New rule: fixture first, then the rule, then `run_fixtures.py` must be all green.
140
+
141
+ New language: add `vetgate/languages/<lang>/` exposing `NAME`, `EXTENSIONS`, `FOCUSES`, `is_test_file`,
142
+ `analyze(path, source, focuses, options)` and register it in `vetgate/languages/__init__.py`.
143
+
144
+ ```
145
+ vetvetgate/cli.py, core.py CLI, finding schema, suppressions, diff mode, json/text/compact/sarif
146
+ vetvetgate/languages/csharp/ common (parser + taint), security, security_web, debug, quality, practices
147
+ fixtures/ regression fixtures per language
148
+ hooks/post_edit_gate.py Claude Code post-edit hook
149
+ ```
@@ -0,0 +1,107 @@
1
+ # vetgate
2
+
3
+ > **Beta.** C# only for now. Calibrated on a private 1,200-file .NET codebase and on public repos (eShop, nopCommerce, Bitwarden server, Jellyfin). Issues with false positives are very welcome.
4
+
5
+ A fast, local, low-noise security and quality vetgate for code written or changed by LLM coding agents.
6
+ C# / ASP.NET Core first; more languages plug into the same architecture.
7
+
8
+ - **Deterministic and explainable.** Every finding says where the data comes from (`source`), which control is
9
+ missing (`guard`), where it lands (`sink`) and why that is exploitable (`reason`).
10
+ - **Fast.** Milliseconds per file, no server, no model download. `--diff` scans only what changed.
11
+ - **Low noise by design.** Intra-procedural taint with guard recognition. The default vetgate is calibrated to
12
+ 0 medium+ findings on a large real-world .NET codebase (1,200+ files).
13
+ - **Built for agents.** A post-edit hook feeds findings back to the coding agent after every edit, and the
14
+ `compact` format uses one line per finding.
15
+
16
+ It is a pre-filter, not a full SAST: no cross-file flow, no business-logic or IDOR analysis. Use it to catch the
17
+ obvious things cheaply, and keep human or LLM review for what needs reasoning.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pip install vetgate # Python 3.10+; depends only on tree-sitter + tree-sitter-c-sharp
23
+ ```
24
+
25
+ ## Use
26
+
27
+ ```bash
28
+ vetgate src/ # security focus, blocks on medium+
29
+ vetgate src/ --focus all --format text # security + debug + quality + practices
30
+ vetgate . --diff # only files changed vs HEAD (+ untracked)
31
+ vetgate . --diff origin/main --format sarif > gate.sarif
32
+ git diff --name-only | vetgate --files-from -
33
+ ```
34
+
35
+ | Option | Meaning |
36
+ |---|---|
37
+ | `--focus security,debug,quality,practices,all` | which checks to run (default `security`) |
38
+ | `--min-severity low/medium/high` | default `medium` for security only, `low` otherwise |
39
+ | `--format json/text/compact/sarif` | SARIF works with GitHub code scanning |
40
+ | `--disable RULE,...` | skip rules |
41
+ | `--include-tests` | also scan test projects (skipped by default) |
42
+ | `--include-dapper` | C#: also check dynamic Dapper SQL |
43
+ | `--no-fail` | always exit 0 |
44
+
45
+ Exit code: `0` clean, `1` findings at or above the threshold, `2` error.
46
+
47
+ Suppress one finding: `// vetgate-ignore: RULE -- reason` on the line or the line above.
48
+
49
+ ## Rules (C#)
50
+
51
+ **security** (default gate): `SQL_INJ`, `CMD_INJ`, `PATH_TRAVERSAL`, `INSECURE_DESERIALIZATION`,
52
+ `HARDCODED_SECRET`, `ENDPOINT_NO_AUTH`, `WEAK_CRYPTO`, `SSRF`, `OPEN_REDIRECT`, `XSS_RAW_HTML`, `XXE`,
53
+ `CERT_VALIDATION_DISABLED`, `JWT_VALIDATION_DISABLED`, `INSECURE_RANDOM`, `CORS_PERMISSIVE`
54
+ (`ENDPOINT_NO_AUTH` is reported as low: many apps expose public endpoints without `[AllowAnonymous]`.)
55
+
56
+ **debug** (low): `DEBUG_CONSOLE_OUTPUT`, `SECURITY_BYPASS_TODO`, `TEST_STUB_LEAK`
57
+ **quality** (low): `ASYNC_NO_TRY_CATCH`, `EMPTY_CATCH_BLOCK`, `OVERLONG_METHOD`
58
+ **practices** (low): `ASYNC_VOID`, `SYNC_OVER_ASYNC`, `THREAD_SLEEP_IN_ASYNC`, `LOG_INTERPOLATION`,
59
+ `HTTPCLIENT_PER_CALL`, `THROW_EX_RESETS_STACK`
60
+
61
+ Full reference (what is flagged, what is not, how to fix): [docs/rules/csharp.md](docs/rules/csharp.md)
62
+
63
+ ## Example
64
+
65
+ ```
66
+ $ vetgate Controllers/ToolsController.cs --format text
67
+ Controllers/ToolsController.cs:19: [HIGH] CMD_INJ (deterministic, 1.0)
68
+ source: request parameter 'tool' ([FromQuery])
69
+ guard : no allowlist / argument escaping before process start
70
+ sink : process execution (executable: tool)
71
+ reason: Request-controlled text becomes part of the executable or its command line; ...
72
+ ```
73
+
74
+ ## Coding-agent integration
75
+
76
+ - **Post-edit hook (Claude Code):** the `vetgate-hook` command runs as a `PostToolUse` hook on `Edit|Write`.
77
+ It reports medium+ findings anywhere in the edited file and low findings only on lines changed vs git `HEAD`,
78
+ so legacy noise does not flood the context. It says nothing when the file is clean and never blocks the edit.
79
+ ```json
80
+ { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write|MultiEdit", "hooks": [
81
+ { "type": "command", "command": "vetgate-hook", "timeout": 30 } ] } ] } }
82
+ ```
83
+ - **Skill:** [SKILL.md](SKILL.md) tells an agent when to run the vetgate and how to act on the results.
84
+
85
+ ## Development
86
+
87
+ ```bash
88
+ python -m unittest discover -s tests # fixtures + core tests
89
+ python run_fixtures.py # fixtures + false-positive check on real codebases
90
+ ```
91
+
92
+ Each rule has a fixture in `fixtures/<lang>/` with a `FIXTURE-RULES: ...` header and an `EXPECT: RULE` marker on
93
+ every line that must be flagged. Vulnerable and safe cases sit side by side, and the reported set must match
94
+ exactly. Real-codebase false-positive targets come from `--fp-target`, `$VETGATE_FP_TARGETS` or a gitignored
95
+ `vetgate.local.json` (`{"fp_targets": ["..."]}`). They must give 0 medium+ findings.
96
+
97
+ New rule: fixture first, then the rule, then `run_fixtures.py` must be all green.
98
+
99
+ New language: add `vetgate/languages/<lang>/` exposing `NAME`, `EXTENSIONS`, `FOCUSES`, `is_test_file`,
100
+ `analyze(path, source, focuses, options)` and register it in `vetgate/languages/__init__.py`.
101
+
102
+ ```
103
+ vetvetgate/cli.py, core.py CLI, finding schema, suppressions, diff mode, json/text/compact/sarif
104
+ vetvetgate/languages/csharp/ common (parser + taint), security, security_web, debug, quality, practices
105
+ fixtures/ regression fixtures per language
106
+ hooks/post_edit_gate.py Claude Code post-edit hook
107
+ ```
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "vetgate"
7
+ version = "0.1.0"
8
+ description = "Fast local security & quality gate for LLM-generated code (C# first). Deterministic, explainable, millisecond diff mode."
9
+ readme = "README.md"
10
+ keywords = ["security", "sast", "csharp", "dotnet", "llm", "code-review", "claude-code"]
11
+ requires-python = ">=3.10"
12
+ license = { file = "LICENSE" }
13
+ dependencies = [
14
+ "tree-sitter>=0.23",
15
+ "tree-sitter-c-sharp>=0.23",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: C#",
22
+ "Topic :: Security",
23
+ "Topic :: Software Development :: Quality Assurance",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/stuckerbsas/vetgate"
28
+ Issues = "https://github.com/stuckerbsas/vetgate/issues"
29
+
30
+ [project.scripts]
31
+ vetgate = "vetgate.cli:main"
32
+ vetgate-hook = "vetgate.hook:main"
33
+
34
+ [tool.setuptools.packages.find]
35
+ include = ["vetgate*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,46 @@
1
+ """Stdlib-only test entry point: every fixture must match its EXPECT markers exactly.
2
+
3
+ Run: python -m unittest discover -s tests
4
+ """
5
+ import sys
6
+ import unittest
7
+ from pathlib import Path
8
+
9
+ ROOT = Path(__file__).resolve().parents[1]
10
+ sys.path.insert(0, str(ROOT))
11
+
12
+ from vetgate import languages # noqa: E402
13
+ from vetgate.core import render_sarif, suppressions # noqa: E402
14
+ from run_fixtures import check_fixture # noqa: E402
15
+
16
+
17
+ class FixtureTests(unittest.TestCase):
18
+ def test_fixtures(self):
19
+ ran = 0
20
+ for name in languages.LANGUAGE_PACKAGES:
21
+ lang = languages.get(name)
22
+ for fx in sorted((ROOT / "fixtures" / name).glob("*_fixture.*")):
23
+ with self.subTest(fixture=f"{name}/{fx.name}"):
24
+ self.assertEqual(check_fixture(fx, lang), [])
25
+ ran += 1
26
+ self.assertGreater(ran, 0, "no fixtures found")
27
+
28
+
29
+ class CoreTests(unittest.TestCase):
30
+ def test_suppressions(self):
31
+ src = b"a // vetgate-ignore: SQL_INJ, CMD_INJ\nb\nc // vetgate-ignore\n"
32
+ s = suppressions(src)
33
+ self.assertEqual(s[1], {"SQL_INJ", "CMD_INJ"})
34
+ self.assertEqual(s[2], {"SQL_INJ", "CMD_INJ"})
35
+ self.assertIsNone(s[3])
36
+
37
+ def test_sarif_shape(self):
38
+ res = [{"findings": [{"file": "a.cs", "line": 3, "rule": "SQL_INJ", "severity": "high", "confidence": 1.0,
39
+ "engine": "deterministic", "source": "x", "guard": "g", "sink": "s", "reason": "r"}]}]
40
+ sarif = render_sarif(res)
41
+ self.assertEqual(sarif["version"], "2.1.0")
42
+ self.assertEqual(sarif["runs"][0]["results"][0]["level"], "error")
43
+
44
+
45
+ if __name__ == "__main__":
46
+ unittest.main()
@@ -0,0 +1,3 @@
1
+ """vetgate: local security & quality gate for LLM-written code."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,124 @@
1
+ """vetgate: multi-language, multi-focus local code gate.
2
+
3
+ vetgate [targets...] --focus security,quality [--lang auto|csharp,...] [--diff [REF]] [--files-from PATH]
4
+
5
+ Files are routed to a language pack by extension; each pack runs only the focuses it supports.
6
+ Exit codes: 0 = no findings at/above threshold, 1 = findings, 2 = usage/runtime error.
7
+ """
8
+ import argparse
9
+ import json
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+
14
+ from . import languages
15
+ from . import __version__
16
+ from .core import (
17
+ expand_targets, files_from_diff, files_from_list, finalize, keep_file, render_compact, render_sarif, render_text,
18
+ )
19
+
20
+ ALL_FOCUSES = ("security", "debug", "quality", "practices")
21
+
22
+
23
+ def _csv(value: str) -> list[str]:
24
+ return [v.strip() for v in value.split(",") if v.strip()]
25
+
26
+
27
+ def build_parser() -> argparse.ArgumentParser:
28
+ p = argparse.ArgumentParser(prog="vetgate", description="Local multi-language security & quality gate.")
29
+ p.add_argument("targets", nargs="*", default=["."], help="Files or directories (default: current directory).")
30
+ p.add_argument("--focus", type=_csv, default=["security"],
31
+ help="Comma list of: security, debug, quality, practices, all (default: security).")
32
+ p.add_argument("--lang", type=_csv, default=["auto"],
33
+ help=f"Comma list of language packs or 'auto' (available: {', '.join(languages.LANGUAGE_PACKAGES)}).")
34
+ p.add_argument("--min-severity", choices=["low", "medium", "high"], default=None,
35
+ help="Default: medium for security-only runs, low when debug/quality are selected.")
36
+ p.add_argument("--files-from", metavar="PATH", help="Scan only the paths listed in PATH ('-' = stdin).")
37
+ p.add_argument("--diff", nargs="?", const="HEAD", metavar="REF",
38
+ help="Scan only files changed vs REF (default HEAD) plus untracked files.")
39
+ p.add_argument("--include-tests", action="store_true", help="Do not skip test projects/files.")
40
+ p.add_argument("--format", choices=["json", "text", "compact", "sarif"], default="json")
41
+ p.add_argument("--disable", type=_csv, default=[], metavar="RULES", help="Comma list of rule ids to skip.")
42
+ p.add_argument("--version", action="version", version=f"vetgate {__version__}")
43
+ p.add_argument("--no-fail", action="store_true", help="Always exit 0 (report-only).")
44
+ g = p.add_argument_group("language-specific options")
45
+ g.add_argument("--include-dapper", action="store_true", help="[csharp] Include dynamic Dapper SQL calls.")
46
+ return p
47
+
48
+
49
+ def run(args) -> tuple[dict, int]:
50
+ focuses = list(ALL_FOCUSES) if "all" in args.focus else args.focus
51
+ bad = [f for f in focuses if f not in ALL_FOCUSES]
52
+ if bad:
53
+ raise ValueError(f"unknown focus: {', '.join(bad)}")
54
+ langs = languages.all_languages() if "auto" in args.lang else [languages.get(n) for n in args.lang]
55
+ min_sev = args.min_severity or ("medium" if focuses == ["security"] else "low")
56
+ options = {"include_dapper": args.include_dapper}
57
+ ext_map = {ext: lang for lang in langs for ext in lang.EXTENSIONS}
58
+
59
+ t0 = time.perf_counter()
60
+ targets = [Path(t) for t in args.targets]
61
+ if args.files_from or args.diff is not None:
62
+ base = targets[0] if targets and targets[0].is_dir() else None
63
+ candidates = files_from_list(args.files_from, base) if args.files_from else files_from_diff(targets[0], args.diff)
64
+ explicit = False
65
+ else:
66
+ candidates = expand_targets(targets, set(ext_map))
67
+ explicit_files = {t.resolve() for t in targets if t.is_file()}
68
+ explicit = None # decided per file below
69
+
70
+ results, skipped = [], {}
71
+ for f in sorted(set(candidates)):
72
+ lang = ext_map.get(f.suffix.lower())
73
+ if lang is None:
74
+ continue
75
+ is_explicit = explicit if explicit is not None else f.resolve() in explicit_files
76
+ if not keep_file(f, is_explicit, args.include_tests, lang.is_test_file):
77
+ continue
78
+ active = [x for x in focuses if x in lang.FOCUSES]
79
+ for x in focuses:
80
+ if x not in lang.FOCUSES:
81
+ skipped.setdefault(lang.NAME, set()).add(x)
82
+ source = f.read_bytes()
83
+ findings, syntax_errors = lang.analyze(f, source, active, options)
84
+ for fd in findings:
85
+ fd.setdefault("language", lang.NAME)
86
+ results.append({"file": str(f), "language": lang.NAME, "syntax_errors": syntax_errors,
87
+ "findings": finalize(f, findings, min_sev, source, set(args.disable))})
88
+
89
+ total = sum(len(r["findings"]) for r in results)
90
+ report = {
91
+ "focus": focuses,
92
+ "languages": sorted({r["language"] for r in results}),
93
+ "min_severity": min_sev,
94
+ "scanned_files": len(results),
95
+ "total_findings": total,
96
+ "elapsed_ms": round((time.perf_counter() - t0) * 1000),
97
+ "unsupported_focus": {k: sorted(v) for k, v in skipped.items()},
98
+ "results": [r for r in results if r["findings"]],
99
+ }
100
+ return report, (0 if args.no_fail or total == 0 else 1)
101
+
102
+
103
+ def main(argv=None) -> int:
104
+ args = build_parser().parse_args(argv)
105
+ try:
106
+ report, code = run(args)
107
+ except (FileNotFoundError, RuntimeError, ValueError, ModuleNotFoundError) as e:
108
+ print(f"Error: {e}", file=sys.stderr)
109
+ return 2
110
+ if args.format == "text":
111
+ print(render_text(report["results"]))
112
+ print(f"-- {report['scanned_files']} file(s), {report['total_findings']} finding(s), "
113
+ f"min-severity={report['min_severity']}, {report['elapsed_ms']} ms", file=sys.stderr)
114
+ elif args.format == "compact":
115
+ print(render_compact(report["results"]))
116
+ elif args.format == "sarif":
117
+ print(json.dumps(render_sarif(report["results"], __version__), indent=2))
118
+ else:
119
+ print(json.dumps(report, indent=2))
120
+ return code
121
+
122
+
123
+ if __name__ == "__main__":
124
+ sys.exit(main())