Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
74 changes: 74 additions & 0 deletions apps/git_grep_utils.py
Original file line number Diff line number Diff line change
@@ -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): \<body\>
"""
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
91 changes: 12 additions & 79 deletions apps/unused_code/unused_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 []:
Expand Down Expand Up @@ -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): \<name\>
"""
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:
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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}")
Expand Down
128 changes: 128 additions & 0 deletions apps/unused_constants/README.md
Original file line number Diff line number Diff line change
@@ -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
```
Empty file.
Loading