changewhy 0.1.6__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.
@@ -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,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: changewhy
3
+ Version: 0.1.6
4
+ Summary: Genera un changelog real comparando dos versiones: diff de API pública Python, cambios de dependencias, y comandos CLI añadidos/eliminados -- no solo mensajes de commit.
5
+ Author: José Luis Segura Yuste
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jl-segurayuste/changewhy
8
+ Project-URL: Source, https://github.com/jl-segurayuste/changewhy
9
+ Project-URL: Issues, https://github.com/jl-segurayuste/changewhy/issues
10
+ Project-URL: Changelog, https://github.com/jl-segurayuste/changewhy/releases
11
+ Keywords: developer-tools,changelog,git
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 :: Version Control :: Git
24
+ Classifier: Topic :: Software Development :: Documentation
25
+ Requires-Python: >=3.11
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: pydantic>=2.6
29
+ Requires-Dist: packaging>=23.0
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7.4; extra == "dev"
32
+ Requires-Dist: pytest-cov>=5; extra == "dev"
33
+ Requires-Dist: ruff==0.17.6; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # changewhy
37
+
38
+ [![PyPI](https://img.shields.io/pypi/v/changewhy.svg)](https://pypi.org/project/changewhy/)
39
+ [![CI](https://github.com/jl-segurayuste/changewhy/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/changewhy/actions/workflows/ci.yml)
40
+ [![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/changewhy/blob/main/pyproject.toml)
41
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/changewhy/blob/main/LICENSE)
42
+
43
+ Un changelog real: compara dos versiones de un repo (tags, ramas, commits) y
44
+ explica qué cambió de verdad — no solo lee los mensajes de commit, que
45
+ pueden mentir, faltar o no reflejar el impacto real.
46
+
47
+ ```
48
+ $ changewhy diff v1.2.0 v1.3.0
49
+
50
+ changewhy — /ruta/al/repo (v1.2.0 -> v1.3.0)
51
+
52
+ ── api_diff ──────────────────────────────
53
+ 3 fichero(s) .py comparados, 2 cambio(s) de API.
54
+ [MEDIUM] Eliminado: Client.connect(host, port)
55
+ Posible cambio incompatible si alguien lo usaba.
56
+ [INFO ] Añadido: Client.connect_async(host, port, timeout=30)
57
+
58
+ ── dependency_diff ───────────────────────
59
+ 1 cambio(s) de dependencias.
60
+ [LOW ] Versión cambiada: requests>=2.28 -> requests>=2.31
61
+
62
+ Total: 3 cambio(s).
63
+ ```
64
+
65
+ ## Así se ve
66
+
67
+ ![Salida de changewhy sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/changewhy/main/docs/img/demo.svg)
68
+
69
+ <sub>Ejecución real sobre dos versiones etiquetadas de un proyecto de ejemplo (todos los datos son ficticios).</sub>
70
+
71
+ ## Por qué existe
72
+
73
+ Los generadores de changelog habituales resumen mensajes de commit — útil,
74
+ pero no dice si rompiste la API pública, si cambiaste una dependencia de
75
+ forma incompatible, o si quitaste un comando de la CLI. `changewhy` compara
76
+ el código y la configuración reales entre dos refs de git, no el texto de
77
+ los commits.
78
+
79
+ ## Instalación
80
+
81
+ Todavía no está en PyPI:
82
+
83
+ ```bash
84
+ pipx install changewhy # recomendado para herramientas de línea de comandos
85
+ # o bien
86
+ pip install changewhy
87
+ ```
88
+
89
+ ## Uso
90
+
91
+ ```bash
92
+ changewhy diff v1.2.0 v1.3.0 # dos tags
93
+ changewhy diff main HEAD # rama vs. HEAD actual
94
+ changewhy diff abc123 def456 ruta/al/repo
95
+ changewhy diff v1.2.0 v1.3.0 --json
96
+ changewhy diff v1.2.0 v1.3.0 --fail-on medium # código 1 si hay algo "medium" o peor
97
+ # código 2 si la ref no existe o algún check no se pudo ejecutar
98
+ changewhy list-checks
99
+ ```
100
+
101
+ ## Checks incluidos
102
+
103
+ | Check | Qué detecta |
104
+ |---|---|
105
+ | `api_diff` | Funciones/métodos públicos de Python (sin `_` inicial) añadidos, eliminados o con la firma cambiada, vía AST — no regex |
106
+ | `dependency_diff` | Dependencias añadidas/eliminadas/con versión cambiada en `requirements.txt`/`pyproject.toml` (incluidos los extras de `optional-dependencies`) |
107
+ | `cli_diff` | Comandos de `[project.scripts]` añadidos, eliminados o redirigidos a otro entry point |
108
+
109
+ Nunca ejecuta el código de ninguno de los dos refs — solo lee su contenido
110
+ vía `git show <ref>:<path>` y lo analiza estáticamente. Cada check es un
111
+ plugin independiente (`importlib.metadata.entry_points`, grupo
112
+ `changewhy.checks`).
113
+
114
+ ## Desarrollo
115
+
116
+ ```bash
117
+ pip install -e ".[dev]"
118
+ ruff check .
119
+ pytest
120
+ ```
@@ -0,0 +1,85 @@
1
+ # changewhy
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/changewhy.svg)](https://pypi.org/project/changewhy/)
4
+ [![CI](https://github.com/jl-segurayuste/changewhy/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/changewhy/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/changewhy/blob/main/pyproject.toml)
6
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/changewhy/blob/main/LICENSE)
7
+
8
+ Un changelog real: compara dos versiones de un repo (tags, ramas, commits) y
9
+ explica qué cambió de verdad — no solo lee los mensajes de commit, que
10
+ pueden mentir, faltar o no reflejar el impacto real.
11
+
12
+ ```
13
+ $ changewhy diff v1.2.0 v1.3.0
14
+
15
+ changewhy — /ruta/al/repo (v1.2.0 -> v1.3.0)
16
+
17
+ ── api_diff ──────────────────────────────
18
+ 3 fichero(s) .py comparados, 2 cambio(s) de API.
19
+ [MEDIUM] Eliminado: Client.connect(host, port)
20
+ Posible cambio incompatible si alguien lo usaba.
21
+ [INFO ] Añadido: Client.connect_async(host, port, timeout=30)
22
+
23
+ ── dependency_diff ───────────────────────
24
+ 1 cambio(s) de dependencias.
25
+ [LOW ] Versión cambiada: requests>=2.28 -> requests>=2.31
26
+
27
+ Total: 3 cambio(s).
28
+ ```
29
+
30
+ ## Así se ve
31
+
32
+ ![Salida de changewhy sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/changewhy/main/docs/img/demo.svg)
33
+
34
+ <sub>Ejecución real sobre dos versiones etiquetadas de un proyecto de ejemplo (todos los datos son ficticios).</sub>
35
+
36
+ ## Por qué existe
37
+
38
+ Los generadores de changelog habituales resumen mensajes de commit — útil,
39
+ pero no dice si rompiste la API pública, si cambiaste una dependencia de
40
+ forma incompatible, o si quitaste un comando de la CLI. `changewhy` compara
41
+ el código y la configuración reales entre dos refs de git, no el texto de
42
+ los commits.
43
+
44
+ ## Instalación
45
+
46
+ Todavía no está en PyPI:
47
+
48
+ ```bash
49
+ pipx install changewhy # recomendado para herramientas de línea de comandos
50
+ # o bien
51
+ pip install changewhy
52
+ ```
53
+
54
+ ## Uso
55
+
56
+ ```bash
57
+ changewhy diff v1.2.0 v1.3.0 # dos tags
58
+ changewhy diff main HEAD # rama vs. HEAD actual
59
+ changewhy diff abc123 def456 ruta/al/repo
60
+ changewhy diff v1.2.0 v1.3.0 --json
61
+ changewhy diff v1.2.0 v1.3.0 --fail-on medium # código 1 si hay algo "medium" o peor
62
+ # código 2 si la ref no existe o algún check no se pudo ejecutar
63
+ changewhy list-checks
64
+ ```
65
+
66
+ ## Checks incluidos
67
+
68
+ | Check | Qué detecta |
69
+ |---|---|
70
+ | `api_diff` | Funciones/métodos públicos de Python (sin `_` inicial) añadidos, eliminados o con la firma cambiada, vía AST — no regex |
71
+ | `dependency_diff` | Dependencias añadidas/eliminadas/con versión cambiada en `requirements.txt`/`pyproject.toml` (incluidos los extras de `optional-dependencies`) |
72
+ | `cli_diff` | Comandos de `[project.scripts]` añadidos, eliminados o redirigidos a otro entry point |
73
+
74
+ Nunca ejecuta el código de ninguno de los dos refs — solo lee su contenido
75
+ vía `git show <ref>:<path>` y lo analiza estáticamente. Cada check es un
76
+ plugin independiente (`importlib.metadata.entry_points`, grupo
77
+ `changewhy.checks`).
78
+
79
+ ## Desarrollo
80
+
81
+ ```bash
82
+ pip install -e ".[dev]"
83
+ ruff check .
84
+ pytest
85
+ ```
@@ -0,0 +1,3 @@
1
+ """changewhy — genera un changelog real comparando dos versiones de un repo."""
2
+
3
+ __version__ = "0.1.6"
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from changewhy.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
File without changes
@@ -0,0 +1,156 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import copy
5
+ from pathlib import Path
6
+
7
+ from changewhy.gitref import list_files_at_ref, read_file_at_ref
8
+ from changewhy.plugin import CheckResult, Finding
9
+
10
+ _EXCLUDED_PARTS = {"tests", "test", "examples"}
11
+
12
+
13
+ def _is_relevant(relpath: str) -> bool:
14
+ """Excluye tests/ejemplos: no son la API pública que le importa a alguien
15
+ que instala el paquete, y contarlos como "cambios de API" es puro ruido
16
+ (funciones test_* no empiezan por "_" pero tampoco son API real)."""
17
+ if not relpath.endswith(".py"):
18
+ return False
19
+ parts = set(Path(relpath).parts[:-1])
20
+ return not (parts & _EXCLUDED_PARTS)
21
+
22
+
23
+ def _public_functions(source: str) -> dict[str, ast.arguments]:
24
+ try:
25
+ tree = ast.parse(source)
26
+ except SyntaxError:
27
+ return {}
28
+
29
+ funcs: dict[str, ast.arguments] = {}
30
+ for node in tree.body:
31
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and not node.name.startswith("_"):
32
+ funcs[node.name] = node.args
33
+ elif isinstance(node, ast.ClassDef) and not node.name.startswith("_"):
34
+ for item in node.body:
35
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and not item.name.startswith("_"):
36
+ funcs[f"{node.name}.{item.name}"] = item.args
37
+ return funcs
38
+
39
+
40
+ def extract_signatures(source: str) -> dict[str, str]:
41
+ """Nombre.completo -> firma de cada función/método público de nivel superior."""
42
+ return {name: ast.unparse(args) for name, args in _public_functions(source).items()}
43
+
44
+
45
+ def _params(args: ast.arguments) -> tuple[list[tuple[str, bool]], dict[str, bool], bool, bool]:
46
+ """(posicionales [(nombre, tiene_default)], solo-nombre {nombre: tiene_default}, *args, **kwargs)."""
47
+ positional = [*args.posonlyargs, *args.args]
48
+ first_default = len(positional) - len(args.defaults)
49
+ pos = [(a.arg, i >= first_default) for i, a in enumerate(positional)]
50
+ kwonly = {a.arg: d is not None for a, d in zip(args.kwonlyargs, args.kw_defaults, strict=True)}
51
+ return pos, kwonly, args.vararg is not None, args.kwarg is not None
52
+
53
+
54
+ def _strip_annotations(args: ast.arguments) -> str:
55
+ args = copy.deepcopy(args)
56
+ for a in [*args.posonlyargs, *args.args, *args.kwonlyargs, args.vararg, args.kwarg]:
57
+ if a is not None:
58
+ a.annotation = None
59
+ return ast.unparse(args)
60
+
61
+
62
+ def classify_change(old: ast.arguments, new: ast.arguments) -> str:
63
+ """"annotations" (solo tipos), "compatible" (parámetros opcionales nuevos) o "breaking".
64
+
65
+ Antes cualquier diferencia contaba como posible incompatibilidad: cambiar `dict=None` por
66
+ `dict | None=None` o añadir un parámetro opcional al final salían como avisos medios."""
67
+ if _strip_annotations(old) == _strip_annotations(new):
68
+ return "annotations"
69
+ old_pos, old_kw, old_var, old_kwargs = _params(old)
70
+ new_pos, new_kw, new_var, new_kwargs = _params(new)
71
+ if (old_var and not new_var) or (old_kwargs and not new_kwargs):
72
+ return "breaking"
73
+ if [n for n, _ in new_pos[: len(old_pos)]] != [n for n, _ in old_pos]:
74
+ return "breaking" # se quitan o reordenan posicionales
75
+ if any(had and not has for (_, had), (_, has) in zip(old_pos, new_pos, strict=False)):
76
+ return "breaking" # un parámetro pierde su valor por defecto
77
+ if not all(has for _, has in new_pos[len(old_pos):]):
78
+ return "breaking" # posicional nuevo obligatorio
79
+ for name, had in old_kw.items():
80
+ if name not in new_kw or (had and not new_kw[name]):
81
+ return "breaking"
82
+ if not all(has for name, has in new_kw.items() if name not in old_kw):
83
+ return "breaking" # solo-nombre nuevo obligatorio
84
+ return "compatible"
85
+
86
+
87
+ class ApiDiffCheck:
88
+ """Diff de la API pública de Python (funciones y métodos top-level, sin '_' inicial) entre dos refs."""
89
+
90
+ name = "api_diff"
91
+
92
+ def run(self, repo_path: Path, ref_a: str, ref_b: str) -> CheckResult:
93
+ files_a = {f for f in list_files_at_ref(repo_path, ref_a) if _is_relevant(f)}
94
+ files_b = {f for f in list_files_at_ref(repo_path, ref_b) if _is_relevant(f)}
95
+
96
+ findings: list[Finding] = []
97
+ files_checked = 0
98
+
99
+ for relpath in sorted(files_a & files_b):
100
+ src_a = read_file_at_ref(repo_path, ref_a, relpath)
101
+ src_b = read_file_at_ref(repo_path, ref_b, relpath)
102
+ if src_a is None or src_b is None:
103
+ continue
104
+ files_checked += 1
105
+
106
+ funcs_a = _public_functions(src_a)
107
+ funcs_b = _public_functions(src_b)
108
+ sigs_a = {name: ast.unparse(args) for name, args in funcs_a.items()}
109
+ sigs_b = {name: ast.unparse(args) for name, args in funcs_b.items()}
110
+
111
+ for name in sorted(set(sigs_b) - set(sigs_a)):
112
+ findings.append(
113
+ Finding(
114
+ severity="info",
115
+ title=f"Añadido: {name}({sigs_b[name]})",
116
+ path=relpath,
117
+ )
118
+ )
119
+ for name in sorted(set(sigs_a) - set(sigs_b)):
120
+ findings.append(
121
+ Finding(
122
+ severity="medium",
123
+ title=f"Eliminado: {name}({sigs_a[name]})",
124
+ detail="Posible cambio incompatible si alguien lo usaba.",
125
+ path=relpath,
126
+ )
127
+ )
128
+ for name in sorted(set(sigs_a) & set(sigs_b)):
129
+ if sigs_a[name] != sigs_b[name]:
130
+ kind = classify_change(funcs_a[name], funcs_b[name])
131
+ severity, detail = {
132
+ "annotations": ("info", "Solo cambian las anotaciones de tipo: compatible."),
133
+ "compatible": ("low", "Parámetros opcionales nuevos: las llamadas existentes siguen valiendo."),
134
+ "breaking": ("medium", "Posible cambio incompatible si alguien lo usaba."),
135
+ }[kind]
136
+ findings.append(
137
+ Finding(
138
+ severity=severity,
139
+ title=f"Firma cambiada: {name}({sigs_a[name]}) -> {name}({sigs_b[name]})",
140
+ detail=detail,
141
+ path=relpath,
142
+ )
143
+ )
144
+
145
+ for relpath in sorted(files_b - files_a):
146
+ findings.append(Finding(severity="info", title=f"Fichero nuevo: {relpath}", path=relpath))
147
+ for relpath in sorted(files_a - files_b):
148
+ findings.append(
149
+ Finding(severity="medium", title=f"Fichero eliminado: {relpath}", path=relpath)
150
+ )
151
+
152
+ return CheckResult(
153
+ check_name=self.name,
154
+ summary=f"{files_checked} fichero(s) .py comparados, {len(findings)} cambio(s) de API.",
155
+ findings=findings,
156
+ )
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ import tomllib
4
+ from pathlib import Path
5
+
6
+ from changewhy.gitref import read_file_at_ref
7
+ from changewhy.plugin import CheckResult, Finding
8
+
9
+
10
+ def _scripts_at_ref(repo_path: Path, ref: str) -> dict[str, str]:
11
+ text = read_file_at_ref(repo_path, ref, "pyproject.toml")
12
+ if text is None:
13
+ return {}
14
+ try:
15
+ data = tomllib.loads(text)
16
+ except tomllib.TOMLDecodeError:
17
+ return {}
18
+ return dict(data.get("project", {}).get("scripts", {}))
19
+
20
+
21
+ class CliDiffCheck:
22
+ """Comandos de [project.scripts] añadidos/eliminados/redirigidos entre dos refs."""
23
+
24
+ name = "cli_diff"
25
+
26
+ def run(self, repo_path: Path, ref_a: str, ref_b: str) -> CheckResult:
27
+ scripts_a = _scripts_at_ref(repo_path, ref_a)
28
+ scripts_b = _scripts_at_ref(repo_path, ref_b)
29
+
30
+ findings: list[Finding] = []
31
+ for cmd in sorted(set(scripts_b) - set(scripts_a)):
32
+ findings.append(Finding(severity="info", title=f"Comando añadido: {cmd}"))
33
+ for cmd in sorted(set(scripts_a) - set(scripts_b)):
34
+ findings.append(
35
+ Finding(
36
+ severity="medium",
37
+ title=f"Comando eliminado: {cmd}",
38
+ detail="Quien lo use en scripts/CI dejará de funcionar.",
39
+ )
40
+ )
41
+ for cmd in sorted(set(scripts_a) & set(scripts_b)):
42
+ if scripts_a[cmd] != scripts_b[cmd]:
43
+ findings.append(
44
+ Finding(
45
+ severity="low",
46
+ title=f"Comando redirigido: {cmd} ({scripts_a[cmd]} -> {scripts_b[cmd]})",
47
+ )
48
+ )
49
+
50
+ return CheckResult(
51
+ check_name=self.name,
52
+ summary=f"{len(findings)} cambio(s) en comandos CLI.",
53
+ findings=findings,
54
+ )
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+
3
+ import tomllib
4
+ from pathlib import Path
5
+
6
+ from packaging.requirements import InvalidRequirement, Requirement
7
+ from packaging.specifiers import SpecifierSet
8
+ from packaging.utils import canonicalize_name
9
+
10
+ from changewhy.gitref import read_file_at_ref
11
+ from changewhy.plugin import CheckResult, Finding
12
+
13
+ # Nombre canónico (PEP 503) -> (nombre tal como se declaró, especificador).
14
+ # Comparar por el nombre literal haría que un simple recapitalizado entre
15
+ # refs ("requests" -> "Requests", con la misma versión) se reportara como
16
+ # "eliminada + añadida" en vez de ningún cambio real -- o, peor, enmascarase
17
+ # un cambio de versión genuino que ocurriera en el mismo commit.
18
+ _DeclaredDeps = dict[str, tuple[str, SpecifierSet]]
19
+
20
+
21
+ def _parse_requirement_line(line: str) -> Requirement | None:
22
+ line = line.split("#", 1)[0].strip()
23
+ if not line or line.startswith("-"):
24
+ return None
25
+ try:
26
+ return Requirement(line)
27
+ except InvalidRequirement:
28
+ return None
29
+
30
+
31
+ def _parse_requirements_txt(text: str) -> _DeclaredDeps:
32
+ declared: _DeclaredDeps = {}
33
+ for line in text.splitlines():
34
+ req = _parse_requirement_line(line)
35
+ if req is not None:
36
+ declared[canonicalize_name(req.name)] = (req.name, req.specifier)
37
+ return declared
38
+
39
+
40
+ def _parse_pyproject_toml(text: str) -> _DeclaredDeps:
41
+ try:
42
+ data = tomllib.loads(text)
43
+ except tomllib.TOMLDecodeError:
44
+ return {}
45
+ project = data.get("project", {})
46
+ declared: _DeclaredDeps = {}
47
+ for line in project.get("dependencies", []):
48
+ req = _parse_requirement_line(line)
49
+ if req is not None:
50
+ declared[canonicalize_name(req.name)] = (req.name, req.specifier)
51
+ # Los extras (`pip install pkg[x]`) también los instala quien usa el paquete.
52
+ for extra, lines in project.get("optional-dependencies", {}).items():
53
+ for line in lines:
54
+ req = _parse_requirement_line(line)
55
+ if req is not None:
56
+ key = f"{canonicalize_name(req.name)}[{extra}]"
57
+ declared[key] = (f"{req.name} (extra {extra}) ", req.specifier)
58
+ return declared
59
+
60
+
61
+ def _declared_deps_at_ref(repo_path: Path, ref: str) -> _DeclaredDeps:
62
+ declared: _DeclaredDeps = {}
63
+ req_text = read_file_at_ref(repo_path, ref, "requirements.txt")
64
+ if req_text is not None:
65
+ declared.update(_parse_requirements_txt(req_text))
66
+ pyproject_text = read_file_at_ref(repo_path, ref, "pyproject.toml")
67
+ if pyproject_text is not None:
68
+ declared.update(_parse_pyproject_toml(pyproject_text))
69
+ return declared
70
+
71
+
72
+ class DependencyDiffCheck:
73
+ """Cambios en las dependencias declaradas (requirements.txt/pyproject.toml) entre dos refs."""
74
+
75
+ name = "dependency_diff"
76
+
77
+ def run(self, repo_path: Path, ref_a: str, ref_b: str) -> CheckResult:
78
+ deps_a = _declared_deps_at_ref(repo_path, ref_a)
79
+ deps_b = _declared_deps_at_ref(repo_path, ref_b)
80
+
81
+ findings: list[Finding] = []
82
+ for key in sorted(set(deps_b) - set(deps_a)):
83
+ name, specifier = deps_b[key]
84
+ findings.append(
85
+ Finding(severity="info", title=f"Dependencia añadida: {name}{specifier}")
86
+ )
87
+ for key in sorted(set(deps_a) - set(deps_b)):
88
+ name, specifier = deps_a[key]
89
+ findings.append(
90
+ Finding(severity="low", title=f"Dependencia eliminada: {name}{specifier}")
91
+ )
92
+ for key in sorted(set(deps_a) & set(deps_b)):
93
+ name_a, specifier_a = deps_a[key]
94
+ name_b, specifier_b = deps_b[key]
95
+ if str(specifier_a) != str(specifier_b):
96
+ findings.append(
97
+ Finding(
98
+ severity="low",
99
+ title=f"Versión cambiada: {name_a}{specifier_a} -> {name_b}{specifier_b}",
100
+ )
101
+ )
102
+
103
+ return CheckResult(
104
+ check_name=self.name,
105
+ summary=f"{len(findings)} cambio(s) de dependencias.",
106
+ findings=findings,
107
+ )
@@ -0,0 +1,88 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from changewhy import __version__
8
+ from changewhy.gitref import is_commit
9
+ from changewhy.plugin import SEVERITIES
10
+ from changewhy.report import build_report, write_json
11
+ from changewhy.runner import discover_checks, run_checks
12
+
13
+ _SEVERITY_ORDER = {sev: idx for idx, sev in enumerate(SEVERITIES)}
14
+
15
+
16
+ def _cmd_diff(args: argparse.Namespace) -> int:
17
+ repo_path = Path(args.path).resolve()
18
+ only = set(args.only) if args.only else None
19
+ skip = set(args.skip) if args.skip else None
20
+
21
+ for ref in (args.ref_a, args.ref_b):
22
+ if not is_commit(repo_path, ref):
23
+ print(f"error: '{ref}' no es una ref válida en {repo_path}", file=sys.stderr)
24
+ return 2
25
+ unknown = ((only or set()) | (skip or set())) - set(discover_checks())
26
+ if unknown:
27
+ print(f"error: check(s) desconocido(s): {', '.join(sorted(unknown))} "
28
+ "(ver `changewhy list-checks`)", file=sys.stderr)
29
+ return 2
30
+
31
+ results = run_checks(repo_path, args.ref_a, args.ref_b, only=only, skip=skip)
32
+ report = build_report(repo_path, args.ref_a, args.ref_b, results)
33
+
34
+ if args.json:
35
+ print(write_json(report))
36
+ else:
37
+ print(report.to_console())
38
+
39
+ # Un check que revienta deja el análisis incompleto: antes solo se avisaba y salía 0 (o 1 según
40
+ # --fail-on), y en un CI pasaba por verde sin haber mirado lo que ese check mira.
41
+ failed = [r.check_name for r in results if r.error]
42
+ if failed:
43
+ print(f"error: no se pudieron ejecutar: {', '.join(failed)} (análisis incompleto)", file=sys.stderr)
44
+ return 2
45
+
46
+ if args.fail_on:
47
+ worst = report.worst_severity()
48
+ if worst is not None and _SEVERITY_ORDER[worst] >= _SEVERITY_ORDER[args.fail_on]:
49
+ return 1
50
+ return 0
51
+
52
+
53
+ def _cmd_list_checks(args: argparse.Namespace) -> int:
54
+ for name, cls in sorted(discover_checks().items()):
55
+ doc = (cls.__doc__ or "").strip().splitlines()[0] if cls.__doc__ else ""
56
+ print(f"{name}: {doc}")
57
+ return 0
58
+
59
+
60
+ def build_parser() -> argparse.ArgumentParser:
61
+ parser = argparse.ArgumentParser(prog="changewhy")
62
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
63
+ sub = parser.add_subparsers(dest="command", required=True)
64
+
65
+ p_diff = sub.add_parser("diff", help="Compara dos refs de git y explica qué cambió")
66
+ p_diff.add_argument("ref_a", help="Ref antigua (p.ej. v1.2.0)")
67
+ p_diff.add_argument("ref_b", help="Ref nueva (p.ej. v1.3.0 o HEAD)")
68
+ p_diff.add_argument("path", nargs="?", default=".")
69
+ p_diff.add_argument("--only", action="append", help="Ejecutar solo este check (repetible)")
70
+ p_diff.add_argument("--skip", action="append", help="Saltar este check (repetible)")
71
+ p_diff.add_argument("--json", action="store_true")
72
+ p_diff.add_argument("--fail-on", choices=SEVERITIES, default=None)
73
+ p_diff.set_defaults(func=_cmd_diff)
74
+
75
+ p_list = sub.add_parser("list-checks", help="Lista los checks instalados")
76
+ p_list.set_defaults(func=_cmd_list_checks)
77
+
78
+ return parser
79
+
80
+
81
+ def main(argv: list[str] | None = None) -> int:
82
+ parser = build_parser()
83
+ args = parser.parse_args(argv)
84
+ return args.func(args)
85
+
86
+
87
+ if __name__ == "__main__":
88
+ sys.exit(main())