code-prune 1.3.0__tar.gz → 1.5.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,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.5.0 - 2026-11-29
4
+
5
+ ### Changed
6
+
7
+ - `unused-symbol` no longer reports overriding members: Java `@Override`, Gosu
8
+ `override` / `@Override`, TypeScript `override`, and Python `@override` /
9
+ `@typing.override` (including stacked decorators such as `@property`).
10
+ - `unused-symbol` no longer reports Java and Gosu declarations annotated with
11
+ `@SuppressWarnings("unused")` or `@SuppressWarnings("all")` (string, array,
12
+ or `value =` forms). An annotated class exempts all of its members.
13
+
14
+ ## 1.4.0 - 2026-11-22
15
+
16
+ ### Changed
17
+
18
+ - The `--search-path` textual symbol search now shows a live progress bar
19
+ (file count and elapsed time) while it reads through the search files,
20
+ instead of leaving the CLI apparently idle after the "Scanning" phase
21
+ finishes.
22
+ - The `--search-path` search is much faster on large search sets: each file is
23
+ tokenized once and matched against all candidate names at once (instead of
24
+ testing every candidate against every file), and search files are read in
25
+ parallel using `--workers`. File discovery also uses `os.scandir`.
26
+
3
27
  ## 1.3.0 - 2026-11-16
4
28
 
5
29
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: code-prune
3
- Version: 1.3.0
3
+ Version: 1.5.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.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/)
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.5.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,
@@ -120,7 +120,7 @@ Common options:
120
120
  | `--format` | Output format: `json`, `html`, or `all` (default: `json`). |
121
121
  | `--output` | Base output filename without extension (default: `code-prune-output`). |
122
122
  | `--output-dir` | Directory for the report file(s) (default: `reports`). |
123
- | `--workers` | Number of parallel worker threads used to scan files. |
123
+ | `--workers` | Number of parallel worker threads used to scan files and to read `--search-path` files. |
124
124
  | `--db` | Path to the SQLite scratch database used during a scan run. |
125
125
  | `--target-list` | Treat `path` as a file listing target paths, one per line. |
126
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. |
@@ -168,6 +168,12 @@ names to suppress from "unused function/class/method/field" findings — useful
168
168
  dunder methods, `main`, test hooks (`test_*`, `setUp`), `serialVersionUID`, and similar
169
169
  intentionally-unreferenced symbols.
170
170
 
171
+ Overriding members are also never reported as unused symbols: Java `@Override`,
172
+ Gosu `override` / `@Override`, TypeScript `override`, and Python `@override` /
173
+ `@typing.override`. In Java and Gosu, declarations annotated with
174
+ `@SuppressWarnings("unused")` or `@SuppressWarnings("all")` (including a class
175
+ annotated that way, which covers all of its members) are skipped as well.
176
+
171
177
  ## Development
172
178
 
173
179
  Development uses [Poetry](https://python-poetry.org/) `2.2`.
@@ -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.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/)
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.5.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,
@@ -64,7 +64,7 @@ Common options:
64
64
  | `--format` | Output format: `json`, `html`, or `all` (default: `json`). |
65
65
  | `--output` | Base output filename without extension (default: `code-prune-output`). |
66
66
  | `--output-dir` | Directory for the report file(s) (default: `reports`). |
67
- | `--workers` | Number of parallel worker threads used to scan files. |
67
+ | `--workers` | Number of parallel worker threads used to scan files and to read `--search-path` files. |
68
68
  | `--db` | Path to the SQLite scratch database used during a scan run. |
69
69
  | `--target-list` | Treat `path` as a file listing target paths, one per line. |
70
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. |
@@ -112,6 +112,12 @@ names to suppress from "unused function/class/method/field" findings — useful
112
112
  dunder methods, `main`, test hooks (`test_*`, `setUp`), `serialVersionUID`, and similar
113
113
  intentionally-unreferenced symbols.
114
114
 
115
+ Overriding members are also never reported as unused symbols: Java `@Override`,
116
+ Gosu `override` / `@Override`, TypeScript `override`, and Python `@override` /
117
+ `@typing.override`. In Java and Gosu, declarations annotated with
118
+ `@SuppressWarnings("unused")` or `@SuppressWarnings("all")` (including a class
119
+ annotated that way, which covers all of its members) are skipped as well.
120
+
115
121
  ## Development
116
122
 
