diff --git a/README.md b/README.md
index d1c677d..eb5d4ce 100644
--- a/README.md
+++ b/README.md
@@ -3,6 +3,7 @@
Repository for various python utility scripts
- [pyutils-unusedcode](https://github.com/RedHatQE/python-utility-scripts/blob/main/apps/unused_code/README.md)
+- [pyutils-unusedconstants](https://github.com/RedHatQE/python-utility-scripts/blob/main/apps/unused_constants/README.md)
- [pyutils-polarion-verify-tc-requirements](https://github.com/RedHatQE/python-utility-scripts/blob/main/apps/polarion/README.md)
- [pyutils-jira](https://github.com/RedHatQE/python-utility-scripts/blob/main/apps/jira_utils/README.md)
- [pyutils-polarion-set-automated](https://github.com/RedHatQE/python-utility-scripts/blob/main/apps/polarion/README.md)
diff --git a/apps/git_grep_utils.py b/apps/git_grep_utils.py
new file mode 100644
index 0000000..b14765b
--- /dev/null
+++ b/apps/git_grep_utils.py
@@ -0,0 +1,74 @@
+from __future__ import annotations
+
+import os
+import subprocess
+from functools import lru_cache
+from pathlib import Path
+
+from simple_logger.logger import get_logger
+
+LOGGER = get_logger(name=__name__)
+
+
+@lru_cache(maxsize=1)
+def detect_supported_grep_flag() -> str:
+ r"""Detect and cache a supported regex engine flag for git grep.
+
+ Prefer PCRE ("-P") for proper \b handling; fall back to basic regex ("-G").
+ Run a harmless grep to verify support and cache the first working flag.
+ Uses lru_cache for thread-safe caching that runs only once per process.
+ """
+ candidate_flags = ["-P", "-G"]
+ for flag in candidate_flags:
+ try:
+ probe_cmd = [
+ "git",
+ "grep",
+ "-n",
+ "--no-color",
+ "--untracked",
+ "-I",
+ flag,
+ "^$",
+ ]
+ result = subprocess.run(probe_cmd, check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ if result.returncode in (0, 1):
+ return flag
+ except (OSError, subprocess.SubprocessError):
+ LOGGER.debug(f"git grep flag {flag!r} probe failed, trying next candidate")
+
+ raise RuntimeError(
+ "git grep does not support '-P' (PCRE) or '-G' (basic regex) on this platform. "
+ "Please ensure a compatible git/grep is installed."
+ )
+
+
+def wrap_grep_word(body: str, *, flag: str | None = None) -> str:
+ r"""Wrap `body` in word boundaries for a git grep engine.
+
+ - PCRE (-P): \bbody\b
+ - Basic (-G): \
+ """
+ if (flag or detect_supported_grep_flag()) == "-P":
+ return rf"\b{body}\b"
+ return rf"\<{body}\>"
+
+
+def find_git_root(file_path: str) -> str:
+ """Return the git repository root containing `file_path`."""
+ path = Path(file_path).resolve().parent
+
+ while path != path.parent:
+ if (path / ".git").exists():
+ return str(path)
+ path = path.parent
+
+ return os.getcwd()
+
+
+def resolve_absolute_path(git_grep_path: str, reference_file: str) -> str:
+ """Convert a git grep path to an absolute path if needed."""
+ if not os.path.isabs(git_grep_path):
+ git_root = find_git_root(reference_file)
+ return os.path.join(git_root, git_grep_path)
+ return git_grep_path
diff --git a/apps/unused_code/unused_code.py b/apps/unused_code/unused_code.py
index 1e27db1..decf69e 100644
--- a/apps/unused_code/unused_code.py
+++ b/apps/unused_code/unused_code.py
@@ -8,55 +8,27 @@
import sys
from collections.abc import Callable, Iterable
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
-from functools import lru_cache
-from pathlib import Path
from typing import Any
import click
from ast_comments import parse
from simple_logger.logger import get_logger
+from apps.git_grep_utils import (
+ detect_supported_grep_flag as _detect_supported_grep_flag,
+)
+from apps.git_grep_utils import (
+ find_git_root as _find_git_root,
+)
+from apps.git_grep_utils import (
+ resolve_absolute_path as _resolve_absolute_path,
+)
+from apps.git_grep_utils import wrap_grep_word
from apps.utils import ListParamType, all_python_files, get_util_config
LOGGER = get_logger(name=__name__)
-@lru_cache(maxsize=1)
-def _detect_supported_grep_flag() -> str:
- r"""Detect and cache a supported regex engine flag for git grep.
-
- Prefer PCRE ("-P") for proper \b handling; fall back to basic regex ("-G").
- Run a harmless grep to verify support and cache the first working flag.
- Uses lru_cache for thread-safe caching that runs only once per process.
- """
- candidate_flags = ["-P", "-G"]
- for flag in candidate_flags:
- try:
- # Use a trivial pattern to minimize output. We only care that the flag is accepted.
- # Discard stdout/stderr to prevent capturing large data in big repositories.
- probe_cmd = [
- "git",
- "grep",
- "-n",
- "--no-color",
- "--untracked",
- "-I",
- flag,
- "^$", # match empty lines; success (rc=0) or no matches (rc=1) are both fine
- ]
- result = subprocess.run(probe_cmd, check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- if result.returncode in (0, 1):
- return flag
- except (OSError, subprocess.SubprocessError):
- # Try next candidate
- LOGGER.debug(f"git grep flag {flag!r} probe failed, trying next candidate")
-
- raise RuntimeError(
- "git grep does not support '-P' (PCRE) or '-G' (basic regex) on this platform. "
- "Please ensure a compatible git/grep is installed."
- )
-
-
def is_fixture_autouse(func: ast.FunctionDef) -> bool:
deco_list: list[Any] = func.decorator_list
for deco in deco_list or []:
@@ -111,19 +83,8 @@ def is_pytest_fixture(func: ast.FunctionDef) -> bool:
def _build_usage_pattern(function_name: str) -> str:
- r"""Build a portable regex to match function usages.
-
- Uses word boundary semantics based on the detected grep engine.
- The pattern is designed to match function calls as well as references
- (e.g., when passed as an argument).
- - PCRE (-P): \bname\b
- - Basic (-G): \
- """
- flag = _detect_supported_grep_flag()
- if flag == "-P":
- return rf"\b{function_name}\b"
- # -G basic regex: use word-start and word-end tokens
- return rf"\<{function_name}\>"
+ """Build a portable regex to match a function name as a whole word."""
+ return wrap_grep_word(function_name, flag=_detect_supported_grep_flag())
def _build_fixture_param_pattern(function_name: str) -> str:
@@ -367,26 +328,6 @@ def _is_documentation_pattern(line: str, function_name: str) -> bool:
return any(stripped_line.startswith(starter) for starter in doc_starters) and f"{function_name}(" in stripped_line
-def _find_git_root(file_path: str) -> str:
- """Find the git repository root for a given file path.
-
- Args:
- file_path: Path to a file within a git repository
-
- Returns:
- The git repository root path
- """
- path = Path(file_path).resolve().parent
-
- while path != path.parent: # Stop at filesystem root
- if (path / ".git").exists():
- return str(path)
- path = path.parent
-
- # Fallback to current directory (we know it's a git repo from the main check)
- return os.getcwd()
-
-
def _git_grep(pattern: str, file_path: str | None = None) -> list[str]:
"""Run git grep with a pattern and return matching lines.
@@ -448,14 +389,6 @@ def is_ignore_function_list(ignore_prefix_list: list[str], function: ast.Functio
return bool(ignore_function_lists)
-def _resolve_absolute_path(git_grep_path: str, reference_file: str) -> str:
- """Convert git grep path to absolute path if needed."""
- if not os.path.isabs(git_grep_path):
- git_root = _find_git_root(reference_file)
- return os.path.join(git_root, git_grep_path)
- return git_grep_path
-
-
def process_file(py_file: str, func_ignore_prefix: list[str], file_ignore_list: list[str]) -> str:
if os.path.basename(py_file) in file_ignore_list:
LOGGER.debug(f"Skipping file: {py_file}")
diff --git a/apps/unused_constants/README.md b/apps/unused_constants/README.md
new file mode 100644
index 0000000..5705809
--- /dev/null
+++ b/apps/unused_constants/README.md
@@ -0,0 +1,128 @@
+# pyutils-unusedconstants
+
+Helper to identify unused module-level constants in a pytest repository. It should be run from inside the test repository using this tool.
+
+## Usage
+
+### Basic Usage
+
+```bash
+# Analyze Python files in the current directory (must be a git repository)
+pyutils-unusedconstants
+
+# Show help with all available options
+pyutils-unusedconstants --help
+```
+
+### Analyze specific files or directories
+
+```bash
+# Analyze a single Python file
+pyutils-unusedconstants --file-path /path/to/your/file.py
+pyutils-unusedconstants -f /path/to/your/file.py
+
+# Analyze all Python files in a specific directory recursively
+pyutils-unusedconstants --directory /path/to/your/project
+pyutils-unusedconstants -d /path/to/your/project
+
+# Limit analysis to specific paths (relative to git root)
+pyutils-unusedconstants --include-files "utilities/constants.py,tests/conftest.py"
+```
+
+**Note:** When using `--file-path` or `--directory`, the tool analyzes files from any git repository, not just the current working directory; the repository root is resolved with `git rev-parse --show-toplevel`.
+
+Exit codes match `pyutils-unusedcode`: `0` when nothing is reported, `1` when
+unused constants are found or when the run cannot continue (for example not in
+a git repository, bad `--file-path`/`--directory`, or `git grep` failure).
+
+Reported paths are relative to the git root, matching `--include-files`.
+
+Unparseable files are skipped with a warning rather than failing the run.
+
+## Command-Line Options
+
+| Option | Short | Description |
+|--------|-------|-------------|
+| `--file-path` | `-f` | Analyze a single Python file for unused module-level constants. |
+| `--directory` | `-d` | Analyze all Python files in a directory recursively. |
+| `--include-files` | | Comma-separated list of paths or globs to include, relative to the git root (e.g. `utilities/constants.py`, `tests/*/consts.py`). A bare `constants.py` matches only the file at the repository root, not every `constants.py` in the tree. |
+| `--exclude-files` | | Comma-separated list of file basenames to exclude from analysis. |
+| `--exclude-names` | | Comma-separated list of constant names to exclude. |
+| `--uppercase-only` / `--all-names` | | When `--uppercase-only` (default), only check `ALL_CAPS` names. |
+| `--config-file-path` | | Path to custom config file (default: `~/.config/python-utility-scripts/config.yaml`). |
+| `--verbose` | `-v` | Enable verbose logging for debugging. |
+| `--help` | | Show help message with all available options. |
+
+## What counts as a usage
+
+A constant is reported when no occurrence of its name is found anywhere in the
+repository, other than a line in its own file that binds it. The search is
+textual, over tracked and untracked files of every type, so the following count
+as usages and the constant is **not** reported:
+
+- the name inside a string literal or a docstring
+- the name in a non-Python file: Markdown, YAML, JSON, a test parameter id
+- the same name defined in another module, if that other one is used. Two
+ parallel constants modules both defining `TIMEOUT` mask each other: a single
+ use of `tests/network/constants.py`'s `TIMEOUT` marks
+ `tests/storage/constants.py`'s `TIMEOUT` used as well, so duplicated names
+ across sibling modules are exactly the case this will not report
+- the name referenced only by other dead code
+
+A clean run therefore means "no unused constant was proved", not "there are
+none". Findings are reliable; their absence is not. The uppercase-only default
+also means lowercase module-level names are skipped unless `--all-names` is
+given, and constants bound in a class body are never module level.
+
+## Library use
+
+`process_file_constants` and `find_used_constants` are importable. They resolve
+the repository root from the files they are given, so the caller's working
+directory does not matter and need not be inside the repository.
+
+`find_used_constants` raises `RuntimeError` when the paths are not in a git
+repository or when `git grep` fails (the CLI logs the error and exits `1`).
+
+All paths passed to `find_used_constants` must live in one git repository; the
+root is taken from the first file when `repository_root` is omitted.
+
+Usage is resolved with one `git grep` per call (character-class pattern, then
+tokenising in Python), not one search per constant.
+
+Each `process_file_constants` call runs its own repository scan. That is fine
+for a single file, but looping it over many files runs one scan per file; use
+`collect_file_constants` for each file and then one `find_used_constants` over
+the union, which is what the CLI does.
+
+## Config file
+
+To skip unused constant checks on specific files or names, add a config section to
+`~/.config/python-utility-scripts/config.yaml`
+
+### Example
+
+```yaml
+pyutils-unusedconstants:
+ include_files:
+ - "utilities/constants.py"
+ - "tests/conftest.py"
+ exclude_files:
+ - "my_exclude_file.py"
+ exclude_names:
+ - "__all__"
+ uppercase_only: true
+```
+
+To run from CLI with `--exclude-names`
+
+```bash
+pyutils-unusedconstants --exclude-names '__all__,MY_LEGACY_CONSTANT'
+```
+
+### Skip a single constant
+
+Add `# skip-unused-code` on the same line as the assignment:
+
+```python
+MY_CONSTANT = "value" # skip-unused-code
+```
diff --git a/apps/unused_constants/__init__.py b/apps/unused_constants/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/apps/unused_constants/unused_constants.py b/apps/unused_constants/unused_constants.py
new file mode 100644
index 0000000..915b814
--- /dev/null
+++ b/apps/unused_constants/unused_constants.py
@@ -0,0 +1,543 @@
+from __future__ import annotations
+
+import ast
+import fnmatch
+import logging
+import os
+import re
+import subprocess
+import sys
+import tempfile
+from collections import defaultdict
+from collections.abc import Generator, Iterable
+from contextlib import contextmanager
+
+import click
+from ast_comments import parse
+from simple_logger.logger import get_logger
+
+from apps.git_grep_utils import (
+ detect_supported_grep_flag as _detect_supported_grep_flag,
+)
+from apps.git_grep_utils import (
+ find_git_root as _find_git_root,
+)
+from apps.git_grep_utils import (
+ resolve_absolute_path as _resolve_absolute_path,
+)
+from apps.git_grep_utils import wrap_grep_word
+from apps.utils import ListParamType, all_python_files, get_util_config
+
+LOGGER = get_logger(name=__name__)
+
+UPPERCASE_CONSTANT_RE = re.compile(r"^[A-Z][A-Z0-9_]*$")
+IDENTIFIER_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
+SKIP_UNUSED_CODE_MARKER = "# skip-unused-code"
+
+
+def _iter_target_names(target: ast.expr) -> Iterable[ast.Name]:
+ """Yield every Name bound by an assignment target, including unpacking."""
+ if isinstance(target, ast.Name):
+ yield target
+ elif isinstance(target, (ast.Tuple, ast.List)):
+ for element in target.elts:
+ yield from _iter_target_names(target=element)
+ elif isinstance(target, ast.Starred):
+ yield from _iter_target_names(target=target.value)
+
+
+def _iter_module_level_constants(tree: ast.Module) -> Iterable[tuple[str, int, int]]:
+ """Yield (name, lineno, col_offset) for module-level bindings.
+
+ Descends into module-level if/try/with; not into class or function bodies.
+ """
+ constants: list[tuple[str, int, int]] = []
+ pending: list[ast.stmt] = list(tree.body)
+
+ while pending:
+ element = pending.pop()
+
+ if isinstance(element, (ast.If, ast.Try, ast.With)):
+ for block in ("body", "orelse", "finalbody"):
+ pending.extend(getattr(element, block, None) or [])
+ for handler in getattr(element, "handlers", None) or []:
+ pending.extend(handler.body)
+ continue
+
+ if isinstance(element, ast.Assign):
+ for target in element.targets:
+ for name in _iter_target_names(target=target):
+ constants.append((name.id, element.lineno, name.col_offset))
+ elif isinstance(element, ast.AnnAssign) and isinstance(element.target, ast.Name):
+ constants.append((element.target.id, element.lineno, element.target.col_offset))
+
+ # Nested blocks are visited out of order; sort so callers see source order and
+ # the first binding of a repeated name is the earliest one in the file.
+ yield from sorted(constants, key=lambda constant: (constant[1], constant[2]))
+
+
+def _has_skip_unused_code_comment(source_lines: list[str], lineno: int) -> bool:
+ if lineno < 1 or lineno > len(source_lines):
+ return False
+ return SKIP_UNUSED_CODE_MARKER in source_lines[lineno - 1]
+
+
+def _is_uppercase_constant(name: str) -> bool:
+ return bool(UPPERCASE_CONSTANT_RE.match(name))
+
+
+COMPARISON_OPERATOR_TAIL_RE = re.compile(r"[=!<>+\-*/%&|^~]$|//$|\*\*$|>>$|<<$")
+
+
+def _is_constant_definition_line(line_content: str, constant_name: str) -> bool:
+ """Return True when the line binds `constant_name` rather than reading it."""
+ code_part = line_content.split("#", 1)[0].strip()
+
+ name_colon = re.match(rf"^{re.escape(constant_name)}\s*:", code_part)
+ if name_colon:
+ rest = code_part[name_colon.end() :]
+ equals_index = rest.find("=")
+ if equals_index != -1 and "(" not in rest[:equals_index]:
+ # `TIMEOUT: int = 300`, not dict keys like `KEY: func(kw=val)`.
+ return True
+
+ if re.match(rf"^{re.escape(constant_name)}\s*=", code_part):
+ return True
+
+ left_hand_side, separator, right_hand_side = code_part.partition("=")
+ if not separator or not right_hand_side:
+ return False
+
+ # Reject comparisons and augmented assignment: `A == B`, `A != B`, `A += 1`.
+ if COMPARISON_OPERATOR_TAIL_RE.search(left_hand_side.rstrip()) or right_hand_side.startswith("="):
+ return False
+
+ targets = {target.strip().strip("()[]").lstrip("*").strip() for target in left_hand_side.split(",")}
+ return constant_name in targets
+
+
+def _relative_path(py_file: str) -> str:
+ resolved_file = os.path.realpath(py_file)
+ return os.path.relpath(resolved_file, _find_git_root(resolved_file))
+
+
+def _resolve_repository_root(target: str) -> str | None:
+ """Return the git repository root containing `target`, or None."""
+ directory = target if os.path.isdir(target) else os.path.dirname(os.path.abspath(target))
+ try:
+ result = subprocess.run(
+ ["git", "rev-parse", "--show-toplevel"],
+ check=False,
+ capture_output=True,
+ text=True,
+ cwd=directory or ".",
+ )
+ except (OSError, subprocess.SubprocessError) as error:
+ LOGGER.debug(f"git rev-parse failed for {directory}: {error}")
+ return None
+
+ if result.returncode != 0:
+ return None
+ return result.stdout.strip() or None
+
+
+def _file_matches_include_list(py_file: str, include_files: list[str]) -> bool:
+ """Match a file against git-root-relative --include-files paths or globs."""
+ if not include_files:
+ return True
+
+ relative_path = _relative_path(py_file=py_file)
+ for include_path in include_files:
+ normalized = include_path.strip().lstrip("./")
+ if relative_path == normalized or fnmatch.fnmatch(relative_path, normalized):
+ return True
+ return False
+
+
+def _is_name_excluded(name: str, exclude_names: list[str]) -> bool:
+ return name in exclude_names
+
+
+def collect_file_constants(
+ py_file: str,
+ exclude_names: list[str],
+ uppercase_only: bool,
+ file_ignore_list: list[str],
+) -> list[tuple[str, int, int]]:
+ """Return (name, lineno, col_offset) module-level constant candidates for one file."""
+ if os.path.basename(py_file) in file_ignore_list:
+ LOGGER.debug(f"Skipping file: {py_file}")
+ return []
+
+ # A file that cannot be parsed is skipped with a warning rather than failing
+ # the run: real repositories contain generated, vendored and templated
+ # sources, and one of them must not decide the exit code for everything else.
+ try:
+ with open(py_file, encoding="utf-8") as file_descriptor:
+ source = file_descriptor.read()
+ tree = parse(source=source)
+ except (SyntaxError, UnicodeDecodeError, ValueError) as error:
+ LOGGER.warning(f"Skipping {py_file}: cannot parse ({error})")
+ return []
+
+ source_lines = source.splitlines()
+ candidates: list[tuple[str, int, int]] = []
+ seen_names: set[str] = set()
+
+ for constant_name, lineno, col_offset in _iter_module_level_constants(tree=tree):
+ # A name bound more than once at module level is one constant; report the
+ # first binding only.
+ if constant_name in seen_names:
+ continue
+ seen_names.add(constant_name)
+
+ if _is_name_excluded(name=constant_name, exclude_names=exclude_names):
+ LOGGER.debug(f"Skipping excluded constant: {constant_name}")
+ continue
+
+ if uppercase_only and not _is_uppercase_constant(name=constant_name):
+ LOGGER.debug(f"Skipping non-uppercase constant: {constant_name}")
+ continue
+
+ if _has_skip_unused_code_comment(source_lines=source_lines, lineno=lineno):
+ LOGGER.debug(f"Skipping constant {constant_name}: found `{SKIP_UNUSED_CODE_MARKER}`")
+ continue
+
+ candidates.append((constant_name, lineno, col_offset))
+
+ return candidates
+
+
+def _usage_search_pattern(candidate_names: Iterable[str]) -> str:
+ r"""Build a git grep pattern that may match any candidate name.
+
+ Uses a single character class per run (tokenise hits in Python). For -G,
+ any-identifier uses \w\+ because + is literal in POSIX basic regex.
+ """
+ all_uppercase = all(_is_uppercase_constant(name=name) for name in candidate_names)
+ flag = _detect_supported_grep_flag()
+ if all_uppercase:
+ body = "[A-Z][A-Z0-9_]*"
+ elif flag == "-P":
+ body = r"\w+"
+ else:
+ # -G basic regex: + is literal, so the quantifier is \+
+ body = r"\w\+"
+ return wrap_grep_word(body, flag=flag)
+
+
+def find_used_constants(
+ constants_by_file: dict[str, set[str]],
+ repository_root: str | None = None,
+) -> set[tuple[str, str]]:
+ """Return (absolute file, constant name) pairs that have a usage.
+
+ One streamed git grep for all candidates. Binding lines in the defining file
+ are not usages. ``repository_root`` defaults from the given files; the
+ caller's working directory need not be inside the repository.
+ """
+ names_to_files: dict[str, list[str]] = defaultdict(list)
+ for py_file_absolute, names in constants_by_file.items():
+ for name in names:
+ names_to_files[name].append(py_file_absolute)
+
+ if not names_to_files:
+ return set()
+
+ if repository_root is None:
+ first_file = next(iter(constants_by_file))
+ repository_root = _resolve_repository_root(target=first_file)
+ if repository_root is None:
+ raise RuntimeError(f"{first_file} is not inside a git repository.")
+
+ if os.path.abspath(os.getcwd()) == os.path.abspath(repository_root):
+ return _scan_for_usage(names_to_files=names_to_files)
+
+ with _working_directory(path=repository_root):
+ return _scan_for_usage(names_to_files=names_to_files)
+
+
+def _scan_for_usage(names_to_files: dict[str, list[str]]) -> set[tuple[str, str]]:
+ used: set[tuple[str, str]] = set()
+ command = [
+ "git",
+ "grep",
+ "-n",
+ "--no-color",
+ "--untracked",
+ "-I",
+ _detect_supported_grep_flag(),
+ "-e",
+ _usage_search_pattern(candidate_names=names_to_files),
+ ]
+
+ # stderr goes to a temp file, not a second pipe: draining stdout to
+ # completion before reading stderr would deadlock if git ever filled the
+ # stderr pipe buffer first.
+ with (
+ tempfile.TemporaryFile(mode="w+") as stderr_file,
+ subprocess.Popen(command, stdout=subprocess.PIPE, stderr=stderr_file, text=True) as process,
+ ):
+ assert process.stdout is not None
+ for raw_line in process.stdout:
+ parts = raw_line.rstrip("\n").split(":", 2)
+ if len(parts) != 3:
+ continue
+ grep_path, _grep_lineno, grep_line = parts
+
+ if grep_line.strip().startswith("#"):
+ continue
+ code_part = grep_line.split("#", 1)[0]
+
+ hit_absolute: str | None = None
+ for token in IDENTIFIER_RE.findall(code_part):
+ defining_files = names_to_files.get(token)
+ if not defining_files:
+ continue
+ if hit_absolute is None:
+ hit_absolute = os.path.realpath(
+ _resolve_absolute_path(git_grep_path=grep_path, reference_file=grep_path)
+ )
+ for defining_file in defining_files:
+ if (defining_file, token) in used:
+ continue
+ if hit_absolute == os.path.realpath(defining_file) and _is_constant_definition_line(
+ line_content=code_part, constant_name=token
+ ):
+ continue
+ used.add((defining_file, token))
+
+ process.wait()
+ stderr_file.seek(0)
+ stderr = stderr_file.read()
+
+ # rc=1 means "no matches", which is a legitimate answer, not a failure.
+ if process.returncode not in (0, 1):
+ error_message = stderr.strip() or "unknown error"
+ raise RuntimeError(f"git grep failed (rc={process.returncode}): {error_message}")
+
+ return used
+
+
+def process_file_constants(
+ py_file: str,
+ exclude_names: list[str],
+ uppercase_only: bool,
+ file_ignore_list: list[str],
+) -> str:
+ """Report the unused module-level constants of a single file."""
+ candidates = collect_file_constants(
+ py_file=py_file,
+ exclude_names=exclude_names,
+ uppercase_only=uppercase_only,
+ file_ignore_list=file_ignore_list,
+ )
+ if not candidates:
+ return ""
+
+ py_file_absolute = os.path.abspath(py_file)
+ used = find_used_constants(constants_by_file={py_file_absolute: {name for name, _, _ in candidates}})
+
+ return "\n".join(
+ _format_findings(py_file=py_file, candidates=candidates, used=used, py_file_absolute=py_file_absolute)
+ )
+
+
+def _format_findings(
+ py_file: str,
+ candidates: list[tuple[str, int, int]],
+ used: set[tuple[str, str]],
+ py_file_absolute: str,
+) -> list[str]:
+ # Repository-root relative, matching --include-files, so one run does not mix
+ # path bases depending on where it was invoked from.
+ relative_path = _relative_path(py_file=py_file)
+ return [
+ f"{relative_path}:{constant_name}:{lineno}:{col_offset} No usage found."
+ for constant_name, lineno, col_offset in candidates
+ if (py_file_absolute, constant_name) not in used
+ ]
+
+
+@contextmanager
+def _working_directory(path: str) -> Generator[None, None, None]:
+ """Temporarily chdir to `path`, then restore the previous working directory."""
+ previous = os.getcwd()
+ os.chdir(path)
+ try:
+ yield
+ finally:
+ os.chdir(previous)
+
+
+def _iter_files_to_process(
+ file_path: str | None,
+ directory: str | None,
+ include_files: list[str],
+ file_ignore_list: list[str],
+) -> Iterable[str]:
+ if file_path:
+ yield file_path
+ return
+
+ for py_file in all_python_files(directory=directory):
+ if os.path.basename(py_file) in file_ignore_list:
+ continue
+ if not _file_matches_include_list(py_file=py_file, include_files=include_files):
+ continue
+ yield py_file
+
+
+@click.command()
+@click.option(
+ "--config-file-path",
+ help="Provide absolute path to the config file. Any CLI option(s) would override YAML file",
+ type=click.Path(),
+ default=os.path.expanduser("~/.config/python-utility-scripts/config.yaml"),
+)
+@click.option(
+ "--exclude-files",
+ help="Provide a comma-separated string or list of files to exclude",
+ type=ListParamType(),
+)
+@click.option(
+ "--exclude-names",
+ help="Provide a comma-separated string or list of constant names to exclude",
+ type=ListParamType(),
+)
+@click.option(
+ "--include-files",
+ help="Provide a comma-separated string or list of files to include (paths relative to git root)",
+ type=ListParamType(),
+)
+@click.option(
+ "--uppercase-only/--all-names",
+ # Three-state: None means "not given on the command line", which is what lets
+ # the config value apply while an explicit flag still wins over it.
+ default=None,
+ help="When enabled, only check ALL_CAPS module-level names (default: enabled)",
+)
+@click.option("--verbose", "-v", default=False, is_flag=True)
+@click.option(
+ "--file-path",
+ "-f",
+ help="Analyze a single Python file for unused module-level constants. Must be an existing .py file.",
+ type=click.Path(exists=True),
+)
+@click.option(
+ "--directory",
+ "-d",
+ help=(
+ "Analyze Python files in a directory recursively for unused module-level constants. "
+ "Must be an existing directory."
+ ),
+ type=click.Path(exists=True, dir_okay=True),
+)
+def get_unused_constants(
+ config_file_path: str,
+ exclude_files: list[str],
+ exclude_names: list[str],
+ include_files: list[str],
+ uppercase_only: bool | None,
+ verbose: bool,
+ file_path: click.Path,
+ directory: click.Path,
+) -> None:
+ LOGGER.setLevel(logging.DEBUG if verbose else logging.INFO)
+
+ if file_path and not os.path.isfile(str(file_path)):
+ LOGGER.error("File path must be a file, not a directory.")
+ sys.exit(1)
+
+ if directory and not os.path.isdir(str(directory)):
+ LOGGER.error("Directory must be a directory, not a file.")
+ sys.exit(1)
+
+ unused_constants_config = get_util_config(util_name="pyutils-unusedconstants", config_file_path=config_file_path)
+ file_ignore_list = exclude_files or unused_constants_config.get("exclude_files", [])
+ exclude_name_list = exclude_names or unused_constants_config.get("exclude_names", [])
+ include_file_list = include_files or unused_constants_config.get("include_files", [])
+
+ # An explicit --uppercase-only/--all-names wins over the config file, which
+ # is what --config-file-path's help text promises.
+ if uppercase_only is None:
+ uppercase_only = bool(unused_constants_config.get("uppercase_only", True))
+
+ unused_constants: list[str] = []
+
+ analysis_target = os.path.abspath(str(file_path or directory or os.curdir))
+ repository_root = _resolve_repository_root(target=analysis_target)
+ if repository_root is None:
+ LOGGER.error("Must be run from a git repository")
+ sys.exit(1)
+
+ # Targets are absolute by now, so they survive the move to the repository root.
+ resolved_file_path = analysis_target if file_path else None
+ resolved_directory = analysis_target if directory else None
+
+ with _working_directory(path=repository_root):
+ try:
+ detected_flag = _detect_supported_grep_flag()
+ LOGGER.debug(f"Using git grep flag: {detected_flag}")
+ except RuntimeError as error:
+ LOGGER.error(str(error))
+ sys.exit(1)
+
+ files_to_process = list(
+ _iter_files_to_process(
+ file_path=resolved_file_path,
+ directory=resolved_directory,
+ include_files=include_file_list,
+ file_ignore_list=file_ignore_list,
+ )
+ )
+
+ if not files_to_process:
+ # Not a finding: an empty selection after --exclude-files/--include-files
+ # must not look like "unused constants were found".
+ LOGGER.error("No Python files selected for analysis.")
+ sys.exit(1)
+
+ # Collect every candidate first, then resolve usage for all of them in one
+ # repository scan. Parsing is the only per-file work left, so there is
+ # nothing for a thread pool to overlap.
+ candidates_by_file: dict[str, list[tuple[str, int, int]]] = {}
+ for py_file in files_to_process:
+ candidates = collect_file_constants(
+ py_file=py_file,
+ exclude_names=exclude_name_list,
+ uppercase_only=uppercase_only,
+ file_ignore_list=file_ignore_list,
+ )
+ if candidates:
+ candidates_by_file[py_file] = candidates
+
+ try:
+ used = find_used_constants(
+ constants_by_file={
+ os.path.abspath(py_file): {name for name, _, _ in candidates}
+ for py_file, candidates in candidates_by_file.items()
+ },
+ repository_root=repository_root,
+ )
+ except RuntimeError as error:
+ LOGGER.error(str(error))
+ sys.exit(1)
+
+ for py_file, candidates in candidates_by_file.items():
+ unused_constants.extend(
+ _format_findings(
+ py_file=py_file,
+ candidates=candidates,
+ used=used,
+ py_file_absolute=os.path.abspath(py_file),
+ )
+ )
+
+ if unused_constants:
+ click.echo("\n".join(sorted(unused_constants)))
+ raise SystemExit(1)
+
+
+if __name__ == "__main__":
+ get_unused_constants()
diff --git a/apps/utils.py b/apps/utils.py
index 8def6de..25d287e 100644
--- a/apps/utils.py
+++ b/apps/utils.py
@@ -74,9 +74,12 @@ def convert(self, cli_value: Any, param: click.Parameter | None, ctx: click.Cont
)
-def all_python_files(directory: click.Path | None = None) -> Iterable[str]:
+def all_python_files(directory: str | click.Path | None = None) -> Iterable[str]:
"""
Get all python files from current directory and subdirectories
+
+ `directory` is annotated to accept `str` as well: click.Path converts to a
+ string at parse time, so every caller already passes one.
"""
exclude_dirs = [".tox", "venv", ".pytest_cache", "site-packages", ".git"]
target = str(directory) if directory else os.path.abspath(os.curdir)
diff --git a/config.example.yaml b/config.example.yaml
index d6c86be..c7a162c 100644
--- a/config.example.yaml
+++ b/config.example.yaml
@@ -3,6 +3,15 @@ pyutils-unusedcode:
- "my_exclude_file.py"
exclude_function_prefix:
- "my_exclude_function_prefix"
+pyutils-unusedconstants:
+ include_files:
+ - "utilities/constants.py"
+ - "tests/conftest.py"
+ exclude_files:
+ - "my_exclude_file.py"
+ exclude_names:
+ - "__all__"
+ uppercase_only: true
pyutils-polarion-verify-tc-requirements:
project_id: "ABCDEF"
branch: "origin/main"
diff --git a/pyproject.toml b/pyproject.toml
index a54f2df..ac32ac4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -32,6 +32,7 @@ Documentation = "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/RedHatQE/python-utility-scripts/blob/main/RE
[project.scripts]
pyutils-unusedcode = "apps.unused_code.unused_code:get_unused_functions"
+pyutils-unusedconstants = "apps.unused_constants.unused_constants:get_unused_constants"
pyutils-polarion-verify-tc-requirements = "apps.polarion.polarion_verify_tc_requirements:has_verify"
pyutils-polarion-set-automated = "apps.polarion.polarion_set_automated:polarion_approve_automate"
pyutils-jira = "apps.jira_utils.jira_information:get_jira_mismatch"
diff --git a/tests/unused_code/test_unused_code_coverage.py b/tests/unused_code/test_unused_code_coverage.py
index f1355fb..837db12 100644
--- a/tests/unused_code/test_unused_code_coverage.py
+++ b/tests/unused_code/test_unused_code_coverage.py
@@ -240,9 +240,11 @@ def test_one(self):
def test_detect_supported_grep_flag_fallback(mocker):
- apps.unused_code.unused_code._detect_supported_grep_flag.cache_clear()
+ from apps.git_grep_utils import detect_supported_grep_flag
+
+ detect_supported_grep_flag.cache_clear()
mocker.patch(
- "apps.unused_code.unused_code.subprocess.run",
+ "apps.git_grep_utils.subprocess.run",
side_effect=[
subprocess.CalledProcessError(1, "git"),
subprocess.CalledProcessError(1, "git"),
@@ -454,25 +456,46 @@ def my_function():
def test_find_git_root(tmp_path):
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / ".git").mkdir()
+ source = repo / "pkg" / "file.py"
+ source.parent.mkdir()
+ source.touch()
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ original_cwd = os.getcwd()
+ try:
+ os.chdir(outside)
+ assert _find_git_root(str(source)) == str(repo)
+ finally:
+ os.chdir(original_cwd)
+
+
+def test_find_git_root_falls_back_to_cwd(tmp_path):
+ source = tmp_path / "file.py"
+ source.touch()
original_cwd = os.getcwd()
try:
os.chdir(tmp_path)
- git_dir = tmp_path / ".git"
- git_dir.mkdir()
- assert str(tmp_path) == _find_git_root(str(tmp_path))
+ assert _find_git_root(str(source)) == os.getcwd()
finally:
os.chdir(original_cwd)
def test_resolve_absolute_path(tmp_path):
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / ".git").mkdir()
+ source = repo / "my_file.py"
+ source.touch()
+ outside = tmp_path / "outside"
+ outside.mkdir()
original_cwd = os.getcwd()
try:
- os.chdir(tmp_path)
- git_dir = tmp_path / ".git"
- git_dir.mkdir()
- file_path = tmp_path / "my_file.py"
- file_path.touch()
- assert str(file_path) == _resolve_absolute_path("my_file.py", str(tmp_path))
+ os.chdir(outside)
+ assert str(source) == _resolve_absolute_path("my_file.py", str(source))
+ assert "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/already/absolute.py" == _resolve_absolute_path("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/already/absolute.py", str(source))
finally:
os.chdir(original_cwd)
diff --git a/tests/unused_constants/conftest.py b/tests/unused_constants/conftest.py
new file mode 100644
index 0000000..696e3f6
--- /dev/null
+++ b/tests/unused_constants/conftest.py
@@ -0,0 +1,78 @@
+from __future__ import annotations
+
+import subprocess
+import textwrap
+from collections.abc import Callable
+from pathlib import Path
+
+import pytest
+from click.testing import Result
+
+from apps.unused_constants.unused_constants import get_unused_constants
+from tests.utils import get_cli_runner
+
+
+def _git(*arguments: str, cwd: Path) -> None:
+ subprocess.run(["git", *arguments], cwd=cwd, check=True, capture_output=True)
+
+
+@pytest.fixture
+def git_repository(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Callable[..., Path]:
+ """Build a real, committed git repository and move the working directory into it.
+
+ The usage oracle is `git grep` over a real repository, so the tests drive a
+ real repository. Mocking _git_grep would assert the mock's return value
+ rather than the tool's behaviour.
+ """
+
+ def _build(files: dict[str, str], chdir: bool = True) -> Path:
+ # A subdirectory, not tmp_path itself, so that tmp_path/"outside" is
+ # genuinely outside the repository rather than a directory within it.
+ root = tmp_path / "repository"
+ root.mkdir()
+
+ for relative_path, content in files.items():
+ target = root / relative_path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(textwrap.dedent(content).lstrip(), encoding="utf-8")
+
+ _git("init", "-q", ".", cwd=root)
+ _git("config", "user.email", "test@example.com", cwd=root)
+ _git("config", "user.name", "Test", cwd=root)
+ _git("add", "-A", cwd=root)
+ _git("commit", "-qm", "fixture", cwd=root)
+
+ if chdir:
+ monkeypatch.chdir(root)
+ return root
+
+ return _build
+
+
+@pytest.fixture
+def outside_any_repository(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Move the working directory to a path that is in no git repository.
+
+ `git rev-parse` walks upwards, so this needs its own repository-free root
+ rather than a subdirectory of a fixture repository.
+ """
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ monkeypatch.chdir(outside)
+ return outside
+
+
+@pytest.fixture
+def run_unused_constants(tmp_path: Path) -> Callable[..., Result]:
+ """Invoke the CLI with config isolation.
+
+ --config-file-path defaults to ~/.config/python-utility-scripts/config.yaml,
+ so without this a developer's own config would change the result.
+ """
+
+ def _run(*arguments: str) -> Result:
+ if "--config-file-path" not in arguments:
+ arguments = (*arguments, "--config-file-path", str(tmp_path / "absent-config.yaml"))
+ return get_cli_runner().invoke(get_unused_constants, list(arguments))
+
+ return _run
diff --git a/tests/unused_constants/test_unused_constants.py b/tests/unused_constants/test_unused_constants.py
new file mode 100644
index 0000000..e2b58d3
--- /dev/null
+++ b/tests/unused_constants/test_unused_constants.py
@@ -0,0 +1,723 @@
+from __future__ import annotations
+
+import logging
+import os
+import subprocess
+import textwrap
+from collections.abc import Callable
+from pathlib import Path
+
+import pytest
+from ast_comments import parse
+from click.testing import Result
+from simple_logger.logger import get_logger
+
+from apps.unused_constants.unused_constants import (
+ _file_matches_include_list,
+ _has_skip_unused_code_comment,
+ _is_constant_definition_line,
+ _is_name_excluded,
+ _is_uppercase_constant,
+ _iter_module_level_constants,
+ _usage_search_pattern,
+ collect_file_constants,
+ find_used_constants,
+ process_file_constants,
+)
+
+LOGGER = get_logger(name=__name__)
+
+CONSTANTS_MODULE = """
+ USED_CONSTANT = "used"
+ UNUSED_CONSTANT = "unused"
+"""
+
+CONSUMER_MODULE = """
+ from constants import USED_CONSTANT
+
+
+ def consume() -> str:
+ return USED_CONSTANT
+"""
+
+
+def _reported_names(result: Result) -> set[str]:
+ """Constant names from `path:NAME:line:col No usage found.` output lines."""
+ return {line.split(":")[1] for line in result.output.splitlines() if "No usage found." in line}
+
+
+# --------------------------------------------------------------------------- #
+# Detection, against a real repository
+# --------------------------------------------------------------------------- #
+
+
+def test_reports_only_the_unused_constant(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ git_repository({"constants.py": CONSTANTS_MODULE, "consumer.py": CONSUMER_MODULE})
+
+ result = run_unused_constants()
+
+ assert result.exit_code == 1
+ assert _reported_names(result=result) == {"UNUSED_CONSTANT"}
+
+
+def test_clean_repository_exits_zero(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ git_repository({"constants.py": 'USED_CONSTANT = "used"\n', "consumer.py": CONSUMER_MODULE})
+
+ result = run_unused_constants()
+
+ assert result.exit_code == 0
+ assert not result.output.strip()
+
+
+def test_reports_unpacking_targets(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ """`A, B = 1, 2` binds two constants; both are module level and unused."""
+ git_repository({"constants.py": "FIRST, SECOND = 1, 2\n"})
+
+ result = run_unused_constants()
+
+ assert result.exit_code == 1
+ assert _reported_names(result=result) == {"FIRST", "SECOND"}
+
+
+def test_reports_nested_and_starred_unpacking_targets(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ git_repository({"constants.py": "OUTER, (LEFT, RIGHT) = 1, (2, 3)\nHEAD, *TAIL = [1, 2, 3]\n"})
+
+ result = run_unused_constants()
+
+ assert _reported_names(result=result) == {"OUTER", "LEFT", "RIGHT", "HEAD", "TAIL"}
+
+
+def test_reports_constants_defined_in_module_level_blocks(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ """Constants are routinely bound inside module-level if/try/with."""
+ git_repository({
+ "constants.py": """
+ import os
+
+ if os.environ.get("FLAG"):
+ INSIDE_IF = 1
+ else:
+ INSIDE_ELSE = 2
+
+ try:
+ INSIDE_TRY = 3
+ except Exception:
+ pass
+ finally:
+ INSIDE_FINALLY = 4
+ """
+ })
+
+ result = run_unused_constants()
+
+ assert _reported_names(result=result) == {"INSIDE_IF", "INSIDE_ELSE", "INSIDE_TRY", "INSIDE_FINALLY"}
+
+
+def test_repeated_binding_reported_once_at_first_line(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ """The try/except ImportError pattern binds one name twice."""
+ git_repository({
+ "constants.py": """
+ try:
+ TIMEOUT = 1
+ except ImportError:
+ TIMEOUT = 2
+ """
+ })
+
+ result = run_unused_constants()
+
+ findings = [line for line in result.output.splitlines() if "No usage found." in line]
+ assert len(findings) == 1
+ assert findings[0].startswith("constants.py:TIMEOUT:2:")
+
+
+def test_skip_unused_code_marker_suppresses_a_constant(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ git_repository({"constants.py": 'KEPT = "value" # skip-unused-code\nREPORTED = "value"\n'})
+
+ result = run_unused_constants()
+
+ assert _reported_names(result=result) == {"REPORTED"}
+
+
+# --------------------------------------------------------------------------- #
+# Name selection
+# --------------------------------------------------------------------------- #
+
+
+def test_uppercase_only_is_the_default(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ git_repository({"constants.py": "UPPER = 1\nlower = 2\n"})
+
+ assert _reported_names(result=run_unused_constants()) == {"UPPER"}
+
+
+def test_all_names_includes_lowercase(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ git_repository({"constants.py": "UPPER = 1\nlower = 2\n"})
+
+ assert _reported_names(result=run_unused_constants("--all-names")) == {"UPPER", "lower"}
+
+
+def test_config_uppercase_only_applies_when_no_flag_is_given(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ repository = git_repository({
+ "constants.py": "UPPER = 1\nlower = 2\n",
+ "config.yaml": "pyutils-unusedconstants:\n uppercase_only: false\n",
+ })
+
+ result = run_unused_constants("--config-file-path", str(repository / "config.yaml"))
+
+ assert _reported_names(result=result) == {"UPPER", "lower"}
+
+
+def test_cli_flag_overrides_config_uppercase_only(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ """--config-file-path's help text promises the CLI wins."""
+ repository = git_repository({
+ "constants.py": "UPPER = 1\nlower = 2\n",
+ "config.yaml": "pyutils-unusedconstants:\n uppercase_only: true\n",
+ })
+
+ result = run_unused_constants("--all-names", "--config-file-path", str(repository / "config.yaml"))
+
+ assert _reported_names(result=result) == {"UPPER", "lower"}
+
+
+def test_exclude_names(git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]) -> None:
+ git_repository({"constants.py": "KEPT = 1\nREPORTED = 2\n"})
+
+ assert _reported_names(result=run_unused_constants("--exclude-names", "KEPT")) == {"REPORTED"}
+
+
+# --------------------------------------------------------------------------- #
+# File selection
+# --------------------------------------------------------------------------- #
+
+
+def test_exclude_files_skips_only_that_file(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ """Excluding one file must not hide findings in the others."""
+ git_repository({"skipped.py": "IN_SKIPPED = 1\n", "scanned.py": "IN_SCANNED = 2\n"})
+
+ result = run_unused_constants("--exclude-files", "skipped.py")
+
+ assert result.exit_code == 1
+ assert _reported_names(result=result) == {"IN_SCANNED"}
+
+
+def test_include_files_accepts_a_glob(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ git_repository({"utilities/constants.py": "IN_UTILITIES = 1\n", "other.py": "IN_OTHER = 2\n"})
+
+ result = run_unused_constants("--include-files", "utilities/*.py")
+
+ assert _reported_names(result=result) == {"IN_UTILITIES"}
+
+
+def test_include_files_path_does_not_match_a_basename_elsewhere(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ """`constants.py` means the file at the root, not every constants.py in the tree."""
+ git_repository({"constants.py": "AT_ROOT = 1\n", "nested/constants.py": "NESTED = 2\n"})
+
+ result = run_unused_constants("--include-files", "constants.py")
+
+ assert _reported_names(result=result) == {"AT_ROOT"}
+
+
+def test_empty_selection_exits_one_not_a_finding(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result], caplog: pytest.LogCaptureFixture
+) -> None:
+ git_repository({"constants.py": "UNUSED = 1\n"})
+
+ with caplog.at_level(logging.ERROR):
+ result = run_unused_constants("--exclude-files", "constants.py")
+
+ assert result.exit_code == 1
+ assert "No Python files selected" in caplog.text
+
+
+# --------------------------------------------------------------------------- #
+# Repository resolution and paths
+# --------------------------------------------------------------------------- #
+
+
+def test_directory_option_analyses_a_repository_elsewhere(
+ git_repository: Callable[..., Path],
+ run_unused_constants: Callable[..., Result],
+ outside_any_repository: Path,
+) -> None:
+ """The README states --directory works against any repository.
+
+ Run from a directory in no repository at all, not merely a directory that
+ is not the repository root.
+ """
+ repository = git_repository({"constants.py": "UNUSED = 1\n"}, chdir=False)
+
+ result = run_unused_constants("--directory", str(repository))
+
+ assert result.exit_code == 1
+ assert _reported_names(result=result) == {"UNUSED"}
+
+
+def test_file_path_option_analyses_a_repository_elsewhere(
+ git_repository: Callable[..., Path],
+ run_unused_constants: Callable[..., Result],
+ outside_any_repository: Path,
+) -> None:
+ repository = git_repository({"constants.py": "UNUSED = 1\n"}, chdir=False)
+
+ result = run_unused_constants("--file-path", str(repository / "constants.py"))
+
+ assert result.exit_code == 1
+ assert _reported_names(result=result) == {"UNUSED"}
+
+
+def test_symlinked_directory_still_skips_definition_lines(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result], tmp_path: Path
+) -> None:
+ repository = git_repository(
+ {"constants.py": 'USED_CONSTANT = "used"\nUNUSED_CONSTANT = "unused"\n', "consumer.py": CONSUMER_MODULE},
+ chdir=False,
+ )
+ checkout = tmp_path / "checkout"
+ checkout.symlink_to(repository, target_is_directory=True)
+
+ result = run_unused_constants("--directory", str(checkout))
+
+ assert result.exit_code == 1
+ assert _reported_names(result=result) == {"UNUSED_CONSTANT"}
+ assert "constants.py:UNUSED_CONSTANT:" in result.output
+ assert ".." not in result.output
+
+
+def test_symlinked_directory_include_files_stays_repository_relative(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result], tmp_path: Path
+) -> None:
+ repository = git_repository(
+ {"constants.py": "AT_ROOT = 1\n", "nested/constants.py": "NESTED = 2\n"},
+ chdir=False,
+ )
+ checkout = tmp_path / "checkout"
+ checkout.symlink_to(repository, target_is_directory=True)
+
+ result = run_unused_constants("--directory", str(checkout), "--include-files", "constants.py")
+
+ assert _reported_names(result=result) == {"AT_ROOT"}
+ assert "constants.py:AT_ROOT:" in result.output
+
+
+def test_reported_paths_are_repository_relative(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """--include-files is git-root relative, so the output uses the same base."""
+ repository = git_repository({"utilities/constants.py": "UNUSED = 1\n"})
+ monkeypatch.chdir(repository / "utilities")
+
+ result = run_unused_constants("--directory", str(repository))
+
+ assert "utilities/constants.py:UNUSED:1:0 No usage found." in result.output
+
+
+def test_process_file_constants_works_from_outside_any_repository(
+ git_repository: Callable[..., Path], outside_any_repository: Path
+) -> None:
+ """A library caller's working directory need not be in the repository.
+
+ The CLI resolves the root and moves there; a direct caller gets whatever
+ working directory it happens to have. Without the root being resolved from
+ the file, the grep-flag probe fails and reports that the platform's git
+ lacks PCRE support, which is not the problem.
+ """
+ repository = git_repository({"utilities/constants.py": "UNUSED = 1\n"}, chdir=False)
+
+ output = process_file_constants(
+ py_file=str(repository / "utilities" / "constants.py"),
+ exclude_names=[],
+ uppercase_only=True,
+ file_ignore_list=[],
+ )
+
+ assert output.startswith("utilities/constants.py:UNUSED:1:0")
+
+
+def test_working_directory_is_restored(
+ git_repository: Callable[..., Path],
+ run_unused_constants: Callable[..., Result],
+ outside_any_repository: Path,
+) -> None:
+ repository = git_repository({"constants.py": "UNUSED = 1\n"}, chdir=False)
+
+ run_unused_constants("--directory", str(repository))
+
+ assert Path(os.getcwd()).resolve() == outside_any_repository.resolve()
+
+
+def test_not_a_git_repository_exits_one(
+ run_unused_constants: Callable[..., Result],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+
+ with caplog.at_level(logging.ERROR):
+ result = run_unused_constants()
+
+ assert result.exit_code == 1
+ assert "git repository" in caplog.text
+
+
+@pytest.mark.parametrize(
+ ("option", "target", "expected_message"),
+ [
+ ("--file-path", "a_directory", "must be a file"),
+ ("--directory", "a_file.py", "must be a directory"),
+ ],
+)
+def test_mismatched_target_type_exits_one(
+ run_unused_constants: Callable[..., Result],
+ tmp_path: Path,
+ caplog: pytest.LogCaptureFixture,
+ option: str,
+ target: str,
+ expected_message: str,
+) -> None:
+ (tmp_path / "a_directory").mkdir()
+ (tmp_path / "a_file.py").write_text("X = 1\n", encoding="utf-8")
+
+ with caplog.at_level(logging.ERROR):
+ result = run_unused_constants(option, str(tmp_path / target))
+
+ assert result.exit_code == 1
+ assert expected_message in caplog.text
+
+
+# --------------------------------------------------------------------------- #
+# Unparseable sources
+# --------------------------------------------------------------------------- #
+
+
+def test_unparseable_file_is_skipped_without_failing_the_run(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ """Generated and vendored sources must not decide the exit code."""
+ git_repository({"constants.py": "UNUSED = 1\n", "broken.py": "def broken(:\n"})
+
+ result = run_unused_constants()
+
+ assert result.exit_code == 1
+ assert _reported_names(result=result) == {"UNUSED"}
+ assert result.exception is None or isinstance(result.exception, SystemExit)
+
+
+def test_unparseable_single_file_exits_clean(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result]
+) -> None:
+ repository = git_repository({"broken.py": "def broken(:\n"})
+
+ result = run_unused_constants("--file-path", str(repository / "broken.py"))
+
+ assert result.exit_code == 0
+ assert not isinstance(result.exception, SyntaxError)
+
+
+def test_process_file_constants_returns_empty_for_unparseable_source(tmp_path: Path) -> None:
+ broken = tmp_path / "broken.py"
+ broken.write_text("def broken(:\n", encoding="utf-8")
+
+ assert (
+ process_file_constants(
+ py_file=str(broken),
+ exclude_names=[],
+ uppercase_only=True,
+ file_ignore_list=[],
+ )
+ == ""
+ )
+
+
+def test_process_file_constants_honours_the_file_ignore_list(tmp_path: Path) -> None:
+ source = tmp_path / "constants.py"
+ source.write_text("UNUSED = 1\n", encoding="utf-8")
+
+ assert (
+ process_file_constants(
+ py_file=str(source),
+ exclude_names=[],
+ uppercase_only=True,
+ file_ignore_list=["constants.py"],
+ )
+ == ""
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Pure helpers
+# --------------------------------------------------------------------------- #
+
+
+def test_iter_module_level_constants() -> None:
+ tree = parse(
+ source=textwrap.dedent(
+ """
+ FOO = 1
+ BAR: str = "x"
+
+ def func():
+ LOCAL = 2
+ """
+ )
+ )
+ assert [name for name, _, _ in _iter_module_level_constants(tree=tree)] == ["FOO", "BAR"]
+
+
+@pytest.mark.parametrize(
+ ("source", "expected"),
+ [
+ pytest.param("A, B = 1, 2\n", ["A", "B"], id="tuple-unpacking"),
+ pytest.param("[A, B] = [1, 2]\n", ["A", "B"], id="list-unpacking"),
+ pytest.param("A, (B, C) = 1, (2, 3)\n", ["A", "B", "C"], id="nested-unpacking"),
+ pytest.param("A, *REST = [1, 2, 3]\n", ["A", "REST"], id="starred-unpacking"),
+ pytest.param("A = B = 1\n", ["A", "B"], id="chained-assignment"),
+ pytest.param("if True:\n A = 1\n", ["A"], id="module-level-if"),
+ pytest.param("if False:\n A = 1\nelse:\n B = 2\n", ["A", "B"], id="module-level-if-else"),
+ pytest.param(
+ "try:\n A = 1\nexcept ImportError:\n B = 2\nfinally:\n C = 3\n",
+ ["A", "B", "C"],
+ id="module-level-try",
+ ),
+ pytest.param("with open('f') as fd:\n A = fd\n", ["A"], id="module-level-with"),
+ pytest.param("class Holder:\n A = 1\n", [], id="class-body-is-not-module-level"),
+ pytest.param("def func():\n A = 1\n", [], id="function-body-is-not-module-level"),
+ ],
+)
+def test_iter_module_level_constants_binding_forms(source: str, expected: list[str]) -> None:
+ assert [name for name, _, _ in _iter_module_level_constants(tree=parse(source=source))] == expected
+
+
+def test_iter_module_level_constants_reports_each_target_column() -> None:
+ tree = parse(source="ALPHA, BETA = 1, 2\n")
+ assert list(_iter_module_level_constants(tree=tree)) == [("ALPHA", 1, 0), ("BETA", 1, 7)]
+
+
+@pytest.mark.parametrize(
+ ("name", "expected"),
+ [
+ ("USED_CONSTANT", True),
+ ("used_constant", False),
+ ("UsedConstant", False),
+ ],
+)
+def test_is_uppercase_constant(name: str, expected: bool) -> None:
+ assert _is_uppercase_constant(name=name) is expected
+
+
+@pytest.mark.parametrize(
+ ("line", "name", "expected"),
+ [
+ ("FOO = 1", "FOO", True),
+ ("FOO: str = 'a'", "FOO", True),
+ ("FOOBAR = FOO", "FOO", False),
+ pytest.param("FOO, BAR = 1, 2", "FOO", True, id="first-unpacking-target"),
+ pytest.param("FOO, BAR = 1, 2", "BAR", True, id="second-unpacking-target"),
+ pytest.param(" FOO = 1", "FOO", True, id="indented-definition"),
+ pytest.param("FOO = 1 # trailing comment", "FOO", True, id="inline-comment-stripped"),
+ pytest.param("if FOO == BAR:", "FOO", False, id="equality-comparison"),
+ pytest.param("if FOO != BAR:", "FOO", False, id="inequality-comparison"),
+ pytest.param("FOO += 1", "FOO", False, id="augmented-assignment-is-a-read"),
+ pytest.param("assert FOO >= BAR", "FOO", False, id="greater-equal-comparison"),
+ pytest.param("call(FOO, BAR)", "FOO", False, id="call-argument"),
+ pytest.param("BAZ = FOO, BAR", "FOO", False, id="right-hand-side-tuple"),
+ pytest.param("HEAD, *TAIL = values", "TAIL", True, id="starred-unpacking-target"),
+ pytest.param("[FIRST, SECOND] = pair", "SECOND", True, id="list-unpacking-target"),
+ pytest.param(
+ "VMI_SOURCE_POD_STR: vm.vmi.get_virt_launcher_pod(privileged_client=admin_client),",
+ "VMI_SOURCE_POD_STR",
+ False,
+ id="dict-key-with-kwargs-is-a-usage",
+ ),
+ pytest.param("FOO: Optional[List[int]] = []", "FOO", True, id="annotated-assign-with-subscript"),
+ ],
+)
+def test_is_constant_definition_line(line: str, name: str, expected: bool) -> None:
+ assert _is_constant_definition_line(line_content=line, constant_name=name) is expected
+
+
+def test_has_skip_unused_code_comment() -> None:
+ lines = ["FOO = 1 # skip-unused-code", "BAR = 2"]
+ assert _has_skip_unused_code_comment(source_lines=lines, lineno=1)
+ assert not _has_skip_unused_code_comment(source_lines=lines, lineno=2)
+
+
+@pytest.mark.parametrize("lineno", [0, -1, 99])
+def test_has_skip_unused_code_comment_out_of_range(lineno: int) -> None:
+ assert not _has_skip_unused_code_comment(source_lines=["FOO = 1"], lineno=lineno)
+
+
+def test_is_name_excluded() -> None:
+ assert _is_name_excluded(name="__all__", exclude_names=["__all__"])
+ assert not _is_name_excluded(name="FOO", exclude_names=["__all__"])
+
+
+def test_file_matches_include_list(git_repository: Callable[..., Path]) -> None:
+ repository = git_repository({"utilities/constants.py": "A = 1\n"})
+ py_file = str(repository / "utilities" / "constants.py")
+
+ assert _file_matches_include_list(py_file=py_file, include_files=[])
+ assert _file_matches_include_list(py_file=py_file, include_files=["utilities/constants.py"])
+ assert _file_matches_include_list(py_file=py_file, include_files=["./utilities/constants.py"])
+ assert _file_matches_include_list(py_file=py_file, include_files=["utilities/*.py"])
+ assert not _file_matches_include_list(py_file=py_file, include_files=["other.py"])
+ assert not _file_matches_include_list(py_file=py_file, include_files=["constants.py"])
+
+
+def test_find_used_constants_single_scan_sees_usage_in_any_file_type(
+ git_repository: Callable[..., Path],
+) -> None:
+ """Usage in a non-Python file counts, as it did with the per-constant search."""
+ repository = git_repository({
+ "constants.py": "IN_YAML = 1\nIN_MARKDOWN = 2\nNOWHERE = 3\n",
+ "config.yaml": "key: IN_YAML\n",
+ "docs.md": "Mentions IN_MARKDOWN in prose.\n",
+ })
+ constants_file = str(repository / "constants.py")
+
+ used = find_used_constants(constants_by_file={constants_file: {"IN_YAML", "IN_MARKDOWN", "NOWHERE"}})
+
+ assert (constants_file, "IN_YAML") in used
+ assert (constants_file, "IN_MARKDOWN") in used
+ assert (constants_file, "NOWHERE") not in used
+
+
+def test_find_used_constants_handles_no_candidates() -> None:
+ assert find_used_constants(constants_by_file={}) == set()
+
+
+def test_collect_file_constants_applies_every_exclusion(
+ git_repository: Callable[..., Path],
+) -> None:
+ repository = git_repository({"constants.py": "KEPT = 1\nEXCLUDED = 2\nMARKED = 3 # skip-unused-code\nlower = 4\n"})
+
+ names = [
+ name
+ for name, _, _ in collect_file_constants(
+ py_file=str(repository / "constants.py"),
+ exclude_names=["EXCLUDED"],
+ uppercase_only=True,
+ file_ignore_list=[],
+ )
+ ]
+
+ assert names == ["KEPT"]
+
+
+@pytest.mark.parametrize(
+ ("names", "expected_body"),
+ [
+ pytest.param({"UPPER_ONE", "UPPER_TWO"}, "[A-Z][A-Z0-9_]*", id="all-uppercase-uses-narrow-class"),
+ pytest.param({"UPPER", "lower"}, r"\w+", id="any-lowercase-widens-the-class"),
+ ],
+)
+def test_usage_search_pattern_narrows_when_it_can(names: set[str], expected_body: str) -> None:
+ assert expected_body in _usage_search_pattern(candidate_names=names)
+
+
+# --------------------------------------------------------------------------- #
+# git grep engine and failure handling
+# --------------------------------------------------------------------------- #
+
+
+def test_basic_regex_fallback_still_finds_usage(
+ git_repository: Callable[..., Path], run_unused_constants: Callable[..., Result], mocker
+) -> None:
+ r"""The -G pattern must be valid POSIX basic regex.
+
+ `+` is a literal in BRE, so a `\\w+` body matches nothing and every
+ candidate would be reported unused -- a false positive, which is the
+ dangerous direction for a tool whose output is "delete this".
+ """
+ mocker.patch(
+ "apps.unused_constants.unused_constants._detect_supported_grep_flag",
+ return_value="-G",
+ )
+ git_repository({
+ "constants.py": "used_lower = 1\nunused_lower = 2\n",
+ "consumer.py": "from constants import used_lower\n\n\ndef consume():\n return used_lower\n",
+ })
+
+ result = run_unused_constants("--all-names")
+
+ assert _reported_names(result=result) == {"unused_lower"}
+
+
+@pytest.mark.parametrize("flag", ["-P", "-G"])
+def test_usage_search_pattern_is_valid_for_its_engine(git_repository: Callable[..., Path], mocker, flag: str) -> None:
+ """Run the generated pattern through git grep and require it to match."""
+ mocker.patch(
+ "apps.unused_constants.unused_constants._detect_supported_grep_flag",
+ return_value=flag,
+ )
+ repository = git_repository({"constants.py": "mixed_case = 1\n"})
+ pattern = _usage_search_pattern(candidate_names={"mixed_case"})
+
+ completed = subprocess.run(
+ ["git", "grep", "-n", "--no-color", "-I", flag, "-e", pattern],
+ cwd=repository,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ assert completed.returncode == 0, f"pattern {pattern!r} matched nothing under {flag}"
+ assert "mixed_case" in completed.stdout
+
+
+def test_git_grep_failure_exits_one(
+ git_repository: Callable[..., Path],
+ run_unused_constants: Callable[..., Result],
+ mocker,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """Same as pyutils-unusedcode: grep / engine errors exit 1, not 0."""
+ mocker.patch(
+ "apps.unused_constants.unused_constants._detect_supported_grep_flag",
+ return_value="--not-a-real-git-grep-flag",
+ )
+ git_repository({"constants.py": "UNUSED = 1\n"})
+
+ with caplog.at_level(logging.ERROR):
+ result = run_unused_constants()
+
+ assert result.exit_code == 1
+ assert "git grep" in caplog.text.lower()
+
+
+def test_find_used_constants_outside_a_repository_names_the_real_cause(
+ tmp_path: Path, outside_any_repository: Path
+) -> None:
+ """Not "your git lacks PCRE", which is what the grep-flag probe would say."""
+ stray = tmp_path / "stray.py"
+ stray.write_text("UNUSED = 1\n", encoding="utf-8")
+
+ with pytest.raises(RuntimeError, match="not inside a git repository"):
+ find_used_constants(constants_by_file={str(stray): {"UNUSED"}})