python-utility-scripts 1.0.23__tar.gz → 1.0.25__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.
Files changed (20) hide show
  1. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/.gitignore +8 -0
  2. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/PKG-INFO +1 -1
  3. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/apps/jira_utils/jira_information.py +1 -0
  4. python_utility_scripts-1.0.25/apps/unused_code/README.md +79 -0
  5. python_utility_scripts-1.0.25/apps/unused_code/unused_code.py +642 -0
  6. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/apps/utils.py +4 -2
  7. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/pyproject.toml +2 -2
  8. python_utility_scripts-1.0.23/apps/unused_code/README.md +0 -48
  9. python_utility_scripts-1.0.23/apps/unused_code/unused_code.py +0 -153
  10. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/LICENSE +0 -0
  11. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/README.md +0 -0
  12. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/apps/__init__.py +0 -0
  13. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/apps/jira_utils/README.md +0 -0
  14. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/apps/jira_utils/__init__.py +0 -0
  15. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/apps/polarion/README.md +0 -0
  16. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/apps/polarion/__init__.py +0 -0
  17. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/apps/polarion/polarion_set_automated.py +0 -0
  18. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/apps/polarion/polarion_utils.py +0 -0
  19. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/apps/polarion/polarion_verify_tc_requirements.py +0 -0
  20. {python_utility_scripts-1.0.23 → python_utility_scripts-1.0.25}/apps/unused_code/__init__.py +0 -0
@@ -159,3 +159,11 @@ cython_debug/
159
159
  # and can be added to the global gitignore or merged into this file. For a more nuclear
160
160
  # option (not recommended) you can uncomment the following to ignore the entire idea folder.
161
161
  .idea/
162
+
163
+ # AI
164
+ .cursor/
165
+ CLAUDE.md
166
+ .agent-os/
167
+ .cursorrules
168
+ .claude/
169
+ GEMINI.md
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-utility-scripts
3
- Version: 1.0.23
3
+ Version: 1.0.25
4
4
  Summary: Python utility scripts
5
5
  Project-URL: Homepage, https://github.com/RedHatQE/python-utility-scripts
6
6
  Project-URL: Repository, https://github.com/RedHatQE/python-utility-scripts