117
123
  Development uses [Poetry](https://python-poetry.org/) `2.2`.
@@ -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.3.0"
13
+ __version__ = "1.5.0"
14
14
 
15
15
  _bootstrapper = EnvDirBootstrap(
16
16
  env_var="CODE_PRUNE_CONFIG_DIR",
@@ -8,6 +8,7 @@ from __future__ import annotations
8
8
 
9
9
  import concurrent.futures
10
10
  import os
11
+ import re
11
12
  import sys
12
13
  import tempfile
13
14
  import uuid
@@ -276,13 +277,15 @@ def _walk_unignored(
276
277
  Author: Ron Webb
277
278
  Since: 1.0.0
278
279
  """
279
- for entry in root.iterdir():
280
- if ignore is not None and ignore.is_ignored(entry):
281
- continue
282
- if entry.is_dir():
283
- yield from _walk_unignored(entry, ignore)
284
- elif entry.is_file():
285
- yield entry
280
+ with os.scandir(root) as entries:
281
+ for entry in entries:
282
+ path = Path(entry.path)
283
+ if ignore is not None and ignore.is_ignored(path):
284
+ continue
285
+ if entry.is_dir():
286
+ yield from _walk_unignored(path, ignore)
287
+ elif entry.is_file():
288
+ yield path
286
289
 
287
290
 
288
291
  def discover_files(
@@ -324,6 +327,26 @@ def discover_files(
324
327
  return [f for f in candidates if f.suffix.lower() in allowed]
325
328
 
326
329
 
330
+ def _build_progress() -> Progress:
331
+ """Return a :class:`~rich.progress.Progress` with the CLI's standard columns.
332
+
333
+ Shared by every long-running phase (file scanning, symbol search) so they
334
+ all render a spinner, bar, completed-count and elapsed time consistently.
335
+
336
+ Author: Ron Webb
337
+ Since: 1.4.0
338
+ """
339
+ return Progress(
340
+ SpinnerColumn(),
341
+ TextColumn("[progress.description]{task.description}"),
342
+ BarColumn(),
343
+ MofNCompleteColumn(),
344
+ TimeElapsedColumn(),
345
+ console=_console,
346
+ transient=True,
347
+ )
348
+
349
+
327
350
  def _run_concurrent_scan(
328
351
  files: list[Path],
329
352
  store: SessionStore,
@@ -338,15 +361,7 @@ def _run_concurrent_scan(
338
361
  Author: Ron Webb
339
362
  Since: 1.0.0
340
363
  """
341
- with Progress(
342
- SpinnerColumn(),
343
- TextColumn("[progress.description]{task.description}"),
344
- BarColumn(),
345
- MofNCompleteColumn(),
346
- TimeElapsedColumn(),
347
- console=_console,
348
- transient=True,
349
- ) as progress:
364
+ with _build_progress() as progress:
350
365
  task = progress.add_task("[cyan]Scanning\u2026", total=len(files))
351
366
  with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
352
367
  futures = {
@@ -405,7 +420,8 @@ def _run_concurrent_scan(
405
420
  type=int,
406
421
  default=min(32, (os.cpu_count() or 1) + 4),
407
422
  help=(
408
- "Number of parallel worker threads used to scan files "
423
+ "Number of parallel worker threads used to scan files and to read "
424
+ "--search-path files "
409
425
  "(default: min(32, cpu_count + 4))."
410
426
  ),
411
427
  )
@@ -508,7 +524,7 @@ def main( # pylint: disable=too-many-arguments,too-many-positional-arguments,to
508
524
 
509
525
  _console.print(f"[bold]Scanning[/bold] {len(files)} file(s)\u2026")
510
526
 
511
- searcher = _build_searcher(search_paths, search_extensions)
527
+ searcher = _build_searcher(search_paths, search_extensions, workers)
512
528
  findings, interrupted = _scan_project(
513
529
  files, db_path, workers, selected_categories, searcher
514
530
  )
@@ -558,10 +574,12 @@ def _discover_all_files(
558
574
 
559
575
 
560
576
  def _build_searcher(
561
- search_paths: list[Path], search_extensions: list[str]
577
+ search_paths: list[Path], search_extensions: list[str], workers: int = 1
562
578
  ) -> SymbolSearcher | None:
563
579
  """Build a :class:`SymbolSearcher` over *search_paths*, or ``None`` when unset.
564
580
 
581
+ *workers* is the number of threads used to read the search files.
582
+
565
583
  Author: Ron Webb
566
584
  Since: 1.2.0
567
585
  """
@@ -569,7 +587,37 @@ def _build_searcher(
569
587
  return None
570
588
  search_files = _discover_all_files(search_paths, search_extensions, False)
571
589
  _logger.info("Searching %s file(s) for unused-symbol references", len(search_files))
572
- return SymbolSearcher(search_files)
590
+ return SymbolSearcher(search_files, workers)
591
+
592
+
593
+ def _compute_unused_symbols(
594
+ store: SessionStore,
595
+ session_id: str,
596
+ name_ignore_patterns: list[re.Pattern[str]],
597
+ searcher: SymbolSearcher | None,
598
+ ) -> list[dict[str, object]]:
599
+ """Resolve ``unused-symbol`` findings, reporting progress when *searcher* is set.
600
+
601
+ Without a search path this is instant (a single SQL anti-join), so no
602
+ progress bar is shown. With one, every search file has to be read
603
+ textually, which can take a while and would otherwise leave the CLI
604
+ looking unresponsive; a live progress bar is shown in that case.
605
+
606
+ Author: Ron Webb
607
+ Since: 1.4.0
608
+ """
609
+ if searcher is None:
610
+ return store.compute_unused_symbols(session_id, name_ignore_patterns)
611
+ with _build_progress() as progress:
612
+ task = progress.add_task(
613
+ "[cyan]Searching for symbol references\u2026", total=searcher.file_count
614
+ )
615
+ return store.compute_unused_symbols(
616
+ session_id,
617
+ name_ignore_patterns,
618
+ searcher,
619
+ on_progress=lambda: progress.advance(task),
620
+ )
573
621
 
574
622
 
575
623
  def _scan_project(
@@ -594,7 +642,9 @@ def _scan_project(
594
642
  if CATEGORY_UNUSED_SYMBOL in categories:
595
643
  name_ignore_patterns = load_name_ignore_patterns(Path(SYMBOL_IGNORE_PATH))
596
644
  findings.extend(
597
- store.compute_unused_symbols(session_id, name_ignore_patterns, searcher)
645
+ _compute_unused_symbols(
646
+ store, session_id, name_ignore_patterns, searcher
647
+ )
598
648
  )
599
649
  except KeyboardInterrupt:
600
650
  interrupted = True
@@ -145,6 +145,30 @@ DECORATOR_NODE_TYPES: dict[str, frozenset[str]] = {
145
145
  "Gosu": frozenset({"annotation"}),
146
146
  }
147
147
 
148
+ #: Languages whose declarations may carry ``@SuppressWarnings`` annotations.
149
+ SUPPRESSIBLE_LANGUAGES = frozenset({"Java", "Gosu"})
150
+
151
+ #: Annotation node types found inside a ``modifiers`` node, per language.
152
+ ANNOTATION_NODE_TYPES: dict[str, frozenset[str]] = {
153
+ "Java": frozenset({"marker_annotation", "annotation"}),
154
+ "Gosu": frozenset({"annotation"}),
155
+ }
156
+
157
+ #: Name of the annotation that suppresses warnings.
158
+ SUPPRESS_WARNINGS_NAME = "SuppressWarnings"
159
+
160
+ #: ``@SuppressWarnings`` values (lower-case) that suppress unused-symbol findings.
161
+ SUPPRESS_WARNINGS_VALUES = frozenset({"unused", "all"})
162
+
163
+ #: Annotation names marking a method as an override.
164
+ OVERRIDE_ANNOTATION_NAMES = frozenset({"Override"})
165
+
166
+ #: Modifier node types marking a declaration as an override, per language.
167
+ OVERRIDE_MODIFIER_TYPES: dict[str, frozenset[str]] = {
168
+ "TypeScript": frozenset({"override_modifier"}),
169
+ "Gosu": frozenset({"override"}),
170
+ }
171
+
148
172
  #: Identifier-like node types counted as a "usage" of a name.
149
173
  USAGE_NODE_TYPES: dict[str, frozenset[str]] = {
150
174
  "Python": frozenset({"identifier"}),
@@ -37,6 +37,7 @@ from .language_tables import (
37
37
  USAGE_NODE_TYPES,
38
38
  )
39
39
  from .parser import parse
40
+ from .suppression import is_exempt_symbol
40
41
 
41
42
  _logger = logging.getLogger(__name__)
42
43
 
@@ -546,16 +547,17 @@ class _BindingCollector:
546
547
  if name_node is not None:
547
548
  decoded_name = _decode(self._source, name_node)
548
549
  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,
550
+ if not is_exempt_symbol(node, self._source, self._language):
551
+ self.bindings.definitions.append(
552
+ Definition(
553
+ name=decoded_name,
554
+ kind=SYMBOL_KIND_CLASS if is_class else SYMBOL_KIND_FUNCTION,
555
+ file_path=self._file_path,
556
+ line=name_node.start_point[0] + 1,
557
+ column=name_node.start_point[1],
558
+ enclosing_class=None if is_class else scope.enclosing_class,
559
+ )
557
560
  )
558
- )
559
561
  self.bindings.excluded_positions.add(name_node.start_byte)
560
562
  return _Scope(
561
563
  inside_function=scope.inside_function or not is_class,
@@ -573,7 +575,9 @@ class _BindingCollector:
573
575
  if scope.enclosing_class is not None:
574
576
  if node.type in FIELD_NODE_TYPES.get(language, frozenset()):
575
577
  self._add_fields(
576
- _field_name_nodes(node, language), scope.enclosing_class
578
+ _field_name_nodes(node, language),
579
+ scope.enclosing_class,
580
+ exempt=is_exempt_symbol(node, self._source, language),
577
581
  )
578
582
  elif language == "TypeScript" and node.type in FUNCTION_NODE_TYPES.get(
579
583
  language, frozenset()
@@ -591,11 +595,14 @@ class _BindingCollector:
591
595
  if name_node is not None:
592
596
  self._add_fields([name_node], scope.owner_class)
593
597
 
594
- def _add_fields(self, name_nodes: list[Node], class_name: str) -> None:
598
+ def _add_fields(
599
+ self, name_nodes: list[Node], class_name: str, exempt: bool = False
600
+ ) -> None:
595
601
  """Record each of *name_nodes* as a field of *class_name*.
596
602
 
597
603
  Every declaration position is excluded from usages; only the first
598
- declaration of a field yields a :class:`Definition`.
604
+ declaration of a field yields a :class:`Definition`, and *exempt*
605
+ declarations (overrides, ``@SuppressWarnings``) yield none.
599
606
 
600
607
  Author: Ron Webb
601
608
  Since: 1.3.0
@@ -603,7 +610,7 @@ class _BindingCollector:
603
610
  for name_node in name_nodes:
604
611
  self.bindings.excluded_positions.add(name_node.start_byte)
605
612
  decoded_name = _decode(self._source, name_node)
606
- if (class_name, decoded_name) in self._seen_fields:
613
+ if exempt or (class_name, decoded_name) in self._seen_fields:
607
614
  continue
608
615
  self._seen_fields.add((class_name, decoded_name))
609
616
  self.bindings.definitions.append(
@@ -0,0 +1,273 @@
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
+ Each search file is read and tokenized once (``[\\w$]+`` words) and the tokens
12
+ are intersected with the set of names being looked for, so the cost per file
13
+ does not grow with the number of candidates. Files are read on a thread pool
14
+ and consumed in order, keeping early exit and progress reporting deterministic.
15
+
16
+ Author: Ron Webb
17
+ Since: 1.2.0
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import concurrent.futures
23
+ import re
24
+ from collections import deque
25
+ from collections.abc import Callable, Iterable, Iterator
26
+ from itertools import islice
27
+ from pathlib import Path
28
+
29
+ #: ``(name, kind, defining_file, enclosing_class)``. ``enclosing_class`` is
30
+ #: ``None`` for classes and free functions.
31
+ Candidate = tuple[str, str, str, str | None]
32
+
33
+ _WORD_RE = re.compile(r"[\w$]+")
34
+ _PLAIN_NAME_RE = re.compile(r"[\w$]+")
35
+ #: In-flight read tasks per worker thread; bounds memory held by pending reads.
36
+ _WINDOW_PER_WORKER = 4
37
+
38
+
39
+ def _build_pattern(name: str) -> re.Pattern[str]:
40
+ """Return a whole-word regex for *name* that also treats ``$`` as a word character.
41
+
42
+ Author: Ron Webb
43
+ Since: 1.2.0
44
+ """
45
+ return re.compile(rf"(?<![\w$]){re.escape(name)}(?![\w$])")
46
+
47
+
48
+ def _read_text(file_path: Path) -> str | None:
49
+ """Return the text of *file_path*, or ``None`` for unreadable/binary files.
50
+
51
+ Author: Ron Webb
52
+ Since: 1.2.0
53
+ """
54
+ try:
55
+ data = file_path.read_bytes()
56
+ except OSError:
57
+ return None
58
+ if b"\x00" in data:
59
+ return None
60
+ return data.decode("utf-8", errors="replace")
61
+
62
+
63
+ def _read_names(
64
+ file_path: Path,
65
+ plain_names: frozenset[str],
66
+ special_patterns: dict[str, re.Pattern[str]],
67
+ ) -> tuple[set[str], str] | None:
68
+ """Return ``(names_present, resolved_path)`` for *file_path*, or ``None``.
69
+
70
+ *plain_names* consist solely of word characters, so they are found by one
71
+ tokenization pass. *special_patterns* holds the rare other names, each
72
+ looked up with its own whole-word regex. ``None`` marks an unreadable or
73
+ binary file.
74
+
75
+ Author: Ron Webb
76
+ Since: 1.4.0
77
+ """
78
+ text = _read_text(file_path)
79
+ if text is None:
80
+ return None
81
+ present = set(plain_names.intersection(_WORD_RE.findall(text)))
82
+ for name, pattern in special_patterns.items():
83
+ if name in text and pattern.search(text):
84
+ present.add(name)
85
+ return present, _resolve(file_path)
86
+
87
+
88
+ class _CandidateIndex:
89
+ """Pending candidates grouped by name, for lookups against a file's names.
90
+
91
+ Author: Ron Webb
92
+ Since: 1.4.0
93
+ """
94
+
95
+ def __init__(self, candidates: Iterable[Candidate]) -> None:
96
+ """Group *candidates* by name and derive the names to search for.
97
+
98
+ Author: Ron Webb
99
+ Since: 1.4.0
100
+ """
101
+ self._by_name: dict[str, list[Candidate]] = {}
102
+ self._resolved_files: dict[str, str] = {}
103
+ needed: set[str] = set()
104
+ for candidate in set(candidates):
105
+ name, _, _, enclosing_class = candidate
106
+ self._by_name.setdefault(name, []).append(candidate)
107
+ needed.add(name)
108
+ if enclosing_class:
109
+ needed.add(enclosing_class)
110
+ self.plain_names = frozenset(n for n in needed if _PLAIN_NAME_RE.fullmatch(n))
111
+ self.special_patterns = {
112
+ n: _build_pattern(n) for n in needed if n not in self.plain_names
113
+ }
114
+
115
+ def __bool__(self) -> bool:
116
+ """Return whether any candidate is still unresolved.
117
+
118
+ Author: Ron Webb
119
+ Since: 1.4.0
120
+ """
121
+ return bool(self._by_name)
122
+
123
+ def resolve(self, names_present: set[str], resolved_file: str) -> set[Candidate]:
124
+ """Remove and return the candidates referenced by a file.
125
+
126
+ A plain class or free function matches once its own name is present. A
127
+ method or field (``enclosing_class`` set) additionally requires its
128
+ enclosing class's name to be present. A candidate's own defining file
129
+ never counts.
130
+
131
+ Author: Ron Webb
132
+ Since: 1.4.0
133
+ """
134
+ hits: set[Candidate] = set()
135
+ for name in names_present.intersection(self._by_name):
136
+ remaining: list[Candidate] = []
137
+ for candidate in self._by_name[name]:
138
+ _, _, defining_file, enclosing_class = candidate
139
+ if self._is_own_file(defining_file, resolved_file) or (
140
+ enclosing_class and enclosing_class not in names_present
141
+ ):
142
+ remaining.append(candidate)
143
+ else:
144
+ hits.add(candidate)
145
+ if remaining:
146
+ self._by_name[name] = remaining
147
+ else:
148
+ del self._by_name[name]
149
+ return hits
150
+
151
+ def _is_own_file(self, defining_file: str, resolved_file: str) -> bool:
152
+ """Return whether *defining_file* is the file at *resolved_file*.
153
+
154
+ Each defining file is resolved on the file system only once.
155
+
156
+ Author: Ron Webb
157
+ Since: 1.4.0
158
+ """
159
+ if defining_file not in self._resolved_files:
160
+ self._resolved_files[defining_file] = _resolve(Path(defining_file))
161
+ return self._resolved_files[defining_file] == resolved_file
162
+
163
+
164
+ class SymbolSearcher:
165
+ """Find which symbols are textually referenced in a set of search files.
166
+
167
+ Author: Ron Webb
168
+ Since: 1.2.0
169
+ """
170
+
171
+ def __init__(self, search_files: list[Path], workers: int = 1) -> None:
172
+ """Store the files to search and the number of reader threads.
173
+
174
+ Author: Ron Webb
175
+ Since: 1.2.0
176
+ """
177
+ self._search_files = search_files
178
+ self._workers = max(1, workers)
179
+
180
+ @property
181
+ def file_count(self) -> int:
182
+ """Return the number of search files this searcher was built with.
183
+
184
+ Lets callers (e.g. the CLI) size a progress indicator without
185
+ reaching into the private file list.
186
+
187
+ Author: Ron Webb
188
+ Since: 1.4.0
189
+ """
190
+ return len(self._search_files)
191
+
192
+ def find_referenced(
193
+ self,
194
+ candidates: list[Candidate],
195
+ on_progress: Callable[[], None] | None = None,
196
+ ) -> set[Candidate]:
197
+ """Return the subset of *candidates* found in the search files.
198
+
199
+ The candidate's own defining file is never counted as a reference.
200
+ Every search file is read once and the search stops as soon as every
201
+ candidate has been resolved. When given, *on_progress* is called once
202
+ per search file considered (including skipped/binary/missing ones and
203
+ the one that resolves the last pending candidate), so a caller can
204
+ drive a progress indicator over a potentially long-running search.
205
+
206
+ Author: Ron Webb
207
+ Since: 1.2.0
208
+ """
209
+ index = _CandidateIndex(candidates)
210
+ found: set[Candidate] = set()
211
+ if not index:
212
+ return found
213
+ results = self._iter_file_names(index.plain_names, index.special_patterns)
214
+ try:
215
+ for result in results:
216
+ if result is not None:
217
+ names_present, resolved_file = result
218
+ found.update(index.resolve(names_present, resolved_file))
219
+ if on_progress is not None:
220
+ on_progress()
221
+ if not index:
222
+ break
223
+ finally:
224
+ results.close()
225
+ return found
226
+
227
+ def _iter_file_names(
228
+ self,
229
+ plain_names: frozenset[str],
230
+ special_patterns: dict[str, re.Pattern[str]],
231
+ ) -> Iterator[tuple[set[str], str] | None]:
232
+ """Yield :func:`_read_names` for every search file, in file order.
233
+
234
+ With more than one worker, files are read ahead on a thread pool
235
+ through a bounded window; leftover reads are cancelled when the
236
+ consumer stops early.
237
+
238
+ Author: Ron Webb
239
+ Since: 1.4.0
240
+ """
241
+
242
+ def read(file_path: Path) -> tuple[set[str], str] | None:
243
+ return _read_names(file_path, plain_names, special_patterns)
244
+
245
+ files = iter(self._search_files)
246
+ if self._workers == 1:
247
+ yield from map(read, files)
248
+ return
249
+ with concurrent.futures.ThreadPoolExecutor(self._workers) as executor:
250
+ window = deque(
251
+ executor.submit(read, f)
252
+ for f in islice(files, self._workers * _WINDOW_PER_WORKER)
253
+ )
254
+ try:
255
+ while window:
256
+ result = window.popleft().result()
257
+ window.extend(executor.submit(read, f) for f in islice(files, 1))
258
+ yield result
259
+ finally:
260
+ for future in window:
261
+ future.cancel()
262
+
263
+
264
+ def _resolve(path: Path) -> str:
265
+ """Return a normalised string form of *path* for own-file comparison.
266
+
267
+ Author: Ron Webb
268
+ Since: 1.2.0
269
+ """
270
+ try:
271
+ return str(path.resolve())
272
+ except OSError:
273
+ return str(path.absolute())
@@ -18,6 +18,7 @@ from __future__ import annotations
18
18
  import re
19
19
  import sqlite3
20
20
  import threading
21
+ from collections.abc import Callable
21
22
  from pathlib import Path
22
23
 
23
24
  from .scanner import CATEGORY_UNUSED_SYMBOL, Definition, Finding
@@ -228,6 +229,7 @@ class SessionStore:
228
229
  session_id: str,
229
230
  ignore_patterns: list[re.Pattern[str]],
230
231
  searcher: SymbolSearcher | None = None,
232
+ on_progress: Callable[[], None] | None = None,
231
233
  ) -> list[dict[str, object]]:
232
234
  """Return a finding for every definition never referenced elsewhere.
233
235
 
@@ -236,7 +238,9 @@ class SessionStore:
236
238
  project-wide ``identifiers`` table collected for *session_id*. Names
237
239
  matching any of *ignore_patterns* (e.g. dunder methods, ``main``,
238
240
  test hooks) are suppressed. When *searcher* is given, definitions that
239
- it finds textually referenced in the search paths are suppressed too.
241
+ it finds textually referenced in the search paths are suppressed too;
242
+ *on_progress* (forwarded to the searcher) lets a caller drive a
243
+ progress indicator over that, potentially long-running, search.
240
244
 
241
245
  Author: Ron Webb
242
246
  Since: 1.0.0
@@ -250,12 +254,11 @@ class SessionStore:
250
254
  ]
251
255
  referenced: set[tuple[str, str, str, str | None]] = set()
252
256
  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
- )
257
+ candidates = [
258
+ (name, kind, file_path, enclosing_class)
259
+ for file_path, _, _, name, kind, enclosing_class in rows
260
+ ]
261
+ referenced = searcher.find_referenced(candidates, on_progress)
259
262
  results: list[dict[str, object]] = []
260
263
  for file_path, line, col, name, kind, enclosing_class in rows:
261
264
  if (name, kind, file_path, enclosing_class) in referenced:
@@ -0,0 +1,192 @@
1
+ """Detection of declarations exempt from ``unused-symbol`` findings.
2
+
3
+ A declaration is exempt when it overrides an inherited member (it is invoked
4
+ through its base type, so it never has a textual usage) or, for Java and Gosu,
5
+ when it (or an enclosing class) carries ``@SuppressWarnings`` with ``"unused"``
6
+ or ``"all"``.
7
+
8
+ Author: Ron Webb
9
+ Since: 1.5.0
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from tree_sitter import Node # type: ignore[import-untyped]
15
+
16
+ from .language_tables import (
17
+ ANNOTATION_NODE_TYPES,
18
+ OVERRIDE_ANNOTATION_NAMES,
19
+ OVERRIDE_MODIFIER_TYPES,
20
+ SUPPRESS_WARNINGS_NAME,
21
+ SUPPRESS_WARNINGS_VALUES,
22
+ SUPPRESSIBLE_LANGUAGES,
23
+ )
24
+
25
+ _STRING_NODE_TYPE = "string_literal"
26
+ _MODIFIERS_NODE_TYPE = "modifiers"
27
+ _DECORATED_NODE_TYPE = "decorated_definition"
28
+ _DECORATOR_NODE_TYPE = "decorator"
29
+ _PYTHON_OVERRIDE_NAME = "override"
30
+
31
+
32
+ def _decode(source_bytes: bytes, node: Node) -> str:
33
+ """Return the source text covered by *node*.
34
+
35
+ Author: Ron Webb
36
+ Since: 1.5.0
37
+ """
38
+ return source_bytes[node.start_byte : node.end_byte].decode(
39
+ "utf-8", errors="replace"
40
+ )
41
+
42
+
43
+ def _simple_name(text: str) -> str:
44
+ """Return the last dotted segment of *text* (``a.b.C`` -> ``C``).
45
+
46
+ Author: Ron Webb
47
+ Since: 1.5.0
48
+ """
49
+ return text.strip().rsplit(".", maxsplit=1)[-1]
50
+
51
+
52
+ def _modifier_nodes(node: Node, language: str) -> list[Node]:
53
+ """Return the ``modifiers`` nodes attached to the declaration *node*.
54
+
55
+ Java holds ``modifiers`` as a child; Gosu places it as the preceding
56
+ sibling of the declaration (so a Gosu node's own children are never its
57
+ modifiers, e.g. a ``class_body`` holds its members' modifiers).
58
+
59
+ Author: Ron Webb
60
+ Since: 1.5.0
61
+ """
62
+ if language == "Java":
63
+ return [child for child in node.children if child.type == _MODIFIERS_NODE_TYPE]
64
+ previous = node.prev_named_sibling
65
+ if previous is not None and previous.type == _MODIFIERS_NODE_TYPE:
66
+ return [previous]
67
+ return []
68
+
69
+
70
+ def _annotations(node: Node, language: str) -> list[Node]:
71
+ """Return the annotation nodes applied to the declaration *node*.
72
+
73
+ Author: Ron Webb
74
+ Since: 1.5.0
75
+ """
76
+ annotation_types = ANNOTATION_NODE_TYPES.get(language, frozenset())
77
+ return [
78
+ child
79
+ for modifiers in _modifier_nodes(node, language)
80
+ for child in modifiers.children
81
+ if child.type in annotation_types
82
+ ]
83
+
84
+
85
+ def _annotation_name(annotation: Node, source_bytes: bytes) -> str:
86
+ """Return the simple name of *annotation* (``@a.B(...)`` -> ``B``).
87
+
88
+ Author: Ron Webb
89
+ Since: 1.5.0
90
+ """
91
+ for child in annotation.named_children:
92
+ if child.type in {"identifier", "qualified_name", "scoped_identifier"}:
93
+ return _simple_name(_decode(source_bytes, child))
94
+ return ""
95
+
96
+
97
+ def _string_arguments(annotation: Node, source_bytes: bytes) -> set[str]:
98
+ """Return the lower-cased string literal values passed to *annotation*.
99
+
100
+ Author: Ron Webb
101
+ Since: 1.5.0
102
+ """
103
+ values: set[str] = set()
104
+ pending = list(annotation.children)
105
+ while pending:
106
+ node = pending.pop()
107
+ if node.type == _STRING_NODE_TYPE:
108
+ values.add(_decode(source_bytes, node).strip("\"'").lower())
109
+ else:
110
+ pending.extend(node.children)
111
+ return values
112
+
113
+
114
+ def _is_suppressed_here(node: Node, source_bytes: bytes, language: str) -> bool:
115
+ """Return whether *node* itself carries a matching ``@SuppressWarnings``.
116
+
117
+ Author: Ron Webb
118
+ Since: 1.5.0
119
+ """
120
+ return any(
121
+ _annotation_name(annotation, source_bytes) == SUPPRESS_WARNINGS_NAME
122
+ and _string_arguments(annotation, source_bytes) & SUPPRESS_WARNINGS_VALUES
123
+ for annotation in _annotations(node, language)
124
+ )
125
+
126
+
127
+ def _is_suppressed(node: Node, source_bytes: bytes, language: str) -> bool:
128
+ """Return whether *node* or any enclosing declaration suppresses ``unused``.
129
+
130
+ Author: Ron Webb
131
+ Since: 1.5.0
132
+ """
133
+ if language not in SUPPRESSIBLE_LANGUAGES:
134
+ return False
135
+ current: Node | None = node
136
+ while current is not None:
137
+ if _is_suppressed_here(current, source_bytes, language):
138
+ return True
139
+ current = current.parent
140
+ return False
141
+
142
+
143
+ def _python_overrides(node: Node, source_bytes: bytes) -> bool:
144
+ """Return whether the Python definition *node* is decorated ``@override``.
145
+
146
+ Author: Ron Webb
147
+ Since: 1.5.0
148
+ """
149
+ parent = node.parent
150
+ if parent is None or parent.type != _DECORATED_NODE_TYPE:
151
+ return False
152
+ return any(
153
+ _simple_name(_decode(source_bytes, child).lstrip("@")) == _PYTHON_OVERRIDE_NAME
154
+ for child in parent.children
155
+ if child.type == _DECORATOR_NODE_TYPE
156
+ )
157
+
158
+
159
+ def _is_override(node: Node, source_bytes: bytes, language: str) -> bool:
160
+ """Return whether *node* is explicitly marked as overriding a member.
161
+
162
+ Author: Ron Webb
163
+ Since: 1.5.0
164
+ """
165
+ if language == "Python":
166
+ return _python_overrides(node, source_bytes)
167
+ modifier_types = OVERRIDE_MODIFIER_TYPES.get(language, frozenset())
168
+ if any(child.type in modifier_types for child in node.children):
169
+ return True
170
+ if language not in SUPPRESSIBLE_LANGUAGES:
171
+ return False
172
+ if any(
173
+ child.type in modifier_types
174
+ for modifiers in _modifier_nodes(node, language)
175
+ for child in modifiers.children
176
+ ):
177
+ return True
178
+ return any(
179
+ _annotation_name(annotation, source_bytes) in OVERRIDE_ANNOTATION_NAMES
180
+ for annotation in _annotations(node, language)
181
+ )
182
+
183
+
184
+ def is_exempt_symbol(node: Node, source_bytes: bytes, language: str) -> bool:
185
+ """Return whether the declaration *node* must not be an unused-symbol finding.
186
+
187
+ Author: Ron Webb
188
+ Since: 1.5.0
189
+ """
190
+ return _is_override(node, source_bytes, language) or _is_suppressed(
191
+ node, source_bytes, language
192
+ )
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "code-prune"
3
- version = "1.3.0"
3
+ version = "1.5.0"
4
4
  description = "Find unreachable, unused, and obsolete code before it becomes technical debt."
5
5
  authors = [
6
6
  {name = "Ron Webb"}
@@ -1,139 +0,0 @@
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())
File without changes