codefactory-cli 0.20.1__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.
- codefactory_cli-0.20.1/LICENSE +21 -0
- codefactory_cli-0.20.1/PKG-INFO +250 -0
- codefactory_cli-0.20.1/README.md +216 -0
- codefactory_cli-0.20.1/codefactory/__init__.py +3 -0
- codefactory_cli-0.20.1/codefactory/__main__.py +5 -0
- codefactory_cli-0.20.1/codefactory/accept.py +68 -0
- codefactory_cli-0.20.1/codefactory/analyzers/__init__.py +55 -0
- codefactory_cli-0.20.1/codefactory/analyzers/generic.py +392 -0
- codefactory_cli-0.20.1/codefactory/analyzers/parallel.py +113 -0
- codefactory_cli-0.20.1/codefactory/analyzers/python.py +279 -0
- codefactory_cli-0.20.1/codefactory/analyzers/python_parse.py +402 -0
- codefactory_cli-0.20.1/codefactory/analyzers/treewalk.py +299 -0
- codefactory_cli-0.20.1/codefactory/analyzers/ts_helper.js +483 -0
- codefactory_cli-0.20.1/codefactory/analyzers/typescript.py +118 -0
- codefactory_cli-0.20.1/codefactory/apple.py +80 -0
- codefactory_cli-0.20.1/codefactory/audit.py +227 -0
- codefactory_cli-0.20.1/codefactory/baseline.py +58 -0
- codefactory_cli-0.20.1/codefactory/brief.py +330 -0
- codefactory_cli-0.20.1/codefactory/cache.py +93 -0
- codefactory_cli-0.20.1/codefactory/checks.py +608 -0
- codefactory_cli-0.20.1/codefactory/cli.py +782 -0
- codefactory_cli-0.20.1/codefactory/config.py +157 -0
- codefactory_cli-0.20.1/codefactory/coverage.py +104 -0
- codefactory_cli-0.20.1/codefactory/deps.py +182 -0
- codefactory_cli-0.20.1/codefactory/diff.py +197 -0
- codefactory_cli-0.20.1/codefactory/efficiency.py +250 -0
- codefactory_cli-0.20.1/codefactory/flags.py +263 -0
- codefactory_cli-0.20.1/codefactory/graph.py +95 -0
- codefactory_cli-0.20.1/codefactory/hotspots.py +344 -0
- codefactory_cli-0.20.1/codefactory/infra.py +242 -0
- codefactory_cli-0.20.1/codefactory/intent.py +106 -0
- codefactory_cli-0.20.1/codefactory/layers.py +143 -0
- codefactory_cli-0.20.1/codefactory/org.py +131 -0
- codefactory_cli-0.20.1/codefactory/owners.py +72 -0
- codefactory_cli-0.20.1/codefactory/patch.py +81 -0
- codefactory_cli-0.20.1/codefactory/paths.py +93 -0
- codefactory_cli-0.20.1/codefactory/plan.py +476 -0
- codefactory_cli-0.20.1/codefactory/privacy.py +221 -0
- codefactory_cli-0.20.1/codefactory/profile.py +667 -0
- codefactory_cli-0.20.1/codefactory/rerank.py +161 -0
- codefactory_cli-0.20.1/codefactory/review.py +1504 -0
- codefactory_cli-0.20.1/codefactory/rules.py +50 -0
- codefactory_cli-0.20.1/codefactory/sarif.py +661 -0
- codefactory_cli-0.20.1/codefactory/sbom.py +78 -0
- codefactory_cli-0.20.1/codefactory/security.py +537 -0
- codefactory_cli-0.20.1/codefactory/similar.py +199 -0
- codefactory_cli-0.20.1/codefactory/skill.py +144 -0
- codefactory_cli-0.20.1/codefactory/skill_template/SKILL.md +68 -0
- codefactory_cli-0.20.1/codefactory/skill_template/__init__.py +0 -0
- codefactory_cli-0.20.1/codefactory/sqlgraph.py +109 -0
- codefactory_cli-0.20.1/codefactory/suppress.py +92 -0
- codefactory_cli-0.20.1/codefactory/taint.py +439 -0
- codefactory_cli-0.20.1/codefactory/trace.py +72 -0
- codefactory_cli-0.20.1/codefactory/viewer/__init__.py +19 -0
- codefactory_cli-0.20.1/codefactory/viewer/dashboard.html +43 -0
- codefactory_cli-0.20.1/codefactory/viewer/factory.css +61 -0
- codefactory_cli-0.20.1/codefactory/viewer/factory.js +665 -0
- codefactory_cli-0.20.1/codefactory/viewer/template.html +47 -0
- codefactory_cli-0.20.1/codefactory_cli.egg-info/PKG-INFO +250 -0
- codefactory_cli-0.20.1/codefactory_cli.egg-info/SOURCES.txt +97 -0
- codefactory_cli-0.20.1/codefactory_cli.egg-info/dependency_links.txt +1 -0
- codefactory_cli-0.20.1/codefactory_cli.egg-info/entry_points.txt +2 -0
- codefactory_cli-0.20.1/codefactory_cli.egg-info/requires.txt +4 -0
- codefactory_cli-0.20.1/codefactory_cli.egg-info/top_level.txt +1 -0
- codefactory_cli-0.20.1/pyproject.toml +66 -0
- codefactory_cli-0.20.1/setup.cfg +4 -0
- codefactory_cli-0.20.1/tests/test_accept.py +57 -0
- codefactory_cli-0.20.1/tests/test_agent.py +103 -0
- codefactory_cli-0.20.1/tests/test_apple.py +78 -0
- codefactory_cli-0.20.1/tests/test_audit.py +146 -0
- codefactory_cli-0.20.1/tests/test_bench.py +34 -0
- codefactory_cli-0.20.1/tests/test_cache.py +47 -0
- codefactory_cli-0.20.1/tests/test_cli_errors.py +59 -0
- codefactory_cli-0.20.1/tests/test_coverage.py +48 -0
- codefactory_cli-0.20.1/tests/test_diff.py +129 -0
- codefactory_cli-0.20.1/tests/test_efficiency.py +146 -0
- codefactory_cli-0.20.1/tests/test_findings_review.py +240 -0
- codefactory_cli-0.20.1/tests/test_generic.py +170 -0
- codefactory_cli-0.20.1/tests/test_golden.py +46 -0
- codefactory_cli-0.20.1/tests/test_hotspots.py +82 -0
- codefactory_cli-0.20.1/tests/test_intent.py +89 -0
- codefactory_cli-0.20.1/tests/test_org.py +109 -0
- codefactory_cli-0.20.1/tests/test_parallel.py +40 -0
- codefactory_cli-0.20.1/tests/test_patch.py +80 -0
- codefactory_cli-0.20.1/tests/test_privacy.py +63 -0
- codefactory_cli-0.20.1/tests/test_profile.py +137 -0
- codefactory_cli-0.20.1/tests/test_public_repos.py +375 -0
- codefactory_cli-0.20.1/tests/test_python_scopes.py +31 -0
- codefactory_cli-0.20.1/tests/test_release.py +86 -0
- codefactory_cli-0.20.1/tests/test_review.py +113 -0
- codefactory_cli-0.20.1/tests/test_rules.py +138 -0
- codefactory_cli-0.20.1/tests/test_sarif.py +121 -0
- codefactory_cli-0.20.1/tests/test_security.py +209 -0
- codefactory_cli-0.20.1/tests/test_shop.py +74 -0
- codefactory_cli-0.20.1/tests/test_skill.py +91 -0
- codefactory_cli-0.20.1/tests/test_sql_trace.py +115 -0
- codefactory_cli-0.20.1/tests/test_taint.py +45 -0
- codefactory_cli-0.20.1/tests/test_typescript.py +63 -0
- codefactory_cli-0.20.1/tests/test_workflow.py +135 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dominickkubica
|
|
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,250 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: codefactory-cli
|
|
3
|
+
Version: 0.20.1
|
|
4
|
+
Summary: See a codebase as a factory floor, find what's wrong with it (copies, N+1 loops, dead code, import loops, security and reliability problems), and turn it into ranked work.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/dominickkubica/codefactory
|
|
7
|
+
Project-URL: Documentation, https://github.com/dominickkubica/codefactory/blob/main/docs/USAGE.md
|
|
8
|
+
Project-URL: Design, https://github.com/dominickkubica/codefactory/blob/main/docs/DESIGN.md
|
|
9
|
+
Project-URL: Changelog, https://github.com/dominickkubica/codefactory/blob/main/CHANGELOG.md
|
|
10
|
+
Keywords: static analysis,code review,architecture,call graph,duplicate code,refactoring,sarif,claude code
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: JavaScript
|
|
20
|
+
Classifier: Programming Language :: Go
|
|
21
|
+
Classifier: Programming Language :: Java
|
|
22
|
+
Classifier: Programming Language :: Rust
|
|
23
|
+
Classifier: Programming Language :: C
|
|
24
|
+
Classifier: Programming Language :: C++
|
|
25
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
26
|
+
Classifier: Topic :: Software Development :: Testing
|
|
27
|
+
Requires-Python: >=3.11
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Provides-Extra: languages
|
|
31
|
+
Requires-Dist: tree-sitter>=0.25; extra == "languages"
|
|
32
|
+
Requires-Dist: tree-sitter-language-pack<2,>=1.0; extra == "languages"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# codefactory
|
|
36
|
+
|
|
37
|
+
[](https://github.com/dominickkubica/codefactory/actions/workflows/ci.yml)
|
|
38
|
+
[](LICENSE)
|
|
39
|
+

|
|
40
|
+
|
|
41
|
+
**See a codebase as a factory floor, find what's wrong with it, and turn that into work.**
|
|
42
|
+
|
|
43
|
+
codefactory reads a repository without running it, builds a map of every file, function and call, and checks that
|
|
44
|
+
map for copied code, database calls inside loops, dead code, import loops and dozens of security, reliability and
|
|
45
|
+
delivery problems. It shows the result as an interactive floor plan, writes a technical review, ranks the fixes, and
|
|
46
|
+
hands each one to you, or to an AI coding agent, as a ready-made task.
|
|
47
|
+
|
|
48
|
+
It works on Python, TypeScript/JavaScript, Go, Java, Kotlin, Swift, Rust, C/C++, C#, Ruby, PHP and more, runs
|
|
49
|
+
entirely on your machine, and needs no account, server or API key.
|
|
50
|
+
|
|
51
|
+

|
|
52
|
+
|
|
53
|
+
<sub>pip's own source (150 files), zoomed out: one hall per area of the code, one conveyor per pair of areas, labelled with
|
|
54
|
+
the number of calls it carries. Dashed orange conveyors run backwards, from a lower layer up into a higher one.</sub>
|
|
55
|
+
|
|
56
|
+
## Quick start
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install "codefactory[languages] @ git+https://github.com/dominickkubica/codefactory"
|
|
60
|
+
cd path/to/your/repo
|
|
61
|
+
|
|
62
|
+
codefactory review -o review.md # a technical review of the repository (--online: also vulnerable dependencies)
|
|
63
|
+
codefactory view # the interactive map, in your browser
|
|
64
|
+
codefactory plan # what to fix first, ranked; then: codefactory prompt 1
|
|
65
|
+
codefactory profile # what kind of project it thinks this is (findings are ranked for it)
|
|
66
|
+
codefactory hotspots # where change happens: complex code that keeps changing
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
- **Python 3.11 or newer.** On Windows, run the same commands in PowerShell; use `py -m pip` if `pip` isn't found.
|
|
70
|
+
- **TypeScript/JavaScript projects:** run `npm install` in the project first, because codefactory uses the project's
|
|
71
|
+
own TypeScript compiler (needs [Node.js](https://nodejs.org)). Without it, those files are still analyzed, less
|
|
72
|
+
precisely.
|
|
73
|
+
- **`[languages]`** adds the tree-sitter language pack for everything beyond Python and TypeScript. Leave it out for
|
|
74
|
+
a dependency-free install.
|
|
75
|
+
- **Upgrade any time** with `codefactory update`.
|
|
76
|
+
|
|
77
|
+
## What it does
|
|
78
|
+
|
|
79
|
+
- **Map.** Every file is a machine, every call between files a belt, every layer a zone. Zoom out for the halls and
|
|
80
|
+
how they depend on each other; zoom in for files and functions; click a function to light up everything it calls.
|
|
81
|
+
- **Find.** Each finding points at a `file:line` and says what to do about it:
|
|
82
|
+
|
|
83
|
+
| Area | Examples |
|
|
84
|
+
|---|---|
|
|
85
|
+
| Performance | Database or network calls once per item (N+1), searches inside loops over loaded data, writes outside a transaction |
|
|
86
|
+
| Duplication | Identical and near-identical functions, merged into one task per group |
|
|
87
|
+
| Structure | Import loops, layer-rule breaks, unused code, functions nobody tests, very long or complex functions |
|
|
88
|
+
| Data flow | Python: request values traced variable by variable, through helper functions, into SQL, shell commands, `eval`, file paths, outgoing URLs, redirects and templates, with sanitizers (`int()`, bound SQL parameters, `shlex.quote`…) respected |
|
|
89
|
+
| Privacy | Personal data (contact details, birth dates, location, health readings, device ids) in logs, analytics and unencrypted storage; iOS permissions without usage descriptions; required-reason APIs without a privacy manifest (App Store rejections) |
|
|
90
|
+
| Security | Every HTTP endpoint and whether it checks who's asking; endpoints that change data without an auth check; risky lines (SQL built from strings, shell, `eval`, raw HTML) ranked by whether a request reaches them, with the route → … → line chain; leaked credentials, including ones deleted but still in git history; debug mode, CORS `*`, insecure cookies, unverified JWTs, weak crypto and random numbers; unsafe CI workflows, root containers, secrets in images; known-vulnerable dependencies (`--online`) |
|
|
91
|
+
| Reliability | Swallowed errors, network calls without a timeout, missing error boundaries |
|
|
92
|
+
| Apple platforms | Swift: disk or database work on the main thread, retain cycles in stored closures, `try!`/`as!`; entitlements that weaken code signing |
|
|
93
|
+
| Shell, Make, YAML, HTML, Pkl | Credentials in config files (quoted or not); `curl … \| sh`, `rm -rf "$DIR/"` with an empty variable, `eval` of a variable (scripts and Makefile recipes); docker-compose and Kubernetes: privileged or host-network containers, databases published on every interface, committed passwords and Secrets; HTML: scripts and forms over plain HTTP, CDN scripts without integrity hashes; plain-HTTP URLs in Pkl, TOML and Terraform |
|
|
94
|
+
| Patches | `codefactory diff --patch pr.diff` checks the lines a unified diff adds, with no repository: a downloaded pull request, a mailing-list patch, an AI agent's proposed change |
|
|
95
|
+
| Delivery | No CI or CI without tests, floating dependency versions, no lockfile, no runtime pin |
|
|
96
|
+
|
|
97
|
+
- **Assess.** Before judging, it works out what the project is: a local-first mobile app, a deployed API with
|
|
98
|
+
accounts, a LAN tool, a command-line tool or a library; where it runs, who uses it, and whether it holds health,
|
|
99
|
+
financial or other sensitive data. Findings are ranked for that, each change with its reason: SQL built from
|
|
100
|
+
strings matters less in a single-user offline app; an untested write matters more when the phone holds the only
|
|
101
|
+
copy. Git history adds the other half: **hotspots** (complex code that changes every week, where debt costs the
|
|
102
|
+
most), files that always change together with nothing linking them, and code only one person knows.
|
|
103
|
+
- **Review.** `codefactory review` writes a technical review in the shape a principal engineer would: summary,
|
|
104
|
+
project profile, system map, where change happens, findings by severity with evidence, what's working, gaps and
|
|
105
|
+
open questions. No AI needed.
|
|
106
|
+
- **Fix.** `codefactory plan` turns findings into ranked tasks with steps and the tests to run. Each task becomes a
|
|
107
|
+
self-contained prompt for Claude Code, and a baseline keeps new problems out in CI.
|
|
108
|
+
|
|
109
|
+
| | |
|
|
110
|
+
|---|---|
|
|
111
|
+
|  |  |
|
|
112
|
+
| **Duplication lens.** Files holding copies of each other's code, joined by arcs labelled with their similarity. | **Trace.** Everything a function eventually calls, by depth, with the total amount of code involved. |
|
|
113
|
+
|
|
114
|
+
## Languages
|
|
115
|
+
|
|
116
|
+
| Language | How calls are resolved | Notes |
|
|
117
|
+
|---|---|---|
|
|
118
|
+
| Python | Precisely: imports, `self`/`cls`, classes, re-exports, dispatch tables, `getattr` | Standard library only |
|
|
119
|
+
| TypeScript, JavaScript | Precisely: the project's own TypeScript type checker (path aliases, hooks, JSX, lazy `require`) | Needs Node.js and `npm install` |
|
|
120
|
+
| Go, Java, Kotlin, Swift, Rust, C, C++, C#, Ruby, PHP, Scala, Dart, Lua, Elixir and more | By name, plus declared types, through tree-sitter | `[languages]` install; grammars download once, then work offline |
|
|
121
|
+
| Shell, Makefiles, YAML (docker-compose, Kubernetes, GitHub Actions), HTML, Pkl, TOML, Terraform, `.diff`/`.patch` | Not a call graph: line checks for credentials, unsafe commands and configuration | No install needed |
|
|
122
|
+
|
|
123
|
+
For the by-name languages, call, impact and unused-code findings are leads to confirm, and the review says so.
|
|
124
|
+
|
|
125
|
+
## Commands
|
|
126
|
+
|
|
127
|
+
| Command | What it gives you |
|
|
128
|
+
|---|---|
|
|
129
|
+
| `review` | A full technical review in Markdown; `--for-ai` adds an evidence pack for an AI to finish the judgement calls |
|
|
130
|
+
| `view` | The interactive factory floor (one HTML file), with lenses for duplication, efficiency and size |
|
|
131
|
+
| `flags` | Every issue with `file:line`; `--min warn`, `--kind similar`, `--json`, `--github` |
|
|
132
|
+
| `plan` / `prompt` | Ranked tasks with steps and tests / one task as a ready-to-paste Claude Code prompt |
|
|
133
|
+
| `diff` | What a change adds and fixes, compared with the base branch: a pull-request comment, annotations or JSON; `--patch file.diff` checks a patch on its own, no repository needed |
|
|
134
|
+
| `profile` | What kind of project this is (mobile app, web service, CLI, library…), where it runs, who uses it, what sensitive data it holds, with evidence; the review ranks findings for it |
|
|
135
|
+
| `hotspots` | From git history: complex code that changes often, files that change together without importing each other, code only one person knows |
|
|
136
|
+
| `sbom` | A CycloneDX software bill of materials of every pinned dependency |
|
|
137
|
+
| `org` | A dashboard across many repositories: health, findings, trends, and findings per owning team |
|
|
138
|
+
| `surface` | The attack surface: every HTTP endpoint, its auth check, and whether it changes data or reaches risky code |
|
|
139
|
+
| `accept` | Mark a finding as intended, with the reason, so later runs show only what's new |
|
|
140
|
+
| `brief` / `context` | A compact map of the repo / everything about one file or function before you change it |
|
|
141
|
+
| `trace` / `path` | What a function eventually calls / how one function reaches another |
|
|
142
|
+
| `baseline` / `check` | Save today's issues / fail CI or a pre-commit hook only on new ones |
|
|
143
|
+
| `sarif` | Issues for GitHub code scanning and VS Code (SARIF 2.1.0) |
|
|
144
|
+
| `query` / `sql` | Ask anything in SQL / export the graph as a SQLite database |
|
|
145
|
+
| `analyze` | The raw graph as JSON |
|
|
146
|
+
| `skill` | Teach Claude Code in a repository when and how to use all of the above (`--hook`: keep it current) |
|
|
147
|
+
| `update` | Upgrade codefactory to the latest version |
|
|
148
|
+
|
|
149
|
+
Commands that take a name work from inside the repository: `codefactory context checkout`. `codefactory --help` and
|
|
150
|
+
`codefactory <command> --help` list every option.
|
|
151
|
+
|
|
152
|
+
## With Claude Code
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
codefactory skill --hook # once per repository; commit .claude/
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
This writes a skill (`.claude/skills/codefactory/SKILL.md`) and a session-start hook. Every Claude Code session in
|
|
159
|
+
that repository, on your machine or in the cloud, then starts with codefactory installed, upgraded at most once a
|
|
160
|
+
day, and its instructions matching the installed version.
|
|
161
|
+
|
|
162
|
+
Then ask in plain words: *"what should I clean up first?"*, *"review the codebase"*, *"what breaks if I change
|
|
163
|
+
`useCart`?"*, *"did my change add any problems?"*. Claude Code runs the right command, reads a few thousand tokens of
|
|
164
|
+
findings instead of the whole repository, and verifies each change with the tests codefactory lists.
|
|
165
|
+
|
|
166
|
+
## In CI
|
|
167
|
+
|
|
168
|
+
Comment on every pull request with the findings it adds and fixes (one comment, updated on each push), and
|
|
169
|
+
optionally fail on new ones:
|
|
170
|
+
|
|
171
|
+
```yaml
|
|
172
|
+
# .github/workflows/codefactory.yml
|
|
173
|
+
on: pull_request
|
|
174
|
+
permissions: { contents: read, pull-requests: write }
|
|
175
|
+
jobs:
|
|
176
|
+
codefactory:
|
|
177
|
+
runs-on: ubuntu-latest
|
|
178
|
+
steps:
|
|
179
|
+
- uses: actions/checkout@v4
|
|
180
|
+
with: { fetch-depth: 0 }
|
|
181
|
+
- uses: dominickkubica/codefactory@v0 # follows releases; or pin v0.20.1 or a commit SHA
|
|
182
|
+
with: { fail-on: high }
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Locally, `codefactory diff --base main` shows the same. Findings are matched by identity, not line, so code that
|
|
186
|
+
moved isn't "new", and each one names its owners when the repository has a CODEOWNERS file.
|
|
187
|
+
|
|
188
|
+
`codefactory sarif -o codefactory.sarif` feeds GitHub code scanning instead. The [usage guide](docs/USAGE.md#keeping-new-problems-out-baseline-and-check)
|
|
189
|
+
has complete workflows.
|
|
190
|
+
|
|
191
|
+
## How far to trust it
|
|
192
|
+
|
|
193
|
+
Analysis is static: nothing is executed. Most of codefactory's accuracy came from running it on real projects and
|
|
194
|
+
fixing what it got wrong: each false positive got a test before its fix, and snapshot tests of every finding on
|
|
195
|
+
three sample apps make any change in output visible in CI.
|
|
196
|
+
|
|
197
|
+
- **Precision and recall are measured** on a labeled corpus in eight languages, in CI: 91% precision and 84%
|
|
198
|
+
recall the first time it met code it hadn't been tuned on; 100% and 100% after fixing what that found. Details,
|
|
199
|
+
per check, in [Accuracy](docs/ACCURACY.md).
|
|
200
|
+
- **Checked on real code** in each language family: two production apps (React Native, FastAPI), pip, Python's and
|
|
201
|
+
Go's standard libraries, Apache commons-lang (Java), OkHttp (Kotlin), Rack (Ruby), and 24 public projects assessed
|
|
202
|
+
in three rounds (Rails, Django, Laravel, Spring, ASP.NET, Phoenix, Next.js, Rust, Go, Kotlin Android, Swift,
|
|
203
|
+
Flutter, Electron, data pipelines). Every false finding they showed was fixed, with a regression test copied from
|
|
204
|
+
the real repository; the results are in [Accuracy](docs/ACCURACY.md).
|
|
205
|
+
- **Hints are labelled as hints.** Calls through reflection or untyped objects can be missed, so "unused" and "no
|
|
206
|
+
test reaches it" are reported as leads to verify.
|
|
207
|
+
- **Measured where it can be.** With a coverage report in the repository (`coverage/lcov.info`, Istanbul's
|
|
208
|
+
`coverage-final.json`, coverage.py's `coverage.json`), "untested" comes from what actually ran. Without one, the
|
|
209
|
+
call-graph estimate matched Jest's real coverage for 97.6% of functions on a 500-file React Native app.
|
|
210
|
+
- **Intended findings stay quiet.** Mark them once, in the code or from the command line, and say why:
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
// codefactory: ignore io_in_loop — one query per table, and there are seven
|
|
214
|
+
```
|
|
215
|
+
```bash
|
|
216
|
+
codefactory accept sql_built src/db/encrypt.ts --why "the key is 64 hex characters we generate"
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
## Speed
|
|
220
|
+
|
|
221
|
+
Files are parsed on every core and cached one by one, so a repeat run re-reads only what changed:
|
|
222
|
+
|
|
223
|
+
| Codebase (full review, 4 cores) | First run | Nothing changed |
|
|
224
|
+
|---|---|---|
|
|
225
|
+
| A React Native app with a Swift watch app, 535 files, 36k lines | 11 s | 2 s |
|
|
226
|
+
| A TypeScript monorepo (Actual Budget), 2,400 files, 1,500 commits of history | 22 s | 4.5 s |
|
|
227
|
+
| Python's standard library and packages, 3,900 files, 1.7M lines | 54 s | 11 s |
|
|
228
|
+
|
|
229
|
+
A changed file re-reads just that file, except TypeScript\*.
|
|
230
|
+
|
|
231
|
+
\*The TypeScript type checker needs the whole program, so a TypeScript change re-runs it. Other commands (`flags`,
|
|
232
|
+
`brief`, `context`, `plan`) answer from the cache in well under a second when nothing changed.
|
|
233
|
+
|
|
234
|
+
## Privacy
|
|
235
|
+
|
|
236
|
+
Everything runs locally and nothing is uploaded. The map is a single HTML file with no network access. The only
|
|
237
|
+
network use is the install itself, `codefactory update`, tree-sitter grammars downloading the first time a language
|
|
238
|
+
is analyzed, and `review --online`, which sends package names and versions (nothing else) to OSV.dev. Caches live in `.codefactory/` inside the repository, which ignores itself in git.
|
|
239
|
+
|
|
240
|
+
## Documentation
|
|
241
|
+
|
|
242
|
+
- [Usage guide](docs/USAGE.md): every command, the viewer, every check, configuration, CI and Claude Code
|
|
243
|
+
- [Design](docs/DESIGN.md): how it works and why, data model, algorithms, trade-offs and limits
|
|
244
|
+
- [Accuracy](docs/ACCURACY.md): precision and recall per check, measured, and the real-code spot checks
|
|
245
|
+
- [Changelog](CHANGELOG.md) · [Contributing](CONTRIBUTING.md)
|
|
246
|
+
|
|
247
|
+
## Status and license
|
|
248
|
+
|
|
249
|
+
Version 0.20, actively developed and used on real projects. Issues and pull requests are welcome; see
|
|
250
|
+
[Contributing](CONTRIBUTING.md). [MIT licensed](LICENSE): use it, change it, share it.
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
# codefactory
|
|
2
|
+
|
|
3
|
+
[](https://github.com/dominickkubica/codefactory/actions/workflows/ci.yml)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
**See a codebase as a factory floor, find what's wrong with it, and turn that into work.**
|
|
8
|
+
|
|
9
|
+
codefactory reads a repository without running it, builds a map of every file, function and call, and checks that
|
|
10
|
+
map for copied code, database calls inside loops, dead code, import loops and dozens of security, reliability and
|
|
11
|
+
delivery problems. It shows the result as an interactive floor plan, writes a technical review, ranks the fixes, and
|
|
12
|
+
hands each one to you, or to an AI coding agent, as a ready-made task.
|
|
13
|
+
|
|
14
|
+
It works on Python, TypeScript/JavaScript, Go, Java, Kotlin, Swift, Rust, C/C++, C#, Ruby, PHP and more, runs
|
|
15
|
+
entirely on your machine, and needs no account, server or API key.
|
|
16
|
+
|
|
17
|
+

|
|
18
|
+
|
|
19
|
+
<sub>pip's own source (150 files), zoomed out: one hall per area of the code, one conveyor per pair of areas, labelled with
|
|
20
|
+
the number of calls it carries. Dashed orange conveyors run backwards, from a lower layer up into a higher one.</sub>
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install "codefactory[languages] @ git+https://github.com/dominickkubica/codefactory"
|
|
26
|
+
cd path/to/your/repo
|
|
27
|
+
|
|
28
|
+
codefactory review -o review.md # a technical review of the repository (--online: also vulnerable dependencies)
|
|
29
|
+
codefactory view # the interactive map, in your browser
|
|
30
|
+
codefactory plan # what to fix first, ranked; then: codefactory prompt 1
|
|
31
|
+
codefactory profile # what kind of project it thinks this is (findings are ranked for it)
|
|
32
|
+
codefactory hotspots # where change happens: complex code that keeps changing
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
- **Python 3.11 or newer.** On Windows, run the same commands in PowerShell; use `py -m pip` if `pip` isn't found.
|
|
36
|
+
- **TypeScript/JavaScript projects:** run `npm install` in the project first, because codefactory uses the project's
|
|
37
|
+
own TypeScript compiler (needs [Node.js](https://nodejs.org)). Without it, those files are still analyzed, less
|
|
38
|
+
precisely.
|
|
39
|
+
- **`[languages]`** adds the tree-sitter language pack for everything beyond Python and TypeScript. Leave it out for
|
|
40
|
+
a dependency-free install.
|
|
41
|
+
- **Upgrade any time** with `codefactory update`.
|
|
42
|
+
|
|
43
|
+
## What it does
|
|
44
|
+
|
|
45
|
+
- **Map.** Every file is a machine, every call between files a belt, every layer a zone. Zoom out for the halls and
|
|
46
|
+
how they depend on each other; zoom in for files and functions; click a function to light up everything it calls.
|
|
47
|
+
- **Find.** Each finding points at a `file:line` and says what to do about it:
|
|
48
|
+
|
|
49
|
+
| Area | Examples |
|
|
50
|
+
|---|---|
|
|
51
|
+
| Performance | Database or network calls once per item (N+1), searches inside loops over loaded data, writes outside a transaction |
|
|
52
|
+
| Duplication | Identical and near-identical functions, merged into one task per group |
|
|
53
|
+
| Structure | Import loops, layer-rule breaks, unused code, functions nobody tests, very long or complex functions |
|
|
54
|
+
| Data flow | Python: request values traced variable by variable, through helper functions, into SQL, shell commands, `eval`, file paths, outgoing URLs, redirects and templates, with sanitizers (`int()`, bound SQL parameters, `shlex.quote`…) respected |
|
|
55
|
+
| Privacy | Personal data (contact details, birth dates, location, health readings, device ids) in logs, analytics and unencrypted storage; iOS permissions without usage descriptions; required-reason APIs without a privacy manifest (App Store rejections) |
|
|
56
|
+
| Security | Every HTTP endpoint and whether it checks who's asking; endpoints that change data without an auth check; risky lines (SQL built from strings, shell, `eval`, raw HTML) ranked by whether a request reaches them, with the route → … → line chain; leaked credentials, including ones deleted but still in git history; debug mode, CORS `*`, insecure cookies, unverified JWTs, weak crypto and random numbers; unsafe CI workflows, root containers, secrets in images; known-vulnerable dependencies (`--online`) |
|
|
57
|
+
| Reliability | Swallowed errors, network calls without a timeout, missing error boundaries |
|
|
58
|
+
| Apple platforms | Swift: disk or database work on the main thread, retain cycles in stored closures, `try!`/`as!`; entitlements that weaken code signing |
|
|
59
|
+
| Shell, Make, YAML, HTML, Pkl | Credentials in config files (quoted or not); `curl … \| sh`, `rm -rf "$DIR/"` with an empty variable, `eval` of a variable (scripts and Makefile recipes); docker-compose and Kubernetes: privileged or host-network containers, databases published on every interface, committed passwords and Secrets; HTML: scripts and forms over plain HTTP, CDN scripts without integrity hashes; plain-HTTP URLs in Pkl, TOML and Terraform |
|
|
60
|
+
| Patches | `codefactory diff --patch pr.diff` checks the lines a unified diff adds, with no repository: a downloaded pull request, a mailing-list patch, an AI agent's proposed change |
|
|
61
|
+
| Delivery | No CI or CI without tests, floating dependency versions, no lockfile, no runtime pin |
|
|
62
|
+
|
|
63
|
+
- **Assess.** Before judging, it works out what the project is: a local-first mobile app, a deployed API with
|
|
64
|
+
accounts, a LAN tool, a command-line tool or a library; where it runs, who uses it, and whether it holds health,
|
|
65
|
+
financial or other sensitive data. Findings are ranked for that, each change with its reason: SQL built from
|
|
66
|
+
strings matters less in a single-user offline app; an untested write matters more when the phone holds the only
|
|
67
|
+
copy. Git history adds the other half: **hotspots** (complex code that changes every week, where debt costs the
|
|
68
|
+
most), files that always change together with nothing linking them, and code only one person knows.
|
|
69
|
+
- **Review.** `codefactory review` writes a technical review in the shape a principal engineer would: summary,
|
|
70
|
+
project profile, system map, where change happens, findings by severity with evidence, what's working, gaps and
|
|
71
|
+
open questions. No AI needed.
|
|
72
|
+
- **Fix.** `codefactory plan` turns findings into ranked tasks with steps and the tests to run. Each task becomes a
|
|
73
|
+
self-contained prompt for Claude Code, and a baseline keeps new problems out in CI.
|
|
74
|
+
|
|
75
|
+
| | |
|
|
76
|
+
|---|---|
|
|
77
|
+
|  |  |
|
|
78
|
+
| **Duplication lens.** Files holding copies of each other's code, joined by arcs labelled with their similarity. | **Trace.** Everything a function eventually calls, by depth, with the total amount of code involved. |
|
|
79
|
+
|
|
80
|
+
## Languages
|
|
81
|
+
|
|
82
|
+
| Language | How calls are resolved | Notes |
|
|
83
|
+
|---|---|---|
|
|
84
|
+
| Python | Precisely: imports, `self`/`cls`, classes, re-exports, dispatch tables, `getattr` | Standard library only |
|
|
85
|
+
| TypeScript, JavaScript | Precisely: the project's own TypeScript type checker (path aliases, hooks, JSX, lazy `require`) | Needs Node.js and `npm install` |
|
|
86
|
+
| Go, Java, Kotlin, Swift, Rust, C, C++, C#, Ruby, PHP, Scala, Dart, Lua, Elixir and more | By name, plus declared types, through tree-sitter | `[languages]` install; grammars download once, then work offline |
|
|
87
|
+
| Shell, Makefiles, YAML (docker-compose, Kubernetes, GitHub Actions), HTML, Pkl, TOML, Terraform, `.diff`/`.patch` | Not a call graph: line checks for credentials, unsafe commands and configuration | No install needed |
|
|
88
|
+
|
|
89
|
+
For the by-name languages, call, impact and unused-code findings are leads to confirm, and the review says so.
|
|
90
|
+
|
|
91
|
+
## Commands
|
|
92
|
+
|
|
93
|
+
| Command | What it gives you |
|
|
94
|
+
|---|---|
|
|
95
|
+
| `review` | A full technical review in Markdown; `--for-ai` adds an evidence pack for an AI to finish the judgement calls |
|
|
96
|
+
| `view` | The interactive factory floor (one HTML file), with lenses for duplication, efficiency and size |
|
|
97
|
+
| `flags` | Every issue with `file:line`; `--min warn`, `--kind similar`, `--json`, `--github` |
|
|
98
|
+
| `plan` / `prompt` | Ranked tasks with steps and tests / one task as a ready-to-paste Claude Code prompt |
|
|
99
|
+
| `diff` | What a change adds and fixes, compared with the base branch: a pull-request comment, annotations or JSON; `--patch file.diff` checks a patch on its own, no repository needed |
|
|
100
|
+
| `profile` | What kind of project this is (mobile app, web service, CLI, library…), where it runs, who uses it, what sensitive data it holds, with evidence; the review ranks findings for it |
|
|
101
|
+
| `hotspots` | From git history: complex code that changes often, files that change together without importing each other, code only one person knows |
|
|
102
|
+
| `sbom` | A CycloneDX software bill of materials of every pinned dependency |
|
|
103
|
+
| `org` | A dashboard across many repositories: health, findings, trends, and findings per owning team |
|
|
104
|
+
| `surface` | The attack surface: every HTTP endpoint, its auth check, and whether it changes data or reaches risky code |
|
|
105
|
+
| `accept` | Mark a finding as intended, with the reason, so later runs show only what's new |
|
|
106
|
+
| `brief` / `context` | A compact map of the repo / everything about one file or function before you change it |
|
|
107
|
+
| `trace` / `path` | What a function eventually calls / how one function reaches another |
|
|
108
|
+
| `baseline` / `check` | Save today's issues / fail CI or a pre-commit hook only on new ones |
|
|
109
|
+
| `sarif` | Issues for GitHub code scanning and VS Code (SARIF 2.1.0) |
|
|
110
|
+
| `query` / `sql` | Ask anything in SQL / export the graph as a SQLite database |
|
|
111
|
+
| `analyze` | The raw graph as JSON |
|
|
112
|
+
| `skill` | Teach Claude Code in a repository when and how to use all of the above (`--hook`: keep it current) |
|
|
113
|
+
| `update` | Upgrade codefactory to the latest version |
|
|
114
|
+
|
|
115
|
+
Commands that take a name work from inside the repository: `codefactory context checkout`. `codefactory --help` and
|
|
116
|
+
`codefactory <command> --help` list every option.
|
|
117
|
+
|
|
118
|
+
## With Claude Code
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
codefactory skill --hook # once per repository; commit .claude/
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
This writes a skill (`.claude/skills/codefactory/SKILL.md`) and a session-start hook. Every Claude Code session in
|
|
125
|
+
that repository, on your machine or in the cloud, then starts with codefactory installed, upgraded at most once a
|
|
126
|
+
day, and its instructions matching the installed version.
|
|
127
|
+
|
|
128
|
+
Then ask in plain words: *"what should I clean up first?"*, *"review the codebase"*, *"what breaks if I change
|
|
129
|
+
`useCart`?"*, *"did my change add any problems?"*. Claude Code runs the right command, reads a few thousand tokens of
|
|
130
|
+
findings instead of the whole repository, and verifies each change with the tests codefactory lists.
|
|
131
|
+
|
|
132
|
+
## In CI
|
|
133
|
+
|
|
134
|
+
Comment on every pull request with the findings it adds and fixes (one comment, updated on each push), and
|
|
135
|
+
optionally fail on new ones:
|
|
136
|
+
|
|
137
|
+
```yaml
|
|
138
|
+
# .github/workflows/codefactory.yml
|
|
139
|
+
on: pull_request
|
|
140
|
+
permissions: { contents: read, pull-requests: write }
|
|
141
|
+
jobs:
|
|
142
|
+
codefactory:
|
|
143
|
+
runs-on: ubuntu-latest
|
|
144
|
+
steps:
|
|
145
|
+
- uses: actions/checkout@v4
|
|
146
|
+
with: { fetch-depth: 0 }
|
|
147
|
+
- uses: dominickkubica/codefactory@v0 # follows releases; or pin v0.20.1 or a commit SHA
|
|
148
|
+
with: { fail-on: high }
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Locally, `codefactory diff --base main` shows the same. Findings are matched by identity, not line, so code that
|
|
152
|
+
moved isn't "new", and each one names its owners when the repository has a CODEOWNERS file.
|
|
153
|
+
|
|
154
|
+
`codefactory sarif -o codefactory.sarif` feeds GitHub code scanning instead. The [usage guide](docs/USAGE.md#keeping-new-problems-out-baseline-and-check)
|
|
155
|
+
has complete workflows.
|
|
156
|
+
|
|
157
|
+
## How far to trust it
|
|
158
|
+
|
|
159
|
+
Analysis is static: nothing is executed. Most of codefactory's accuracy came from running it on real projects and
|
|
160
|
+
fixing what it got wrong: each false positive got a test before its fix, and snapshot tests of every finding on
|
|
161
|
+
three sample apps make any change in output visible in CI.
|
|
162
|
+
|
|
163
|
+
- **Precision and recall are measured** on a labeled corpus in eight languages, in CI: 91% precision and 84%
|
|
164
|
+
recall the first time it met code it hadn't been tuned on; 100% and 100% after fixing what that found. Details,
|
|
165
|
+
per check, in [Accuracy](docs/ACCURACY.md).
|
|
166
|
+
- **Checked on real code** in each language family: two production apps (React Native, FastAPI), pip, Python's and
|
|
167
|
+
Go's standard libraries, Apache commons-lang (Java), OkHttp (Kotlin), Rack (Ruby), and 24 public projects assessed
|
|
168
|
+
in three rounds (Rails, Django, Laravel, Spring, ASP.NET, Phoenix, Next.js, Rust, Go, Kotlin Android, Swift,
|
|
169
|
+
Flutter, Electron, data pipelines). Every false finding they showed was fixed, with a regression test copied from
|
|
170
|
+
the real repository; the results are in [Accuracy](docs/ACCURACY.md).
|
|
171
|
+
- **Hints are labelled as hints.** Calls through reflection or untyped objects can be missed, so "unused" and "no
|
|
172
|
+
test reaches it" are reported as leads to verify.
|
|
173
|
+
- **Measured where it can be.** With a coverage report in the repository (`coverage/lcov.info`, Istanbul's
|
|
174
|
+
`coverage-final.json`, coverage.py's `coverage.json`), "untested" comes from what actually ran. Without one, the
|
|
175
|
+
call-graph estimate matched Jest's real coverage for 97.6% of functions on a 500-file React Native app.
|
|
176
|
+
- **Intended findings stay quiet.** Mark them once, in the code or from the command line, and say why:
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
// codefactory: ignore io_in_loop — one query per table, and there are seven
|
|
180
|
+
```
|
|
181
|
+
```bash
|
|
182
|
+
codefactory accept sql_built src/db/encrypt.ts --why "the key is 64 hex characters we generate"
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## Speed
|
|
186
|
+
|
|
187
|
+
Files are parsed on every core and cached one by one, so a repeat run re-reads only what changed:
|
|
188
|
+
|
|
189
|
+
| Codebase (full review, 4 cores) | First run | Nothing changed |
|
|
190
|
+
|---|---|---|
|
|
191
|
+
| A React Native app with a Swift watch app, 535 files, 36k lines | 11 s | 2 s |
|
|
192
|
+
| A TypeScript monorepo (Actual Budget), 2,400 files, 1,500 commits of history | 22 s | 4.5 s |
|
|
193
|
+
| Python's standard library and packages, 3,900 files, 1.7M lines | 54 s | 11 s |
|
|
194
|
+
|
|
195
|
+
A changed file re-reads just that file, except TypeScript\*.
|
|
196
|
+
|
|
197
|
+
\*The TypeScript type checker needs the whole program, so a TypeScript change re-runs it. Other commands (`flags`,
|
|
198
|
+
`brief`, `context`, `plan`) answer from the cache in well under a second when nothing changed.
|
|
199
|
+
|
|
200
|
+
## Privacy
|
|
201
|
+
|
|
202
|
+
Everything runs locally and nothing is uploaded. The map is a single HTML file with no network access. The only
|
|
203
|
+
network use is the install itself, `codefactory update`, tree-sitter grammars downloading the first time a language
|
|
204
|
+
is analyzed, and `review --online`, which sends package names and versions (nothing else) to OSV.dev. Caches live in `.codefactory/` inside the repository, which ignores itself in git.
|
|
205
|
+
|
|
206
|
+
## Documentation
|
|
207
|
+
|
|
208
|
+
- [Usage guide](docs/USAGE.md): every command, the viewer, every check, configuration, CI and Claude Code
|
|
209
|
+
- [Design](docs/DESIGN.md): how it works and why, data model, algorithms, trade-offs and limits
|
|
210
|
+
- [Accuracy](docs/ACCURACY.md): precision and recall per check, measured, and the real-code spot checks
|
|
211
|
+
- [Changelog](CHANGELOG.md) · [Contributing](CONTRIBUTING.md)
|
|
212
|
+
|
|
213
|
+
## Status and license
|
|
214
|
+
|
|
215
|
+
Version 0.20, actively developed and used on real projects. Issues and pull requests are welcome; see
|
|
216
|
+
[Contributing](CONTRIBUTING.md). [MIT licensed](LICENSE): use it, change it, share it.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""`codefactory accept`: record that a finding is intended, with the reason, in factory.toml.
|
|
2
|
+
|
|
3
|
+
A comment next to the code (`codefactory: ignore <kind> — why`) is the first choice, because the reason sits where
|
|
4
|
+
the next reader looks. `accept` is for when editing the code isn't wanted (generated code, a finding in a file you
|
|
5
|
+
don't own, a quick triage pass), and for review findings: it appends a [[silence]] rule that every command honours.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import getpass
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import subprocess
|
|
14
|
+
from datetime import date
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from .sarif import RULES
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def known_kinds() -> set[str]:
|
|
21
|
+
return set(RULES) # every graph and review finding has a SARIF rule
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def rules_for_task(task: dict, graph: dict) -> list[tuple[str, str]]:
|
|
25
|
+
"""(kind, where) for every finding behind a plan task."""
|
|
26
|
+
fn = {f["id"]: f for f in graph["functions"]}
|
|
27
|
+
out = []
|
|
28
|
+
for i in task["flags"]:
|
|
29
|
+
flag = graph["flags"][i]
|
|
30
|
+
f = fn.get(flag["target"])
|
|
31
|
+
where = f"{f['file']}::{f['qualname']}" if f and f["kind"] != "module" else (f["file"] if f else flag["target"])
|
|
32
|
+
out.append((flag["kind"], where))
|
|
33
|
+
return sorted(set(out))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def normalize_where(where: str) -> str:
|
|
37
|
+
"""`src/a.py:42` -> `src/a.py` (a line moves; the file or function doesn't). Backslashes become slashes."""
|
|
38
|
+
where = where.replace("\\", "/")
|
|
39
|
+
return re.sub(r":\d+$", "", where)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _who(root: Path) -> str:
|
|
43
|
+
"""The person accepting: git's user.name, else the login name."""
|
|
44
|
+
try:
|
|
45
|
+
proc = subprocess.run(["git", "-C", str(root), "config", "user.name"], capture_output=True, text=True, timeout=10)
|
|
46
|
+
name = proc.stdout.strip()
|
|
47
|
+
except (OSError, subprocess.SubprocessError):
|
|
48
|
+
name = ""
|
|
49
|
+
try:
|
|
50
|
+
return name or getpass.getuser()
|
|
51
|
+
except (OSError, KeyError):
|
|
52
|
+
return "unknown"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def append_rules(root: Path, rules: list[tuple[str, str]], reason: str) -> Path:
|
|
56
|
+
path = root / "factory.toml"
|
|
57
|
+
text = path.read_text(encoding="utf-8") if path.is_file() else ""
|
|
58
|
+
blocks = []
|
|
59
|
+
by, on = _who(root), date.today().isoformat() # the audit trail: who accepted it, and when
|
|
60
|
+
for kind, where in rules:
|
|
61
|
+
# JSON strings are valid TOML basic strings (same escapes), so quoting can't break the file
|
|
62
|
+
blocks.append(
|
|
63
|
+
f"[[silence]]\nkind = {json.dumps(kind)}\nwhere = {json.dumps(where)}\nreason = {json.dumps(reason)}\n"
|
|
64
|
+
f"by = {json.dumps(by)}\non = {json.dumps(on)}\n"
|
|
65
|
+
)
|
|
66
|
+
sep = "" if not text or text.endswith("\n\n") else ("\n" if text.endswith("\n") else "\n\n")
|
|
67
|
+
path.write_text(text + sep + "\n".join(blocks), encoding="utf-8")
|
|
68
|
+
return path
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Language analyzers. Each reads a codebase and returns a Graph; add a language by adding a module here.
|
|
2
|
+
|
|
3
|
+
Python and TypeScript/JavaScript have precise analyzers (the standard library's ast; the TypeScript type checker).
|
|
4
|
+
Every other language goes through tree-sitter (generic.py), which also stands in for TypeScript/JavaScript when the
|
|
5
|
+
typescript package isn't installed.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from ..graph import Graph
|
|
14
|
+
from .generic import analyze_generic
|
|
15
|
+
from .python import analyze_python
|
|
16
|
+
from .typescript import TypeScriptUnavailable, analyze_typescript
|
|
17
|
+
|
|
18
|
+
LANGUAGES = ("python", "typescript", "other")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def analyze(root: Path, ignore: list[str], languages: list[str] | None = None, cache: bool = True) -> Graph:
|
|
22
|
+
g = Graph(root=str(root), language="")
|
|
23
|
+
wanted = languages or list(LANGUAGES)
|
|
24
|
+
js_fallback = False
|
|
25
|
+
for lang in wanted:
|
|
26
|
+
if lang == "python":
|
|
27
|
+
part = analyze_python(root, ignore, cache=cache)
|
|
28
|
+
elif lang == "typescript":
|
|
29
|
+
try:
|
|
30
|
+
part = analyze_typescript(root, ignore, cache=cache)
|
|
31
|
+
except TypeScriptUnavailable as e:
|
|
32
|
+
if languages and "other" not in languages: # asked for explicitly: that's an error
|
|
33
|
+
raise SystemExit(f"codefactory: {e}") from None
|
|
34
|
+
print(f"codefactory: {e} Using the general analyzer for TypeScript/JavaScript instead.", file=sys.stderr)
|
|
35
|
+
js_fallback = True
|
|
36
|
+
continue
|
|
37
|
+
elif lang == "other":
|
|
38
|
+
part = analyze_generic(root, ignore, include_js=js_fallback, cache=cache)
|
|
39
|
+
else:
|
|
40
|
+
raise ValueError(f"unknown language {lang!r} (choose from {', '.join(LANGUAGES)})")
|
|
41
|
+
if part.files:
|
|
42
|
+
g.merge(part)
|
|
43
|
+
_unique_ids(g)
|
|
44
|
+
return g
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _unique_ids(g: Graph) -> None:
|
|
48
|
+
"""Every function id once, whatever an analyzer produced (minified or generated code can repeat a name on one
|
|
49
|
+
line): a repeat gets #2, #3… Edges keep pointing at the first."""
|
|
50
|
+
seen: dict[str, int] = {}
|
|
51
|
+
for f in g.functions:
|
|
52
|
+
n = seen.get(f.id, 0)
|
|
53
|
+
seen[f.id] = n + 1
|
|
54
|
+
if n:
|
|
55
|
+
f.id = f"{f.id}#{n + 1}"
|