code-prune 1.3.0__tar.gz → 1.4.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.
- {code_prune-1.3.0 → code_prune-1.4.0}/CHANGELOG.md +13 -0
- {code_prune-1.3.0 → code_prune-1.4.0}/PKG-INFO +3 -3
- {code_prune-1.3.0 → code_prune-1.4.0}/README.md +2 -2
- {code_prune-1.3.0 → code_prune-1.4.0}/code_prune/__init__.py +1 -1
- {code_prune-1.3.0 → code_prune-1.4.0}/code_prune/cli.py +71 -21
- code_prune-1.4.0/code_prune/searcher.py +273 -0
- {code_prune-1.3.0 → code_prune-1.4.0}/code_prune/store.py +10 -7
- {code_prune-1.3.0 → code_prune-1.4.0}/pyproject.toml +1 -1
- code_prune-1.3.0/code_prune/searcher.py +0 -139
- {code_prune-1.3.0 → code_prune-1.4.0}/LICENSE +0 -0
- {code_prune-1.3.0 → code_prune-1.4.0}/code_prune/.codepruneignore +0 -0
- {code_prune-1.3.0 → code_prune-1.4.0}/code_prune/config.ini +0 -0
- {code_prune-1.3.0 → code_prune-1.4.0}/code_prune/config.py +0 -0
- {code_prune-1.3.0 → code_prune-1.4.0}/code_prune/language_tables.py +0 -0
- {code_prune-1.3.0 → code_prune-1.4.0}/code_prune/logging.ini +0 -0
- {code_prune-1.3.0 → code_prune-1.4.0}/code_prune/parser.py +0 -0
- {code_prune-1.3.0 → code_prune-1.4.0}/code_prune/reporter.py +0 -0
- {code_prune-1.3.0 → code_prune-1.4.0}/code_prune/scanner.py +0 -0
- {code_prune-1.3.0 → code_prune-1.4.0}/code_prune/symbol_ignore +0 -0
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.4.0 - 2026-11-22
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- The `--search-path` textual symbol search now shows a live progress bar
|
|
8
|
+
(file count and elapsed time) while it reads through the search files,
|
|
9
|
+
instead of leaving the CLI apparently idle after the "Scanning" phase
|
|
10
|
+
finishes.
|
|
11
|
+
- The `--search-path` search is much faster on large search sets: each file is
|
|
12
|
+
tokenized once and matched against all candidate names at once (instead of
|
|
13
|
+
testing every candidate against every file), and search files are read in
|
|
14
|
+
parallel using `--workers`. File discovery also uses `os.scandir`.
|
|
15
|
+
|
|
3
16
|
## 1.3.0 - 2026-11-16
|
|
4
17
|
|
|
5
18
|
### Added
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: code-prune
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.4.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
|
-
[](https://github.com/rcw3bb/code-prune/blob/main/LICENSE) [](https://github.com/rcw3bb/code-prune/blob/main/LICENSE) [](https://github.com/rcw3bb/code-prune/blob/main/CHANGELOG.md) [](https://www.python.org/) [](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. |
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# code-prune
|
|
2
2
|
|
|
3
|
-
[](https://github.com/rcw3bb/code-prune/blob/main/LICENSE) [](https://github.com/rcw3bb/code-prune/blob/main/LICENSE) [](https://github.com/rcw3bb/code-prune/blob/main/CHANGELOG.md) [](https://www.python.org/) [](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. |
|
|
@@ -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
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
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
|
|
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
|
-
|
|
645
|
+
_compute_unused_symbols(
|
|
646
|
+
store, session_id, name_ignore_patterns, searcher
|
|
647
|
+
)
|
|
598
648
|
)
|
|
599
649
|
except KeyboardInterrupt:
|
|
600
650
|
interrupted = True
|
|
@@ -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
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
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:
|
|
@@ -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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|