staleif 0.1.5__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.
staleif-0.1.5/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 José Luis Segura Yuste
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
staleif-0.1.5/PKG-INFO ADDED
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: staleif
3
+ Version: 0.1.5
4
+ Summary: Encuentra bloques 'if sys.version_info < (X, Y)' que ya son codigo muerto porque el requires-python del proyecto ya no soporta versiones tan viejas -- con contexto de git blame de cuando se anadieron.
5
+ Author: José Luis Segura Yuste
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jl-segurayuste/staleif
8
+ Project-URL: Source, https://github.com/jl-segurayuste/staleif
9
+ Project-URL: Issues, https://github.com/jl-segurayuste/staleif/issues
10
+ Project-URL: Changelog, https://github.com/jl-segurayuste/staleif/releases
11
+ Keywords: developer-tools,dead-code,static-analysis
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Natural Language :: Spanish
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
23
+ Classifier: Topic :: Software Development :: Quality Assurance
24
+ Requires-Python: >=3.11
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: pydantic>=2.6
28
+ Requires-Dist: packaging>=23.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.4; extra == "dev"
31
+ Requires-Dist: pytest-cov>=5; extra == "dev"
32
+ Requires-Dist: ruff==0.17.6; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # staleif
36
+
37
+ [![PyPI](https://img.shields.io/pypi/v/staleif.svg)](https://pypi.org/project/staleif/)
38
+ [![CI](https://github.com/jl-segurayuste/staleif/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/staleif/actions/workflows/ci.yml)
39
+ [![Python 3.11–3.15](https://img.shields.io/badge/python-3.11%20%E2%80%93%203.15-blue.svg)](https://github.com/jl-segurayuste/staleif/blob/main/pyproject.toml)
40
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/staleif/blob/main/LICENSE)
41
+
42
+ Encuentra bloques `if sys.version_info < (X, Y):` que ya son código muerto
43
+ — porque el propio `requires-python` del proyecto hace tiempo que dejó de
44
+ soportar versiones tan viejas — con el contexto de git blame de cuándo y
45
+ por qué se añadieron.
46
+
47
+ ```
48
+ $ staleif scan .
49
+
50
+ [IF MUERTO] compat.py:12 -- sys.version_info < (3, 8)
51
+ El proyecto ya requiere Python >= 3.11, así que esta condición
52
+ nunca es verdadera -- la rama 'if' es inalcanzable.
53
+ Añadido en a1b2c3d4 por dev@ejemplo-demo.es: "workaround para python 3.7"
54
+
55
+ Total: 1 guarda(s) de versión muerta(s).
56
+ ```
57
+
58
+ ## Así se ve
59
+
60
+ ![Salida de staleif sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/staleif/main/docs/img/demo.svg)
61
+
62
+ <sub>Ejecución real sobre una librería que ya exige Python 3.11 pero conserva guardas para 3.7 (todos los datos son ficticios).</sub>
63
+
64
+ ## Por qué existe
65
+
66
+ Los "workarounds" condicionados a la versión de Python son de los tipos de
67
+ código muerto más fáciles de dejar olvidados: se añaden con buena razón, el
68
+ proyecto sube su `requires-python` mínimo con el tiempo, y nadie vuelve a
69
+ por el `if` que ya nunca se ejecuta. A diferencia de detectar código muerto
70
+ en general (funciones/imports sin usar), esto es 100% mecánico: si el
71
+ proyecto ya no soporta la versión que el `if` comprueba, la rama es
72
+ matemáticamente inalcanzable — no hace falta ninguna heurística.
73
+
74
+ ## Instalación
75
+
76
+ Todavía no está en PyPI:
77
+
78
+ ```bash
79
+ pipx install staleif # recomendado para herramientas de línea de comandos
80
+ # o bien
81
+ pip install staleif
82
+ ```
83
+
84
+ ## Uso
85
+
86
+ ```bash
87
+ staleif scan .
88
+ staleif scan . --json
89
+ staleif scan . --fail-on-found # código de salida 1 si hay alguna
90
+ ```
91
+
92
+ Lee el `requires-python` de `pyproject.toml`, recorre los ficheros `.py`
93
+ rastreados por git buscando comparaciones contra `sys.version_info` (vía
94
+ `ast`, no regex), y usa `git blame` para mostrar cuándo y por qué se
95
+ introdujo cada guarda que ya es código muerto.
96
+
97
+ ## Qué NO detecta (todavía)
98
+
99
+ - Comparaciones contra `__version__` de paquetes de terceros (ver
100
+ [depweight](https://github.com/jl-segurayuste/depweight)/
101
+ [depexplain](https://github.com/jl-segurayuste/depexplain) para el
102
+ ángulo de dependencias).
103
+ - `platform.python_version_tuple()` u otras formas no literales de
104
+ comprobar la versión.
105
+ - Comparaciones con `==` (ambiguas: podrían seguir aplicando a una versión
106
+ exacta dentro del rango soportado).
107
+
108
+ ## Desarrollo
109
+
110
+ ```bash
111
+ pip install -e ".[dev]"
112
+ ruff check .
113
+ pytest
114
+ ```
@@ -0,0 +1,80 @@
1
+ # staleif
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/staleif.svg)](https://pypi.org/project/staleif/)
4
+ [![CI](https://github.com/jl-segurayuste/staleif/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/staleif/actions/workflows/ci.yml)
5
+ [![Python 3.11–3.15](https://img.shields.io/badge/python-3.11%20%E2%80%93%203.15-blue.svg)](https://github.com/jl-segurayuste/staleif/blob/main/pyproject.toml)
6
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/staleif/blob/main/LICENSE)
7
+
8
+ Encuentra bloques `if sys.version_info < (X, Y):` que ya son código muerto
9
+ — porque el propio `requires-python` del proyecto hace tiempo que dejó de
10
+ soportar versiones tan viejas — con el contexto de git blame de cuándo y
11
+ por qué se añadieron.
12
+
13
+ ```
14
+ $ staleif scan .
15
+
16
+ [IF MUERTO] compat.py:12 -- sys.version_info < (3, 8)
17
+ El proyecto ya requiere Python >= 3.11, así que esta condición
18
+ nunca es verdadera -- la rama 'if' es inalcanzable.
19
+ Añadido en a1b2c3d4 por dev@ejemplo-demo.es: "workaround para python 3.7"
20
+
21
+ Total: 1 guarda(s) de versión muerta(s).
22
+ ```
23
+
24
+ ## Así se ve
25
+
26
+ ![Salida de staleif sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/staleif/main/docs/img/demo.svg)
27
+
28
+ <sub>Ejecución real sobre una librería que ya exige Python 3.11 pero conserva guardas para 3.7 (todos los datos son ficticios).</sub>
29
+
30
+ ## Por qué existe
31
+
32
+ Los "workarounds" condicionados a la versión de Python son de los tipos de
33
+ código muerto más fáciles de dejar olvidados: se añaden con buena razón, el
34
+ proyecto sube su `requires-python` mínimo con el tiempo, y nadie vuelve a
35
+ por el `if` que ya nunca se ejecuta. A diferencia de detectar código muerto
36
+ en general (funciones/imports sin usar), esto es 100% mecánico: si el
37
+ proyecto ya no soporta la versión que el `if` comprueba, la rama es
38
+ matemáticamente inalcanzable — no hace falta ninguna heurística.
39
+
40
+ ## Instalación
41
+
42
+ Todavía no está en PyPI:
43
+
44
+ ```bash
45
+ pipx install staleif # recomendado para herramientas de línea de comandos
46
+ # o bien
47
+ pip install staleif
48
+ ```
49
+
50
+ ## Uso
51
+
52
+ ```bash
53
+ staleif scan .
54
+ staleif scan . --json
55
+ staleif scan . --fail-on-found # código de salida 1 si hay alguna
56
+ ```
57
+
58
+ Lee el `requires-python` de `pyproject.toml`, recorre los ficheros `.py`
59
+ rastreados por git buscando comparaciones contra `sys.version_info` (vía
60
+ `ast`, no regex), y usa `git blame` para mostrar cuándo y por qué se
61
+ introdujo cada guarda que ya es código muerto.
62
+
63
+ ## Qué NO detecta (todavía)
64
+
65
+ - Comparaciones contra `__version__` de paquetes de terceros (ver
66
+ [depweight](https://github.com/jl-segurayuste/depweight)/
67
+ [depexplain](https://github.com/jl-segurayuste/depexplain) para el
68
+ ángulo de dependencias).
69
+ - `platform.python_version_tuple()` u otras formas no literales de
70
+ comprobar la versión.
71
+ - Comparaciones con `==` (ambiguas: podrían seguir aplicando a una versión
72
+ exacta dentro del rango soportado).
73
+
74
+ ## Desarrollo
75
+
76
+ ```bash
77
+ pip install -e ".[dev]"
78
+ ruff check .
79
+ pytest
80
+ ```
@@ -0,0 +1,60 @@
1
+ [project]
2
+ name = "staleif"
3
+ version = "0.1.5"
4
+ description = "Encuentra bloques 'if sys.version_info < (X, Y)' que ya son codigo muerto porque el requires-python del proyecto ya no soporta versiones tan viejas -- con contexto de git blame de cuando se anadieron."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ authors = [{ name = "José Luis Segura Yuste" }]
8
+ keywords = ["developer-tools", "dead-code", "static-analysis"]
9
+ classifiers = [
10
+ "Development Status :: 4 - Beta",
11
+ "Environment :: Console",
12
+ "Intended Audience :: Developers",
13
+ "Natural Language :: Spanish",
14
+ "Operating System :: OS Independent",
15
+ "Programming Language :: Python :: 3 :: Only",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Programming Language :: Python :: 3.14",
20
+ "Programming Language :: Python :: 3.15",
21
+ "Topic :: Software Development :: Quality Assurance",
22
+ ]
23
+ requires-python = ">=3.11"
24
+ dependencies = ["pydantic>=2.6", "packaging>=23.0"]
25
+
26
+ [project.optional-dependencies]
27
+ dev = ["pytest>=7.4", "pytest-cov>=5", "ruff==0.17.6"]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/jl-segurayuste/staleif"
31
+ Source = "https://github.com/jl-segurayuste/staleif"
32
+ Issues = "https://github.com/jl-segurayuste/staleif/issues"
33
+ Changelog = "https://github.com/jl-segurayuste/staleif/releases"
34
+
35
+ [project.scripts]
36
+ staleif = "staleif.cli:main"
37
+
38
+ [tool.setuptools.packages.find]
39
+ include = ["staleif*"]
40
+
41
+ [tool.ruff]
42
+ line-length = 100
43
+ target-version = "py311"
44
+
45
+ [tool.pytest.ini_options]
46
+ testpaths = ["tests"]
47
+
48
+ [build-system]
49
+ requires = ["setuptools>=77"]
50
+ build-backend = "setuptools.build_meta"
51
+
52
+ [tool.coverage.run]
53
+ branch = true
54
+ source = ["staleif"]
55
+
56
+ [tool.coverage.report]
57
+ # Mínimo exigido en el CI: la cobertura medida al añadirlo (92 %) menos un margen.
58
+ fail_under = 89
59
+ show_missing = true
60
+ skip_covered = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """staleif — encuentra guardas de versión de Python que ya son código muerto."""
2
+
3
+ __version__ = "0.1.5"
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from staleif.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
@@ -0,0 +1,92 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import subprocess
5
+ from pathlib import Path
6
+
7
+ from staleif.blame import blame_line
8
+ from staleif.detect import find_version_guards
9
+ from staleif.plugin import Finding
10
+ from staleif.pyver import project_min_python_version
11
+ from staleif.verlogic import branch_verdict
12
+
13
+ _OP_SYMBOL = {"Lt": "<", "LtE": "<=", "Gt": ">", "GtE": ">="}
14
+
15
+
16
+ def _tracked_python_files(repo_path: Path) -> list[Path] | None:
17
+ result = subprocess.run(
18
+ ["git", "-c", "core.quotePath=false", "ls-files", "*.py"], cwd=repo_path, capture_output=True, text=True, check=False
19
+ )
20
+ if result.returncode != 0:
21
+ return None
22
+ return [repo_path / line for line in result.stdout.splitlines() if line]
23
+
24
+
25
+ def analyze_repo(repo_path: Path) -> list[Finding] | None:
26
+ """None si no hay `requires-python` declarado (no aplica) o si no es un repo git."""
27
+ min_version = project_min_python_version(repo_path)
28
+ if min_version is None:
29
+ return None
30
+
31
+ files = _tracked_python_files(repo_path)
32
+ if files is None:
33
+ return None
34
+
35
+ findings: list[Finding] = []
36
+ for path in files:
37
+ try:
38
+ source = path.read_text(encoding="utf-8")
39
+ tree = ast.parse(source)
40
+ except (OSError, UnicodeDecodeError, SyntaxError):
41
+ continue
42
+
43
+ rel = str(path.relative_to(repo_path))
44
+ for guard in find_version_guards(tree):
45
+ # Si la comparación real era contra un subíndice/slice (ej.
46
+ # "sys.version_info[0]"), solo esos componentes iniciales del suelo
47
+ # mínimo son relevantes -- comparar contra el resto (ej. el minor de
48
+ # un "requires-python >=3.8") produce un veredicto incorrecto. Si no
49
+ # hay suelo fiable para ese subíndice concreto (ej. "[2]" -- micro --
50
+ # cuando requires-python solo da mayor.menor), no se puede razonar
51
+ # con seguridad: se omite el guard en vez de adivinar.
52
+ if guard.projection is None:
53
+ effective_min_version = min_version
54
+ elif guard.projection <= len(min_version):
55
+ effective_min_version = min_version[: guard.projection]
56
+ else:
57
+ continue
58
+ verdict = branch_verdict(guard.op_name, guard.threshold, effective_min_version)
59
+ if verdict == "live":
60
+ continue
61
+ if verdict == "else_dead" and not guard.has_else:
62
+ continue # no hay rama else que sea codigo muerto
63
+
64
+ condition = f"sys.version_info {_OP_SYMBOL[guard.op_name]} {guard.threshold}"
65
+ lineno = guard.if_node.lineno
66
+ blame = blame_line(repo_path, rel, lineno) or {}
67
+
68
+ if verdict == "if_dead":
69
+ detail = (
70
+ f"El proyecto ya requiere Python >= {'.'.join(map(str, min_version))}, "
71
+ "así que esta condición nunca es verdadera -- la rama 'if' es inalcanzable."
72
+ )
73
+ else:
74
+ detail = (
75
+ f"El proyecto ya requiere Python >= {'.'.join(map(str, min_version))}, "
76
+ "así que esta condición siempre es verdadera -- la rama 'else' es inalcanzable."
77
+ )
78
+
79
+ findings.append(
80
+ Finding(
81
+ path=rel,
82
+ line=lineno,
83
+ verdict=verdict,
84
+ condition=condition,
85
+ detail=detail,
86
+ commit=blame.get("commit"),
87
+ author=blame.get("author"),
88
+ summary=blame.get("summary"),
89
+ )
90
+ )
91
+
92
+ return findings
@@ -0,0 +1,30 @@
1
+ from __future__ import annotations
2
+
3
+ import subprocess
4
+ from pathlib import Path
5
+
6
+
7
+ def blame_line(repo_path: Path, relpath: str, lineno: int) -> dict[str, str] | None:
8
+ """Autor/commit/resumen de la línea `lineno` de `relpath`, vía `git blame`."""
9
+ result = subprocess.run(
10
+ ["git", "blame", "-L", f"{lineno},{lineno}", "--porcelain", "--", relpath],
11
+ cwd=repo_path,
12
+ capture_output=True,
13
+ text=True,
14
+ check=False,
15
+ )
16
+ if result.returncode != 0 or not result.stdout:
17
+ return None
18
+ if set(result.stdout.split(maxsplit=1)[0]) == {"0"}:
19
+ return None # línea sin commitear: git la atribuye a «Not Committed Yet»
20
+
21
+ lines = result.stdout.splitlines()
22
+ info: dict[str, str] = {"commit": lines[0].split()[0]}
23
+ for line in lines[1:]:
24
+ if line.startswith("author "):
25
+ info["author"] = line[len("author ") :]
26
+ elif line.startswith("author-time "):
27
+ info["author_time"] = line[len("author-time ") :]
28
+ elif line.startswith("summary "):
29
+ info["summary"] = line[len("summary ") :]
30
+ return info
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from staleif import __version__
8
+ from staleif.analyze import analyze_repo
9
+ from staleif.report import to_console, to_json
10
+
11
+
12
+ def _cmd_scan(args: argparse.Namespace) -> int:
13
+ repo_path = Path(args.path).resolve()
14
+ findings = analyze_repo(repo_path)
15
+
16
+ if findings is None:
17
+ print("No aplica: no hay 'requires-python' en pyproject.toml, o no es un repo git.")
18
+ return 0
19
+
20
+ if args.json:
21
+ print(to_json(findings))
22
+ else:
23
+ print(to_console(findings))
24
+
25
+ if args.fail_on_found and findings:
26
+ return 1
27
+ return 0
28
+
29
+
30
+ def build_parser() -> argparse.ArgumentParser:
31
+ parser = argparse.ArgumentParser(prog="staleif")
32
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
33
+ sub = parser.add_subparsers(dest="command", required=True)
34
+
35
+ p_scan = sub.add_parser("scan", help="Busca guardas de sys.version_info ya muertas")
36
+ p_scan.add_argument("path", nargs="?", default=".")
37
+ p_scan.add_argument("--json", action="store_true")
38
+ p_scan.add_argument("--fail-on-found", action="store_true")
39
+ p_scan.set_defaults(func=_cmd_scan)
40
+
41
+ return parser
42
+
43
+
44
+ def main(argv: list[str] | None = None) -> int:
45
+ parser = build_parser()
46
+ args = parser.parse_args(argv)
47
+ return args.func(args)
48
+
49
+
50
+ if __name__ == "__main__":
51
+ sys.exit(main())
@@ -0,0 +1,109 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+
5
+ _FLIP_OP = {"Lt": "Gt", "LtE": "GtE", "Gt": "Lt", "GtE": "LtE", "Eq": "Eq"}
6
+
7
+
8
+ def _is_version_info_expr(node: ast.AST) -> bool:
9
+ if isinstance(node, ast.Attribute) and node.attr == "version_info":
10
+ return isinstance(node.value, ast.Name) and node.value.id == "sys"
11
+ if isinstance(node, ast.Attribute) and node.attr in ("major", "minor", "micro"):
12
+ return _is_version_info_expr(node.value) # sys.version_info.major
13
+ if isinstance(node, ast.Subscript):
14
+ return _is_version_info_expr(node.value)
15
+ return False
16
+
17
+
18
+ def _projection_from_node(node: ast.AST) -> int | None:
19
+ """Si `node` es `sys.version_info` sin subíndice, devuelve None (compara la
20
+ tupla entera). Si es `sys.version_info[N]` (índice entero literal), devuelve
21
+ N+1 -- el número de componentes iniciales que de verdad importan para esta
22
+ comparación ("[0]" solo mira el mayor, así que solo el componente 0 cuenta).
23
+ Si es `sys.version_info[:N]`, igualmente devuelve N. Cualquier otra forma de
24
+ subíndice (variable, slice con paso, índice negativo...) devuelve -1: "no se
25
+ puede razonar con seguridad", para que el llamador se abstenga en vez de
26
+ adivinar -- ver el bug real de `sys.version_info[0] > 3` en el docstring del
27
+ módulo."""
28
+ if isinstance(node, ast.Attribute):
29
+ if node.attr == "major":
30
+ return 1 # como "[0]"
31
+ if node.attr in ("minor", "micro"):
32
+ return -1 # sin el mayor delante no dice nada fiable
33
+ return None # sys.version_info sin subíndice: tupla completa
34
+ if not isinstance(node, ast.Subscript):
35
+ return -1
36
+ sl = node.slice
37
+ if isinstance(sl, ast.Constant) and isinstance(sl.value, int) and sl.value >= 0:
38
+ return sl.value + 1
39
+ if isinstance(sl, ast.Slice) and sl.lower is None and sl.step is None:
40
+ if sl.upper is None:
41
+ return None # "[:]" -- equivale a la tupla completa
42
+ if isinstance(sl.upper, ast.Constant) and isinstance(sl.upper.value, int):
43
+ return sl.upper.value
44
+ return -1
45
+
46
+
47
+ def _version_tuple_from_node(node: ast.AST) -> tuple[int, ...] | None:
48
+ if isinstance(node, ast.Tuple):
49
+ values = []
50
+ for elt in node.elts:
51
+ if isinstance(elt, ast.Constant) and isinstance(elt.value, int):
52
+ values.append(elt.value)
53
+ else:
54
+ return None
55
+ return tuple(values)
56
+ if isinstance(node, ast.Constant) and isinstance(node.value, int):
57
+ return (node.value,)
58
+ return None
59
+
60
+
61
+ class VersionGuard:
62
+ def __init__(
63
+ self, if_node: ast.If, op_name: str, threshold: tuple[int, ...], projection: int | None
64
+ ):
65
+ self.if_node = if_node
66
+ self.op_name = op_name
67
+ self.threshold = threshold
68
+ self.has_else = bool(if_node.orelse)
69
+ # Cuántos componentes iniciales de sys.version_info mira de verdad esta
70
+ # comparación -- None si mira la tupla entera (sin subíndice). Ver
71
+ # `_projection_from_node`: sin esto, "sys.version_info[0] > 3" se trataba
72
+ # como si comparase la tupla completa, produciendo un veredicto REAL
73
+ # incorrecto (marcaba como muerta una rama else que sí se ejecuta) en
74
+ # cuanto el `requires-python` del proyecto incluía un minor -- ej.
75
+ # ">=3.8" hacía que "[0] > 3" pareciera "siempre verdadero" por culpa
76
+ # del "8" de min_version, que ese subíndice ni siquiera mira.
77
+ self.projection = projection
78
+
79
+
80
+ def find_version_guards(tree: ast.Module) -> list[VersionGuard]:
81
+ """Cada `if` cuya condición compara sys.version_info (o un subíndice/slice
82
+ reconocible del mismo, ej. `[0]`/`[:2]`) contra una tupla/entero literal."""
83
+ guards: list[VersionGuard] = []
84
+ for node in ast.walk(tree):
85
+ if not isinstance(node, ast.If):
86
+ continue
87
+ test = node.test
88
+ if not isinstance(test, ast.Compare) or len(test.ops) != 1:
89
+ continue
90
+
91
+ left, op, right = test.left, test.ops[0], test.comparators[0]
92
+ op_name = type(op).__name__
93
+ if op_name not in _FLIP_OP:
94
+ continue
95
+
96
+ if _is_version_info_expr(left):
97
+ threshold = _version_tuple_from_node(right)
98
+ projection = _projection_from_node(left)
99
+ elif _is_version_info_expr(right):
100
+ threshold = _version_tuple_from_node(left)
101
+ op_name = _FLIP_OP[op_name] # "(3,8) <= sys.version_info" -> "version_info >= (3,8)"
102
+ projection = _projection_from_node(right)
103
+ else:
104
+ continue
105
+
106
+ if threshold is None or projection == -1:
107
+ continue
108
+ guards.append(VersionGuard(node, op_name, threshold, projection))
109
+ return guards
@@ -0,0 +1,14 @@
1
+ from __future__ import annotations
2
+
3
+ from pydantic import BaseModel
4
+
5
+
6
+ class Finding(BaseModel):
7
+ path: str
8
+ line: int
9
+ verdict: str # "if_dead" | "else_dead"
10
+ condition: str
11
+ detail: str = ""
12
+ commit: str | None = None
13
+ author: str | None = None
14
+ summary: str | None = None
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ import tomllib
4
+ from pathlib import Path
5
+
6
+ from packaging.specifiers import SpecifierSet
7
+ from packaging.version import Version
8
+
9
+
10
+ def min_python_version(requires_python: str) -> tuple[int, ...] | None:
11
+ """Versión mínima (X, Y) a partir de un 'requires-python' tipo '>=3.11,<4'.
12
+ None si no hay ninguna cota inferior (>=/>)."""
13
+ try:
14
+ specifiers = SpecifierSet(requires_python)
15
+ except Exception: # noqa: BLE001 -- requires-python puede tener sintaxis rara
16
+ return None
17
+
18
+ candidates: list[tuple[int, ...]] = []
19
+ for spec in specifiers:
20
+ # "~=3.11" (>=3.11,<4) y "==3.11.*" también fijan el mínimo; antes se ignoraban y la
21
+ # herramienta decía que no había requires-python.
22
+ if spec.operator in (">=", ">", "~=") or (spec.operator == "==" and spec.version.endswith(".*")):
23
+ try:
24
+ v = Version(spec.version.removesuffix(".*"))
25
+ except Exception: # noqa: BLE001, S112 -- version rara en el specifier, se ignora
26
+ continue
27
+ candidates.append(v.release[:2])
28
+
29
+ if not candidates:
30
+ return None
31
+ return max(candidates)
32
+
33
+
34
+ def project_min_python_version(repo_path: Path) -> tuple[int, ...] | None:
35
+ pyproject = repo_path / "pyproject.toml"
36
+ if not pyproject.exists():
37
+ return None
38
+ try:
39
+ data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
40
+ except tomllib.TOMLDecodeError:
41
+ return None
42
+ requires_python = data.get("project", {}).get("requires-python")
43
+ if not requires_python:
44
+ return None
45
+ return min_python_version(requires_python)
@@ -0,0 +1,30 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ from staleif.plugin import Finding
6
+
7
+ _LABEL = {"if_dead": "IF MUERTO", "else_dead": "ELSE MUERTO"}
8
+
9
+
10
+ def to_console(findings: list[Finding]) -> str:
11
+ if not findings:
12
+ return "No se encontraron guardas de versión muertas."
13
+
14
+ lines = []
15
+ for f in findings:
16
+ lines.append(f"[{_LABEL[f.verdict]}] {f.path}:{f.line} -- {f.condition}")
17
+ lines.append(f" {f.detail}")
18
+ if f.commit:
19
+ short = f.commit[:8]
20
+ author = f.author or "?"
21
+ summary = f.summary or ""
22
+ lines.append(f" Añadido en {short} por {author}: \"{summary}\"")
23
+ lines.append("")
24
+
25
+ lines.append(f"Total: {len(findings)} guarda(s) de versión muerta(s).")
26
+ return "\n".join(lines)
27
+
28
+
29
+ def to_json(findings: list[Finding]) -> str:
30
+ return json.dumps([f.model_dump() for f in findings], ensure_ascii=False, indent=2)
@@ -0,0 +1,27 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ def _pad(a: tuple[int, ...], b: tuple[int, ...]) -> tuple[tuple[int, ...], tuple[int, ...]]:
5
+ n = max(len(a), len(b))
6
+ return a + (0,) * (n - len(a)), b + (0,) * (n - len(b))
7
+
8
+
9
+ def branch_verdict(op_name: str, threshold: tuple[int, ...], min_version: tuple[int, ...]) -> str:
10
+ """'if_dead' | 'else_dead' | 'live'.
11
+
12
+ Dado que la versión de Python en ejecución siempre es >= min_version
13
+ (por `requires-python`), decide si la comparación `sys.version_info <op>
14
+ threshold` puede seguir siendo verdadera o falsa alguna vez, o si ya
15
+ está decidida para siempre.
16
+ """
17
+ t, m = _pad(threshold, min_version)
18
+
19
+ if op_name == "Lt":
20
+ return "if_dead" if m >= t else "live"
21
+ if op_name == "LtE":
22
+ return "if_dead" if m > t else "live"
23
+ if op_name == "Gt":
24
+ return "else_dead" if m > t else "live"
25
+ if op_name == "GtE":
26
+ return "else_dead" if m >= t else "live"
27
+ return "live" # Eq (y cualquier otro): ambiguo, no se marca
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: staleif
3
+ Version: 0.1.5
4
+ Summary: Encuentra bloques 'if sys.version_info < (X, Y)' que ya son codigo muerto porque el requires-python del proyecto ya no soporta versiones tan viejas -- con contexto de git blame de cuando se anadieron.
5
+ Author: José Luis Segura Yuste
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jl-segurayuste/staleif
8
+ Project-URL: Source, https://github.com/jl-segurayuste/staleif
9
+ Project-URL: Issues, https://github.com/jl-segurayuste/staleif/issues
10
+ Project-URL: Changelog, https://github.com/jl-segurayuste/staleif/releases
11
+ Keywords: developer-tools,dead-code,static-analysis
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Natural Language :: Spanish
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
23
+ Classifier: Topic :: Software Development :: Quality Assurance
24
+ Requires-Python: >=3.11
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: pydantic>=2.6
28
+ Requires-Dist: packaging>=23.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.4; extra == "dev"
31
+ Requires-Dist: pytest-cov>=5; extra == "dev"
32
+ Requires-Dist: ruff==0.17.6; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # staleif
36
+
37
+ [![PyPI](https://img.shields.io/pypi/v/staleif.svg)](https://pypi.org/project/staleif/)
38
+ [![CI](https://github.com/jl-segurayuste/staleif/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/staleif/actions/workflows/ci.yml)
39
+ [![Python 3.11–3.15](https://img.shields.io/badge/python-3.11%20%E2%80%93%203.15-blue.svg)](https://github.com/jl-segurayuste/staleif/blob/main/pyproject.toml)
40
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/staleif/blob/main/LICENSE)
41
+
42
+ Encuentra bloques `if sys.version_info < (X, Y):` que ya son código muerto
43
+ — porque el propio `requires-python` del proyecto hace tiempo que dejó de
44
+ soportar versiones tan viejas — con el contexto de git blame de cuándo y
45
+ por qué se añadieron.
46
+
47
+ ```
48
+ $ staleif scan .
49
+
50
+ [IF MUERTO] compat.py:12 -- sys.version_info < (3, 8)
51
+ El proyecto ya requiere Python >= 3.11, así que esta condición
52
+ nunca es verdadera -- la rama 'if' es inalcanzable.
53
+ Añadido en a1b2c3d4 por dev@ejemplo-demo.es: "workaround para python 3.7"
54
+
55
+ Total: 1 guarda(s) de versión muerta(s).
56
+ ```
57
+
58
+ ## Así se ve
59
+
60
+ ![Salida de staleif sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/staleif/main/docs/img/demo.svg)
61
+
62
+ <sub>Ejecución real sobre una librería que ya exige Python 3.11 pero conserva guardas para 3.7 (todos los datos son ficticios).</sub>
63
+
64
+ ## Por qué existe
65
+
66
+ Los "workarounds" condicionados a la versión de Python son de los tipos de
67
+ código muerto más fáciles de dejar olvidados: se añaden con buena razón, el
68
+ proyecto sube su `requires-python` mínimo con el tiempo, y nadie vuelve a
69
+ por el `if` que ya nunca se ejecuta. A diferencia de detectar código muerto
70
+ en general (funciones/imports sin usar), esto es 100% mecánico: si el
71
+ proyecto ya no soporta la versión que el `if` comprueba, la rama es
72
+ matemáticamente inalcanzable — no hace falta ninguna heurística.
73
+
74
+ ## Instalación
75
+
76
+ Todavía no está en PyPI:
77
+
78
+ ```bash
79
+ pipx install staleif # recomendado para herramientas de línea de comandos
80
+ # o bien
81
+ pip install staleif
82
+ ```
83
+
84
+ ## Uso
85
+
86
+ ```bash
87
+ staleif scan .
88
+ staleif scan . --json
89
+ staleif scan . --fail-on-found # código de salida 1 si hay alguna
90
+ ```
91
+
92
+ Lee el `requires-python` de `pyproject.toml`, recorre los ficheros `.py`
93
+ rastreados por git buscando comparaciones contra `sys.version_info` (vía
94
+ `ast`, no regex), y usa `git blame` para mostrar cuándo y por qué se
95
+ introdujo cada guarda que ya es código muerto.
96
+
97
+ ## Qué NO detecta (todavía)
98
+
99
+ - Comparaciones contra `__version__` de paquetes de terceros (ver
100
+ [depweight](https://github.com/jl-segurayuste/depweight)/
101
+ [depexplain](https://github.com/jl-segurayuste/depexplain) para el
102
+ ángulo de dependencias).
103
+ - `platform.python_version_tuple()` u otras formas no literales de
104
+ comprobar la versión.
105
+ - Comparaciones con `==` (ambiguas: podrían seguir aplicando a una versión
106
+ exacta dentro del rango soportado).
107
+
108
+ ## Desarrollo
109
+
110
+ ```bash
111
+ pip install -e ".[dev]"
112
+ ruff check .
113
+ pytest
114
+ ```
@@ -0,0 +1,27 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ staleif/__init__.py
5
+ staleif/__main__.py
6
+ staleif/analyze.py
7
+ staleif/blame.py
8
+ staleif/cli.py
9
+ staleif/detect.py
10
+ staleif/plugin.py
11
+ staleif/pyver.py
12
+ staleif/report.py
13
+ staleif/verlogic.py
14
+ staleif.egg-info/PKG-INFO
15
+ staleif.egg-info/SOURCES.txt
16
+ staleif.egg-info/dependency_links.txt
17
+ staleif.egg-info/entry_points.txt
18
+ staleif.egg-info/requires.txt
19
+ staleif.egg-info/top_level.txt
20
+ tests/test_analyze.py
21
+ tests/test_blame.py
22
+ tests/test_cli.py
23
+ tests/test_detect.py
24
+ tests/test_pyver.py
25
+ tests/test_report.py
26
+ tests/test_verlogic.py
27
+ tests/test_version.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ staleif = staleif.cli:main
@@ -0,0 +1,7 @@
1
+ pydantic>=2.6
2
+ packaging>=23.0
3
+
4
+ [dev]
5
+ pytest>=7.4
6
+ pytest-cov>=5
7
+ ruff==0.17.6
@@ -0,0 +1 @@
1
+ staleif
@@ -0,0 +1,131 @@
1
+ from conftest import commit_all, write
2
+
3
+ from staleif.analyze import analyze_repo
4
+
5
+
6
+ def _init_project(repo, requires_python):
7
+ write(repo, "pyproject.toml", f'[project]\nname="x"\nrequires-python="{requires_python}"\n')
8
+
9
+
10
+ def test_guarda_muerta_se_detecta_con_blame(git_repo):
11
+ _init_project(git_repo, ">=3.11")
12
+ write(
13
+ git_repo,
14
+ "compat.py",
15
+ "import sys\n\ndef foo():\n if sys.version_info < (3, 8):\n return 'old'\n return 'new'\n",
16
+ )
17
+ commit_all(git_repo, "workaround para python viejo")
18
+
19
+ findings = analyze_repo(git_repo)
20
+ assert len(findings) == 1
21
+ f = findings[0]
22
+ assert f.verdict == "if_dead"
23
+ assert f.path == "compat.py"
24
+ assert f.summary == "workaround para python viejo"
25
+ assert f.commit is not None
26
+
27
+
28
+ def test_guarda_viva_no_se_marca(git_repo):
29
+ _init_project(git_repo, ">=3.8")
30
+ write(
31
+ git_repo,
32
+ "compat.py",
33
+ "import sys\nif sys.version_info < (3, 12):\n x = 1\nelse:\n x = 2\n",
34
+ )
35
+ commit_all(git_repo)
36
+ assert analyze_repo(git_repo) == []
37
+
38
+
39
+ def test_else_muerto_se_detecta(git_repo):
40
+ _init_project(git_repo, ">=3.11")
41
+ write(
42
+ git_repo,
43
+ "compat.py",
44
+ "import sys\nif sys.version_info >= (3, 8):\n x = 1\nelse:\n x = 2\n",
45
+ )
46
+ commit_all(git_repo)
47
+ findings = analyze_repo(git_repo)
48
+ assert len(findings) == 1
49
+ assert findings[0].verdict == "else_dead"
50
+
51
+
52
+ def test_sin_else_no_marca_else_dead(git_repo):
53
+ _init_project(git_repo, ">=3.11")
54
+ write(git_repo, "compat.py", "import sys\nif sys.version_info >= (3, 8):\n x = 1\n")
55
+ commit_all(git_repo)
56
+ assert analyze_repo(git_repo) == []
57
+
58
+
59
+ def test_sin_requires_python_devuelve_none(git_repo):
60
+ write(git_repo, "pyproject.toml", '[project]\nname="x"\n')
61
+ write(git_repo, "compat.py", "import sys\nif sys.version_info < (3, 8):\n pass\n")
62
+ commit_all(git_repo)
63
+ assert analyze_repo(git_repo) is None
64
+
65
+
66
+ def test_subindice_0_no_se_confunde_con_tupla_completa(git_repo):
67
+ # Bug real encontrado 2026-08-09: "sys.version_info[0] > 3" solo mira el
68
+ # mayor, pero se comparaba contra el min_version COMPLETO ("3.8" con
69
+ # requires-python ">=3.8"), así que "[0] > 3" parecía "siempre verdadero"
70
+ # por culpa del "8" -- un componente que esa comparación ni siquiera lee.
71
+ # Eso marcaba la rama "else" (que sí se ejecuta en Python 3.8) como código
72
+ # muerto. Con la proyección correcta (solo el componente 0 cuenta), la
73
+ # rama "else" sigue siendo alcanzable y no debe marcarse.
74
+ _init_project(git_repo, ">=3.8")
75
+ write(
76
+ git_repo,
77
+ "compat.py",
78
+ "import sys\nif sys.version_info[0] > 3:\n x = 1\nelse:\n x = 2\n",
79
+ )
80
+ commit_all(git_repo)
81
+ assert analyze_repo(git_repo) == []
82
+
83
+
84
+ def test_subindice_0_guarda_realmente_muerta_se_sigue_detectando(git_repo):
85
+ _init_project(git_repo, ">=3.11")
86
+ write(
87
+ git_repo,
88
+ "compat.py",
89
+ "import sys\nif sys.version_info[0] < 3:\n x = 1\n",
90
+ )
91
+ commit_all(git_repo)
92
+ findings = analyze_repo(git_repo)
93
+ assert len(findings) == 1
94
+ assert findings[0].verdict == "if_dead"
95
+
96
+
97
+ def test_slice_guarda_muerta_se_detecta(git_repo):
98
+ _init_project(git_repo, ">=3.11")
99
+ write(
100
+ git_repo,
101
+ "compat.py",
102
+ "import sys\nif sys.version_info[:2] < (3, 6):\n x = 1\n",
103
+ )
104
+ commit_all(git_repo)
105
+ findings = analyze_repo(git_repo)
106
+ assert len(findings) == 1
107
+ assert findings[0].verdict == "if_dead"
108
+
109
+
110
+ def test_subindice_micro_sin_suelo_fiable_se_abstiene(git_repo):
111
+ # requires-python ">=3.8" solo da mayor.menor -- no hay suelo fiable para
112
+ # el componente micro ("[2]"), así que no se puede razonar con seguridad
113
+ # y hay que abstenerse en vez de adivinar.
114
+ _init_project(git_repo, ">=3.8")
115
+ write(
116
+ git_repo,
117
+ "compat.py",
118
+ "import sys\nif sys.version_info[2] < 5:\n x = 1\n",
119
+ )
120
+ commit_all(git_repo)
121
+ assert analyze_repo(git_repo) == []
122
+
123
+
124
+ def test_fichero_con_syntaxerror_se_ignora_sin_romper(git_repo):
125
+ _init_project(git_repo, ">=3.11")
126
+ write(git_repo, "roto.py", "esto no es python valido [[[")
127
+ write(git_repo, "compat.py", "import sys\nif sys.version_info < (3, 8):\n pass\n")
128
+ commit_all(git_repo)
129
+ findings = analyze_repo(git_repo)
130
+ assert len(findings) == 1
131
+ assert findings[0].path == "compat.py"
@@ -0,0 +1,36 @@
1
+ from conftest import commit_all, write
2
+
3
+ from staleif.blame import blame_line
4
+
5
+
6
+ def test_blame_line_devuelve_info_del_commit(git_repo):
7
+ write(git_repo, "mod.py", "x = 1\ny = 2\n")
8
+ commit_all(git_repo, "añade x e y")
9
+ info = blame_line(git_repo, "mod.py", 1)
10
+ assert info is not None
11
+ assert "commit" in info
12
+ assert info.get("summary") == "añade x e y"
13
+
14
+
15
+ def test_blame_line_fichero_inexistente(git_repo):
16
+ assert blame_line(git_repo, "no-existe.py", 1) is None
17
+
18
+
19
+ def test_blame_line_distingue_lineas_de_commits_distintos(git_repo):
20
+ write(git_repo, "mod.py", "x = 1\n")
21
+ commit_all(git_repo, "primero")
22
+ write(git_repo, "mod.py", "x = 1\ny = 2\n")
23
+ commit_all(git_repo, "segundo")
24
+
25
+ info1 = blame_line(git_repo, "mod.py", 1)
26
+ info2 = blame_line(git_repo, "mod.py", 2)
27
+ assert info1["summary"] == "primero"
28
+ assert info2["summary"] == "segundo"
29
+
30
+
31
+ def test_blame_line_sin_commitear_no_inventa_autor(git_repo):
32
+ write(git_repo, "a.py", "x = 1\n")
33
+ commit_all(git_repo)
34
+ write(git_repo, "a.py", "x = 2\n")
35
+ assert blame_line(git_repo, "a.py", 1) is None
36
+
@@ -0,0 +1,36 @@
1
+ from conftest import commit_all, write
2
+
3
+ from staleif.cli import main
4
+
5
+
6
+ def test_scan_sin_requires_python_exit_0(git_repo, capsys):
7
+ write(git_repo, "a.py", "x = 1\n")
8
+ commit_all(git_repo)
9
+ rc = main(["scan", str(git_repo)])
10
+ assert rc == 0
11
+ assert "No aplica" in capsys.readouterr().out
12
+
13
+
14
+ def test_scan_con_guarda_muerta_exit_1_si_fail_on_found(git_repo, capsys):
15
+ write(git_repo, "pyproject.toml", '[project]\nname="x"\nrequires-python=">=3.11"\n')
16
+ write(git_repo, "compat.py", "import sys\nif sys.version_info < (3, 8):\n pass\n")
17
+ commit_all(git_repo)
18
+ rc = main(["scan", str(git_repo), "--fail-on-found"])
19
+ assert rc == 1
20
+
21
+
22
+ def test_scan_sin_guardas_muertas_exit_0(git_repo, capsys):
23
+ write(git_repo, "pyproject.toml", '[project]\nname="x"\nrequires-python=">=3.8"\n')
24
+ write(git_repo, "compat.py", "import sys\nif sys.version_info < (3, 12):\n pass\n")
25
+ commit_all(git_repo)
26
+ rc = main(["scan", str(git_repo), "--fail-on-found"])
27
+ assert rc == 0
28
+
29
+
30
+ def test_scan_json(git_repo, capsys):
31
+ write(git_repo, "pyproject.toml", '[project]\nname="x"\nrequires-python=">=3.11"\n')
32
+ write(git_repo, "compat.py", "import sys\nif sys.version_info < (3, 8):\n pass\n")
33
+ commit_all(git_repo)
34
+ main(["scan", str(git_repo), "--json"])
35
+ out = capsys.readouterr().out
36
+ assert '"path"' in out
@@ -0,0 +1,92 @@
1
+ import ast
2
+
3
+ from staleif.detect import find_version_guards
4
+
5
+
6
+ def test_detecta_lt_tupla():
7
+ tree = ast.parse("import sys\nif sys.version_info < (3, 8):\n pass\n")
8
+ guards = find_version_guards(tree)
9
+ assert len(guards) == 1
10
+ assert guards[0].op_name == "Lt"
11
+ assert guards[0].threshold == (3, 8)
12
+
13
+
14
+ def test_detecta_gte_tupla():
15
+ tree = ast.parse("import sys\nif sys.version_info >= (3, 10):\n pass\n")
16
+ guards = find_version_guards(tree)
17
+ assert guards[0].op_name == "GtE"
18
+ assert guards[0].threshold == (3, 10)
19
+
20
+
21
+ def test_detecta_comparacion_invertida():
22
+ tree = ast.parse("import sys\nif (3, 8) <= sys.version_info:\n pass\n")
23
+ guards = find_version_guards(tree)
24
+ assert len(guards) == 1
25
+ assert guards[0].op_name == "GtE" # (3,8) <= v equivale a v >= (3,8)
26
+ assert guards[0].threshold == (3, 8)
27
+
28
+
29
+ def test_detecta_subscript_indice_0():
30
+ tree = ast.parse("import sys\nif sys.version_info[0] < 3:\n pass\n")
31
+ guards = find_version_guards(tree)
32
+ assert guards[0].threshold == (3,)
33
+
34
+
35
+ def test_tupla_completa_sin_subindice_tiene_projection_none():
36
+ tree = ast.parse("import sys\nif sys.version_info < (3, 8):\n pass\n")
37
+ guards = find_version_guards(tree)
38
+ assert guards[0].projection is None
39
+
40
+
41
+ def test_subindice_0_tiene_projection_1():
42
+ # Bug real encontrado 2026-08-09: "sys.version_info[0]" solo mira el
43
+ # componente mayor, así que su `projection` debe ser 1 -- no None (tupla
44
+ # completa), o se compararía contra minor/micro que ese subíndice ni
45
+ # siquiera lee.
46
+ tree = ast.parse("import sys\nif sys.version_info[0] > 3:\n pass\n")
47
+ guards = find_version_guards(tree)
48
+ assert guards[0].projection == 1
49
+
50
+
51
+ def test_slice_hasta_2_tiene_projection_2():
52
+ tree = ast.parse("import sys\nif sys.version_info[:2] < (3, 6):\n pass\n")
53
+ guards = find_version_guards(tree)
54
+ assert guards[0].projection == 2
55
+
56
+
57
+ def test_subindice_con_variable_se_ignora():
58
+ tree = ast.parse("import sys\ni = 0\nif sys.version_info[i] < 3:\n pass\n")
59
+ assert find_version_guards(tree) == []
60
+
61
+
62
+ def test_detecta_presencia_de_else():
63
+ tree = ast.parse("import sys\nif sys.version_info < (3, 8):\n pass\nelse:\n pass\n")
64
+ guards = find_version_guards(tree)
65
+ assert guards[0].has_else is True
66
+
67
+
68
+ def test_sin_else_has_else_false():
69
+ tree = ast.parse("import sys\nif sys.version_info < (3, 8):\n pass\n")
70
+ guards = find_version_guards(tree)
71
+ assert guards[0].has_else is False
72
+
73
+
74
+ def test_if_normal_no_se_detecta():
75
+ tree = ast.parse("if x > 5:\n pass\n")
76
+ assert find_version_guards(tree) == []
77
+
78
+
79
+ def test_comparacion_con_variable_no_literal_se_ignora():
80
+ tree = ast.parse("import sys\nlimite = (3, 8)\nif sys.version_info < limite:\n pass\n")
81
+ assert find_version_guards(tree) == []
82
+
83
+
84
+ def test_atributo_major_equivale_a_indice_0():
85
+ tree = ast.parse("import sys\nif sys.version_info.major < 3:\n pass\n")
86
+ guards = find_version_guards(tree)
87
+ assert len(guards) == 1 and guards[0].projection == 1 and guards[0].threshold == (3,)
88
+
89
+
90
+ def test_atributo_minor_solo_se_omite():
91
+ tree = ast.parse("import sys\nif sys.version_info.minor < 8:\n pass\n")
92
+ assert find_version_guards(tree) == []
@@ -0,0 +1,45 @@
1
+ from conftest import write
2
+
3
+ from staleif.pyver import min_python_version, project_min_python_version
4
+
5
+
6
+ def test_min_python_version_simple():
7
+ assert min_python_version(">=3.11") == (3, 11)
8
+
9
+
10
+ def test_min_python_version_con_cota_superior():
11
+ assert min_python_version(">=3.8,<4") == (3, 8)
12
+
13
+
14
+ def test_min_python_version_toma_la_mas_alta_si_hay_varias():
15
+ assert min_python_version(">=3.8,>=3.10") == (3, 10)
16
+
17
+
18
+ def test_min_python_version_sin_cota_inferior():
19
+ assert min_python_version("<4") is None
20
+
21
+
22
+ def test_min_python_version_sintaxis_invalida():
23
+ assert min_python_version("no es un specifier valido !!!") is None
24
+
25
+
26
+ def test_project_min_python_version_lee_pyproject(git_repo):
27
+ write(git_repo, "pyproject.toml", '[project]\nname="x"\nrequires-python=">=3.10"\n')
28
+ assert project_min_python_version(git_repo) == (3, 10)
29
+
30
+
31
+ def test_project_min_python_version_sin_fichero(git_repo):
32
+ assert project_min_python_version(git_repo) is None
33
+
34
+
35
+ def test_project_min_python_version_sin_requires_python(git_repo):
36
+ write(git_repo, "pyproject.toml", '[project]\nname="x"\n')
37
+ assert project_min_python_version(git_repo) is None
38
+
39
+
40
+ def test_min_python_version_compatible_release():
41
+ assert min_python_version("~=3.11") == (3, 11)
42
+
43
+
44
+ def test_min_python_version_comodin():
45
+ assert min_python_version("==3.11.*") == (3, 11)
@@ -0,0 +1,33 @@
1
+ from staleif.plugin import Finding
2
+ from staleif.report import to_console, to_json
3
+
4
+
5
+ def test_to_console_sin_hallazgos():
6
+ out = to_console([])
7
+ assert "No se encontraron" in out
8
+
9
+
10
+ def test_to_console_con_hallazgos_sin_emojis():
11
+ findings = [
12
+ Finding(
13
+ path="a.py",
14
+ line=5,
15
+ verdict="if_dead",
16
+ condition="sys.version_info < (3, 8)",
17
+ detail="ya no aplica",
18
+ commit="abc12345",
19
+ author="dev@ejemplo-demo.es",
20
+ summary="workaround viejo",
21
+ )
22
+ ]
23
+ out = to_console(findings)
24
+ assert "IF MUERTO" in out
25
+ assert "a.py:5" in out
26
+ assert "abc12345" in out
27
+ assert "🔧" not in out and "⚠" not in out
28
+
29
+
30
+ def test_to_json_valido():
31
+ findings = [Finding(path="a.py", line=1, verdict="if_dead", condition="x")]
32
+ out = to_json(findings)
33
+ assert '"path": "a.py"' in out
@@ -0,0 +1,43 @@
1
+ from staleif.verlogic import branch_verdict
2
+
3
+
4
+ def test_lt_if_dead_cuando_min_ya_lo_supera():
5
+ # sys.version_info < (3, 8), min_version = (3, 11) -> nunca es verdad
6
+ assert branch_verdict("Lt", (3, 8), (3, 11)) == "if_dead"
7
+
8
+
9
+ def test_lt_live_cuando_min_es_menor():
10
+ assert branch_verdict("Lt", (3, 12), (3, 11)) == "live"
11
+
12
+
13
+ def test_lte_if_dead_cuando_min_supera_estrictamente():
14
+ assert branch_verdict("LtE", (3, 8), (3, 11)) == "if_dead"
15
+
16
+
17
+ def test_lte_live_cuando_min_es_igual():
18
+ assert branch_verdict("LtE", (3, 11), (3, 11)) == "live"
19
+
20
+
21
+ def test_gte_else_dead_cuando_min_ya_lo_cumple():
22
+ assert branch_verdict("GtE", (3, 8), (3, 11)) == "else_dead"
23
+
24
+
25
+ def test_gte_live_cuando_min_no_lo_cumple():
26
+ assert branch_verdict("GtE", (3, 12), (3, 11)) == "live"
27
+
28
+
29
+ def test_gt_else_dead_cuando_min_supera_estrictamente():
30
+ assert branch_verdict("Gt", (3, 8), (3, 11)) == "else_dead"
31
+
32
+
33
+ def test_gt_live_cuando_min_es_igual():
34
+ assert branch_verdict("Gt", (3, 11), (3, 11)) == "live"
35
+
36
+
37
+ def test_eq_nunca_se_marca():
38
+ assert branch_verdict("Eq", (3, 8), (3, 11)) == "live"
39
+
40
+
41
+ def test_tuplas_de_longitud_distinta_se_normalizan():
42
+ # sys.version_info[0] < 3, min_version = (3, 11) -> False siempre (3 >= 3)
43
+ assert branch_verdict("Lt", (3,), (3, 11)) == "if_dead"
@@ -0,0 +1,11 @@
1
+ import pytest
2
+
3
+ from staleif import __version__
4
+ from staleif.cli import main
5
+
6
+
7
+ def test_version(capsys):
8
+ with pytest.raises(SystemExit) as exc:
9
+ main(["--version"])
10
+ assert exc.value.code == 0
11
+ assert capsys.readouterr().out.strip() == f"staleif {__version__}"