@@ -151,6 +151,7 @@ def process_jira_command_line_config_file(
151
151
  config_dict = get_util_config(util_name="pyutils-jira", config_file_path=config_file_path)
152
152
  url = url or config_dict.get("url", "")
153
153
  token = token or config_dict.get("token", "")
154
+
154
155
  if not (url and token):
155
156
  LOGGER.error("Jira url and token are required.")
156
157
  sys.exit(1)
@@ -0,0 +1,79 @@
1
+ # pyutils-unusedcode
2
+
3
+ Helper to identify unused code in a pytest repository. It should be run from inside the test repository using this tool.
4
+
5
+ ## Usage
6
+
7
+ ### Basic Usage
8
+
9
+ ```bash
10
+ # Analyze all Python files in the current directory (must be a git repository)
11
+ pyutils-unusedcode
12
+
13
+ # Show help with all available options
14
+ pyutils-unusedcode --help
15
+ ```
16
+
17
+ ### Analyze Specific Files or Directories
18
+
19
+ ```bash
20
+ # Analyze a single Python file
21
+ pyutils-unusedcode --file-path /path/to/your/file.py
22
+ pyutils-unusedcode -f /path/to/your/file.py
23
+
24
+ # Analyze all Python files in a specific directory recursively
25
+ pyutils-unusedcode --directory /path/to/your/project
26
+ pyutils-unusedcode -d /path/to/your/project
27
+ ```
28
+
29
+ **Note:** When using `--file-path` or `--directory`, the tool will analyze files from any git repository, not just the current working directory.
30
+
31
+ ## Command-Line Options
32
+
33
+ | Option | Short | Description |
34
+ |--------|-------|-------------|
35
+ | `--file-path` | `-f` | Analyze a single Python file for unused functions. Must be an existing .py file. |
36
+ | `--directory` | `-d` | Analyze all Python files in a directory recursively for unused functions. Must be an existing directory. |
37
+ | `--exclude-files` | | Comma-separated list of files to exclude from analysis. |
38
+ | `--exclude-function-prefixes` | | Comma-separated list of function prefixes to exclude from analysis. |
39
+ | `--config-file-path` | | Path to custom config file (default: `~/.config/python-utility-scripts/config.yaml`). |
40
+ | `--verbose` | `-v` | Enable verbose logging for debugging. |
41
+ | `--help` | | Show help message with all available options. |
42
+
43
+ ## Config file
44
+
45
+ To skip unused code check on specific files or functions of a repository, a config file with the list of names of such files and function prefixes should be added to
46
+ `~/.config/python-utility-scripts/config.yaml`
47
+
48
+ ### Example
49
+
50
+ ```yaml
51
+ pyutils-unusedcode:
52
+ exclude_files:
53
+ - "my_exclude_file.py"
54
+ exclude_function_prefix:
55
+ - "my_exclude_function_prefix"
56
+ ```
57
+
58
+ This would exclude any functions with prefix my_exclude_function_prefix and file my_exclude_file.py from unused code check
59
+
60
+ To run from CLI with `--exclude-function-prefixes`
61
+
62
+ ```bash
63
+ pyutils-unusedcode --exclude-function-prefixes 'my_exclude_function1,my_exclude_function2'
64
+ ```
65
+
66
+ To run from CLI with `--exclude-files`
67
+
68
+ ```bash
69
+ pyutils-unusedcode --exclude-files 'my_exclude_file1.py,my_exclude_file2.py'
70
+ ```
71
+
72
+ ### Skip single function in file
73
+
74
+ Add `# skip-unused-code` comment in the function name list to skip it from check.
75
+
76
+ ```python
77
+ def my_function(): # skip-unused-code
78
+ pass
79
+ ```
@@ -0,0 +1,642 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import logging
5
+ import os
6
+ import re
7
+ import subprocess
8
+ import sys
9
+ from concurrent.futures import Future, ThreadPoolExecutor, as_completed
10
+ from functools import lru_cache
11
+ from pathlib import Path
12
+ from typing import Any, Callable, Iterable
13
+
14
+ import click
15
+ from ast_comments import parse
16
+ from simple_logger.logger import get_logger
17
+
18
+ from apps.utils import ListParamType, all_python_files, get_util_config
19
+
20
+ LOGGER = get_logger(name=__name__)
21
+
22
+
23
+ @lru_cache(maxsize=1)
24
+ def _detect_supported_grep_flag() -> str:
25
+ """Detect and cache a supported regex engine flag for git grep.
26
+
27
+ Prefer PCRE ("-P") for proper \b handling; fall back to basic regex ("-G").
28
+ Run a harmless grep to verify support and cache the first working flag.
29
+ Uses lru_cache for thread-safe caching that runs only once per process.
30
+ """
31
+ candidate_flags = ["-P", "-G"]
32
+ for flag in candidate_flags:
33
+ try:
34
+ # Use a trivial pattern to minimize output. We only care that the flag is accepted.
35
+ # Discard stdout/stderr to prevent capturing large data in big repositories.
36
+ probe_cmd = [
37
+ "git",
38
+ "grep",
39
+ "-n",
40
+ "--no-color",
41
+ "--untracked",
42
+ "-I",
43
+ flag,
44
+ "^$", # match empty lines; success (rc=0) or no matches (rc=1) are both fine
45
+ ]
46
+ result = subprocess.run(probe_cmd, check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
47
+ if result.returncode in (0, 1):
48
+ return flag
49
+ except Exception:
50
+ # Try next candidate
51
+ pass
52
+
53
+ raise RuntimeError(
54
+ "git grep does not support '-P' (PCRE) or '-G' (basic regex) on this platform. "
55
+ "Please ensure a compatible git/grep is installed."
56
+ )
57
+
58
+
59
+ def is_fixture_autouse(func: ast.FunctionDef) -> bool:
60
+ deco_list: list[Any] = func.decorator_list
61
+ for deco in deco_list or []:
62
+ if not hasattr(deco, "func"):
63
+ continue
64
+
65
+ if getattr(deco.func, "attr", None) and getattr(deco.func, "value", None):
66
+ if deco.func.attr == "fixture" and deco.func.value.id == "pytest":
67
+ for _key in deco.keywords:
68
+ if _key.arg == "autouse":
69
+ return True
70
+ return False
71
+
72
+
73
+ def is_pytest_fixture(func: ast.FunctionDef) -> bool:
74
+ """Return True if the function is decorated with @pytest.fixture.
75
+
76
+ Detects any pytest fixture regardless of parameters (scope, autouse, etc.).
77
+ """
78
+ decorators: list[Any] = func.decorator_list
79
+ for decorator in decorators or []:
80
+ # Case 1: @pytest.fixture(...)
81
+ if hasattr(decorator, "func"):
82
+ # e.g. @pytest.fixture(...)
83
+ if getattr(decorator.func, "attr", None) and getattr(decorator.func, "value", None):
84
+ if decorator.func.attr == "fixture" and getattr(decorator.func.value, "id", None) == "pytest":
85
+ return True
86
+ # e.g. from pytest import fixture; @fixture(...)
87
+ if isinstance(decorator.func, ast.Name) and decorator.func.id == "fixture":
88
+ return True
89
+ # Case 2: @pytest.fixture (no parentheses)
90
+ else:
91
+ # e.g. @pytest.fixture
92
+ if getattr(decorator, "attr", None) == "fixture" and getattr(decorator, "value", None):
93
+ if getattr(decorator.value, "id", None) == "pytest":
94
+ return True
95
+ # e.g. from pytest import fixture; @fixture
96
+ if isinstance(decorator, ast.Name) and decorator.id == "fixture":
97
+ return True
98
+ return False
99
+
100
+
101
+ def _build_usage_pattern(function_name: str) -> str:
102
+ r"""Build a portable regex to match function usages.
103
+
104
+ Uses word boundary semantics based on the detected grep engine.
105
+ The pattern is designed to match function calls as well as references
106
+ (e.g., when passed as an argument).
107
+ - PCRE (-P): \bname\b
108
+ - Basic (-G): \<name\>
109
+ """
110
+ flag = _detect_supported_grep_flag()
111
+ if flag == "-P":
112
+ return rf"\b{function_name}\b"
113
+ # -G basic regex: use word-start and word-end tokens
114
+ return rf"\<{function_name}\>"
115
+
116
+
117
+ def _build_fixture_param_pattern(function_name: str) -> str:
118
+ r"""Build a portable regex to find a parameter named `function_name` in a function signature.
119
+
120
+ This pattern is designed to match parameter names in function signatures, including
121
+ multiline function definitions where parameters may be on different lines from the 'def'.
122
+ It looks for the parameter name followed by typical parameter syntax (colon, comma, or closing paren).
123
+ """
124
+ flag = _detect_supported_grep_flag()
125
+ if flag == "-P":
126
+ # Match parameter name followed by type annotation (:), comma, or closing paren
127
+ # This handles both single-line and multiline function definitions
128
+ return rf"\b{function_name}\b\s*[,:]"
129
+ # For -G (basic regex), use POSIX classes
130
+ # Match word boundary + name + optional spaces + (colon or comma or closing paren)
131
+ return rf"\<{function_name}\>[[:space:]]*[,:]"
132
+
133
+
134
+ def _is_pytest_mark_usefixtures_call(call_node: ast.Call) -> bool:
135
+ """Check if an AST Call node represents pytest.mark.usefixtures(...)."""
136
+ if isinstance(call_node.func, ast.Attribute):
137
+ # Handle pytest.mark.usefixtures
138
+ if (
139
+ call_node.func.attr == "usefixtures"
140
+ and isinstance(call_node.func.value, ast.Attribute)
141
+ and call_node.func.value.attr == "mark"
142
+ and isinstance(call_node.func.value.value, ast.Name)
143
+ and call_node.func.value.value.id == "pytest"
144
+ ):
145
+ return True
146
+ return False
147
+
148
+
149
+ def _check_fixturenames_insert_pattern(fixture_name: str, file_path: str) -> bool:
150
+ """Check if a fixture is used in item.fixturenames.insert() pattern.
151
+
152
+ This catches dynamic fixture injection patterns like:
153
+ item.fixturenames.insert(0, "fixture_name")
154
+ """
155
+ try:
156
+ with open(file_path) as f:
157
+ content = f.read()
158
+
159
+ tree = parse(source=content)
160
+
161
+ # Look for method calls like item.fixturenames.insert(...)
162
+ for node in ast.walk(tree):
163
+ if isinstance(node, ast.Call):
164
+ # Check for attribute calls like item.fixturenames.insert
165
+ if (
166
+ isinstance(node.func, ast.Attribute)
167
+ and node.func.attr == "insert"
168
+ and isinstance(node.func.value, ast.Attribute)
169
+ and node.func.value.attr == "fixturenames"
170
+ ):
171
+ # Check the arguments for our fixture name
172
+ for arg in node.args:
173
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
174
+ if arg.value == fixture_name:
175
+ return True
176
+
177
+ return False
178
+ except (FileNotFoundError, SyntaxError, ValueError):
179
+ return False
180
+
181
+
182
+ def _check_getfixturevalue_pattern(fixture_name: str, file_path: str) -> bool:
183
+ """Check if a fixture is used in request.getfixturevalue() pattern.
184
+
185
+ This catches dynamic fixture access patterns like:
186
+ - request.getfixturevalue(argname="fixture_name")
187
+ - request.getfixturevalue("fixture_name")
188
+ """
189
+ try:
190
+ with open(file_path) as f:
191
+ content = f.read()
192
+
193
+ tree = parse(source=content)
194
+
195
+ # Look for method calls like request.getfixturevalue(...)
196
+ for node in ast.walk(tree):
197
+ if isinstance(node, ast.Call):
198
+ # Check for attribute calls like request.getfixturevalue
199
+ if isinstance(node.func, ast.Attribute) and node.func.attr == "getfixturevalue":
200
+ # Check positional arguments
201
+ for arg in node.args:
202
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
203
+ if arg.value == fixture_name:
204
+ return True
205
+
206
+ # Check keyword arguments (argname="fixture_name")
207
+ for keyword in node.keywords:
208
+ if keyword.arg == "argname":
209
+ if (
210
+ isinstance(keyword.value, ast.Constant)
211
+ and isinstance(keyword.value.value, str)
212
+ and keyword.value.value == fixture_name
213
+ ):
214
+ return True
215
+
216
+ return False
217
+ except (FileNotFoundError, SyntaxError, ValueError):
218
+ return False
219
+
220
+
221
+ def _is_usefixtures_context(file_path: str, line_number: str, fixture_name: str) -> bool:
222
+ """Check if a fixture usage is within a pytest.mark.usefixtures context.
223
+
224
+ Uses AST parsing to efficiently check the context instead of reading lines.
225
+ """
226
+ try:
227
+ with open(file_path) as f:
228
+ content = f.read()
229
+
230
+ # Parse the AST of the file
231
+ tree = parse(source=content)
232
+ target_line = int(line_number)
233
+
234
+ # Look for pytest.mark.usefixtures calls that span the target line
235
+ for node in ast.walk(tree):
236
+ if isinstance(node, ast.Assign):
237
+ # Check if the value is a call to pytest.mark.usefixtures
238
+ if isinstance(node.value, ast.Call):
239
+ if _is_pytest_mark_usefixtures_call(node.value):
240
+ # Check if the target line is within this call's range
241
+ call_start = node.value.lineno
242
+ call_end = node.value.end_lineno or call_start
243
+
244
+ if call_start <= target_line <= call_end:
245
+ # Check if any of the arguments contain our fixture name
246
+ for arg in node.value.args:
247
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
248
+ if arg.value == fixture_name:
249
+ return True
250
+
251
+ # Also check if the value is a list containing pytest.mark.usefixtures calls
252
+ elif isinstance(node.value, ast.List):
253
+ for element in node.value.elts:
254
+ if isinstance(element, ast.Call) and _is_pytest_mark_usefixtures_call(element):
255
+ # Check if the target line is within this call's range
256
+ call_start = element.lineno
257
+ call_end = element.end_lineno or call_start
258
+
259
+ if call_start <= target_line <= call_end:
260
+ # Check if any of the arguments contain our fixture name
261
+ for arg in element.args:
262
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
263
+ if arg.value == fixture_name:
264
+ return True
265
+
266
+ # Also check decorators
267
+ elif isinstance(node, (ast.FunctionDef, ast.ClassDef)):
268
+ for decorator in node.decorator_list:
269
+ if isinstance(decorator, ast.Call) and _is_pytest_mark_usefixtures_call(decorator):
270
+ call_start = decorator.lineno
271
+ call_end = decorator.end_lineno or call_start
272
+
273
+ if call_start <= target_line <= call_end:
274
+ for arg in decorator.args:
275
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
276
+ if arg.value == fixture_name:
277
+ return True
278
+
279
+ return False
280
+ except (FileNotFoundError, SyntaxError, ValueError):
281
+ return False
282
+
283
+
284
+ def _is_documentation_pattern(line: str, function_name: str) -> bool:
285
+ """Check if a line contains a documentation pattern rather than a function call.
286
+
287
+ Filters out common documentation patterns that include function names with parentheses:
288
+ - Parameter descriptions: 'param_name (type): description'
289
+ - Type annotations in docstrings
290
+ - Inline documentation patterns
291
+ - Lines within triple-quoted strings that aren't actual code
292
+
293
+ Args:
294
+ line: The line of code to check
295
+ function_name: The function name we're searching for
296
+
297
+ Returns:
298
+ True if this appears to be documentation, False if it might be a function call
299
+ """
300
+ stripped_line = line.strip()
301
+
302
+ # First, exclude obvious code patterns that should never be considered documentation
303
+ # Skip control flow statements and common code patterns
304
+ code_prefixes = ["if ", "elif ", "while ", "for ", "with ", "assert ", "return ", "yield ", "raise "]
305
+ if any(stripped_line.startswith(prefix) for prefix in code_prefixes):
306
+ return False
307
+
308
+ # Skip function definitions (these are already filtered elsewhere but be extra safe)
309
+ if stripped_line.startswith("def "):
310
+ return False
311
+
312
+ # Pattern 1: Parameter description format "name (type): description"
313
+ # But be more specific - require either indentation or specific doc context
314
+ # This catches patterns like " namespace (str): The namespace of the pod."
315
+ if re.search(rf"^\s+{re.escape(function_name)}\s*\([^)]*\)\s*:", line):
316
+ return True
317
+
318
+ # Pattern 2: Lines that look like type annotations in docstrings
319
+ # Must have descriptive text after the colon, not just code
320
+ type_annotation_pattern = rf"\b{re.escape(function_name)}\s*\([^)]*\)\s*:\s+[A-Z][a-z]"
321
+ if re.search(type_annotation_pattern, stripped_line):
322
+ return True
323
+
324
+ # Pattern 3: Lines that contain common documentation keywords near the function name
325
+ doc_keywords = ["Args:", "Arguments:", "Parameters:", "Returns:", "Return:", "Raises:", "Note:", "Example:"]
326
+ for keyword in doc_keywords:
327
+ if keyword in stripped_line:
328
+ # If we find doc keywords and function name with parens, likely documentation
329
+ if f"{function_name}(" in stripped_line:
330
+ return True
331
+ # Also catch cases where the keyword line itself contains the function name
332
+ if keyword.rstrip(":").lower() == function_name.lower():
333
+ return True
334
+
335
+ # Pattern 4: Check for common docstring patterns
336
+ # Lines that start with common documentation patterns
337
+ doc_starters = ['"""', "'''", "# ", "## ", "### ", "*", "-", "•"]
338
+ if any(stripped_line.startswith(starter) for starter in doc_starters):
339
+ if f"{function_name}(" in stripped_line:
340
+ return True
341
+
342
+ return False
343
+
344
+
345
+ def _find_git_root(file_path: str) -> str:
346
+ """Find the git repository root for a given file path.
347
+
348
+ Args:
349
+ file_path: Path to a file within a git repository
350
+
351
+ Returns:
352
+ The git repository root path
353
+ """
354
+ path = Path(file_path).resolve().parent
355
+
356
+ while path != path.parent: # Stop at filesystem root
357
+ if (path / ".git").exists():
358
+ return str(path)
359
+ path = path.parent
360
+
361
+ # Fallback to current directory (we know it's a git repo from the main check)
362
+ return os.getcwd()
363
+
364
+
365
+ def _git_grep(pattern: str, file_path: str | None = None) -> list[str]:
366
+ """Run git grep with a pattern and return matching lines.
367
+
368
+ - Uses dynamically detected regex engine (prefers PCRE ``-P``, falls back to basic ``-G``).
369
+ - Includes untracked files so local changes are considered.
370
+ - Return an empty list when no matches are found (rc=1).
371
+ - Raise on other non-zero exit codes.
372
+ - If file_path is provided, runs git grep from the repository root of that file.
373
+
374
+ Args:
375
+ pattern: The regex pattern to search for
376
+ file_path: Optional file path to determine the git repository root
377
+ """
378
+ # Determine the working directory for git grep
379
+ if file_path:
380
+ cwd = _find_git_root(file_path)
381
+ else:
382
+ # Fall back to current directory (already verified as git repo)
383
+ cwd = os.getcwd()
384
+
385
+ cmd = [
386
+ "git",
387
+ "grep",
388
+ "-n", # include line numbers
389
+ "--no-color",
390
+ "--untracked",
391
+ "-I", # ignore binary files
392
+ _detect_supported_grep_flag(),
393
+ "-e", # safely handle patterns starting with dash
394
+ pattern,
395
+ ]
396
+ result = subprocess.run(cmd, check=False, capture_output=True, text=True, cwd=cwd)
397
+ if result.returncode == 0:
398
+ return [line for line in result.stdout.splitlines() if line]
399
+ # rc=1 means no matches were found
400
+ if result.returncode == 1:
401
+ return []
402
+
403
+ error_message = result.stderr.strip() or "Unknown git grep error"
404
+ raise RuntimeError(f"git grep failed (rc={result.returncode}) for pattern {pattern!r}: {error_message}")
405
+
406
+
407
+ def _iter_functions(tree: ast.Module) -> Iterable[ast.FunctionDef]:
408
+ """
409
+ Get all function from python file
410
+ """
411
+ for elm in tree.body:
412
+ if isinstance(elm, ast.FunctionDef):
413
+ if elm.name.startswith("test_"):
414
+ continue
415
+
416
+ yield elm
417
+
418
+
419
+ def is_ignore_function_list(ignore_prefix_list: list[str], function: ast.FunctionDef) -> bool:
420
+ ignore_function_lists = [
421
+ function.name for ignore_prefix in ignore_prefix_list if function.name.startswith(ignore_prefix)
422
+ ]
423
+ if ignore_function_lists:
424
+ return True
425
+
426
+ return False
427
+
428
+
429
+ def _resolve_absolute_path(git_grep_path: str, reference_file: str) -> str:
430
+ """Convert git grep path to absolute path if needed."""
431
+ if not os.path.isabs(git_grep_path):
432
+ git_root = _find_git_root(reference_file)
433
+ return os.path.join(git_root, git_grep_path)
434
+ return git_grep_path
435
+
436
+
437
+ def process_file(py_file: str, func_ignore_prefix: list[str], file_ignore_list: list[str]) -> str:
438
+ if os.path.basename(py_file) in file_ignore_list:
439
+ LOGGER.debug(f"Skipping file: {py_file}")
440
+ return ""
441
+
442
+ with open(py_file) as fd:
443
+ tree = parse(source=fd.read())
444
+
445
+ unused_messages: list[str] = []
446
+
447
+ for func in _iter_functions(tree=tree):
448
+ if func_ignore_prefix and is_ignore_function_list(ignore_prefix_list=func_ignore_prefix, function=func):
449
+ LOGGER.debug(f"Skipping function: {func.name}")
450
+ continue
451
+
452
+ if is_fixture_autouse(func=func):
453
+ LOGGER.debug(f"Skipping `autouse` fixture function: {func.name}")
454
+ continue
455
+
456
+ if any(getattr(item, "value", None) == "# skip-unused-code" for item in func.body):
457
+ LOGGER.debug(f"Skipping function {func.name}: found `# skip-unused-code`")
458
+ continue
459
+
460
+ used = False
461
+
462
+ # Search for any occurrence of the function name as a whole word.
463
+ for entry in _git_grep(pattern=_build_usage_pattern(function_name=func.name), file_path=py_file):
464
+ # git grep -n output format: path:line-number:line-content
465
+ parts = entry.split(":", 2)
466
+ if len(parts) != 3:
467
+ continue
468
+ _, _, _line = parts
469
+
470
+ # ignore its own definition
471
+ if f"def {func.name}" in _line:
472
+ continue
473
+
474
+ # Filter out documentation patterns that aren't actual function calls
475
+ if _is_documentation_pattern(_line, func.name):
476
+ continue
477
+
478
+ # Ignore commented lines (full line or inline)
479
+ code_part = _line.split("#", 1)[0]
480
+ if code_part.startswith("import") or code_part.startswith("from"):
481
+ continue
482
+
483
+ if func.name not in code_part:
484
+ continue
485
+
486
+ # If we are here, it's a valid usage.
487
+ used = True
488
+ break
489
+
490
+ # If not found and it's a pytest fixture, check all fixture usage patterns
491
+ if not used and is_pytest_fixture(func=func):
492
+ patterns: list[tuple[str, Callable[..., bool] | None]] = [
493
+ (_build_fixture_param_pattern(function_name=func.name), None), # Parameter usage
494
+ (rf'"{func.name}"', _is_usefixtures_context), # usefixtures usage
495
+ (rf'fixturenames\.insert.*"{func.name}"', _check_fixturenames_insert_pattern), # fixturenames.insert
496
+ (rf'getfixturevalue.*"{func.name}"', _check_getfixturevalue_pattern), # getfixturevalue
497
+ ]
498
+
499
+ for pattern, validator_func in patterns:
500
+ for entry in _git_grep(pattern=pattern, file_path=py_file):
501
+ parts = entry.split(":", 2)
502
+ if len(parts) != 3:
503
+ continue
504
+ _path, _lineno, _line = parts
505
+
506
+ # ignore commented lines
507
+ if _line.strip().startswith("#"):
508
+ continue
509
+
510
+ absolute_path = _resolve_absolute_path(_path, py_file)
511
+
512
+ # Apply validator function if provided, otherwise it's a match
513
+ if validator_func is None:
514
+ used = True
515
+ break
516
+ elif validator_func == _is_usefixtures_context:
517
+ if validator_func(absolute_path, _lineno, func.name):
518
+ used = True
519
+ break
520
+ else: # _check_fixturenames_insert_pattern or _check_getfixturevalue_pattern
521
+ if validator_func(func.name, absolute_path):
522
+ used = True
523
+ break
524
+
525
+ if used:
526
+ break
527
+
528
+ if not used:
529
+ unused_messages.append(
530
+ f"{os.path.relpath(py_file)}:{func.name}:{func.lineno}:{func.col_offset} Is not used anywhere in the code."
531
+ )
532
+
533
+ return "\n".join(unused_messages)
534
+
535
+
536
+ @click.command()
537
+ @click.option(
538
+ "--config-file-path",
539
+ help="Provide absolute path to the config file. Any CLI option(s) would override YAML file",
540
+ type=click.Path(),
541
+ default=os.path.expanduser("~/.config/python-utility-scripts/config.yaml"),
542
+ )
543
+ @click.option(
544
+ "--exclude-files",
545
+ help="Provide a comma-separated string or list of files to exclude",
546
+ type=ListParamType(),
547
+ )
548
+ @click.option(
549
+ "--exclude-function-prefixes",
550
+ help="Provide a comma-separated string or list of function prefixes to exclude",
551
+ type=ListParamType(),
552
+ )
553
+ @click.option("--verbose", "-v", default=False, is_flag=True)
554
+ @click.option(
555
+ "--file-path",
556
+ "-f",
557
+ help="Analyze a single Python file for unused functions. Must be an existing .py file.",
558
+ type=click.Path(exists=True),
559
+ )
560
+ @click.option(
561
+ "--directory",
562
+ "-d",
563
+ help="Analyze all Python files in a directory recursively for unused functions. Must be an existing directory.",
564
+ type=click.Path(exists=True, dir_okay=True),
565
+ )
566
+ def get_unused_functions(
567
+ config_file_path: str,
568
+ exclude_files: list[str],
569
+ exclude_function_prefixes: list[str],
570
+ verbose: bool,
571
+ file_path: click.Path,
572
+ directory: click.Path,
573
+ ) -> None:
574
+ LOGGER.setLevel(logging.DEBUG if verbose else logging.INFO)
575
+
576
+ if file_path and not os.path.isfile(str(file_path)):
577
+ LOGGER.error("File path must be a file, not a directory.")
578
+ sys.exit(1)
579
+
580
+ if directory and not os.path.isdir(str(directory)):
581
+ LOGGER.error("Directory must be a directory, not a file.")
582
+ sys.exit(1)
583
+
584
+ unused_functions: list[str] = []
585
+ unused_code_config = get_util_config(util_name="pyutils-unusedcode", config_file_path=config_file_path)
586
+ func_ignore_prefix = exclude_function_prefixes or unused_code_config.get("exclude_function_prefix", [])
587
+ file_ignore_list = exclude_files or unused_code_config.get("exclude_files", [])
588
+
589
+ jobs: dict[Future, str] = {}
590
+ if not os.path.exists(".git"):
591
+ LOGGER.error("Must be run from a git repository")
592
+ sys.exit(1)
593
+
594
+ # Pre-flight grep flag detection to fail fast with clear error if unsupported
595
+ try:
596
+ detected_flag = _detect_supported_grep_flag()
597
+ LOGGER.debug(f"Using git grep flag: {detected_flag}")
598
+ except RuntimeError as e:
599
+ LOGGER.error(str(e))
600
+ sys.exit(1)
601
+
602
+ if file_path:
603
+ _unused_functions = process_file(
604
+ py_file=str(file_path),
605
+ func_ignore_prefix=func_ignore_prefix,
606
+ file_ignore_list=file_ignore_list,
607
+ )
608
+ if _unused_functions:
609
+ unused_functions.append(_unused_functions)
610
+ else:
611
+ with ThreadPoolExecutor() as executor:
612
+ for py_file in all_python_files(directory=directory):
613
+ future = executor.submit(
614
+ process_file,
615
+ py_file=py_file,
616
+ func_ignore_prefix=func_ignore_prefix,
617
+ file_ignore_list=file_ignore_list,
618
+ )
619
+ jobs[future] = py_file
620
+
621
+ processing_errors: list[str] = []
622
+ for future in as_completed(jobs):
623
+ try:
624
+ if unused_func := future.result():
625
+ unused_functions.append(unused_func)
626
+ except Exception as exc:
627
+ processing_errors.append(f"{jobs[future]}: {exc}")
628
+
629
+ if processing_errors:
630
+ joined = "\n".join(processing_errors)
631
+ LOGGER.error(f"One or more files failed to process:\n{joined}")
632
+ sys.exit(2)
633
+
634
+ if unused_functions:
635
+ # Sort output for deterministic CI logs
636
+ sorted_output = sorted(unused_functions)
637
+ click.echo("\n".join(sorted_output))
638
+ sys.exit(1)
639
+
640
+
641
+ if __name__ == "__main__":
642
+ get_unused_functions()
@@ -73,12 +73,14 @@ class ListParamType(click.ParamType):
73
73
  )
74
74
 
75
75
 
76
- def all_python_files() -> Iterable[str]:
76
+ def all_python_files(directory: click.Path | None = None) -> Iterable[str]:
77
77
  """
78
78
  Get all python files from current directory and subdirectories
79
79
  """
80
80
  exclude_dirs = [".tox", "venv", ".pytest_cache", "site-packages", ".git"]
81
- for root, _, files in os.walk(os.path.abspath(os.curdir)):
81
+ target = str(directory) if directory else os.path.abspath(os.curdir)
82
+
83
+ for root, _, files in os.walk(target):
82
84
  if [_dir for _dir in exclude_dirs if _dir in root]:
83
85
  continue
84
86
  for filename in files:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "python-utility-scripts"
3
- version = "1.0.23"
3
+ version = "1.0.25"
4
4
  description = "Python utility scripts"
5
5
  requires-python = ">=3.9"
6
6
  readme = "README.md"
@@ -45,7 +45,7 @@ skip_empty = true
45
45
 
46
46
  [tool.coverage.html]
47
47
  directory = ".tests_coverage"
48
- show_contexts = true
48
+ show_contexts = false
49
49
 
50
50
  [tool.uv]
51
51
  default-groups = [ "dev", "test" ]
@@ -1,48 +0,0 @@
1
- # pyutils-unusedcode
2
-
3
- Helper to identify unused code in a pytest repository. It should be run from inside the test repository using this tool.
4
-
5
- ## Usage
6
-
7
- ```bash
8
- pyutils-unusedcode
9
- pyutils-unusedcode --help
10
- ```
11
-
12
- ## Config file
13
-
14
- To skip unused code check on specific files or functions of a repository, a config file with the list of names of such files and function prefixes should be added to
15
- `~/.config/python-utility-scripts/config.yaml`
16
-
17
- ### Example
18
-
19
- ```yaml
20
- pyutils-unusedcode:
21
- exclude_files:
22
- - "my_exclude_file.py"
23
- exclude_function_prefix:
24
- - "my_exclude_function_prefix"
25
- ```
26
-
27
- This would exclude any functions with prefix my_exclude_function_prefix and file my_exclude_file.py from unused code check
28
-
29
- To run from CLI with `--exclude-function-prefixes`
30
-
31
- ```bash
32
- pyutils-unusedcode --exclude-function-prefixes 'my_exclude_function1,my_exclude_function2'
33
- ```
34
-
35
- To run from CLI with `--exclude-files`
36
-
37
- ```bash
38
- pyutils-unusedcode --exclude-files 'my_exclude_file1.py,my_exclude_file2.py'
39
- ```
40
-
41
- ### Skip single function in file
42
-
43
- Add `# skip-unused-code` comment in the function name list to skip it from check.
44
-
45
- ```python
46
- def my_function(): # skip-unused-code
47
- pass
48
- ```
@@ -1,153 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import ast
4
- import logging
5
- import os
6
- import subprocess
7
- import sys
8
- from concurrent.futures import Future, ThreadPoolExecutor, as_completed
9
- from typing import Any, Iterable
10
-
11
- import click
12
- from ast_comments import parse
13
- from simple_logger.logger import get_logger
14
-
15
- from apps.utils import ListParamType, all_python_files, get_util_config
16
-
17
- LOGGER = get_logger(name=__name__)
18
-
19
-
20
- def is_fixture_autouse(func: ast.FunctionDef) -> bool:
21
- deco_list: list[Any] = func.decorator_list
22
- for deco in deco_list or []:
23
- if not hasattr(deco, "func"):
24
- continue
25
-
26
- if getattr(deco.func, "attr", None) and getattr(deco.func, "value", None):
27
- if deco.func.attr == "fixture" and deco.func.value.id == "pytest":
28
- for _key in deco.keywords:
29
- if _key.arg == "autouse":
30
- return True
31
- return False
32
-
33
-
34
- def _iter_functions(tree: ast.Module) -> Iterable[ast.FunctionDef]:
35
- """
36
- Get all function from python file
37
- """
38
- for elm in tree.body:
39
- if isinstance(elm, ast.FunctionDef):
40
- if elm.name.startswith("test_"):
41
- continue
42
-
43
- yield elm
44
-
45
-
46
- def is_ignore_function_list(ignore_prefix_list: list[str], function: ast.FunctionDef) -> bool:
47
- ignore_function_lists = [
48
- function.name for ignore_prefix in ignore_prefix_list if function.name.startswith(ignore_prefix)
49
- ]
50
- if ignore_function_lists:
51
- return True
52
-
53
- return False
54
-
55
-
56
- def process_file(py_file: str, func_ignore_prefix: list[str], file_ignore_list: list[str]) -> str:
57
- if os.path.basename(py_file) in file_ignore_list:
58
- LOGGER.debug(f"Skipping file: {py_file}")
59
- return ""
60
-
61
- with open(py_file) as fd:
62
- tree = parse(source=fd.read())
63
-
64
- for func in _iter_functions(tree=tree):
65
- if func_ignore_prefix and is_ignore_function_list(ignore_prefix_list=func_ignore_prefix, function=func):
66
- LOGGER.debug(f"Skipping function: {func.name}")
67
- continue
68
-
69
- if is_fixture_autouse(func=func):
70
- LOGGER.debug(f"Skipping `autouse` fixture function: {func.name}")
71
- continue
72
-
73
- if any(getattr(item, "value", None) == "# skip-unused-code" for item in func.body):
74
- LOGGER.debug(f"Skipping function {func.name}: found `# skip-unused-code`")
75
- continue
76
-
77
- used = False
78
- _func_grep_found = subprocess.check_output(["git", "grep", "-wE", f"{func.name}(.*)"], shell=False)
79
-
80
- for entry in _func_grep_found.decode().splitlines():
81
- _, _line = entry.split(":", 1)
82
-
83
- if f"def {func.name}" in _line:
84
- continue
85
-
86
- if _line.strip().startswith("#"):
87
- continue
88
-
89
- if func.name in _line:
90
- used = True
91
- break
92
-
93
- if not used:
94
- return f"{os.path.relpath(py_file)}:{func.name}:{func.lineno}:{func.col_offset} Is not used anywhere in the code."
95
-
96
- return ""
97
-
98
-
99
- @click.command()
100
- @click.option(
101
- "--config-file-path",
102
- help="Provide absolute path to the config file. Any CLI option(s) would override YAML file",
103
- type=click.Path(),
104
- default=os.path.expanduser("~/.config/python-utility-scripts/config.yaml"),
105
- )
106
- @click.option(
107
- "--exclude-files",
108
- help="Provide a comma-separated string or list of files to exclude",
109
- type=ListParamType(),
110
- )
111
- @click.option(
112
- "--exclude-function-prefixes",
113
- help="Provide a comma-separated string or list of function prefixes to exclude",
114
- type=ListParamType(),
115
- )
116
- @click.option("--verbose", "-v", default=False, is_flag=True)
117
- def get_unused_functions(
118
- config_file_path: str, exclude_files: list[str], exclude_function_prefixes: list[str], verbose: bool
119
- ) -> None:
120
- LOGGER.setLevel(logging.DEBUG if verbose else logging.INFO)
121
-
122
- unused_functions: list[str] = []
123
- unused_code_config = get_util_config(util_name="pyutils-unusedcode", config_file_path=config_file_path)
124
- func_ignore_prefix = exclude_function_prefixes or unused_code_config.get("exclude_function_prefix", [])
125
- file_ignore_list = exclude_files or unused_code_config.get("exclude_files", [])
126
-
127
- jobs: list[Future] = []
128
- if not os.path.exists(".git"):
129
- LOGGER.error("Must be run from a git repository")
130
- sys.exit(1)
131
-
132
- with ThreadPoolExecutor() as executor:
133
- for py_file in all_python_files():
134
- jobs.append(
135
- executor.submit(
136
- process_file,
137
- py_file=py_file,
138
- func_ignore_prefix=func_ignore_prefix,
139
- file_ignore_list=file_ignore_list,
140
- )
141
- )
142
-
143
- for result in as_completed(jobs):
144
- if unused_func := result.result():
145
- unused_functions.append(unused_func)
146
-
147
- if unused_functions:
148
- click.echo("\n".join(unused_functions))
149
- sys.exit(1)
150
-
151
-
152
- if __name__ == "__main__":
153
- get_unused_functions()