code-prune 1.1.0__tar.gz → 1.3.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.
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.0 - 2026-11-16
4
+
5
+ ### Added
6
+
7
+ - `unused-symbol` now also reports unused fields/attributes (kind `field`):
8
+ class-level fields in Python, JavaScript (including `#private`), TypeScript
9
+ (including interface properties and constructor parameter properties), Java
10
+ (including enum constants) and Gosu (`var` fields without an `as` alias), plus
11
+ Python `self.x = ...` attributes assigned in methods.
12
+ - `--search-path` applies to fields with the same rule as methods: the field
13
+ name and its enclosing class's name must both be found in the same file.
14
+ - `serialVersionUID` is ignored by the default `symbol_ignore`.
15
+
16
+ ### Changed
17
+
18
+ - Private JavaScript/TypeScript property usages (`this.#x`) are now counted as
19
+ identifier usages.
20
+ - `code_prune.log` now uses a `RotatingFileHandler` (10 MB per file, 10 backups)
21
+ with UTF-8 encoding, instead of an unbounded, platform-default-encoded
22
+ `FileHandler`.
23
+
24
+ ## 1.2.0 - 2026-11-15
25
+
26
+ ### Added
27
+
28
+ - `--search-path`: files and/or directories (separated by `;`) searched
29
+ textually for each `unused-symbol` candidate. Symbols found there are no
30
+ longer reported. Classes and functions/methods are both matched with a
31
+ whole-word regex; a method additionally requires its enclosing class's name
32
+ to be found in the same file. The symbol's own file is ignored and
33
+ `.codepruneignore` rules apply.
34
+ - `--search-ext`: extensions of the files searched in `--search-path`
35
+ (default: every text file). Requires `--search-path`.
36
+
3
37
  ## 1.1.0 - 2026-11-05
4
38
 
5
39
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: code-prune
3
- Version: 1.1.0
3
+ Version: 1.3.0
4
4
  Summary: Find unreachable, unused, and obsolete code before it becomes technical debt.
5
5
  License: MIT License
6
6
 
@@ -56,7 +56,7 @@ Description-Content-Type: text/markdown
56
56
 
57
57
  # code-prune
58
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.1.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/)
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.3.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
60
 
61
61
 
62
62
  A CLI tool that scans a codebase for unreachable, unused, and obsolete code,
@@ -73,8 +73,11 @@ TypeScript, Java, and Gosu**:
73
73
  (`False`/`false`/`0`). Comments are never reported as unreachable.
74
74
  - **Unused imports & local variables** — per-file, syntactic detection of
75
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.
76
+ - **Unused functions/classes/methods/fields** — cross-file detection of
77
+ definitions that are never referenced anywhere in the scanned project. Fields
78
+ cover class-level fields in every language, Python `self.x` attributes,
79
+ JavaScript `#private` fields, TypeScript interface properties and constructor
80
+ parameter properties, and Java enum constants.
78
81
  - **Obsolete markers** — `@deprecated`/`@Deprecated`-style decorators and
79
82
  annotations, plus comments mentioning `deprecated`.
