forceupdate 0.1.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.
- forceupdate/__init__.py +9 -0
- forceupdate/__main__.py +5 -0
- forceupdate/advisories/__init__.py +30 -0
- forceupdate/advisories/cvss.py +95 -0
- forceupdate/advisories/osv.py +584 -0
- forceupdate/checks/__init__.py +49 -0
- forceupdate/checks/base.py +98 -0
- forceupdate/checks/deprecated.py +115 -0
- forceupdate/checks/outdated.py +183 -0
- forceupdate/checks/priority.py +82 -0
- forceupdate/checks/vulns.py +201 -0
- forceupdate/cli.py +309 -0
- forceupdate/detect/__init__.py +5 -0
- forceupdate/detect/languages.py +266 -0
- forceupdate/detect/manifests.py +478 -0
- forceupdate/engine.py +313 -0
- forceupdate/models.py +510 -0
- forceupdate/net/__init__.py +20 -0
- forceupdate/net/cache.py +217 -0
- forceupdate/net/http.py +270 -0
- forceupdate/parsers/__init__.py +43 -0
- forceupdate/parsers/base.py +22 -0
- forceupdate/parsers/json_spans.py +123 -0
- forceupdate/parsers/lockfiles.py +231 -0
- forceupdate/parsers/npm.py +1257 -0
- forceupdate/parsers/python.py +1421 -0
- forceupdate/parsers/toml_spans.py +297 -0
- forceupdate/registries/__init__.py +52 -0
- forceupdate/registries/base.py +294 -0
- forceupdate/registries/npm.py +153 -0
- forceupdate/registries/pypi.py +242 -0
- forceupdate/report/__init__.py +359 -0
- forceupdate/report/json.py +34 -0
- forceupdate/report/markdown.py +169 -0
- forceupdate/report/terminal.py +376 -0
- forceupdate/sources/__init__.py +1 -0
- forceupdate/sources/base.py +45 -0
- forceupdate/sources/local.py +183 -0
- forceupdate/update/__init__.py +8 -0
- forceupdate/update/constraints.py +317 -0
- forceupdate/update/planner.py +531 -0
- forceupdate/versions/__init__.py +40 -0
- forceupdate/versions/base.py +229 -0
- forceupdate/versions/npm.py +432 -0
- forceupdate/versions/pypi.py +220 -0
- forceupdate-0.1.0.dist-info/METADATA +79 -0
- forceupdate-0.1.0.dist-info/RECORD +50 -0
- forceupdate-0.1.0.dist-info/WHEEL +4 -0
- forceupdate-0.1.0.dist-info/entry_points.txt +2 -0
- forceupdate-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
"""Les rapports : le résultat d'une analyse, mis en forme.
|
|
2
|
+
|
|
3
|
+
- ``terminal.py`` : pour la console (``rich``) ;
|
|
4
|
+
- ``json.py`` : le format de l'API (E12), décrit dans ``docs/JSON_FORMAT.md`` ;
|
|
5
|
+
- ``markdown.py`` : un rapport à lire, qui servira aussi de corps aux PR (E18).
|
|
6
|
+
|
|
7
|
+
Ce module garde ce qu'ils partagent : les noms des constats, le résumé, les lignes du
|
|
8
|
+
tableau d'un projet (un paquet par ligne, même déclaré deux fois), et la description des
|
|
9
|
+
mises à jour proposées (``forceupdate update``).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from collections.abc import Iterable
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
|
|
16
|
+
from forceupdate import checks
|
|
17
|
+
from forceupdate.checks import GAP_LABELS, vulns
|
|
18
|
+
from forceupdate.models import (
|
|
19
|
+
Dependency,
|
|
20
|
+
EditKind,
|
|
21
|
+
Finding,
|
|
22
|
+
FindingKind,
|
|
23
|
+
Gap,
|
|
24
|
+
Project,
|
|
25
|
+
Report,
|
|
26
|
+
Scope,
|
|
27
|
+
Update,
|
|
28
|
+
UpdateOption,
|
|
29
|
+
UpdateReason,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
KIND_LABELS = {
|
|
33
|
+
FindingKind.VULNERABLE: "faille",
|
|
34
|
+
FindingKind.EOL: "fin de vie",
|
|
35
|
+
FindingKind.YANKED: "retirée",
|
|
36
|
+
FindingKind.DEPRECATED: "déprécié",
|
|
37
|
+
FindingKind.OUTDATED: "plus récente",
|
|
38
|
+
FindingKind.UNVERIFIABLE: "non vérifiable",
|
|
39
|
+
FindingKind.INCONCLUSIVE: "non concluant",
|
|
40
|
+
}
|
|
41
|
+
"""Le type d'un constat en français, tel qu'on l'affiche."""
|
|
42
|
+
|
|
43
|
+
UP_TO_DATE = "à jour"
|
|
44
|
+
POSSIBLE_VULNERABILITY = "faille possible"
|
|
45
|
+
"""Une faille de la borne basse d'une contrainte, sans lockfile : la version installée peut
|
|
46
|
+
être plus récente, et corrigée."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def label(finding: Finding) -> str:
|
|
50
|
+
"""Le constat en un ou deux mots : ``majeure``, ``retirée``, ``faille possible``…"""
|
|
51
|
+
if finding.kind is FindingKind.OUTDATED and finding.gap is not None:
|
|
52
|
+
return GAP_LABELS[finding.gap]
|
|
53
|
+
if finding.kind is FindingKind.VULNERABLE and finding.current_is_approximate:
|
|
54
|
+
return POSSIBLE_VULNERABILITY
|
|
55
|
+
return KIND_LABELS[finding.kind]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def subject(finding: Finding) -> str:
|
|
59
|
+
"""Ce dont parle le constat, pour le détail : le paquet ; pour une dépendance indirecte, sa
|
|
60
|
+
version aussi (un paquet npm peut y être en plusieurs versions)."""
|
|
61
|
+
dependency = finding.dependency
|
|
62
|
+
if dependency is None:
|
|
63
|
+
return ""
|
|
64
|
+
if dependency.direct:
|
|
65
|
+
return dependency.name
|
|
66
|
+
version = f" {dependency.installed}" if dependency.installed else ""
|
|
67
|
+
return f"{dependency.name}{version} (indirecte)"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
REASON_LABELS = {
|
|
71
|
+
UpdateReason.LATEST_PATCH: "dernier correctif",
|
|
72
|
+
UpdateReason.LATEST_MINOR: "dernière mineure",
|
|
73
|
+
UpdateReason.LATEST_MAJOR: "dernière version",
|
|
74
|
+
UpdateReason.SECURITY_FIX: "correction des failles",
|
|
75
|
+
UpdateReason.REPLACEMENT: "remplace la version retirée ou dépréciée",
|
|
76
|
+
}
|
|
77
|
+
"""Pourquoi une version est proposée, en français."""
|
|
78
|
+
|
|
79
|
+
DOWNGRADE = "retour en arrière"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def update_subject(update: Update) -> str:
|
|
83
|
+
"""Le paquet d'une mise à jour, marqué ``(indirecte)`` pour une dépendance indirecte."""
|
|
84
|
+
return update.name if update.direct else f"{update.name} (indirecte)"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def option_fixed(option: UpdateOption) -> str:
|
|
88
|
+
"""Les failles corrigées, en toutes lettres : ``corrige 2 failles sur 6`` ; vide si le
|
|
89
|
+
paquet n'en a pas."""
|
|
90
|
+
total = len(option.fixes) + len(option.unfixed)
|
|
91
|
+
if not total:
|
|
92
|
+
return ""
|
|
93
|
+
return f"corrige {len(option.fixes)} faille{'s' if len(option.fixes) > 1 else ''} sur {total}"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def option_gap(option: UpdateOption) -> str:
|
|
97
|
+
"""L'écart d'une option en un mot : ``correctif``, ``mineure``, ``majeure``, ou ``retour
|
|
98
|
+
en arrière``."""
|
|
99
|
+
return DOWNGRADE if option.gap is None else GAP_LABELS[option.gap]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def option_fixes(option: UpdateOption) -> str:
|
|
103
|
+
"""Les failles qu'une option corrige : ``2 sur 6`` ; vide si le paquet n'en a pas."""
|
|
104
|
+
total = len(option.fixes) + len(option.unfixed)
|
|
105
|
+
return f"{len(option.fixes)} sur {total}" if total else ""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def option_changes(option: UpdateOption, project: str = ".") -> list[str]:
|
|
109
|
+
"""Ce qu'une option modifie, une ligne par fichier : les contraintes réécrites, le lockfile
|
|
110
|
+
à régénérer, ou pourquoi il faut le faire à la main. Les chemins sont relatifs au dossier
|
|
111
|
+
du projet ``project`` quand ils y sont."""
|
|
112
|
+
lines = []
|
|
113
|
+
for edit in option.edits:
|
|
114
|
+
if edit.kind is EditKind.CATALOG:
|
|
115
|
+
where = "pnpm-workspace.yaml (catalogue)"
|
|
116
|
+
elif edit.kind is EditKind.OVERRIDE and edit.override is not None:
|
|
117
|
+
override = edit.override
|
|
118
|
+
where = f"{_within(edit.file, project)} ({override.section} « {override.key} »)"
|
|
119
|
+
else:
|
|
120
|
+
where = _within(edit.file, project)
|
|
121
|
+
lines.append(f"{where} : {edit.old} → {edit.new}")
|
|
122
|
+
if option.lockfile is not None:
|
|
123
|
+
lockfile = _within(option.lockfile, project)
|
|
124
|
+
lines.append(f"puis {lockfile}" if lines else f"{lockfile} (lockfile seul)")
|
|
125
|
+
if option.manual is not None:
|
|
126
|
+
lines.append(f"à la main : {option.manual}")
|
|
127
|
+
return lines
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _within(path: str, project: str) -> str:
|
|
131
|
+
"""``path`` vu depuis le dossier ``project`` s'il y est, sinon tel quel."""
|
|
132
|
+
if project != "." and path.startswith(project + "/"):
|
|
133
|
+
return path[len(project) + 1 :]
|
|
134
|
+
return path
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def plural(count: int, word: str) -> str:
|
|
138
|
+
"""``count`` suivi de ``word``, au pluriel au-delà de 1 : ``2 majeures``, ``3 fins de vie``."""
|
|
139
|
+
if count > 1:
|
|
140
|
+
word = _PLURALS.get(word, word + "s")
|
|
141
|
+
return f"{count} {word}"
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
_PLURALS = {"fin de vie": "fins de vie"}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def format_date(when: datetime) -> str:
|
|
148
|
+
"""Une date à la française, à l'heure locale : ``27/10/2026 à 14:03``."""
|
|
149
|
+
return when.astimezone().strftime("%d/%m/%Y à %H:%M")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def format_share(part: int, total: int) -> str:
|
|
153
|
+
"""Une part en pourcentage, à la française : `` 75,0 %``."""
|
|
154
|
+
return f"{100 * part / total:5.1f} %".replace(".", ",")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@dataclass(frozen=True, kw_only=True)
|
|
158
|
+
class Summary:
|
|
159
|
+
"""Les chiffres d'une analyse. Un paquet déclaré deux fois dans un projet (runtime et dev)
|
|
160
|
+
donne deux constats identiques : ils comptent pour un."""
|
|
161
|
+
|
|
162
|
+
projects: int
|
|
163
|
+
direct: int
|
|
164
|
+
"""Dépendances directes, toutes déclarations comprises."""
|
|
165
|
+
transitive: int
|
|
166
|
+
checked: int
|
|
167
|
+
"""Dépendances vérifiées auprès des registres (voir ``ScanOptions``)."""
|
|
168
|
+
audited: int = 0
|
|
169
|
+
"""Dépendances dont les failles ont été cherchées (OSV) : toutes celles dont on connaît la
|
|
170
|
+
version, indirectes comprises (voir ``checks.vulns``)."""
|
|
171
|
+
findings: dict[FindingKind, int] = field(default_factory=dict)
|
|
172
|
+
"""Constats par type, dans l'ordre de priorité ; tous les types y sont, même à 0."""
|
|
173
|
+
outdated: dict[Gap, int] = field(default_factory=dict)
|
|
174
|
+
"""Versions plus récentes par écart, de la majeure au correctif."""
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def to_update(self) -> int:
|
|
178
|
+
"""Ce qui est à mettre à jour : tout sauf « non vérifiable » et « non concluant »."""
|
|
179
|
+
return sum(
|
|
180
|
+
count
|
|
181
|
+
for kind, count in self.findings.items()
|
|
182
|
+
if kind not in (FindingKind.UNVERIFIABLE, FindingKind.INCONCLUSIVE)
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def summarize(report: Report) -> Summary:
|
|
187
|
+
"""Le résumé de ``report``."""
|
|
188
|
+
findings = dict.fromkeys(KIND_LABELS, 0)
|
|
189
|
+
outdated = dict.fromkeys(GAP_LABELS, 0)
|
|
190
|
+
for finding in distinct_findings(report.projects):
|
|
191
|
+
findings[finding.kind] += 1
|
|
192
|
+
if finding.kind is FindingKind.OUTDATED and finding.gap is not None:
|
|
193
|
+
outdated[finding.gap] += 1
|
|
194
|
+
dependencies = [d for project in report.projects for d in project.dependencies]
|
|
195
|
+
direct = sum(1 for d in dependencies if d.direct)
|
|
196
|
+
options = report.options
|
|
197
|
+
checked = audited = 0
|
|
198
|
+
if options is not None:
|
|
199
|
+
checked = sum(1 for d in dependencies if checks.selected(d, options))
|
|
200
|
+
audited = sum(
|
|
201
|
+
1
|
|
202
|
+
for d in dependencies
|
|
203
|
+
if vulns.audited(d, options) and vulns.version_to_check(d) is not None
|
|
204
|
+
)
|
|
205
|
+
return Summary(
|
|
206
|
+
projects=len(report.projects),
|
|
207
|
+
direct=direct,
|
|
208
|
+
transitive=len(dependencies) - direct,
|
|
209
|
+
checked=checked,
|
|
210
|
+
audited=audited,
|
|
211
|
+
findings=findings,
|
|
212
|
+
outdated=outdated,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def distinct_findings(projects: Iterable[Project]) -> list[Finding]:
|
|
217
|
+
"""Les constats de ``projects``, du plus grave au moins grave, sans les doubles : un
|
|
218
|
+
paquet déclaré deux fois dans un projet n'est compté qu'une fois."""
|
|
219
|
+
seen = set()
|
|
220
|
+
kept = []
|
|
221
|
+
for project in projects:
|
|
222
|
+
for finding in project.findings:
|
|
223
|
+
dependency = finding.dependency
|
|
224
|
+
key = (
|
|
225
|
+
project.path,
|
|
226
|
+
finding.kind,
|
|
227
|
+
None if dependency is None else (dependency.ecosystem, dependency.name),
|
|
228
|
+
finding.current_version,
|
|
229
|
+
finding.target_version,
|
|
230
|
+
finding.message,
|
|
231
|
+
)
|
|
232
|
+
if key not in seen:
|
|
233
|
+
seen.add(key)
|
|
234
|
+
kept.append(finding)
|
|
235
|
+
return checks.sort_findings(kept)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
@dataclass(frozen=True, kw_only=True)
|
|
239
|
+
class Row:
|
|
240
|
+
"""Une ligne du tableau d'un projet : un paquet, avec toutes ses déclarations."""
|
|
241
|
+
|
|
242
|
+
name: str
|
|
243
|
+
notes: tuple[str, ...]
|
|
244
|
+
"""Ce qui la distingue : scope (sauf ``runtime``), fichier quand le projet en a plusieurs."""
|
|
245
|
+
constraint: str
|
|
246
|
+
"""La contrainte telle qu'écrite (``-`` s'il n'y en a pas), avec la plage d'un catalogue
|
|
247
|
+
pnpm entre parenthèses ; plusieurs, séparées par des virgules."""
|
|
248
|
+
current: str
|
|
249
|
+
"""La version utilisée ; ``≈ 1.2`` pour une borne basse ; ``-`` si on ne la connaît pas."""
|
|
250
|
+
wanted: str
|
|
251
|
+
"""La plus haute que la contrainte accepte ; vide si rien n'est à signaler."""
|
|
252
|
+
latest: str
|
|
253
|
+
"""La dernière ; vide si rien n'est à signaler."""
|
|
254
|
+
findings: tuple[Finding, ...]
|
|
255
|
+
"""Ses constats, sans les doubles, du plus grave au moins grave."""
|
|
256
|
+
checked: bool
|
|
257
|
+
"""Vérifiée auprès du registre."""
|
|
258
|
+
unverifiable: str | None = None
|
|
259
|
+
"""Pourquoi on ne peut pas la vérifier (``Dependency.unverifiable_reason``)."""
|
|
260
|
+
|
|
261
|
+
@property
|
|
262
|
+
def states(self) -> list[str]:
|
|
263
|
+
"""Les constats en un ou deux mots ; « à jour » pour une dépendance vérifiée sans
|
|
264
|
+
constat ; pourquoi elle n'est pas vérifiable (un membre du workspace n'a pas de
|
|
265
|
+
constat) ; rien si elle n'a pas été vérifiée."""
|
|
266
|
+
if self.findings:
|
|
267
|
+
return list(dict.fromkeys(label(finding) for finding in self.findings))
|
|
268
|
+
if self.unverifiable is not None:
|
|
269
|
+
return [f"non vérifiable : {self.unverifiable}"]
|
|
270
|
+
return [UP_TO_DATE] if self.checked else []
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def rows(project: Project, report: Report, *, direct: bool = True) -> list[Row]:
|
|
274
|
+
"""Les lignes du tableau de ``project`` : ses dépendances directes vérifiées (ou toutes si
|
|
275
|
+
rien n'a été vérifié), une ligne par paquet, les plus graves en tête.
|
|
276
|
+
|
|
277
|
+
``direct=False`` : les dépendances indirectes qui ont un constat (une faille, ou ce
|
|
278
|
+
qu'ajoute ``--transitive``) ; une ligne par version installée.
|
|
279
|
+
"""
|
|
280
|
+
several_files = len({d.file for d in project.dependencies if d.direct}) > 1
|
|
281
|
+
groups: dict[tuple[str, ...], list[Dependency]] = {}
|
|
282
|
+
for dependency in project.dependencies:
|
|
283
|
+
if dependency.direct is not direct:
|
|
284
|
+
continue
|
|
285
|
+
if (
|
|
286
|
+
direct
|
|
287
|
+
and report.options is not None
|
|
288
|
+
and not checks.selected(dependency, report.options)
|
|
289
|
+
):
|
|
290
|
+
continue
|
|
291
|
+
key = (dependency.ecosystem, dependency.name)
|
|
292
|
+
if not direct:
|
|
293
|
+
key += (dependency.installed or "",)
|
|
294
|
+
groups.setdefault(key, []).append(dependency)
|
|
295
|
+
found = []
|
|
296
|
+
for group in groups.values():
|
|
297
|
+
row = _row(group, project.findings, several_files, checked=report.options is not None)
|
|
298
|
+
if direct or row.findings:
|
|
299
|
+
found.append(row)
|
|
300
|
+
return sorted(found, key=_row_order)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _row(
|
|
304
|
+
group: list[Dependency], findings: list[Finding], several_files: bool, *, checked: bool
|
|
305
|
+
) -> Row:
|
|
306
|
+
mine = checks.sort_findings(f for f in findings if f.dependency in group)
|
|
307
|
+
unique: dict[tuple[object, ...], Finding] = {}
|
|
308
|
+
for finding in mine:
|
|
309
|
+
unique.setdefault((finding.kind, finding.message), finding)
|
|
310
|
+
notes = []
|
|
311
|
+
for dependency in group:
|
|
312
|
+
if dependency.scope is not Scope.RUNTIME:
|
|
313
|
+
notes.append(str(dependency.scope))
|
|
314
|
+
if several_files:
|
|
315
|
+
notes.append(dependency.file)
|
|
316
|
+
versions = [f for f in unique.values() if f.target_version and f.kind in _VERSION_KINDS]
|
|
317
|
+
return Row(
|
|
318
|
+
name=group[0].name,
|
|
319
|
+
notes=tuple(dict.fromkeys(notes)),
|
|
320
|
+
constraint=_join(_constraint(d) for d in group),
|
|
321
|
+
current=_join(_current(d) for d in group),
|
|
322
|
+
wanted=_join(f.wanted_version or "" for f in versions),
|
|
323
|
+
latest=_join(f.target_version or "" for f in versions),
|
|
324
|
+
findings=tuple(unique.values()),
|
|
325
|
+
checked=checked and all(d.verifiable for d in group),
|
|
326
|
+
unverifiable=next((d.unverifiable_reason for d in group if not d.verifiable), None),
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
_VERSION_KINDS = (FindingKind.OUTDATED, FindingKind.INCONCLUSIVE)
|
|
331
|
+
"""Les constats qui portent la dernière version et celle de la contrainte."""
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _row_order(row: Row) -> tuple[tuple[int, int], str]:
|
|
335
|
+
worst = checks.priority(row.findings[0]) if row.findings else (len(KIND_LABELS), 0)
|
|
336
|
+
return worst, row.name
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _constraint(dependency: Dependency) -> str:
|
|
340
|
+
text = dependency.constraint or "-"
|
|
341
|
+
if dependency.resolved_constraint is not None:
|
|
342
|
+
text += f" ({dependency.resolved_constraint})"
|
|
343
|
+
return text
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _current(dependency: Dependency) -> str:
|
|
347
|
+
if not dependency.verifiable:
|
|
348
|
+
return dependency.installed or "-"
|
|
349
|
+
try:
|
|
350
|
+
current = checks.current_version(dependency)
|
|
351
|
+
except LookupError: # écosystème dont les versions ne sont pas encore gérées
|
|
352
|
+
return dependency.installed or "-"
|
|
353
|
+
if current.version is None:
|
|
354
|
+
return "-"
|
|
355
|
+
return f"≈ {current.version}" if current.approximate else current.version
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _join(values: Iterable[str]) -> str:
|
|
359
|
+
return ", ".join(value for value in dict.fromkeys(values) if value)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Le rapport en JSON : ``forceupdate scan --format json``, et le format de l'API (E12).
|
|
2
|
+
|
|
3
|
+
Le schéma est décrit dans ``docs/JSON_FORMAT.md``. Il porte un numéro (``schema_version``) :
|
|
4
|
+
un changement qui casse un lecteur (champ retiré, renommé, ou de sens changé) le fait passer
|
|
5
|
+
à 2 ; un champ ajouté, non.
|
|
6
|
+
|
|
7
|
+
Le texte est de l'UTF-8 sans échappement des accents (``ensure_ascii=False``) : c'est à qui
|
|
8
|
+
l'écrit de le faire en UTF-8, sur la sortie standard comme dans un fichier.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from forceupdate import __version__
|
|
15
|
+
from forceupdate.models import Report, to_dict
|
|
16
|
+
from forceupdate.report import summarize
|
|
17
|
+
|
|
18
|
+
SCHEMA_VERSION = 1
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build(report: Report) -> dict[str, Any]:
|
|
22
|
+
"""Le rapport en types simples, prêt pour ``json.dumps`` (ou une réponse de l'API)."""
|
|
23
|
+
summary = summarize(report)
|
|
24
|
+
return {
|
|
25
|
+
"schema_version": SCHEMA_VERSION,
|
|
26
|
+
"tool": {"name": "forceupdate", "version": __version__},
|
|
27
|
+
**to_dict(report),
|
|
28
|
+
"summary": {**to_dict(summary), "to_update": summary.to_update},
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def render(report: Report) -> str:
|
|
33
|
+
"""Le rapport en JSON, indenté, terminé par un saut de ligne."""
|
|
34
|
+
return json.dumps(build(report), ensure_ascii=False, indent=2) + "\n"
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Le rapport en Markdown : ``forceupdate scan --format md``. Il servira aussi de corps aux PR
|
|
2
|
+
(E18) : du Markdown que GitHub, GitLab et Bitbucket affichent tous (titres, tableaux,
|
|
3
|
+
listes).
|
|
4
|
+
|
|
5
|
+
Ce qui vient des fichiers analysés ou des registres est échappé : un ``|`` (``^1 || ^2``)
|
|
6
|
+
couperait une cellule de tableau, un ``*`` ou un ``_`` mettrait en forme un message.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
from forceupdate.checks import GAP_LABELS
|
|
12
|
+
from forceupdate.models import FindingKind, Project, Report
|
|
13
|
+
from forceupdate.report import (
|
|
14
|
+
KIND_LABELS,
|
|
15
|
+
Row,
|
|
16
|
+
Summary,
|
|
17
|
+
distinct_findings,
|
|
18
|
+
format_date,
|
|
19
|
+
format_share,
|
|
20
|
+
label,
|
|
21
|
+
plural,
|
|
22
|
+
rows,
|
|
23
|
+
summarize,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_SPECIAL = re.compile(r"([\\`*_{}\[\]<>()#+!|~])")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def render(report: Report) -> str:
|
|
30
|
+
"""Le rapport en Markdown, terminé par un saut de ligne."""
|
|
31
|
+
lines = ["# Rapport forceupdate", ""]
|
|
32
|
+
lines.append(f"Source : `{_code(report.source)}`")
|
|
33
|
+
if report.scanned_at is not None:
|
|
34
|
+
lines += ["", f"Analyse du {format_date(report.scanned_at)}."]
|
|
35
|
+
if report.options is not None and report.options.offline:
|
|
36
|
+
if report.oldest_data is None:
|
|
37
|
+
lines.append("Hors ligne, sans données des registres ni d'OSV en cache.")
|
|
38
|
+
else:
|
|
39
|
+
lines.append(
|
|
40
|
+
"Hors ligne : données des registres et d'OSV prises dans le cache, la plus"
|
|
41
|
+
f" ancienne du {format_date(report.oldest_data)}."
|
|
42
|
+
)
|
|
43
|
+
if report.options is not None:
|
|
44
|
+
lines += ["", "## Résumé", "", *_summary(summarize(report))]
|
|
45
|
+
if not report.options.dev:
|
|
46
|
+
lines += ["", "Dépendances de développement non vérifiées (`--no-dev`)."]
|
|
47
|
+
lines += ["", "## Langages", ""]
|
|
48
|
+
if not report.languages:
|
|
49
|
+
lines.append("Aucun reconnu.")
|
|
50
|
+
else:
|
|
51
|
+
total = sum(language.bytes for language in report.languages)
|
|
52
|
+
lines += ["| Langage | Part | Écosystème |", "|---|---:|---|"]
|
|
53
|
+
for language in report.languages:
|
|
54
|
+
ecosystem = language.ecosystem or "aucun gestionnaire de paquets reconnu"
|
|
55
|
+
share = format_share(language.bytes, total).strip()
|
|
56
|
+
lines.append(f"| {_escape(language.name)} | {share} | {ecosystem} |")
|
|
57
|
+
if not report.projects:
|
|
58
|
+
lines += ["", "## Projets", "", "Aucun."]
|
|
59
|
+
for project in report.projects:
|
|
60
|
+
lines += _project(project, report)
|
|
61
|
+
if report.ignored_manifests:
|
|
62
|
+
lines += [
|
|
63
|
+
"",
|
|
64
|
+
"## Fichiers écartés",
|
|
65
|
+
"",
|
|
66
|
+
"Rangés dans des dossiers de tests ou d'exemples, ce ne sont pas de vrais projets :",
|
|
67
|
+
"",
|
|
68
|
+
]
|
|
69
|
+
lines += [f"- `{_code(path)}`" for path in report.ignored_manifests]
|
|
70
|
+
return "\n".join(lines) + "\n"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _summary(summary: Summary) -> list[str]:
|
|
74
|
+
lines = [
|
|
75
|
+
f"- {plural(summary.projects, 'projet')}, "
|
|
76
|
+
f"{plural(summary.checked, 'dépendance')} vérifiée{'s' if summary.checked > 1 else ''}"
|
|
77
|
+
]
|
|
78
|
+
if summary.audited != summary.checked:
|
|
79
|
+
lines[0] += f", failles cherchées sur {summary.audited}"
|
|
80
|
+
if not summary.to_update:
|
|
81
|
+
lines.append("- Rien à mettre à jour.")
|
|
82
|
+
else:
|
|
83
|
+
lines.append(f"- {summary.to_update} à mettre à jour :")
|
|
84
|
+
for kind, count in summary.findings.items():
|
|
85
|
+
if not count or kind in (FindingKind.UNVERIFIABLE, FindingKind.INCONCLUSIVE):
|
|
86
|
+
continue
|
|
87
|
+
if kind is FindingKind.OUTDATED:
|
|
88
|
+
lines += [
|
|
89
|
+
f" - {plural(n, GAP_LABELS[gap])}" for gap, n in summary.outdated.items() if n
|
|
90
|
+
]
|
|
91
|
+
else:
|
|
92
|
+
lines.append(f" - {plural(count, KIND_LABELS[kind])}")
|
|
93
|
+
for kind in (FindingKind.UNVERIFIABLE, FindingKind.INCONCLUSIVE):
|
|
94
|
+
if summary.findings[kind]:
|
|
95
|
+
lines.append(f"- {plural(summary.findings[kind], KIND_LABELS[kind])}")
|
|
96
|
+
return lines
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _project(project: Project, report: Report) -> list[str]:
|
|
100
|
+
title = f"## Projet `{_code(project.path)}`"
|
|
101
|
+
if project.ecosystems:
|
|
102
|
+
title += f" ({', '.join(project.ecosystems)})"
|
|
103
|
+
lines = ["", title, ""]
|
|
104
|
+
lines.append(f"- Manifestes : {_files(project.manifests)}")
|
|
105
|
+
lines.append(f"- Lockfiles : {_files(project.lockfiles)}")
|
|
106
|
+
directs = sum(1 for d in project.dependencies if d.direct)
|
|
107
|
+
lines.append(
|
|
108
|
+
f"- Dépendances directes : {directs or 'aucune'} ; "
|
|
109
|
+
f"indirectes : {len(project.dependencies) - directs or 'aucune'}"
|
|
110
|
+
)
|
|
111
|
+
direct_rows = rows(project, report)
|
|
112
|
+
if direct_rows:
|
|
113
|
+
lines += ["", *_table(direct_rows)]
|
|
114
|
+
indirect_rows = rows(project, report, direct=False)
|
|
115
|
+
if indirect_rows:
|
|
116
|
+
lines += ["", "### Dépendances indirectes à signaler", "", *_table(indirect_rows)]
|
|
117
|
+
details = [f for f in distinct_findings([project]) if f.kind is not FindingKind.OUTDATED]
|
|
118
|
+
if details:
|
|
119
|
+
lines += ["", "### Détails", ""]
|
|
120
|
+
for finding in details:
|
|
121
|
+
dependency = finding.dependency
|
|
122
|
+
name = ""
|
|
123
|
+
if dependency is not None:
|
|
124
|
+
name = f"`{_code(dependency.name)}`"
|
|
125
|
+
if not dependency.direct and dependency.installed:
|
|
126
|
+
name += f" {_escape(dependency.installed)}"
|
|
127
|
+
name += " (indirecte) : " if not dependency.direct else " : "
|
|
128
|
+
link = ""
|
|
129
|
+
if finding.kind is FindingKind.VULNERABLE and finding.url:
|
|
130
|
+
link = f" [Avis]({finding.url})"
|
|
131
|
+
lines.append(f"- **{label(finding)}** — {name}{_escape(finding.message)}{link}")
|
|
132
|
+
if project.notices:
|
|
133
|
+
lines += ["", "### Remarques", ""]
|
|
134
|
+
lines += [
|
|
135
|
+
f"- `{_code(notice.file)}` : {_escape(notice.message)}" for notice in project.notices
|
|
136
|
+
]
|
|
137
|
+
return lines
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _table(found: list[Row]) -> list[str]:
|
|
141
|
+
lines = [
|
|
142
|
+
"| Paquet | Contrainte | Utilisée | Permise | Dernière | État |",
|
|
143
|
+
"|---|---|---|---|---|---|",
|
|
144
|
+
]
|
|
145
|
+
for row in found:
|
|
146
|
+
name = f"`{_code(row.name)}`"
|
|
147
|
+
if row.notes:
|
|
148
|
+
name += f" ({_escape(', '.join(row.notes))})"
|
|
149
|
+
constraint = f"`{_code(row.constraint)}`" if row.constraint != "-" else "-"
|
|
150
|
+
lines.append(
|
|
151
|
+
f"| {name} | {constraint} | {_escape(row.current)} | {_escape(row.wanted)} "
|
|
152
|
+
f"| {_escape(row.latest)} | {_escape(', '.join(row.states))} |"
|
|
153
|
+
)
|
|
154
|
+
return lines
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _files(paths: list[str]) -> str:
|
|
158
|
+
return ", ".join(f"`{_code(path)}`" for path in paths) or "aucun"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _escape(text: str) -> str:
|
|
162
|
+
"""Du texte ordinaire : les caractères de Markdown échappés, sur une ligne."""
|
|
163
|
+
return _SPECIAL.sub(r"\\\1", " ".join(text.split()))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _code(text: str) -> str:
|
|
167
|
+
"""Du texte entre accents graves : sans accent grave, et ``|`` échappé (dans un tableau,
|
|
168
|
+
GitHub coupe la cellule même dans du code)."""
|
|
169
|
+
return " ".join(text.replace("`", "'").split()).replace("|", "\\|")
|