frontera-runner 0.2.0__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.
- frontera_runner/__init__.py +9 -0
- frontera_runner/__main__.py +3 -0
- frontera_runner/ceros.py +286 -0
- frontera_runner/cli.py +149 -0
- frontera_runner/instrumentos.py +478 -0
- frontera_runner/recibo.py +512 -0
- frontera_runner/render.py +227 -0
- frontera_runner/runner.py +336 -0
- frontera_runner/triaje_frontera.py +138 -0
- frontera_runner-0.2.0.dist-info/METADATA +487 -0
- frontera_runner-0.2.0.dist-info/RECORD +14 -0
- frontera_runner-0.2.0.dist-info/WHEEL +5 -0
- frontera_runner-0.2.0.dist-info/entry_points.txt +3 -0
- frontera_runner-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
"""The four instruments, declared once: how to call each, and how to read what it says.
|
|
2
|
+
|
|
3
|
+
Three of the four return `2` for "no universe to measure" and one returns `4` for "the run does
|
|
4
|
+
not reconcile". Those codes are the whole reason a composite runner has to know its colleagues:
|
|
5
|
+
folding `2` into "0 findings" turns an empty universe into a green, which is the defect this
|
|
6
|
+
repository exists to not commit. The mapping below is the contract, and every code a run can
|
|
7
|
+
emit is either mapped or reported as `RC_NO_DECLARADO` -- never guessed.
|
|
8
|
+
|
|
9
|
+
Nothing here imports an instrument. They are called as subprocesses, from their own repository,
|
|
10
|
+
with the subject as the working directory, so an instrument that only works from its own cwd
|
|
11
|
+
fails loudly here instead of quietly passing.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
import tomllib
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from typing import Callable, Mapping
|
|
25
|
+
|
|
26
|
+
SIN_HALLAZGOS = "SIN_HALLAZGOS"
|
|
27
|
+
CON_HALLAZGOS = "CON_HALLAZGOS"
|
|
28
|
+
SIN_SUJETO = "SIN_SUJETO"
|
|
29
|
+
NO_MEDIDO = "NO_MEDIDO"
|
|
30
|
+
|
|
31
|
+
#: The audit classes whose count is the number the gate reads. The instrument also publishes
|
|
32
|
+
#: `ORPHAN_DOC`, `MOVED` and `RESIDUE`, which are informational: they never move its exit code
|
|
33
|
+
#: and counting them here would make a stale note block a merge.
|
|
34
|
+
CLASES_FALLANTES_AUDITORIA = ("ORPHAN_CODE", "ORPHAN_SECRET_RISK", "HISTORY_SECRET_RISK")
|
|
35
|
+
|
|
36
|
+
#: Separator inside one finding's identity. Every field is escaped with `_parte`, so the key can
|
|
37
|
+
#: be read back by splitting on a `|` that is genuinely a separator.
|
|
38
|
+
SEP = "|"
|
|
39
|
+
|
|
40
|
+
#: The guard's per-par exit codes, read from its payload rather than from the process.
|
|
41
|
+
_RC_DIVERGE = 1
|
|
42
|
+
_RC_NO_MEDIDO = 2
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _parte(valor) -> str:
|
|
46
|
+
"""One field of a finding's identity: single line, and never a `|` that splits the key."""
|
|
47
|
+
return str(valor).replace("|", "%7C").replace("\n", " ")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _clave(*campos) -> str | None:
|
|
51
|
+
"""Join the fields of one finding, or `None` when any of them is missing.
|
|
52
|
+
|
|
53
|
+
A finding the runner cannot name is not a finding it may count: the two numbers would then
|
|
54
|
+
disagree and the receipt would publish a delta over a census it cannot reconcile.
|
|
55
|
+
"""
|
|
56
|
+
if any(c is None or c == "" for c in campos):
|
|
57
|
+
return None
|
|
58
|
+
return SEP.join(_parte(c) for c in campos)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class Instrumento:
|
|
63
|
+
"""One colleague: where it lives, how to call it, and what its exit codes mean."""
|
|
64
|
+
|
|
65
|
+
nombre: str
|
|
66
|
+
modulo: str
|
|
67
|
+
paquete: str
|
|
68
|
+
argumentos: tuple[str, ...]
|
|
69
|
+
rc_contrato: Mapping[int, tuple[str, str]]
|
|
70
|
+
denominador: Callable[[Mapping], dict]
|
|
71
|
+
hallazgos: Callable[[Mapping], int | None]
|
|
72
|
+
identidades: Callable[[Mapping], list[str] | None]
|
|
73
|
+
subruta: str = ""
|
|
74
|
+
#: The unit `hallazgos` counts in. Three instruments count findings; the guard counts pars.
|
|
75
|
+
unidad: str = "hallazgo"
|
|
76
|
+
#: How the named census is reconciled with the instrument's own count. `None` means
|
|
77
|
+
#: "same number", which is right wherever the instrument counts what it lists.
|
|
78
|
+
reconciliar: Callable[[Mapping, list[str]], bool] | None = None
|
|
79
|
+
|
|
80
|
+
def ruta_python(self, repo: str) -> str:
|
|
81
|
+
"""Where the package must be put on `PYTHONPATH` -- a `src/` layout is not optional."""
|
|
82
|
+
return os.path.join(repo, self.subruta) if self.subruta else repo
|
|
83
|
+
|
|
84
|
+
def comando(self, manifiesto: str | None = None) -> list[str]:
|
|
85
|
+
return [self.modulo, *[a.format(manifiesto=manifiesto or "") for a in self.argumentos]]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _suma(claves: tuple[str, ...], salida: Mapping) -> int | None:
|
|
89
|
+
try:
|
|
90
|
+
return sum(int(salida[k]) for k in claves)
|
|
91
|
+
except (KeyError, TypeError, ValueError):
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _auditoria_identidades(salida: Mapping) -> list[str] | None:
|
|
96
|
+
"""One name per failing finding: class, path, and the root it was found under.
|
|
97
|
+
|
|
98
|
+
The oid and the size are left out on purpose. They change when the file at the same path
|
|
99
|
+
changes, and "this path is not reachable from HEAD" is the defect either way; keeping them
|
|
100
|
+
would report every edited orphan as one new finding plus one resolved one.
|
|
101
|
+
"""
|
|
102
|
+
hallazgos = salida.get("findings")
|
|
103
|
+
if not isinstance(hallazgos, list):
|
|
104
|
+
return None
|
|
105
|
+
nombres = []
|
|
106
|
+
for hallazgo in hallazgos:
|
|
107
|
+
if not isinstance(hallazgo, dict) or hallazgo.get("class") not in CLASES_FALLANTES_AUDITORIA:
|
|
108
|
+
continue
|
|
109
|
+
clave = _clave(hallazgo.get("class"), hallazgo.get("path"), hallazgo.get("root"))
|
|
110
|
+
if clave is None:
|
|
111
|
+
return None
|
|
112
|
+
nombres.append(clave)
|
|
113
|
+
return nombres
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _fibras_identidades(salida: Mapping) -> list[str] | None:
|
|
117
|
+
"""Candidate, file, function, family, shape and population -- not the line number.
|
|
118
|
+
|
|
119
|
+
A line number is a position, not an identity: moving twenty lines above a candidate would
|
|
120
|
+
otherwise read as one finding resolved and an unrelated one introduced.
|
|
121
|
+
"""
|
|
122
|
+
lista = salida.get("candidatos")
|
|
123
|
+
if not isinstance(lista, list):
|
|
124
|
+
return None
|
|
125
|
+
nombres = []
|
|
126
|
+
for candidato in lista:
|
|
127
|
+
if not isinstance(candidato, dict):
|
|
128
|
+
return None
|
|
129
|
+
clave = _clave(candidato.get("archivo"),
|
|
130
|
+
candidato.get("qualname") or candidato.get("funcion"),
|
|
131
|
+
candidato.get("familia"), candidato.get("forma"),
|
|
132
|
+
candidato.get("poblacion"))
|
|
133
|
+
if clave is None:
|
|
134
|
+
return None
|
|
135
|
+
nombres.append(clave)
|
|
136
|
+
return nombres
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _ordinal_identidades(salida: Mapping) -> list[str] | None:
|
|
140
|
+
"""Kind, file, scope and the name the collision was reported under."""
|
|
141
|
+
lista = salida.get("collisions")
|
|
142
|
+
if not isinstance(lista, list):
|
|
143
|
+
return None
|
|
144
|
+
nombres = []
|
|
145
|
+
for colision in lista:
|
|
146
|
+
if not isinstance(colision, dict):
|
|
147
|
+
return None
|
|
148
|
+
clave = _clave(colision.get("kind"), colision.get("path"),
|
|
149
|
+
colision.get("scope"), colision.get("name"))
|
|
150
|
+
if clave is None:
|
|
151
|
+
return None
|
|
152
|
+
nombres.append(clave)
|
|
153
|
+
return nombres
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _guardia_identidades(salida: Mapping) -> list[str] | None:
|
|
157
|
+
"""One name per broken or unmeasured anchor, inside the par that owns it.
|
|
158
|
+
|
|
159
|
+
The census is built from what the par *says about its anchors*, not from the par's own exit
|
|
160
|
+
code: that is what lets the partition below catch a payload that contradicts itself -- a par
|
|
161
|
+
the counter calls clean while one of its anchors is marked broken is not reconcilable, and
|
|
162
|
+
the runner has to say so instead of believing the friendlier of the two claims.
|
|
163
|
+
"""
|
|
164
|
+
pares = salida.get("pares")
|
|
165
|
+
if not isinstance(pares, list):
|
|
166
|
+
return None
|
|
167
|
+
nombres = []
|
|
168
|
+
for par in pares:
|
|
169
|
+
if not isinstance(par, dict) or par.get("nombre") in (None, ""):
|
|
170
|
+
return None
|
|
171
|
+
if par.get("rc") not in (0, _RC_DIVERGE, _RC_NO_MEDIDO):
|
|
172
|
+
return None
|
|
173
|
+
nombre = _parte(par.get("nombre"))
|
|
174
|
+
rotas = [a.get("ancla") for a in par.get("anclas") or []
|
|
175
|
+
if isinstance(a, dict) and a.get("ok") is False]
|
|
176
|
+
sueltas = [a.get("ancla") if isinstance(a, dict) else a
|
|
177
|
+
for a in par.get("no_evaluables") or []]
|
|
178
|
+
for ancla in rotas:
|
|
179
|
+
nombres.append(_clave("DIVERGE", nombre, ancla)
|
|
180
|
+
or _clave("DIVERGE", nombre, "SIN_ANCLA"))
|
|
181
|
+
for ancla in sueltas:
|
|
182
|
+
nombres.append(_clave("NO_MEDIDO", nombre, ancla)
|
|
183
|
+
or _clave("NO_MEDIDO", nombre, "SIN_ANCLA"))
|
|
184
|
+
if par.get("rc") == _RC_DIVERGE and not rotas:
|
|
185
|
+
nombres.append(_clave("DIVERGE", nombre, par.get("detalle") or "SIN_ANCLA"))
|
|
186
|
+
if par.get("rc") == _RC_NO_MEDIDO and not sueltas:
|
|
187
|
+
nombres.append(_clave("NO_MEDIDO", nombre, par.get("causa") or "SIN_CAUSA"))
|
|
188
|
+
return nombres
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _guardia_reconcilia(salida: Mapping, identidades: list[str]) -> bool:
|
|
192
|
+
"""The guard counts *pars*, so the census is reconciled as a partition, not as a sum.
|
|
193
|
+
|
|
194
|
+
`totales.divergen` is `sum(1 for p in pares if p["rc"] == RC_DIVERGE)`: one par with three
|
|
195
|
+
broken anchors is one. Comparing that number with the named census would reject a correct
|
|
196
|
+
instrument, so the law here is the partition instead -- every par the counter calls broken
|
|
197
|
+
or unmeasured names at least one finding, and every par it calls clean names none.
|
|
198
|
+
"""
|
|
199
|
+
pares = salida.get("pares")
|
|
200
|
+
if not isinstance(pares, list):
|
|
201
|
+
return False
|
|
202
|
+
nombres = [p.get("nombre") if isinstance(p, dict) else None for p in pares]
|
|
203
|
+
if any(not isinstance(n, str) or n == "" for n in nombres):
|
|
204
|
+
return False
|
|
205
|
+
if len({_parte(n) for n in nombres}) != len(nombres):
|
|
206
|
+
return False
|
|
207
|
+
con_hallazgo = {clave.split(SEP, 2)[1] for clave in identidades if clave}
|
|
208
|
+
for par in pares:
|
|
209
|
+
limpio = par.get("rc") == 0
|
|
210
|
+
if limpio == (_parte(par["nombre"]) in con_hallazgo):
|
|
211
|
+
return False
|
|
212
|
+
return True
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _auditoria_denominador(salida: Mapping) -> dict:
|
|
216
|
+
"""The universe *and* its age partition: a count of refs nobody dates is not actionable.
|
|
217
|
+
|
|
218
|
+
The partition travels in the composite receipt because a raw total invites the answer
|
|
219
|
+
"those are old branches from years ago", which is not an answer to "what is still moving".
|
|
220
|
+
"""
|
|
221
|
+
universo = salida.get("universe") or {}
|
|
222
|
+
estratos = salida.get("age_strata") or {}
|
|
223
|
+
refs = estratos.get("refs") or {}
|
|
224
|
+
return {"paths_fuera_de_head": universo.get("paths"),
|
|
225
|
+
"blobs_fuera_de_head": universo.get("blobs_outside_head"),
|
|
226
|
+
"refs": (salida.get("repo") or {}).get("refs"),
|
|
227
|
+
"refs_vivas_30d": refs.get("live"),
|
|
228
|
+
"refs_recientes_90d": refs.get("recent"),
|
|
229
|
+
"refs_inactivas": refs.get("stale"),
|
|
230
|
+
"refs_sin_fecha": refs.get("undated"),
|
|
231
|
+
"filas_vivas_30d": estratos.get("live"),
|
|
232
|
+
"filas_recientes_90d": estratos.get("recent"),
|
|
233
|
+
"filas_inactivas": estratos.get("stale"),
|
|
234
|
+
"filas_solo_historia": estratos.get("history_only"),
|
|
235
|
+
"estratos_reconcilian": estratos.get("conservation")}
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _guardia_denominador(salida: Mapping) -> dict:
|
|
239
|
+
totales = salida.get("totales") or {}
|
|
240
|
+
return {"pares": totales.get("pares"),
|
|
241
|
+
"anclas_comparadas": totales.get("comparadas"),
|
|
242
|
+
"anclas_declaradas": totales.get("declaradas")}
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _fibras_denominador(salida: Mapping) -> dict:
|
|
246
|
+
return {"archivos_python": salida.get("archivos"),
|
|
247
|
+
"sitios_medidos": salida.get("for_medidos")}
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _ordinal_denominador(salida: Mapping) -> dict:
|
|
251
|
+
return {"archivos_de_prueba": salida.get("files"),
|
|
252
|
+
"archivos_leidos": salida.get("parsed")}
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
INSTRUMENTOS: tuple[Instrumento, ...] = (
|
|
256
|
+
Instrumento(
|
|
257
|
+
nombre="git-complement-audit",
|
|
258
|
+
modulo="git_complement_audit",
|
|
259
|
+
paquete="git_complement_audit",
|
|
260
|
+
argumentos=(".", "--json"),
|
|
261
|
+
rc_contrato={
|
|
262
|
+
0: (SIN_HALLAZGOS, "existe solo lo que HEAD alcanza"),
|
|
263
|
+
1: (CON_HALLAZGOS, "codigo huerfano o riesgo de secreto"),
|
|
264
|
+
2: (NO_MEDIDO, "repositorio o argumentos invalidos"),
|
|
265
|
+
},
|
|
266
|
+
denominador=_auditoria_denominador,
|
|
267
|
+
hallazgos=lambda s: _suma(CLASES_FALLANTES_AUDITORIA, s.get("counts") or {}),
|
|
268
|
+
identidades=_auditoria_identidades,
|
|
269
|
+
),
|
|
270
|
+
Instrumento(
|
|
271
|
+
nombre="fiber-ast-lint",
|
|
272
|
+
modulo="fiber_ast_lint.cli",
|
|
273
|
+
paquete="src/fiber_ast_lint",
|
|
274
|
+
subruta="src",
|
|
275
|
+
argumentos=(".", "--json"),
|
|
276
|
+
rc_contrato={
|
|
277
|
+
0: (SIN_HALLAZGOS, "ningun candidato"),
|
|
278
|
+
1: (CON_HALLAZGOS, "candidatos a revisar"),
|
|
279
|
+
2: (SIN_SUJETO, "universo vacio: ningun archivo Python analizado"),
|
|
280
|
+
4: (NO_MEDIDO, "el instrumento no reconcilia"),
|
|
281
|
+
},
|
|
282
|
+
denominador=_fibras_denominador,
|
|
283
|
+
# An empty list is a measurement; a missing key is not, and `or []` would blur them.
|
|
284
|
+
hallazgos=lambda s: len(s["candidatos"]) if isinstance(s.get("candidatos"), list) else None,
|
|
285
|
+
identidades=_fibras_identidades,
|
|
286
|
+
),
|
|
287
|
+
Instrumento(
|
|
288
|
+
nombre="test-ordinal-ratchet",
|
|
289
|
+
modulo="ordinal_ratchet.cli",
|
|
290
|
+
paquete="ordinal_ratchet",
|
|
291
|
+
argumentos=(".", "--json"),
|
|
292
|
+
rc_contrato={
|
|
293
|
+
0: (SIN_HALLAZGOS, "nada crecio sobre la linea base declarada"),
|
|
294
|
+
1: (CON_HALLAZGOS, "colision nueva, contador sobre la linea base o deuda desaparecida"),
|
|
295
|
+
2: (SIN_SUJETO, "sin archivo de prueba, nada parsea, o no comparable"),
|
|
296
|
+
},
|
|
297
|
+
denominador=_ordinal_denominador,
|
|
298
|
+
hallazgos=lambda s: _suma(("ordinal", "shadow", "shared"), s.get("total") or {}),
|
|
299
|
+
identidades=_ordinal_identidades,
|
|
300
|
+
),
|
|
301
|
+
Instrumento(
|
|
302
|
+
nombre="ts-py-anchor-guard",
|
|
303
|
+
modulo="ts_py_anchor_guard.anchor_oracle",
|
|
304
|
+
paquete="ts_py_anchor_guard",
|
|
305
|
+
argumentos=("--manifest", "{manifiesto}", "--json"),
|
|
306
|
+
rc_contrato={
|
|
307
|
+
0: (SIN_HALLAZGOS, "anclas conformes"),
|
|
308
|
+
1: (CON_HALLAZGOS, "alguna ancla diverge"),
|
|
309
|
+
2: (NO_MEDIDO, "no medido: ancla no evaluable, cobertura incompleta o insumo ilegible"),
|
|
310
|
+
20: (NO_MEDIDO, "invocacion invalida"),
|
|
311
|
+
},
|
|
312
|
+
denominador=_guardia_denominador,
|
|
313
|
+
hallazgos=lambda s: _suma(("divergen", "no_medidos"), s.get("totales") or {}),
|
|
314
|
+
identidades=_guardia_identidades,
|
|
315
|
+
unidad="par",
|
|
316
|
+
reconciliar=_guardia_reconcilia,
|
|
317
|
+
),
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
POR_NOMBRE = {i.nombre: i for i in INSTRUMENTOS}
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def version_de(repo: str, paquete: str = "") -> str | None:
|
|
324
|
+
"""The version the instrument declares: its `pyproject.toml`, or its `__init__.py`.
|
|
325
|
+
|
|
326
|
+
Both spellings exist in the four: three pin the version in the packaging metadata and one
|
|
327
|
+
keeps it in the package and lets the metadata read it dynamically. A reader that knows only
|
|
328
|
+
the first reports `NO_MEDIDO` for a version that is written down and easy to find.
|
|
329
|
+
"""
|
|
330
|
+
try:
|
|
331
|
+
with open(os.path.join(repo, "pyproject.toml"), "rb") as f:
|
|
332
|
+
datos = tomllib.load(f)
|
|
333
|
+
version = (datos.get("project") or {}).get("version")
|
|
334
|
+
if version is not None:
|
|
335
|
+
return str(version)
|
|
336
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
337
|
+
pass
|
|
338
|
+
for candidato in (os.path.join(paquete, "__init__.py") if paquete else "__init__.py",
|
|
339
|
+
"__init__.py"):
|
|
340
|
+
try:
|
|
341
|
+
with open(os.path.join(repo, candidato), encoding="utf-8") as f:
|
|
342
|
+
match = re.search(r'^__version__\s*=\s*["\']([^"\']+)["\']', f.read(), re.MULTILINE)
|
|
343
|
+
except OSError:
|
|
344
|
+
continue
|
|
345
|
+
if match:
|
|
346
|
+
return match.group(1)
|
|
347
|
+
return None
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def commit_de(repo: str) -> str | None:
|
|
351
|
+
"""`HEAD` of the instrument's repository: the tree that ran, not the one it claims."""
|
|
352
|
+
try:
|
|
353
|
+
hecho = subprocess.run(["git", "-C", repo, "rev-parse", "HEAD"],
|
|
354
|
+
capture_output=True, text=True, timeout=60)
|
|
355
|
+
except (OSError, subprocess.SubprocessError):
|
|
356
|
+
return None
|
|
357
|
+
return hecho.stdout.strip() or None if hecho.returncode == 0 else None
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
class _ArbolEnMovimiento(RuntimeError):
|
|
361
|
+
"""The tree changed while it was being read. Not an error of the tree: an error of the attempt."""
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _huella_una_pasada(raiz: str) -> str | None:
|
|
365
|
+
"""One walk and one read. Raises `_ArbolEnMovimiento` if the tree moved underneath it."""
|
|
366
|
+
archivos = []
|
|
367
|
+
for actual, dirs, nombres in os.walk(raiz, onerror=_levantar):
|
|
368
|
+
dirs[:] = sorted(d for d in dirs if d != "__pycache__")
|
|
369
|
+
for nombre in sorted(nombres):
|
|
370
|
+
if nombre.endswith(".py"):
|
|
371
|
+
archivos.append(os.path.join(actual, nombre))
|
|
372
|
+
if not archivos:
|
|
373
|
+
return None
|
|
374
|
+
resumen = hashlib.sha256()
|
|
375
|
+
for ruta in sorted(archivos, key=lambda r: os.path.relpath(r, raiz).replace(os.sep, "/")):
|
|
376
|
+
rel = os.path.relpath(ruta, raiz).replace(os.sep, "/")
|
|
377
|
+
resumen.update(rel.encode("utf-8") + b"\x00")
|
|
378
|
+
try:
|
|
379
|
+
with open(ruta, "rb") as f:
|
|
380
|
+
resumen.update(hashlib.sha256(f.read()).digest())
|
|
381
|
+
except OSError as error:
|
|
382
|
+
raise _ArbolEnMovimiento(ruta) from error
|
|
383
|
+
return "sha256:" + resumen.hexdigest()
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _levantar(error: OSError) -> None:
|
|
387
|
+
"""`os.walk` swallows a directory it cannot list. That silence is the defect, so it is raised.
|
|
388
|
+
|
|
389
|
+
A subtree that vanished between the listing and the descent used to be dropped without a word,
|
|
390
|
+
and the digest that followed was a perfectly valid `sha256:` of a tree nobody has: an absence
|
|
391
|
+
dressed as a measurement.
|
|
392
|
+
"""
|
|
393
|
+
raise _ArbolEnMovimiento(str(error)) from error
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def huella_de_arbol(raiz: str, intentos: int = 2) -> str | None:
|
|
397
|
+
"""`sha256:` over a package's `.py` files, relative path and content, in sorted order.
|
|
398
|
+
|
|
399
|
+
A commit names the tree and the version names the release; neither names the bytes that
|
|
400
|
+
ran if someone edited a checkout. This digest does, and it is taken over relative paths so
|
|
401
|
+
it survives the same package being installed somewhere else.
|
|
402
|
+
|
|
403
|
+
A tree somebody is writing has no digest. A file that disappears between the walk and the read
|
|
404
|
+
would either break the walker -- and this ran uncaught for weeks, once in ~140 full suites --
|
|
405
|
+
or, if the vanished thing were a directory, yield a digest of a silently incomplete tree that
|
|
406
|
+
looks exactly like a measurement. So a raced walk is retried, and a tree that keeps moving
|
|
407
|
+
answers `None`: `NO_MEDIDO`, never a number that reads as one.
|
|
408
|
+
"""
|
|
409
|
+
if not os.path.isdir(raiz):
|
|
410
|
+
return None
|
|
411
|
+
for _ in range(max(1, intentos)):
|
|
412
|
+
try:
|
|
413
|
+
return _huella_una_pasada(raiz)
|
|
414
|
+
except _ArbolEnMovimiento:
|
|
415
|
+
continue
|
|
416
|
+
return None
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def huella_de(repo: str, paquete: str) -> str | None:
|
|
420
|
+
"""The digest of the package inside a checkout: `<repo>/<paquete>`."""
|
|
421
|
+
return huella_de_arbol(os.path.join(repo, paquete))
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
#: Asked in a subprocess on purpose: locating an installed package must not become importing it,
|
|
425
|
+
#: and this package's whole isolation argument is that no instrument ever runs in this process.
|
|
426
|
+
_SONDEO_INSTALADO = """\
|
|
427
|
+
import importlib.metadata, importlib.util, json
|
|
428
|
+
especificacion = importlib.util.find_spec({paquete!r})
|
|
429
|
+
if especificacion is None:
|
|
430
|
+
print(json.dumps(None))
|
|
431
|
+
else:
|
|
432
|
+
rutas = especificacion.submodule_search_locations
|
|
433
|
+
ruta = list(rutas)[0] if rutas else especificacion.origin
|
|
434
|
+
nombre = {paquete!r}.split(".")[0]
|
|
435
|
+
distribuciones = importlib.metadata.packages_distributions().get(nombre) or []
|
|
436
|
+
version = None
|
|
437
|
+
if distribuciones:
|
|
438
|
+
try:
|
|
439
|
+
version = importlib.metadata.version(distribuciones[0])
|
|
440
|
+
except importlib.metadata.PackageNotFoundError:
|
|
441
|
+
version = None
|
|
442
|
+
print(json.dumps({{"ruta": ruta, "distribucion": distribuciones[0] if distribuciones else None,
|
|
443
|
+
"version": version}}))
|
|
444
|
+
"""
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def ubicacion_instalada(paquete: str) -> dict | None:
|
|
448
|
+
"""Where the interpreter that runs this process would import `paquete` from, and its version.
|
|
449
|
+
|
|
450
|
+
This is the route a consumer repository takes: an instrument installed into the environment
|
|
451
|
+
has no sibling clone to point `--raiz` at. Its `commit` is not measurable from the
|
|
452
|
+
installation, so it is reported as absent and a pin, when one is declared, says which
|
|
453
|
+
commit the installation is supposed to be -- as a declaration, never as a measurement.
|
|
454
|
+
"""
|
|
455
|
+
try:
|
|
456
|
+
hecho = subprocess.run([sys.executable, "-c", _SONDEO_INSTALADO.format(paquete=paquete)],
|
|
457
|
+
capture_output=True, text=True, timeout=120,
|
|
458
|
+
env={k: v for k, v in os.environ.items()
|
|
459
|
+
if k in ("PATH", "HOME", "SYSTEMROOT")})
|
|
460
|
+
except (OSError, subprocess.SubprocessError):
|
|
461
|
+
return None
|
|
462
|
+
if hecho.returncode != 0:
|
|
463
|
+
return None
|
|
464
|
+
try:
|
|
465
|
+
datos = json.loads(hecho.stdout or "null")
|
|
466
|
+
except json.JSONDecodeError:
|
|
467
|
+
return None
|
|
468
|
+
if not isinstance(datos, dict) or not datos.get("ruta"):
|
|
469
|
+
return None
|
|
470
|
+
return datos
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def identificar(repo: str, instrumento: Instrumento) -> dict:
|
|
474
|
+
return {
|
|
475
|
+
"version": version_de(repo, instrumento.paquete),
|
|
476
|
+
"commit": commit_de(repo),
|
|
477
|
+
"huella": huella_de(repo, instrumento.paquete),
|
|
478
|
+
}
|