staleif 0.1.5__py3-none-any.whl
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/__init__.py +3 -0
- staleif/__main__.py +6 -0
- staleif/analyze.py +92 -0
- staleif/blame.py +30 -0
- staleif/cli.py +51 -0
- staleif/detect.py +109 -0
- staleif/plugin.py +14 -0
- staleif/pyver.py +45 -0
- staleif/report.py +30 -0
- staleif/verlogic.py +27 -0
- staleif-0.1.5.dist-info/METADATA +114 -0
- staleif-0.1.5.dist-info/RECORD +16 -0
- staleif-0.1.5.dist-info/WHEEL +5 -0
- staleif-0.1.5.dist-info/entry_points.txt +2 -0
- staleif-0.1.5.dist-info/licenses/LICENSE +21 -0
- staleif-0.1.5.dist-info/top_level.txt +1 -0
staleif/__init__.py
ADDED
staleif/__main__.py
ADDED
staleif/analyze.py
ADDED
|
@@ -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
|
staleif/blame.py
ADDED
|
@@ -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
|
staleif/cli.py
ADDED
|
@@ -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())
|
staleif/detect.py
ADDED
|
@@ -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
|
staleif/plugin.py
ADDED
|
@@ -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
|
staleif/pyver.py
ADDED
|
@@ -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)
|
staleif/report.py
ADDED
|
@@ -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)
|
staleif/verlogic.py
ADDED
|
@@ -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
|
+
[](https://pypi.org/project/staleif/)
|
|
38
|
+
[](https://github.com/jl-segurayuste/staleif/actions/workflows/ci.yml)
|
|
39
|
+
[](https://github.com/jl-segurayuste/staleif/blob/main/pyproject.toml)
|
|
40
|
+
[](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
|
+

|
|
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,16 @@
|
|
|
1
|
+
staleif/__init__.py,sha256=PdADs9qst-PALhDHxzV82N-HoB83QBtagrgw9VpkFfw,108
|
|
2
|
+
staleif/__main__.py,sha256=17OR0GrpWaMXUZ2ZFvcH5rT1pUlNC74-eHplZA1vc9g,90
|
|
3
|
+
staleif/analyze.py,sha256=uPN61-9Wez0S_sULzf0gtoYKbEU9hYm-LqEI3Xw5ctI,3652
|
|
4
|
+
staleif/blame.py,sha256=1xkvB2khgkvZ3nqoa55Wfwq2F5CX5Zfe3BppcWnHy5o,1113
|
|
5
|
+
staleif/cli.py,sha256=mHoAhw9SUhYUvBhZsPoiONzbBlEM9l7irFqlattv0VQ,1414
|
|
6
|
+
staleif/detect.py,sha256=n2SX5ioB_eCpFFrspDHdN1kRhECVWdwSIswUk2ANQ44,4749
|
|
7
|
+
staleif/plugin.py,sha256=oYLPQ_KlmQqeF6_cGLnYALfs8uUW6pm2NiXDdrTPZek,298
|
|
8
|
+
staleif/pyver.py,sha256=uUFrsN1KYQeYhg4lrtw7Tbr7P_IOUEsL4VQ6L3fKu-8,1649
|
|
9
|
+
staleif/report.py,sha256=IVwuehdZeDn6NEOAsxIDmdHQ2hrFmORq1qIIUDu-OJ0,933
|
|
10
|
+
staleif/verlogic.py,sha256=LWXj40CSa8Z56Cav9xC31uaAFp5Ctc7_cr6NLVS25k4,1022
|
|
11
|
+
staleif-0.1.5.dist-info/licenses/LICENSE,sha256=70acRqGbi12E-RBHctB4yHLzZOoCFayZUXlhAUvwaAM,1080
|
|
12
|
+
staleif-0.1.5.dist-info/METADATA,sha256=vNTwSqk6m4ZywnH8foOJKQ6B3M1v_JmH-9CJIW4OVvo,4612
|
|
13
|
+
staleif-0.1.5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
14
|
+
staleif-0.1.5.dist-info/entry_points.txt,sha256=i8Ne9M9lDx7JsbufQE2tDc8yDI1XVqn1iUKU0J_owZw,45
|
|
15
|
+
staleif-0.1.5.dist-info/top_level.txt,sha256=icjDZSqYZ9muJCm7eXL-KSua75cC-nCs3rXWD-KHvlg,8
|
|
16
|
+
staleif-0.1.5.dist-info/RECORD,,
|
|
@@ -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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
staleif
|