80
83
  - **TODO markers** — `TODO`/`FIXME`/`XXX` comment tags (not necessarily
@@ -120,11 +123,14 @@ Common options:
120
123
  | `--workers` | Number of parallel worker threads used to scan files. |
121
124
  | `--db` | Path to the SQLite scratch database used during a scan run. |
122
125
  | `--target-list` | Treat `path` as a file listing target paths, one per line. |
126
+ | `--search-path` | Files and/or directories (separated by `;`) searched textually for each `unused-symbol` candidate; a symbol found there is not reported. Classes, functions/methods and fields are all matched by a whole-word regex; a method or field additionally requires its enclosing class's name to appear in the same file. The symbol's own file is skipped and `.codepruneignore` rules apply. |
127
+ | `--search-ext` | Comma-separated extensions of the files searched in `--search-path` (e.g. `xml,json`). Omit to search every text file. Requires `--search-path`. |
123
128
 
124
129
  Example:
125
130
 
126
131
  ```powershell
127
132
  code-prune src --categories unreachable,unused-import,todo-marker --format all
133
+ code-prune src --categories unused-symbol --search-path "templates;../other-repo" --search-ext xml,json,py
128
134
  ```
129
135
 
130
136
  ### Reports
@@ -158,8 +164,8 @@ It always uses that fixed name and is not affected by `config.ini`.
158
164
  ### Ignoring symbol names
159
165
 
160
166
  `symbol_ignore` holds one regex pattern per line, matched against symbol
161
- names to suppress from "unused function/class/method" findings — useful for
162
- dunder methods, `main`, test hooks (`test_*`, `setUp`), and similar
167
+ names to suppress from "unused function/class/method/field" findings — useful for
168
+ dunder methods, `main`, test hooks (`test_*`, `setUp`), `serialVersionUID`, and similar
163
169
  intentionally-unreferenced symbols.
164
170
 
165
171
  ## Development
@@ -1,6 +1,6 @@
1
1
  # code-prune
2
2
 
3
- [![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.1.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/)
3
+ [![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.3.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/)
4
4
 
5
5
 
6
6
  A CLI tool that scans a codebase for unreachable, unused, and obsolete code,
@@ -17,8 +17,11 @@ TypeScript, Java, and Gosu**:
17
17
  (`False`/`false`/`0`). Comments are never reported as unreachable.
18
18
  - **Unused imports & local variables** — per-file, syntactic detection of
19
19
  bindings that are never referenced again in the same file.
20
- - **Unused functions/classes/methods** — cross-file detection of definitions
21
- that are never referenced anywhere in the scanned project.
20
+ - **Unused functions/classes/methods/fields** — cross-file detection of
21
+ definitions that are never referenced anywhere in the scanned project. Fields
22
+ cover class-level fields in every language, Python `self.x` attributes,
23
+ JavaScript `#private` fields, TypeScript interface properties and constructor
24
+ parameter properties, and Java enum constants.
22
25
  - **Obsolete markers** — `@deprecated`/`@Deprecated`-style decorators and
23
26
  annotations, plus comments mentioning `deprecated`.
24
27
  - **TODO markers** — `TODO`/`FIXME`/`XXX` comment tags (not necessarily
@@ -64,11 +67,14 @@ Common options:
64
67
  | `--workers` | Number of parallel worker threads used to scan files. |
65
68
  | `--db` | Path to the SQLite scratch database used during a scan run. |
66
69
  | `--target-list` | Treat `path` as a file listing target paths, one per line. |
70
+ | `--search-path` | Files and/or directories (separated by `;`) searched textually for each `unused-symbol` candidate; a symbol found there is not reported. Classes, functions/methods and fields are all matched by a whole-word regex; a method or field additionally requires its enclosing class's name to appear in the same file. The symbol's own file is skipped and `.codepruneignore` rules apply. |
71
+ | `--search-ext` | Comma-separated extensions of the files searched in `--search-path` (e.g. `xml,json`). Omit to search every text file. Requires `--search-path`. |
67
72
 
68
73
  Example:
69
74
 
70
75
  ```powershell
71
76
  code-prune src --categories unreachable,unused-import,todo-marker --format all
77
+ code-prune src --categories unused-symbol --search-path "templates;../other-repo" --search-ext xml,json,py
72
78
  ```
73
79
 
74
80
  ### Reports
@@ -102,8 +108,8 @@ It always uses that fixed name and is not affected by `config.ini`.
102
108
  ### Ignoring symbol names
103
109
 
104
110
  `symbol_ignore` holds one regex pattern per line, matched against symbol
105
- names to suppress from "unused function/class/method" findings — useful for
106
- dunder methods, `main`, test hooks (`test_*`, `setUp`), and similar
111
+ names to suppress from "unused function/class/method/field" findings — useful for
112
+ dunder methods, `main`, test hooks (`test_*`, `setUp`), `serialVersionUID`, and similar
107
113
  intentionally-unreferenced symbols.
108
114
 
109
115
  ## Development
@@ -10,7 +10,7 @@ Since: 1.0.0
10
10
  from env_dir_bootstrap import EnvDirBootstrap
11
11
 
12
12
  __app_name__ = "code-prune"
13
- __version__ = "1.1.0"
13
+ __version__ = "1.3.0"
14
14
 
15
15
  _bootstrapper = EnvDirBootstrap(
16
16
  env_var="CODE_PRUNE_CONFIG_DIR",
@@ -34,16 +34,17 @@ from . import CONF_DIR
34
34
  from . import PATH_IGNORE_PATH
35
35
  from . import SYMBOL_IGNORE_PATH
36
36
  from .config import Config
37
+ from .language_tables import SUPPORTED_EXTENSIONS
37
38
  from .reporter import write_outputs
38
39
  from .scanner import (
39
40
  CATEGORY_UNUSED_ALIAS,
40
41
  CATEGORY_UNUSED_SYMBOL,
41
42
  CLI_CATEGORIES,
42
- SUPPORTED_EXTENSIONS,
43
43
  UNUSED_CATEGORIES,
44
44
  load_name_ignore_patterns,
45
45
  scan_file,
46
46
  )
47
+ from .searcher import SymbolSearcher
47
48
  from .store import SessionStore
48
49
 
49
50
  _VALID_FORMATS = ("json", "html", "all")
@@ -288,11 +289,14 @@ def discover_files(
288
289
  path: Path,
289
290
  extensions: list[str],
290
291
  ignore: IgnoreFile | _CombinedIgnore | None = None,
292
+ restrict_to_supported: bool = True,
291
293
  ) -> list[Path]:
292
- """Discover supported source files under *path*.
294
+ """Discover source files under *path*.
293
295
 
294
- Only files with an extension in :data:`SUPPORTED_EXTENSIONS` are returned;
295
- when *extensions* is given it narrows that set further. Both files and
296
+ By default only files with an extension in :data:`SUPPORTED_EXTENSIONS`
297
+ are returned and *extensions* narrows that set further. With
298
+ ``restrict_to_supported=False`` (used for search paths) *extensions* is
299
+ taken as-is and an empty list accepts every file. Both files and
296
300
  directories are accepted. When *ignore* is given, matching files are
297
301
  skipped and matching directories are pruned from the walk entirely.
298
302
 
@@ -307,11 +311,16 @@ def discover_files(
307
311
  else:
308
312
  return []
309
313
 
310
- allowed = (
311
- SUPPORTED_EXTENSIONS.intersection(extensions)
312
- if extensions
313
- else SUPPORTED_EXTENSIONS
314
- )
314
+ if restrict_to_supported:
315
+ allowed = (
316
+ SUPPORTED_EXTENSIONS.intersection(extensions)
317
+ if extensions
318
+ else SUPPORTED_EXTENSIONS
319
+ )
320
+ elif not extensions:
321
+ return candidates
322
+ else:
323
+ allowed = frozenset(extensions)
315
324
  return [f for f in candidates if f.suffix.lower() in allowed]
316
325
 
317
326
 
@@ -432,6 +441,25 @@ def _run_concurrent_scan(
432
441
  "path list. Blank lines and lines starting with '#' are skipped."
433
442
  ),
434
443
  )
444
+ @click.option(
445
+ "--search-path",
446
+ "search_path",
447
+ default="",
448
+ help=(
449
+ "Semicolon-separated files and/or directories searched textually for "
450
+ "each unused-symbol candidate. A symbol found there is not reported. "
451
+ "Classes are matched by name; functions/methods by a whole-word regex."
452
+ ),
453
+ )
454
+ @click.option(
455
+ "--search-ext",
456
+ "search_ext",
457
+ default="",
458
+ help=(
459
+ "Comma-separated extensions of the files to search in --search-path "
460
+ "(e.g. xml,json,py). Omit to search every text file."
461
+ ),
462
+ )
435
463
  def main( # pylint: disable=too-many-arguments,too-many-positional-arguments,too-many-locals
436
464
  path: str,
437
465
  ext: str,
@@ -442,6 +470,8 @@ def main( # pylint: disable=too-many-arguments,too-many-positional-arguments,to
442
470
  db_path: Path,
443
471
  categories: str,
444
472
  target_list: bool,
473
+ search_path: str,
474
+ search_ext: str,
445
475
  ) -> None:
446
476
  """Scan source files for unreachable, unused, and obsolete code.
447
477
 
@@ -458,6 +488,10 @@ def main( # pylint: disable=too-many-arguments,too-many-positional-arguments,to
458
488
  f"[yellow]Ignoring unsupported extension(s): {', '.join(unsupported)}[/yellow]"
459
489
  )
460
490
  selected_categories = _parse_categories(categories)
491
+ search_paths = _parse_paths(search_path)
492
+ search_extensions = _parse_extensions(search_ext)
493
+ if search_extensions and not search_paths:
494
+ raise click.UsageError("--search-ext requires --search-path.")
461
495
  paths = _parse_paths(path)
462
496
  if target_list:
463
497
  if len(paths) != 1 or not paths[0].is_file():
@@ -474,7 +508,10 @@ def main( # pylint: disable=too-many-arguments,too-many-positional-arguments,to
474
508
 
475
509
  _console.print(f"[bold]Scanning[/bold] {len(files)} file(s)\u2026")
476
510
 
477
- findings, interrupted = _scan_project(files, db_path, workers, selected_categories)
511
+ searcher = _build_searcher(search_paths, search_extensions)
512
+ findings, interrupted = _scan_project(
513
+ files, db_path, workers, selected_categories, searcher
514
+ )
478
515
 
479
516
  if interrupted:
480
517
  raise SystemExit(1)
@@ -498,7 +535,9 @@ def main( # pylint: disable=too-many-arguments,too-many-positional-arguments,to
498
535
  )
499
536
 
500
537
 
501
- def _discover_all_files(paths: list[Path], extensions: list[str]) -> list[Path]:
538
+ def _discover_all_files(
539
+ paths: list[Path], extensions: list[str], restrict_to_supported: bool = True
540
+ ) -> list[Path]:
502
541
  """Discover the de-duplicated set of files to scan across *paths*.
503
542
 
504
543
  Author: Ron Webb
@@ -509,15 +548,36 @@ def _discover_all_files(paths: list[Path], extensions: list[str]) -> list[Path]:
509
548
  with _console.status("[bold cyan]Discovering files\u2026", spinner="dots"):
510
549
  for target_path in paths:
511
550
  ignore = _build_combined_ignore(target_path)
512
- for found_file in discover_files(target_path, extensions, ignore):
551
+ for found_file in discover_files(
552
+ target_path, extensions, ignore, restrict_to_supported
553
+ ):
513
554
  if found_file not in seen:
514
555
  seen.add(found_file)
515
556
  files.append(found_file)
516
557
  return files
517
558
 
518
559
 
560
+ def _build_searcher(
561
+ search_paths: list[Path], search_extensions: list[str]
562
+ ) -> SymbolSearcher | None:
563
+ """Build a :class:`SymbolSearcher` over *search_paths*, or ``None`` when unset.
564
+
565
+ Author: Ron Webb
566
+ Since: 1.2.0
567
+ """
568
+ if not search_paths:
569
+ return None
570
+ search_files = _discover_all_files(search_paths, search_extensions, False)
571
+ _logger.info("Searching %s file(s) for unused-symbol references", len(search_files))
572
+ return SymbolSearcher(search_files)
573
+
574
+
519
575
  def _scan_project(
520
- files: list[Path], db_path: Path, workers: int, categories: set[str]
576
+ files: list[Path],
577
+ db_path: Path,
578
+ workers: int,
579
+ categories: set[str],
580
+ searcher: SymbolSearcher | None = None,
521
581
  ) -> tuple[list[dict[str, object]], bool]:
522
582
  """Run the full scan pipeline and return ``(findings, interrupted)``.
523
583
 
@@ -534,7 +594,7 @@ def _scan_project(
534
594
  if CATEGORY_UNUSED_SYMBOL in categories:
535
595
  name_ignore_patterns = load_name_ignore_patterns(Path(SYMBOL_IGNORE_PATH))
536
596
  findings.extend(
537
- store.compute_unused_symbols(session_id, name_ignore_patterns)
597
+ store.compute_unused_symbols(session_id, name_ignore_patterns, searcher)
538
598
  )
539
599
  except KeyboardInterrupt:
540
600
  interrupted = True
@@ -0,0 +1,170 @@
1
+ """Per-language tree-sitter node-type tables used by the scanner.
2
+
3
+ The node types were verified empirically against each tree-sitter grammar
4
+ before being hard-coded here.
5
+
6
+ Author: Ron Webb
7
+ Since: 1.3.0
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ EXTENSION_TO_LANGUAGE: dict[str, str] = {
13
+ ".py": "Python",
14
+ ".pyi": "Python",
15
+ ".js": "JavaScript",
16
+ ".mjs": "JavaScript",
17
+ ".cjs": "JavaScript",
18
+ ".ts": "TypeScript",
19
+ ".tsx": "TypeScript",
20
+ ".java": "Java",
21
+ ".gs": "Gosu",
22
+ ".gsx": "Gosu",
23
+ }
24
+
25
+ #: File extensions the scanner can parse.
26
+ SUPPORTED_EXTENSIONS = frozenset(EXTENSION_TO_LANGUAGE)
27
+
28
+ #: Function/method definition node types, per language.
29
+ FUNCTION_NODE_TYPES: dict[str, frozenset[str]] = {
30
+ "Python": frozenset({"function_definition"}),
31
+ "JavaScript": frozenset(
32
+ {
33
+ "function_declaration",
34
+ "function_expression",
35
+ "arrow_function",
36
+ "method_definition",
37
+ }
38
+ ),
39
+ "TypeScript": frozenset(
40
+ {
41
+ "function_declaration",
42
+ "function_expression",
43
+ "arrow_function",
44
+ "method_definition",
45
+ }
46
+ ),
47
+ "Java": frozenset({"method_declaration", "constructor_declaration"}),
48
+ "Gosu": frozenset({"function_declaration", "constructor_declaration"}),
49
+ }
50
+
51
+ #: Class/interface definition node types, per language.
52
+ CLASS_NODE_TYPES: dict[str, frozenset[str]] = {
53
+ "Python": frozenset({"class_definition"}),
54
+ "JavaScript": frozenset({"class_declaration"}),
55
+ "TypeScript": frozenset({"class_declaration", "interface_declaration"}),
56
+ "Java": frozenset(
57
+ {"class_declaration", "interface_declaration", "enum_declaration"}
58
+ ),
59
+ "Gosu": frozenset({"class_declaration"}),
60
+ }
61
+
62
+ #: Field/attribute declaration node types, per language. Python class-level
63
+ #: fields are plain ``assignment`` nodes; ``self.x = ...`` attributes are found
64
+ #: separately inside methods.
65
+ FIELD_NODE_TYPES: dict[str, frozenset[str]] = {
66
+ "Python": frozenset({"assignment"}),
67
+ "JavaScript": frozenset({"field_definition"}),
68
+ "TypeScript": frozenset({"public_field_definition", "property_signature"}),
69
+ "Java": frozenset({"field_declaration", "enum_constant"}),
70
+ "Gosu": frozenset({"field_declaration"}),
71
+ }
72
+
73
+ #: Grammar field holding the declared name of a field node (default ``name``).
74
+ FIELD_NAME_FIELD: dict[str, str] = {"Python": "left", "JavaScript": "property"}
75
+
76
+ #: Node types a field name may have.
77
+ FIELD_NAME_NODE_TYPES = frozenset(
78
+ {"identifier", "property_identifier", "private_property_identifier"}
79
+ )
80
+
81
+ #: Modifiers that turn a TypeScript constructor parameter into a field.
82
+ PARAMETER_PROPERTY_MODIFIERS = frozenset({"accessibility_modifier", "readonly"})
83
+
84
+ #: Import/uses-clause node types, per language.
85
+ IMPORT_NODE_TYPES: dict[str, frozenset[str]] = {
86
+ "Python": frozenset({"import_statement", "import_from_statement"}),
87
+ "JavaScript": frozenset({"import_statement"}),
88
+ "TypeScript": frozenset({"import_statement"}),
89
+ "Java": frozenset({"import_declaration"}),
90
+ "Gosu": frozenset({"uses_declaration"}),
91
+ }
92
+
93
+ #: Local-variable declaration/assignment node types, per language.
94
+ LOCAL_DECL_NODE_TYPES: dict[str, frozenset[str]] = {
95
+ "Python": frozenset({"assignment"}),
96
+ "JavaScript": frozenset({"variable_declarator"}),
97
+ "TypeScript": frozenset({"variable_declarator"}),
98
+ "Java": frozenset({"variable_declarator"}),
99
+ "Gosu": frozenset({"local_variable_declaration"}),
100
+ }
101
+
102
+ #: Statements that terminate control flow within a block, per language.
103
+ TERMINATING_STATEMENT_TYPES: dict[str, frozenset[str]] = {
104
+ "Python": frozenset(
105
+ {"return_statement", "raise_statement", "break_statement", "continue_statement"}
106
+ ),
107
+ "JavaScript": frozenset(
108
+ {"return_statement", "throw_statement", "break_statement", "continue_statement"}
109
+ ),
110
+ "TypeScript": frozenset(
111
+ {"return_statement", "throw_statement", "break_statement", "continue_statement"}
112
+ ),
113
+ "Java": frozenset(
114
+ {"return_statement", "throw_statement", "break_statement", "continue_statement"}
115
+ ),
116
+ "Gosu": frozenset(
117
+ {"return_statement", "throw_statement", "break_statement", "continue_statement"}
118
+ ),
119
+ }
120
+
121
+ #: Node types whose direct named children form a sequential statement list.
122
+ BLOCK_NODE_TYPES: dict[str, frozenset[str]] = {
123
+ "Python": frozenset({"block"}),
124
+ "JavaScript": frozenset({"statement_block"}),
125
+ "TypeScript": frozenset({"statement_block"}),
126
+ "Java": frozenset({"block"}),
127
+ "Gosu": frozenset({"statement_block"}),
128
+ }
129
+
130
+ #: Comment node types, per language.
131
+ COMMENT_NODE_TYPES: dict[str, frozenset[str]] = {
132
+ "Python": frozenset({"comment"}),
133
+ "JavaScript": frozenset({"comment"}),
134
+ "TypeScript": frozenset({"comment"}),
135
+ "Java": frozenset({"line_comment", "block_comment"}),
136
+ "Gosu": frozenset({"line_comment", "block_comment"}),
137
+ }
138
+
139
+ #: Decorator/annotation node types consulted for deprecation markers.
140
+ DECORATOR_NODE_TYPES: dict[str, frozenset[str]] = {
141
+ "Python": frozenset({"decorator"}),
142
+ "JavaScript": frozenset(),
143
+ "TypeScript": frozenset({"decorator"}),
144
+ "Java": frozenset({"marker_annotation", "annotation"}),
145
+ "Gosu": frozenset({"annotation"}),
146
+ }
147
+
148
+ #: Identifier-like node types counted as a "usage" of a name.
149
+ USAGE_NODE_TYPES: dict[str, frozenset[str]] = {
150
+ "Python": frozenset({"identifier"}),
151
+ "JavaScript": frozenset(
152
+ {
153
+ "identifier",
154
+ "property_identifier",
155
+ "private_property_identifier",
156
+ "shorthand_property_identifier",
157
+ }
158
+ ),
159
+ "TypeScript": frozenset(
160
+ {
161
+ "identifier",
162
+ "property_identifier",
163
+ "private_property_identifier",
164
+ "shorthand_property_identifier",
165
+ "type_identifier",
166
+ }
167
+ ),
168
+ "Java": frozenset({"identifier", "type_identifier"}),
169
+ "Gosu": frozenset({"identifier"}),
170
+ }
@@ -17,9 +17,9 @@ formatter=consoleFormatter
17
17
  args=(sys.stderr,)
18
18
 
19
19
  [handler_fileHandler]
20
- class=FileHandler
20
+ class=handlers.RotatingFileHandler
21
21
  formatter=logFormatter
22
- args=('code_prune.log', 'a')
22
+ args=('code_prune.log', 'a', 10485760, 10, 'utf-8')
23
23
 
24
24
  [formatter_logFormatter]
25
25
  format=%(asctime)s [%(levelname)s] %(name)s - %(message)s
@@ -15,11 +15,27 @@ import logging
15
15
  import re
16
16
  from collections import Counter
17
17
  from collections.abc import Generator, Iterable
18
- from dataclasses import dataclass, field
18
+ from dataclasses import dataclass, field, replace
19
19
  from pathlib import Path
20
20
 
21
21
  from tree_sitter import Node, Tree # type: ignore[import-untyped]
22
22
 
23
+ from .language_tables import (
24
+ BLOCK_NODE_TYPES,
25
+ CLASS_NODE_TYPES,
26
+ COMMENT_NODE_TYPES,
27
+ DECORATOR_NODE_TYPES,
28
+ EXTENSION_TO_LANGUAGE,
29
+ FIELD_NAME_FIELD,
30
+ FIELD_NAME_NODE_TYPES,
31
+ FIELD_NODE_TYPES,
32
+ FUNCTION_NODE_TYPES,
33
+ IMPORT_NODE_TYPES,
34
+ LOCAL_DECL_NODE_TYPES,
35
+ PARAMETER_PROPERTY_MODIFIERS,
36
+ TERMINATING_STATEMENT_TYPES,
37
+ USAGE_NODE_TYPES,
38
+ )
23
39
  from .parser import parse
24
40
 
25
41
  _logger = logging.getLogger(__name__)
@@ -32,6 +48,9 @@ CATEGORY_UNREACHABLE = "unreachable"
32
48
  CATEGORY_UNUSED_IMPORT = "unused-import"
33
49
  CATEGORY_UNUSED_LOCAL = "unused-local"
34
50
  CATEGORY_UNUSED_SYMBOL = "unused-symbol"
51
+ SYMBOL_KIND_CLASS = "class"
52
+ SYMBOL_KIND_FUNCTION = "function"
53
+ SYMBOL_KIND_FIELD = "field"
35
54
  CATEGORY_OBSOLETE = "obsolete"
36
55
  CATEGORY_TODO_MARKER = "todo-marker"
37
56
  CATEGORY_COMMENTED_OUT = "commented-out"
@@ -66,143 +85,6 @@ CLI_CATEGORIES = (
66
85
  CATEGORY_COMMENTED_OUT,
67
86
  )
68
87
 
69
- # --------------------------------------------------------------------------
70
- # Per-language grammar node-type tables (verified empirically against each
71
- # tree-sitter grammar before being hard-coded here).
72
- # --------------------------------------------------------------------------
73
-
74
- EXTENSION_TO_LANGUAGE: dict[str, str] = {
75
- ".py": "Python",
76
- ".pyi": "Python",
77
- ".js": "JavaScript",
78
- ".mjs": "JavaScript",
79
- ".cjs": "JavaScript",
80
- ".ts": "TypeScript",
81
- ".tsx": "TypeScript",
82
- ".java": "Java",
83
- ".gs": "Gosu",
84
- ".gsx": "Gosu",
85
- }
86
-
87
- #: File extensions the scanner can parse.
88
- SUPPORTED_EXTENSIONS = frozenset(EXTENSION_TO_LANGUAGE)
89
-
90
- #: Function/method definition node types, per language.
91
- FUNCTION_NODE_TYPES: dict[str, frozenset[str]] = {
92
- "Python": frozenset({"function_definition"}),
93
- "JavaScript": frozenset(
94
- {
95
- "function_declaration",
96
- "function_expression",
97
- "arrow_function",
98
- "method_definition",
99
- }
100
- ),
101
- "TypeScript": frozenset(
102
- {
103
- "function_declaration",
104
- "function_expression",
105
- "arrow_function",
106
- "method_definition",
107
- }
108
- ),
109
- "Java": frozenset({"method_declaration", "constructor_declaration"}),
110
- "Gosu": frozenset({"function_declaration", "constructor_declaration"}),
111
- }
112
-
113
- #: Class/interface definition node types, per language.
114
- CLASS_NODE_TYPES: dict[str, frozenset[str]] = {
115
- "Python": frozenset({"class_definition"}),
116
- "JavaScript": frozenset({"class_declaration"}),
117
- "TypeScript": frozenset({"class_declaration", "interface_declaration"}),
118
- "Java": frozenset(
119
- {"class_declaration", "interface_declaration", "enum_declaration"}
120
- ),
121
- "Gosu": frozenset({"class_declaration"}),
122
- }
123
-
124
- #: Import/uses-clause node types, per language.
125
- IMPORT_NODE_TYPES: dict[str, frozenset[str]] = {
126
- "Python": frozenset({"import_statement", "import_from_statement"}),
127
- "JavaScript": frozenset({"import_statement"}),
128
- "TypeScript": frozenset({"import_statement"}),
129
- "Java": frozenset({"import_declaration"}),
130
- "Gosu": frozenset({"uses_declaration"}),
131
- }
132
-
133
- #: Local-variable declaration/assignment node types, per language.
134
- LOCAL_DECL_NODE_TYPES: dict[str, frozenset[str]] = {
135
- "Python": frozenset({"assignment"}),
136
- "JavaScript": frozenset({"variable_declarator"}),
137
- "TypeScript": frozenset({"variable_declarator"}),
138
- "Java": frozenset({"variable_declarator"}),
139
- "Gosu": frozenset({"local_variable_declaration"}),
140
- }
141
-
142
- #: Statements that terminate control flow within a block, per language.
143
- TERMINATING_STATEMENT_TYPES: dict[str, frozenset[str]] = {
144
- "Python": frozenset(
145
- {"return_statement", "raise_statement", "break_statement", "continue_statement"}
146
- ),
147
- "JavaScript": frozenset(
148
- {"return_statement", "throw_statement", "break_statement", "continue_statement"}
149
- ),
150
- "TypeScript": frozenset(
151
- {"return_statement", "throw_statement", "break_statement", "continue_statement"}
152
- ),
153
- "Java": frozenset(
154
- {"return_statement", "throw_statement", "break_statement", "continue_statement"}
155
- ),
156
- "Gosu": frozenset(
157
- {"return_statement", "throw_statement", "break_statement", "continue_statement"}
158
- ),
159
- }
160
-
161
- #: Node types whose direct named children form a sequential statement list.
162
- BLOCK_NODE_TYPES: dict[str, frozenset[str]] = {
163
- "Python": frozenset({"block"}),
164
- "JavaScript": frozenset({"statement_block"}),
165
- "TypeScript": frozenset({"statement_block"}),
166
- "Java": frozenset({"block"}),
167
- "Gosu": frozenset({"statement_block"}),
168
- }
169
-
170
- #: Comment node types, per language.
171
- COMMENT_NODE_TYPES: dict[str, frozenset[str]] = {
172
- "Python": frozenset({"comment"}),
173
- "JavaScript": frozenset({"comment"}),
174
- "TypeScript": frozenset({"comment"}),
175
- "Java": frozenset({"line_comment", "block_comment"}),
176
- "Gosu": frozenset({"line_comment", "block_comment"}),
177
- }
178
-
179
- #: Decorator/annotation node types consulted for deprecation markers.
180
- DECORATOR_NODE_TYPES: dict[str, frozenset[str]] = {
181
- "Python": frozenset({"decorator"}),
182
- "JavaScript": frozenset(),
183
- "TypeScript": frozenset({"decorator"}),
184
- "Java": frozenset({"marker_annotation", "annotation"}),
185
- "Gosu": frozenset({"annotation"}),
186
- }
187
-
188
- #: Identifier-like node types counted as a "usage" of a name.
189
- USAGE_NODE_TYPES: dict[str, frozenset[str]] = {
190
- "Python": frozenset({"identifier"}),
191
- "JavaScript": frozenset(
192
- {"identifier", "property_identifier", "shorthand_property_identifier"}
193
- ),
194
- "TypeScript": frozenset(
195
- {
196
- "identifier",
197
- "property_identifier",
198
- "shorthand_property_identifier",
199
- "type_identifier",
200
- }
201
- ),
202
- "Java": frozenset({"identifier", "type_identifier"}),
203
- "Gosu": frozenset({"identifier"}),
204
- }
205
-
206
88
  #: Regex matching a condition expression that is always false (after
207
89
  #: optionally stripping surrounding parentheses added by some grammars).
208
90
  _FALSY_CONDITION_RE = re.compile(r"^\(*\s*(False|false|0)\s*\)*$")
@@ -240,7 +122,11 @@ class Finding:
240
122
 
241
123
  @dataclass(frozen=True)
242
124
  class Definition:
243
- """A function/class/method definition discovered in one file.
125
+ """A function/class/method/field definition discovered in one file.
126
+
127
+ ``enclosing_class`` is the name of the class a method or field is directly
128
+ declared in (``None`` for classes and free functions); it lets search-path
129
+ matching require both the class and member names to appear together.
244
130
 
245
131
  Author: Ron Webb
246
132
  Since: 1.0.0
@@ -251,6 +137,7 @@ class Definition:
251
137
  file_path: Path
252
138
  line: int
253
139
  column: int
140
+ enclosing_class: str | None = None
254
141
 
255
142
 
256
143
  @dataclass
@@ -499,55 +386,249 @@ def _local_bound_name_node(decl_node: Node, language: str) -> Node | None:
499
386
  return None
500
387
 
501
388
 
502
- def _collect_bindings(
503
- tree: Tree, source_bytes: bytes, language: str, file_path: Path
504
- ) -> _Bindings:
505
- """Walk *tree* once, collecting import/local/definition bindings.
389
+ def _field_name_nodes(node: Node, language: str) -> list[Node]:
390
+ """Return the name nodes declared by the field *node*.
391
+
392
+ Java ``field_declaration`` may declare several variables. A Gosu field with
393
+ an ``as`` alias is exposed as a property and is therefore never a candidate.
506
394
 
507
395
  Author: Ron Webb
508
- Since: 1.0.0
396
+ Since: 1.3.0
509
397
  """
510
- bindings = _Bindings()
511
- import_types = IMPORT_NODE_TYPES.get(language, frozenset())
512
- local_types = LOCAL_DECL_NODE_TYPES.get(language, frozenset())
513
- function_types = FUNCTION_NODE_TYPES.get(language, frozenset())
514
- class_types = CLASS_NODE_TYPES.get(language, frozenset())
515
-
516
- def walk(node: Node, inside_function: bool) -> None:
517
- if node.type in import_types:
518
- for name_node in _import_bound_name_nodes(node, language):
519
- bindings.import_bindings.append(
520
- (name_node, _decode(source_bytes, name_node))
521
- )
522
- bindings.excluded_positions.add(name_node.start_byte)
398
+ if language == "Java" and node.type == "field_declaration":
399
+ names = [
400
+ declarator.child_by_field_name("name")
401
+ for declarator in node.children_by_field_name("declarator")
402
+ ]
403
+ elif language == "Gosu" and node.child_by_field_name("alias") is not None:
404
+ names = []
405
+ else:
406
+ names = [node.child_by_field_name(FIELD_NAME_FIELD.get(language, "name"))]
407
+ return [n for n in names if n is not None and n.type in FIELD_NAME_NODE_TYPES]
408
+
409
+
410
+ def _parameter_property_name_nodes(function_node: Node) -> list[Node]:
411
+ """Return the names of TypeScript constructor parameter properties.
412
+
413
+ ``constructor(private q: number)`` declares the field ``q``.
414
+
415
+ Author: Ron Webb
416
+ Since: 1.3.0
417
+ """
418
+ parameters = function_node.child_by_field_name("parameters")
419
+ if parameters is None:
420
+ return []
421
+ names: list[Node] = []
422
+ for param in parameters.named_children:
423
+ is_property = any(
424
+ c.type in PARAMETER_PROPERTY_MODIFIERS for c in param.children
425
+ )
426
+ pattern = param.child_by_field_name("pattern")
427
+ if is_property and pattern is not None and pattern.type == "identifier":
428
+ names.append(pattern)
429
+ return names
430
+
431
+
432
+ def _self_attribute_name_node(assign_node: Node, source_bytes: bytes) -> Node | None:
433
+ """Return the ``x`` node of a Python ``self.x = ...`` assignment, if any.
434
+
435
+ Author: Ron Webb
436
+ Since: 1.3.0
437
+ """
438
+ left = assign_node.child_by_field_name("left")
439
+ if left is None or left.type != "attribute":
440
+ return None
441
+ target = left.child_by_field_name("object")
442
+ if target is None or _decode(source_bytes, target) != "self":
443
+ return None
444
+ return left.child_by_field_name("attribute")
445
+
446
+
447
+ @dataclass(frozen=True)
448
+ class _Scope:
449
+ """Lexical position of the node being visited during the binding walk.
450
+
451
+ ``enclosing_class`` is the class a node is a *direct* member of (reset by
452
+ nested functions); ``owner_class`` is the nearest lexically enclosing class
453
+ regardless of functions, used for Python ``self.x`` attributes.
454
+
455
+ Author: Ron Webb
456
+ Since: 1.3.0
457
+ """
458
+
459
+ inside_function: bool = False
460
+ enclosing_class: str | None = None
461
+ owner_class: str | None = None
462
+
463
+
464
+ class _BindingCollector:
465
+ """Walk a tree once, collecting import/local/definition bindings.
466
+
467
+ Author: Ron Webb
468
+ Since: 1.3.0
469
+ """
470
+
471
+ def __init__(self, source_bytes: bytes, language: str, file_path: Path) -> None:
472
+ """Store the file being walked.
473
+
474
+ Author: Ron Webb
475
+ Since: 1.3.0
476
+ """
477
+ self._source = source_bytes
478
+ self._language = language
479
+ self._file_path = file_path
480
+ self._seen_fields: set[tuple[str, str]] = set()
481
+ self.bindings = _Bindings()
482
+
483
+ def walk(self, node: Node, scope: _Scope) -> None:
484
+ """Visit *node* and its descendants, recording bindings.
485
+
486
+ Author: Ron Webb
487
+ Since: 1.3.0
488
+ """
489
+ language = self._language
490
+ if node.type in IMPORT_NODE_TYPES.get(language, frozenset()):
491
+ self._record_imports(node)
523
492
  return
524
- if node.type in local_types and inside_function:
525
- name_node = _local_bound_name_node(node, language)
526
- if name_node is not None:
527
- bindings.local_bindings.append(
528
- (name_node, _decode(source_bytes, name_node))
493
+ if (
494
+ node.type in LOCAL_DECL_NODE_TYPES.get(language, frozenset())
495
+ and scope.inside_function
496
+ ):
497
+ self._record_local(node)
498
+ self._record_fields(node, scope)
499
+ child_scope = scope
500
+ if node.type in FUNCTION_NODE_TYPES.get(
501
+ language, frozenset()
502
+ ) or node.type in CLASS_NODE_TYPES.get(language, frozenset()):
503
+ child_scope = self._record_definition(node, scope)
504
+ elif node.type in FIELD_NODE_TYPES.get(language, frozenset()):
505
+ child_scope = replace(scope, enclosing_class=None)
506
+ for child in node.children:
507
+ self.walk(child, child_scope)
508
+
509
+ def _record_imports(self, node: Node) -> None:
510
+ """Record the names bound by the import *node*.
511
+
512
+ Author: Ron Webb
513
+ Since: 1.3.0
514
+ """
515
+ for name_node in _import_bound_name_nodes(node, self._language):
516
+ self.bindings.import_bindings.append(
517
+ (name_node, _decode(self._source, name_node))
518
+ )
519
+ self.bindings.excluded_positions.add(name_node.start_byte)
520
+
521
+ def _record_local(self, node: Node) -> None:
522
+ """Record the local variable bound by the declaration *node*.
523
+
524
+ Author: Ron Webb
525
+ Since: 1.3.0
526
+ """
527
+ name_node = _local_bound_name_node(node, self._language)
528
+ if name_node is not None:
529
+ self.bindings.local_bindings.append(
530
+ (name_node, _decode(self._source, name_node))
531
+ )
532
+ self.bindings.excluded_positions.add(name_node.start_byte)
533
+
534
+ def _record_definition(self, node: Node, scope: _Scope) -> _Scope:
535
+ """Record a function/class definition and return the scope of its body.
536
+
537
+ A method's body is local scope: nested definitions are not themselves
538
+ direct members of the enclosing class.
539
+
540
+ Author: Ron Webb
541
+ Since: 1.3.0
542
+ """
543
+ is_class = node.type in CLASS_NODE_TYPES.get(self._language, frozenset())
544
+ name_node = node.child_by_field_name("name")
545
+ class_name: str | None = None
546
+ if name_node is not None:
547
+ decoded_name = _decode(self._source, name_node)
548
+ class_name = decoded_name if is_class else None
549
+ self.bindings.definitions.append(
550
+ Definition(
551
+ name=decoded_name,
552
+ kind=SYMBOL_KIND_CLASS if is_class else SYMBOL_KIND_FUNCTION,
553
+ file_path=self._file_path,
554
+ line=name_node.start_point[0] + 1,
555
+ column=name_node.start_point[1],
556
+ enclosing_class=None if is_class else scope.enclosing_class,
529
557
  )
530
- bindings.excluded_positions.add(name_node.start_byte)
531
- if node.type in function_types or node.type in class_types:
532
- name_node = node.child_by_field_name("name")
558
+ )
559
+ self.bindings.excluded_positions.add(name_node.start_byte)
560
+ return _Scope(
561
+ inside_function=scope.inside_function or not is_class,
562
+ enclosing_class=class_name,
563
+ owner_class=class_name if is_class and class_name else scope.owner_class,
564
+ )
565
+
566
+ def _record_fields(self, node: Node, scope: _Scope) -> None:
567
+ """Record any field/attribute declared by *node*.
568
+
569
+ Author: Ron Webb
570
+ Since: 1.3.0
571
+ """
572
+ language = self._language
573
+ if scope.enclosing_class is not None:
574
+ if node.type in FIELD_NODE_TYPES.get(language, frozenset()):
575
+ self._add_fields(
576
+ _field_name_nodes(node, language), scope.enclosing_class
577
+ )
578
+ elif language == "TypeScript" and node.type in FUNCTION_NODE_TYPES.get(
579
+ language, frozenset()
580
+ ):
581
+ self._add_fields(
582
+ _parameter_property_name_nodes(node), scope.enclosing_class
583
+ )
584
+ if (
585
+ language == "Python"
586
+ and node.type == "assignment"
587
+ and scope.inside_function
588
+ and scope.owner_class is not None
589
+ ):
590
+ name_node = _self_attribute_name_node(node, self._source)
533
591
  if name_node is not None:
534
- kind = "class" if node.type in class_types else "function"
535
- bindings.definitions.append(
536
- Definition(
537
- name=_decode(source_bytes, name_node),
538
- kind=kind,
539
- file_path=file_path,
540
- line=name_node.start_point[0] + 1,
541
- column=name_node.start_point[1],
542
- )
592
+ self._add_fields([name_node], scope.owner_class)
593
+
594
+ def _add_fields(self, name_nodes: list[Node], class_name: str) -> None:
595
+ """Record each of *name_nodes* as a field of *class_name*.
596
+
597
+ Every declaration position is excluded from usages; only the first
598
+ declaration of a field yields a :class:`Definition`.
599
+
600
+ Author: Ron Webb
601
+ Since: 1.3.0
602
+ """
603
+ for name_node in name_nodes:
604
+ self.bindings.excluded_positions.add(name_node.start_byte)
605
+ decoded_name = _decode(self._source, name_node)
606
+ if (class_name, decoded_name) in self._seen_fields:
607
+ continue
608
+ self._seen_fields.add((class_name, decoded_name))
609
+ self.bindings.definitions.append(
610
+ Definition(
611
+ name=decoded_name,
612
+ kind=SYMBOL_KIND_FIELD,
613
+ file_path=self._file_path,
614
+ line=name_node.start_point[0] + 1,
615
+ column=name_node.start_point[1],
616
+ enclosing_class=class_name,
543
617
  )
544
- bindings.excluded_positions.add(name_node.start_byte)
545
- inside_function = inside_function or node.type in function_types
546
- for child in node.children:
547
- walk(child, inside_function)
618
+ )
619
+
548
620
 
549
- walk(tree.root_node, False)
550
- return bindings
621
+ def _collect_bindings(
622
+ tree: Tree, source_bytes: bytes, language: str, file_path: Path
623
+ ) -> _Bindings:
624
+ """Walk *tree* once, collecting import/local/definition/field bindings.
625
+
626
+ Author: Ron Webb
627
+ Since: 1.0.0
628
+ """
629
+ collector = _BindingCollector(source_bytes, language, file_path)
630
+ collector.walk(tree.root_node, _Scope())
631
+ return collector.bindings
551
632
 
552
633
 
553
634
  def _collect_usage_names(
@@ -0,0 +1,139 @@
1
+ """Textual search of extra paths for symbols reported as unused.
2
+
3
+ Symbols that are only referenced from files outside the scanned project
4
+ (templates, configuration, other code bases) would otherwise be reported as
5
+ unused. :class:`SymbolSearcher` checks such files purely textually, without
6
+ parsing them. Class, function/method and field names are matched with the same
7
+ whole-word regular expression; a method or field defined inside a class is only
8
+ considered referenced when its own name *and* its enclosing class's name are
9
+ both found in the same search file.
10
+
11
+ Author: Ron Webb
12
+ Since: 1.2.0
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from pathlib import Path
19
+
20
+ #: ``(name, kind, defining_file, enclosing_class)``. ``enclosing_class`` is
21
+ #: ``None`` for classes and free functions.
22
+ Candidate = tuple[str, str, str, str | None]
23
+
24
+
25
+ def _build_pattern(name: str) -> re.Pattern[str]:
26
+ """Return a whole-word regex for *name* that also treats ``$`` as a word character.
27
+
28
+ Author: Ron Webb
29
+ Since: 1.2.0
30
+ """
31
+ return re.compile(rf"(?<![\w$]){re.escape(name)}(?![\w$])")
32
+
33
+
34
+ def _read_text(file_path: Path) -> str | None:
35
+ """Return the text of *file_path*, or ``None`` for unreadable/binary files.
36
+
37
+ Author: Ron Webb
38
+ Since: 1.2.0
39
+ """
40
+ try:
41
+ data = file_path.read_bytes()
42
+ except OSError:
43
+ return None
44
+ if b"\x00" in data:
45
+ return None
46
+ return data.decode("utf-8", errors="replace")
47
+
48
+
49
+ class SymbolSearcher:
50
+ """Find which symbols are textually referenced in a set of search files.
51
+
52
+ Author: Ron Webb
53
+ Since: 1.2.0
54
+ """
55
+
56
+ def __init__(self, search_files: list[Path]) -> None:
57
+ """Store the files to search.
58
+
59
+ Author: Ron Webb
60
+ Since: 1.2.0
61
+ """
62
+ self._search_files = search_files
63
+
64
+ def find_referenced(self, candidates: list[Candidate]) -> set[Candidate]:
65
+ """Return the subset of *candidates* found in the search files.
66
+
67
+ The candidate's own defining file is never counted as a reference.
68
+ Every search file is read once and the search stops as soon as every
69
+ candidate has been resolved.
70
+
71
+ Author: Ron Webb
72
+ Since: 1.2.0
73
+ """
74
+ pending = set(candidates)
75
+ found: set[Candidate] = set()
76
+ patterns: dict[str, re.Pattern[str]] = {}
77
+ for search_file in self._search_files:
78
+ if not pending:
79
+ break
80
+ text = _read_text(search_file)
81
+ if text is None:
82
+ continue
83
+ resolved = _resolve(search_file)
84
+ hits = self._matches_in_text(text, resolved, pending, patterns)
85
+ found.update(hits)
86
+ pending.difference_update(hits)
87
+ return found
88
+
89
+ @staticmethod
90
+ def _matches_in_text(
91
+ text: str,
92
+ resolved_file: str,
93
+ pending: set[Candidate],
94
+ patterns: dict[str, re.Pattern[str]],
95
+ ) -> set[Candidate]:
96
+ """Return the *pending* candidates referenced in *text*.
97
+
98
+ A plain class or free function matches once its own name is found. A
99
+ method or field (``enclosing_class`` set) additionally requires its
100
+ enclosing class's name to be found in the same *text*.
101
+
102
+ Author: Ron Webb
103
+ Since: 1.2.0
104
+ """
105
+ hits: set[Candidate] = set()
106
+ for candidate in pending:
107
+ name, _, defining_file, enclosing_class = candidate
108
+ if _resolve(Path(defining_file)) == resolved_file:
109
+ continue
110
+ if not _name_matches(text, name, patterns):
111
+ continue
112
+ if enclosing_class and not _name_matches(text, enclosing_class, patterns):
113
+ continue
114
+ hits.add(candidate)
115
+ return hits
116
+
117
+
118
+ def _name_matches(text: str, name: str, patterns: dict[str, re.Pattern[str]]) -> bool:
119
+ """Return whether *name* occurs as a whole word in *text*.
120
+
121
+ Author: Ron Webb
122
+ Since: 1.2.0
123
+ """
124
+ if name not in text:
125
+ return False
126
+ pattern = patterns.setdefault(name, _build_pattern(name))
127
+ return pattern.search(text) is not None
128
+
129
+
130
+ def _resolve(path: Path) -> str:
131
+ """Return a normalised string form of *path* for own-file comparison.
132
+
133
+ Author: Ron Webb
134
+ Since: 1.2.0
135
+ """
136
+ try:
137
+ return str(path.resolve())
138
+ except OSError:
139
+ return str(path.absolute())
@@ -21,6 +21,7 @@ import threading
21
21
  from pathlib import Path
22
22
 
23
23
  from .scanner import CATEGORY_UNUSED_SYMBOL, Definition, Finding
24
+ from .searcher import SymbolSearcher
24
25
 
25
26
  _CREATE_FINDINGS_TABLE = (
26
27
  "CREATE TABLE IF NOT EXISTS findings ("
@@ -35,14 +36,16 @@ _CREATE_FINDINGS_TABLE = (
35
36
  )
36
37
  _CREATE_DEFINITIONS_TABLE = (
37
38
  "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"
39
+ " session_id TEXT NOT NULL,"
40
+ " file_path TEXT NOT NULL,"
41
+ " line INTEGER NOT NULL,"
42
+ " col INTEGER NOT NULL,"
43
+ " name TEXT NOT NULL,"
44
+ " kind TEXT NOT NULL,"
45
+ " enclosing_class TEXT"
44
46
  ")"
45
47
  )
48
+ _ADD_ENCLOSING_CLASS_COLUMN = "ALTER TABLE definitions ADD COLUMN enclosing_class TEXT"
46
49
  _CREATE_IDENTIFIERS_TABLE = (
47
50
  "CREATE TABLE IF NOT EXISTS identifiers ("
48
51
  " session_id TEXT NOT NULL,"
@@ -65,8 +68,9 @@ _INSERT_FINDING = (
65
68
  " VALUES (?, ?, ?, ?, ?, ?, ?)"
66
69
  )
67
70
  _INSERT_DEFINITION = (
68
- "INSERT INTO definitions (session_id, file_path, line, col, name, kind)"
69
- " VALUES (?, ?, ?, ?, ?, ?)"
71
+ "INSERT INTO definitions"
72
+ " (session_id, file_path, line, col, name, kind, enclosing_class)"
73
+ " VALUES (?, ?, ?, ?, ?, ?, ?)"
70
74
  )
71
75
  _INSERT_IDENTIFIER = "INSERT INTO identifiers (session_id, name) VALUES (?, ?)"
72
76
 
@@ -75,7 +79,7 @@ _SELECT_FINDINGS = (
75
79
  " WHERE session_id = ? ORDER BY file_path ASC, line ASC, col ASC"
76
80
  )
77
81
  _SELECT_UNUSED_DEFINITIONS = (
78
- "SELECT d.file_path, d.line, d.col, d.name, d.kind"
82
+ "SELECT d.file_path, d.line, d.col, d.name, d.kind, d.enclosing_class"
79
83
  " FROM definitions d"
80
84
  " WHERE d.session_id = ?"
81
85
  " AND NOT EXISTS ("
@@ -121,11 +125,27 @@ class SessionStore:
121
125
  self._conn.execute(_CREATE_FINDINGS_TABLE)
122
126
  self._conn.execute(_CREATE_DEFINITIONS_TABLE)
123
127
  self._conn.execute(_CREATE_IDENTIFIERS_TABLE)
128
+ self._migrate_definitions_table()
124
129
  self._conn.execute(_CREATE_FINDINGS_INDEX)
125
130
  self._conn.execute(_CREATE_DEFINITIONS_INDEX)
126
131
  self._conn.execute(_CREATE_IDENTIFIERS_INDEX)
127
132
  self._conn.commit()
128
133
 
134
+ def _migrate_definitions_table(self) -> None:
135
+ """Add the ``enclosing_class`` column to a pre-1.2.0 ``definitions`` table.
136
+
137
+ The scratch database file is reused across runs, so a table created
138
+ by an older version may be missing this column.
139
+
140
+ Author: Ron Webb
141
+ Since: 1.2.0
142
+ """
143
+ columns = {
144
+ row[1] for row in self._conn.execute("PRAGMA table_info(definitions)")
145
+ }
146
+ if "enclosing_class" not in columns:
147
+ self._conn.execute(_ADD_ENCLOSING_CLASS_COLUMN)
148
+
129
149
  def insert_findings(self, session_id: str, findings: list[Finding]) -> None:
130
150
  """Persist *findings* for *session_id* in the database.
131
151
 
@@ -157,7 +177,15 @@ class SessionStore:
157
177
  Since: 1.0.0
158
178
  """
159
179
  rows = [
160
- (session_id, str(d.file_path), d.line, d.column, d.name, d.kind)
180
+ (
181
+ session_id,
182
+ str(d.file_path),
183
+ d.line,
184
+ d.column,
185
+ d.name,
186
+ d.kind,
187
+ d.enclosing_class,
188
+ )
161
189
  for d in definitions
162
190
  ]
163
191
  with self._lock:
@@ -196,14 +224,19 @@ class SessionStore:
196
224
  ]
197
225
 
198
226
  def compute_unused_symbols(
199
- self, session_id: str, ignore_patterns: list[re.Pattern[str]]
227
+ self,
228
+ session_id: str,
229
+ ignore_patterns: list[re.Pattern[str]],
230
+ searcher: SymbolSearcher | None = None,
200
231
  ) -> list[dict[str, object]]:
201
232
  """Return a finding for every definition never referenced elsewhere.
202
233
 
203
- A definition is "unused" when its name never appears in the
234
+ A definition (class, function/method or field) is "unused" when its
235
+ name never appears in the
204
236
  project-wide ``identifiers`` table collected for *session_id*. Names
205
237
  matching any of *ignore_patterns* (e.g. dunder methods, ``main``,
206
- test hooks) are suppressed.
238
+ test hooks) are suppressed. When *searcher* is given, definitions that
239
+ it finds textually referenced in the search paths are suppressed too.
207
240
 
208
241
  Author: Ron Webb
209
242
  Since: 1.0.0
@@ -212,9 +245,20 @@ class SessionStore:
212
245
  rows = self._conn.execute(
213
246
  _SELECT_UNUSED_DEFINITIONS, (session_id,)
214
247
  ).fetchall()
248
+ rows = [
249
+ row for row in rows if not any(p.search(row[3]) for p in ignore_patterns)
250
+ ]
251
+ referenced: set[tuple[str, str, str, str | None]] = set()
252
+ if searcher is not None:
253
+ referenced = searcher.find_referenced(
254
+ [
255
+ (name, kind, file_path, enclosing_class)
256
+ for file_path, _, _, name, kind, enclosing_class in rows
257
+ ]
258
+ )
215
259
  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):
260
+ for file_path, line, col, name, kind, enclosing_class in rows:
261
+ if (name, kind, file_path, enclosing_class) in referenced:
218
262
  continue
219
263
  results.append(
220
264
  {
@@ -16,3 +16,4 @@
16
16
  ^toString$
17
17
  ^equals$
18
18
  ^hashCode$
19
+ ^serialVersionUID$
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "code-prune"
3
- version = "1.1.0"
3
+ version = "1.3.0"
4
4
  description = "Find unreachable, unused, and obsolete code before it becomes technical debt."
5
5
  authors = [
6
6
  {name = "Ron Webb"}
File without changes