code-prune 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
code_prune/store.py ADDED
@@ -0,0 +1,266 @@
1
+ """Session-scoped SQLite store for scan findings and cross-file analysis.
2
+
3
+ Per-file findings, together with the definitions and usage names collected
4
+ while scanning, are written directly to an SQLite database instead of being
5
+ accumulated in memory. Every scan run is assigned a UUID so multiple
6
+ concurrent invocations share the same database file without interference.
7
+ Once every file has been scanned, :meth:`SessionStore.compute_unused_symbols`
8
+ resolves :data:`~code_prune.scanner.CATEGORY_UNUSED_SYMBOL` findings by
9
+ aggregating definitions against usages in SQL. After the report is written
10
+ the caller deletes the session records, keeping the database lean.
11
+
12
+ Author: Ron Webb
13
+ Since: 1.0.0
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ import sqlite3
20
+ import threading
21
+ from pathlib import Path
22
+
23
+ from .scanner import CATEGORY_UNUSED_SYMBOL, Definition, Finding
24
+
25
+ _CREATE_FINDINGS_TABLE = (
26
+ "CREATE TABLE IF NOT EXISTS findings ("
27
+ " session_id TEXT NOT NULL,"
28
+ " category TEXT NOT NULL,"
29
+ " file_path TEXT NOT NULL,"
30
+ " line INTEGER NOT NULL,"
31
+ " col INTEGER NOT NULL,"
32
+ " name TEXT NOT NULL,"
33
+ " message TEXT NOT NULL"
34
+ ")"
35
+ )
36
+ _CREATE_DEFINITIONS_TABLE = (
37
+ "CREATE TABLE IF NOT EXISTS definitions ("
38
+ " session_id TEXT NOT NULL,"
39
+ " file_path TEXT NOT NULL,"
40
+ " line INTEGER NOT NULL,"
41
+ " col INTEGER NOT NULL,"
42
+ " name TEXT NOT NULL,"
43
+ " kind TEXT NOT NULL"
44
+ ")"
45
+ )
46
+ _CREATE_IDENTIFIERS_TABLE = (
47
+ "CREATE TABLE IF NOT EXISTS identifiers ("
48
+ " session_id TEXT NOT NULL,"
49
+ " name TEXT NOT NULL"
50
+ ")"
51
+ )
52
+ _CREATE_FINDINGS_INDEX = (
53
+ "CREATE INDEX IF NOT EXISTS idx_findings_session ON findings (session_id)"
54
+ )
55
+ _CREATE_DEFINITIONS_INDEX = (
56
+ "CREATE INDEX IF NOT EXISTS idx_definitions_session ON definitions (session_id)"
57
+ )
58
+ _CREATE_IDENTIFIERS_INDEX = (
59
+ "CREATE INDEX IF NOT EXISTS idx_identifiers_session_name"
60
+ " ON identifiers (session_id, name)"
61
+ )
62
+
63
+ _INSERT_FINDING = (
64
+ "INSERT INTO findings (session_id, category, file_path, line, col, name, message)"
65
+ " VALUES (?, ?, ?, ?, ?, ?, ?)"
66
+ )
67
+ _INSERT_DEFINITION = (
68
+ "INSERT INTO definitions (session_id, file_path, line, col, name, kind)"
69
+ " VALUES (?, ?, ?, ?, ?, ?)"
70
+ )
71
+ _INSERT_IDENTIFIER = "INSERT INTO identifiers (session_id, name) VALUES (?, ?)"
72
+
73
+ _SELECT_FINDINGS = (
74
+ "SELECT category, file_path, line, col, name, message FROM findings"
75
+ " WHERE session_id = ? ORDER BY file_path ASC, line ASC, col ASC"
76
+ )
77
+ _SELECT_UNUSED_DEFINITIONS = (
78
+ "SELECT d.file_path, d.line, d.col, d.name, d.kind"
79
+ " FROM definitions d"
80
+ " WHERE d.session_id = ?"
81
+ " AND NOT EXISTS ("
82
+ " SELECT 1 FROM identifiers i"
83
+ " WHERE i.session_id = d.session_id AND i.name = d.name"
84
+ " )"
85
+ " ORDER BY d.file_path ASC, d.line ASC"
86
+ )
87
+
88
+ _DELETE_FINDINGS = "DELETE FROM findings WHERE session_id = ?"
89
+ _DELETE_DEFINITIONS = "DELETE FROM definitions WHERE session_id = ?"
90
+ _DELETE_IDENTIFIERS = "DELETE FROM identifiers WHERE session_id = ?"
91
+
92
+
93
+ class SessionStore:
94
+ """SQLite-backed session store for dead-code scan results.
95
+
96
+ A single database file is shared across all threads and concurrent runs.
97
+ Every run is identified by a *session_id* (UUID string) so records are
98
+ always isolated. The cross-file "unused symbol" pass is performed entirely
99
+ in SQL via a ``NOT EXISTS`` anti-join so Python never has to materialise
100
+ every identifier in memory to resolve it.
101
+
102
+ Author: Ron Webb
103
+ Since: 1.0.0
104
+ """
105
+
106
+ def __init__(self, db_path: Path) -> None:
107
+ """Open (or create) the SQLite database at *db_path*.
108
+
109
+ WAL journal mode is enabled so reads and writes do not block each
110
+ other; a threading lock serialises Python-side connection calls since
111
+ :mod:`sqlite3` connection objects are not thread-safe.
112
+
113
+ Author: Ron Webb
114
+ Since: 1.0.0
115
+ """
116
+ self._conn = sqlite3.connect(db_path, check_same_thread=False)
117
+ self._lock = threading.Lock()
118
+ with self._lock:
119
+ self._conn.execute("PRAGMA journal_mode=WAL")
120
+ self._conn.execute("PRAGMA synchronous=NORMAL")
121
+ self._conn.execute(_CREATE_FINDINGS_TABLE)
122
+ self._conn.execute(_CREATE_DEFINITIONS_TABLE)
123
+ self._conn.execute(_CREATE_IDENTIFIERS_TABLE)
124
+ self._conn.execute(_CREATE_FINDINGS_INDEX)
125
+ self._conn.execute(_CREATE_DEFINITIONS_INDEX)
126
+ self._conn.execute(_CREATE_IDENTIFIERS_INDEX)
127
+ self._conn.commit()
128
+
129
+ def insert_findings(self, session_id: str, findings: list[Finding]) -> None:
130
+ """Persist *findings* for *session_id* in the database.
131
+
132
+ Author: Ron Webb
133
+ Since: 1.0.0
134
+ """
135
+ rows = [
136
+ (
137
+ session_id,
138
+ f.category,
139
+ str(f.file_path),
140
+ f.line,
141
+ f.column,
142
+ f.name,
143
+ f.message,
144
+ )
145
+ for f in findings
146
+ ]
147
+ with self._lock:
148
+ self._conn.executemany(_INSERT_FINDING, rows)
149
+ self._conn.commit()
150
+
151
+ def insert_definitions(
152
+ self, session_id: str, definitions: list[Definition]
153
+ ) -> None:
154
+ """Persist *definitions* for *session_id* in the database.
155
+
156
+ Author: Ron Webb
157
+ Since: 1.0.0
158
+ """
159
+ rows = [
160
+ (session_id, str(d.file_path), d.line, d.column, d.name, d.kind)
161
+ for d in definitions
162
+ ]
163
+ with self._lock:
164
+ self._conn.executemany(_INSERT_DEFINITION, rows)
165
+ self._conn.commit()
166
+
167
+ def insert_identifiers(self, session_id: str, names: list[str]) -> None:
168
+ """Persist usage *names* for *session_id* in the database.
169
+
170
+ Author: Ron Webb
171
+ Since: 1.0.0
172
+ """
173
+ rows = [(session_id, name) for name in names]
174
+ with self._lock:
175
+ self._conn.executemany(_INSERT_IDENTIFIER, rows)
176
+ self._conn.commit()
177
+
178
+ def read_findings(self, session_id: str) -> list[dict[str, object]]:
179
+ """Return every per-file finding recorded for *session_id*.
180
+
181
+ Author: Ron Webb
182
+ Since: 1.0.0
183
+ """
184
+ with self._lock:
185
+ rows = self._conn.execute(_SELECT_FINDINGS, (session_id,)).fetchall()
186
+ return [
187
+ {
188
+ "category": row[0],
189
+ "file": row[1],
190
+ "line": row[2],
191
+ "column": row[3],
192
+ "name": row[4],
193
+ "message": row[5],
194
+ }
195
+ for row in rows
196
+ ]
197
+
198
+ def compute_unused_symbols(
199
+ self, session_id: str, ignore_patterns: list[re.Pattern[str]]
200
+ ) -> list[dict[str, object]]:
201
+ """Return a finding for every definition never referenced elsewhere.
202
+
203
+ A definition is "unused" when its name never appears in the
204
+ project-wide ``identifiers`` table collected for *session_id*. Names
205
+ matching any of *ignore_patterns* (e.g. dunder methods, ``main``,
206
+ test hooks) are suppressed.
207
+
208
+ Author: Ron Webb
209
+ Since: 1.0.0
210
+ """
211
+ with self._lock:
212
+ rows = self._conn.execute(
213
+ _SELECT_UNUSED_DEFINITIONS, (session_id,)
214
+ ).fetchall()
215
+ results: list[dict[str, object]] = []
216
+ for file_path, line, col, name, kind in rows:
217
+ if any(p.search(name) for p in ignore_patterns):
218
+ continue
219
+ results.append(
220
+ {
221
+ "category": CATEGORY_UNUSED_SYMBOL,
222
+ "file": file_path,
223
+ "line": line,
224
+ "column": col,
225
+ "name": name,
226
+ "message": f"{kind.capitalize()} '{name}' is never referenced.",
227
+ }
228
+ )
229
+ return results
230
+
231
+ def delete_session(self, session_id: str) -> None:
232
+ """Remove every record belonging to *session_id* from the database.
233
+
234
+ Author: Ron Webb
235
+ Since: 1.0.0
236
+ """
237
+ with self._lock:
238
+ self._conn.execute(_DELETE_FINDINGS, (session_id,))
239
+ self._conn.execute(_DELETE_DEFINITIONS, (session_id,))
240
+ self._conn.execute(_DELETE_IDENTIFIERS, (session_id,))
241
+ self._conn.commit()
242
+
243
+ def close(self) -> None:
244
+ """Close the underlying database connection.
245
+
246
+ Author: Ron Webb
247
+ Since: 1.0.0
248
+ """
249
+ with self._lock:
250
+ self._conn.close()
251
+
252
+ def __enter__(self) -> SessionStore:
253
+ """Return *self* to support use as a context manager.
254
+
255
+ Author: Ron Webb
256
+ Since: 1.0.0
257
+ """
258
+ return self
259
+
260
+ def __exit__(self, *_: object) -> None:
261
+ """Close the database connection on context manager exit.
262
+
263
+ Author: Ron Webb
264
+ Since: 1.0.0
265
+ """
266
+ self.close()
@@ -0,0 +1,18 @@
1
+ # Regex patterns for symbol names to exclude from unused-code findings.
2
+ # One pattern per line. Lines starting with # are comments. Empty lines are ignored.
3
+
4
+ # Dunder / magic methods and common entry points
5
+ ^__.*__$
6
+ ^main$
7
+
8
+ # Common test hooks and fixtures
9
+ ^[Tt]est
10
+ ^setUp$
11
+ ^tearDown$
12
+ ^setUpClass$
13
+ ^tearDownClass$
14
+
15
+ # Commonly overridden object methods
16
+ ^toString$
17
+ ^equals$
18
+ ^hashCode$
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.4
2
+ Name: code-prune
3
+ Version: 1.0.0
4
+ Summary: Find unreachable, unused, and obsolete code before it becomes technical debt.
5
+ License: MIT License
6
+
7
+ Copyright (c) 2026 Ron Webb
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
+ License-File: LICENSE
27
+ Keywords: cli,static-analysis,dead-code,unused-code,tree-sitter,code-quality
28
+ Author: Ron Webb
29
+ Requires-Python: >=3.14
30
+ Classifier: Development Status :: 4 - Beta
31
+ Classifier: Environment :: Console
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: Operating System :: OS Independent
34
+ Classifier: Programming Language :: Python :: 3
35
+ Classifier: Programming Language :: Python :: 3.14
36
+ Classifier: Programming Language :: Python :: 3 :: Only
37
+ Classifier: Topic :: Software Development :: Quality Assurance
38
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
39
+ Classifier: Typing :: Typed
40
+ Requires-Dist: braincraft (>=1.3.1,<2.0.0)
41
+ Requires-Dist: click (>=8.0.0,<9.0.0)
42
+ Requires-Dist: env-dir-bootstrap (>=1.0.0,<2.0.0)
43
+ Requires-Dist: logenrich (>=1.0.1,<2.0.0)
44
+ Requires-Dist: rich (>=15.0.0,<16.0.0)
45
+ Requires-Dist: tree-sitter (>=0.26.0,<0.27.0)
46
+ Requires-Dist: tree-sitter-gosu (>=0.3.0,<0.4.0)
47
+ Requires-Dist: tree-sitter-java (>=0.23.5,<0.24.0)
48
+ Requires-Dist: tree-sitter-javascript (>=0.25.0,<0.26.0)
49
+ Requires-Dist: tree-sitter-python (>=0.25.0,<0.26.0)
50
+ Requires-Dist: tree-sitter-typescript (>=0.23.2,<0.24.0)
51
+ Project-URL: Changelog, https://github.com/rcw3bb/code-prune/blob/main/CHANGELOG.md
52
+ Project-URL: Homepage, https://github.com/rcw3bb/code-prune
53
+ Project-URL: Issues, https://github.com/rcw3bb/code-prune/issues
54
+ Project-URL: Repository, https://github.com/rcw3bb/code-prune
55
+ Description-Content-Type: text/markdown
56
+
57
+ # code-prune
58
+
59
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/rcw3bb/code-prune/blob/main/LICENSE) [![Version](https://img.shields.io/badge/Version-1.0.0-green.svg)](https://github.com/rcw3bb/code-prune/blob/main/CHANGELOG.md) [![Python](https://img.shields.io/badge/Python-3.14%2B-blue)](https://www.python.org/) [![PyPI](https://img.shields.io/badge/PyPI-code-prune-orange)](https://pypi.org/project/code-prune/)
60
+
61
+
62
+ A CLI tool that scans a codebase for unreachable, unused, and obsolete code,
63
+ helping you find dead code before it becomes technical debt.
64
+
65
+ ## Features
66
+
67
+ `code-prune` parses source files with [tree-sitter](https://tree-sitter.github.io/tree-sitter/)
68
+ and reports five categories of findings across **Python, JavaScript,
69
+ TypeScript, Java, and Gosu**:
70
+
71
+ - **Unreachable code** — statements after `return`/`raise`/`throw`/`break`/
72
+ `continue`, and `if` branches whose condition is a constant falsy literal
73
+ (`False`/`false`/`0`).
74
+ - **Unused imports & local variables** — per-file, syntactic detection of
75
+ bindings that are never referenced again in the same file.
76
+ - **Unused functions/classes/methods** — cross-file detection of definitions
77
+ that are never referenced anywhere in the scanned project.
78
+ - **Obsolete markers** — `@deprecated`/`@Deprecated`-style decorators and
79
+ annotations, plus `TODO`/`FIXME`/`XXX` comment tags.
80
+ - **Commented-out code** — comments whose content heuristically resembles
81
+ source code.
82
+
83
+ > Detection is heuristic and syntactic rather than a full scope- or
84
+ > call-graph-aware analysis — treat findings as a starting point for review,
85
+ > not a guarantee.
86
+
87
+ ## Requirements
88
+
89
+ - Python `>=3.14`
90
+ - Poetry `2.2`
91
+
92
+ ## Installation
93
+
94
+ ```powershell
95
+ poetry install
96
+ ```
97
+
98
+ ## Usage
99
+
100
+ ```powershell
101
+ poetry run code-prune <path> [options]
102
+ ```
103
+
104
+ Common options:
105
+
106
+ | Option | Description |
107
+ |-------------------|------------------------------------------------------------------------------|
108
+ | `--ext` | Comma-separated extensions to include (e.g. `py,js,ts,java,gs,gsx`). |
109
+ | `--categories` | Comma-separated categories to report: `unreachable,unused,obsolete,commented-out` (default: all). |
110
+ | `--format` | Output format: `json`, `html`, or `all` (default: `json`). |
111
+ | `--output` | Base output filename without extension (default: `code-prune-output`). |
112
+ | `--output-dir` | Directory for the report file(s) (default: `reports`). |
113
+ | `--workers` | Number of parallel worker threads used to scan files. |
114
+ | `--db` | Path to the SQLite scratch database used during a scan run. |
115
+ | `--target-list` | Treat `path` as a file listing target paths, one per line. |
116
+
117
+ Example:
118
+
119
+ ```powershell
120
+ poetry run code-prune src --categories unreachable,unused --format all
121
+ ```
122
+
123
+ ## Configuration
124
+
125
+ Logging is bootstrapped via `env-dir-bootstrap`. Set the `CODE_PRUNE_CONFIG_DIR`
126
+ environment variable to override the default configuration directory used to
127
+ resolve `logging.ini`, `config.ini`, `.codepruneignore`, and `symbol_ignore`.
128
+
129
+ ### Ignoring files and directories
130
+
131
+ `.codepruneignore` holds gitignore-style patterns for files/directories to
132
+ exclude from scanning (mirroring `.gitignore` syntax). Override the filename
133
+ via `config.ini`:
134
+
135
+ ```ini
136
+ [override]
137
+ ignore-file = .codepruneignore
138
+ ```
139
+
140
+ ### Ignoring symbol names
141
+
142
+ `symbol_ignore` holds one regex pattern per line, matched against symbol
143
+ names to suppress from "unused function/class/method" findings — useful for
144
+ dunder methods, `main`, test hooks (`test_*`, `setUp`), and similar
145
+ intentionally-unreferenced symbols.
146
+
147
+ ## Development
148
+
149
+ Run tests with coverage and generate an HTML report:
150
+
151
+ ```powershell
152
+ poetry run pytest --cov=code_prune tests --cov-report html
153
+ ```
154
+
155
+ Format and lint the code:
156
+
157
+ ```powershell
158
+ poetry run black code_prune; poetry run pylint code_prune
159
+ ```
160
+
161
+ ## License
162
+
163
+ This project is licensed under the [MIT License](LICENSE).
164
+
@@ -0,0 +1,16 @@
1
+ code_prune/.codepruneignore,sha256=9mRAQiaYZdmlMXazShKy5pjbWEfMfFOTUaHOVC8irJI,218
2
+ code_prune/__init__.py,sha256=CwVyXaoBkWqhSmGXqTI8LuXQJnJZStsT-XAugp4ilV4,601
3
+ code_prune/cli.py,sha256=lAQMhkzygcGMrs_SmqBtQP9G_y_JWo6xWmcMCpN3q70,14524
4
+ code_prune/config.ini,sha256=URW6VcIlLXCuV5MHBIh32ANoLEIRLSdPszWtIxao5Qs,42
5
+ code_prune/config.py,sha256=DcNIfQrGNQK2D7F7aoS5nLN3hJsud0BSVzorHJSBieg,1105
6
+ code_prune/logging.ini,sha256=05lRtFd7GeQoFfVA5I_nLd6WXqsj_aANOtkqm-FHkFw,534
7
+ code_prune/parser.py,sha256=fnMQK7_xY8_uCDL75ZDbmZ6MgFV3sfF73gwnNzZWj50,2219
8
+ code_prune/reporter.py,sha256=4DlIeiEAHQ4QIsRfps18QYOgrodeLpQ9mYFyN4LME0Y,11924
9
+ code_prune/scanner.py,sha256=8Mk7e_J06HS5wJzsVKwR5Q0lQWIGI4zB49-WbKrYTnk,27006
10
+ code_prune/store.py,sha256=ObeAjjIbegLf7PYAqiMQm_p1WHDl02Fd3GPICN15TQY,8895
11
+ code_prune/symbol_ignore,sha256=0GxX-Uaa31ItSPedlsWc8jDN4PMiWZV5P8oidg322S8,383
12
+ code_prune-1.0.0.dist-info/METADATA,sha256=wbPiDVmhtdK9fs3WyeeA61-OwFxjfrpKhoZvr4-hr5Q,6943
13
+ code_prune-1.0.0.dist-info/WHEEL,sha256=M5asmiAlL6HEcOq52Yi5mmk9KmTVjY2RDPtO4p9DMrc,88
14
+ code_prune-1.0.0.dist-info/entry_points.txt,sha256=iyShO9vHCgkDexXC9rYhzNlERG6xRZNXNXg2lOWIZE0,50
15
+ code_prune-1.0.0.dist-info/licenses/LICENSE,sha256=Fs1jiRzMbn9F-lRZC-Z219JKSDzhFFCNibLKwGkRtCY,1065
16
+ code_prune-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.2.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ code-prune=code_prune.cli:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ron Webb
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.