@ucm-kit/cli 0.1.38 → 0.1.40

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.
package/README.md CHANGED
@@ -11,8 +11,8 @@ next to the component's code. This command reads those files and says whether
11
11
  they still hold together.
12
12
 
13
13
  ```sh
14
- npx --yes @ucm-kit/cli@0.1.38 init
15
- npx --yes @ucm-kit/cli@0.1.38 check --report ci-report.md
14
+ npx --yes @ucm-kit/cli@0.1.40 init
15
+ npx --yes @ucm-kit/cli@0.1.40 check --report ci-report.md
16
16
  ```
17
17
 
18
18
  Pin an exact version, without `^`. A range would let npx install a build this
@@ -39,9 +39,10 @@ check`.
39
39
  | `ucm tokens css --out <file>` | Writes the CSS stylesheet of the tokens and their modes |
40
40
  | `ucm aides [<aide>]` | Lists the implementation guides, or prints one |
41
41
  | `ucm guide <contract>` | Prints what an agent reads before implementing that contract |
42
+ | `ucm rapport-gitlab` | Posts the report as a note on a GitLab merge request |
42
43
  | `ucm --help` | Prints the above |
43
44
 
44
- `ucm init` takes four options:
45
+ `ucm init` takes five options:
45
46
 
46
47
  | Option | Effect |
47
48
  |---|---|
@@ -49,6 +50,7 @@ check`.
49
50
  | `--tokens <dir>` | The folder that holds `tokens.json` |
50
51
  | `--implementation <pattern>` | Where a contract's implementation lives |
51
52
  | `--sans-agents` | Writes neither the agent relays, nor `.ucm/conventions.md`, nor the templates |
53
+ | `--forge github\|gitlab` | The forge whose CI is written; see [GitLab](#gitlab) |
52
54
 
53
55
  The first two take a folder, because a folder is what a repository arranges.
54
56
  `--tokens` appends the file name before writing it, so the `tokens` field of
@@ -62,7 +64,7 @@ not write React states its own extension here, rather than carrying a `.tsx`
62
64
  that was wrong the day it was installed:
63
65
 
64
66
  ```sh
65
- npx --yes @ucm-kit/cli@0.1.38 init --components Sources/DesignSystem --implementation '{dir}/{id}.swift'
67
+ npx --yes @ucm-kit/cli@0.1.40 init --components Sources/DesignSystem --implementation '{dir}/{id}.swift'
66
68
  ```
67
69
 
68
70
  All three act only on a first install: `ucm init` never overwrites an existing
@@ -217,12 +219,13 @@ is, and the command names what it left alone.
217
219
  | `.gitattributes` | Keeps contracts and tokens in LF, so a re-export from a Windows machine does not produce a whole-file diff |
218
220
  | `.vscode/settings.json` | Binds `*.contract.json` to the JSON Schema of the installed package, so the editor validates as you read |
219
221
  | `.gitignore` | Keeps `ci-report.md` out of the repository; it is regenerated on every run and describes only that run |
220
- | `.github/workflows/ucm.yml` | Runs the check on every pull request and posts the report as a comment |
222
+ | `.github/workflows/ucm.yml` | Runs the check on every pull request and posts the report as a comment, from a second job |
221
223
  | `.agents/skills/ucm-implementer/SKILL.md`, `.claude/skills/ucm-implementer/SKILL.md` | Two identical relays: an agent loads one before writing a component, and runs `ucm guide` at the pinned version |
222
224
  | `.ucm/conventions.md` | The repository's stack and writings, with its instructions in a comment |
223
225
  | `.ucm/gabarits/` | The templates of the installed stack adapter, when it publishes some |
224
226
 
225
- The workflow is yours once written. It will never be overwritten.
227
+ The workflow is yours once written. It will never be overwritten. On GitLab,
228
+ `.gitlab/ucm.gitlab-ci.yml` and `.gitlab-ci.yml` replace the GitHub workflow.
226
229
 
227
230
  An installed adapter that fails to load is reported, and the rest is
228
231
  installed. The command then prints the lines it does not write, each with its
@@ -253,6 +256,12 @@ is malformed is refused on both sides.
253
256
  `implementation` is a pattern with two tokens, `{dir}` for the contract's folder
254
257
  and `{id}` for its identifier. Replace it with the pattern your repository uses.
255
258
 
259
+ Each of the three paths is relative to the repository root and written with
260
+ `/`. A path that starts with `/` or a drive letter, contains `\`, or has an
261
+ empty, `.` or `..` segment is refused on both sides: the plugin would write
262
+ outside the repository with the designer's token, and the check would read
263
+ outside it.
264
+
256
265
  No version number goes in this file. Which contract versions can be read belongs
257
266
  to the installed package, and repeating it here would create a second authority
258
267
  that drifts on the first update.
@@ -308,6 +317,53 @@ The report also relays two things it does not measure itself: the warnings the
308
317
  export wrote into the contract, and the verdict of the repository's own tests
309
318
  when an orchestrator passes it in through `UCM_ECHECS_DE_TESTS`.
310
319
 
320
+ ## GitLab
321
+
322
+ `ucm init` writes the CI of one forge. `--forge` decides; without it, the host
323
+ of the `origin` remote does, then the presence of `.gitlab-ci.yml`, and GitHub
324
+ otherwise. The command names the forge and the signal it followed.
325
+
326
+ For GitLab it writes `.gitlab/ucm.gitlab-ci.yml`, two jobs with no global key,
327
+ so the project's other jobs keep their rules. `ucm` runs the check in merge
328
+ request pipelines and on the default branch; `ucm-rapport` posts the note in
329
+ merge request pipelines. Both take the default `test` stage. A new
330
+ `.gitlab-ci.yml` includes the file; an existing one is left alone, and the
331
+ command prints the `include` line to add. It also prints three settings it
332
+ cannot make:
333
+
334
+ - create the CI/CD variable `UCM_GITLAB_TOKEN`, masked and not protected,
335
+ holding an `api` token of an account with the Reporter role on this project
336
+ only: a service account's personal token, or a project access token where
337
+ the GitLab plan offers one. Export branches are not protected, so a
338
+ protected variable would be empty there. Every pipeline of every branch reads
339
+ an unprotected variable, and whoever pushes a branch can print it: the
340
+ Reporter role limits that token to reading and commenting;
341
+ - tick "Pipelines must succeed" in the merge request settings. Without it, a red
342
+ report does not block the merge it says is blocked;
343
+ - keep `test` in `stages:` when `.gitlab-ci.yml` declares them: GitLab refuses a
344
+ pipeline whose job names a missing stage.
345
+
346
+ `ucm` unsets `UCM_GITLAB_TOKEN` before `npm ci`, so install scripts do not
347
+ inherit it on executors that set variables in the job script. `ucm-rapport`
348
+ runs no code from the repository: it clones nothing, receives `ci-report.md`
349
+ as an artifact, disables install scripts, and runs `npx` from an empty
350
+ directory. It writes a minimal report when the check stopped before writing
351
+ one, then posts the report:
352
+
353
+ ```sh
354
+ npx --yes @ucm-kit/cli@0.1.40 rapport-gitlab --projet "$CI_PROJECT_ID" --merge-request "$CI_MERGE_REQUEST_IID" --fichier "$CI_PROJECT_DIR/ci-report.md" --api "$CI_API_V4_URL"
355
+ ```
356
+
357
+ The job allows failure: a refused token leaves the pipeline the colour of the
358
+ check, and the report stays in the artifacts.
359
+
360
+ The command reads the token from `UCM_GITLAB_TOKEN` and never prints it. It
361
+ replaces the note that the token's account wrote with the `<!-- ucm-rapport -->`
362
+ marker, across every page of notes, and creates one otherwise. Without the
363
+ variable it says so and exits with `0`: the report stays in the job artifacts.
364
+ A refused token exits with `1` and names the fix. `--api` defaults to
365
+ `https://gitlab.com/api/v4`.
366
+
311
367
  ## Optional stack adapters
312
368
 
313
369
  The first five checks above read contracts and tokens only, so they work
@@ -12,7 +12,14 @@ pistes de grille sont les seules valeurs brutes prévues. Les références d'un
12
12
  contrat se relèvent partout sauf dans `samples` et `meta`, dont une chaîne en
13
13
  forme de référence est un texte.
14
14
 
15
+ Quand ce moyen est une propriété personnalisée CSS, son nom est celui que
16
+ `tokenCssVariable` donne, et la feuille d'`ucm tokens css` le déclare. Une
17
+ projection recopiée tient la même règle : l'accent tombe et la lettre reste.
18
+ `café.fond` donne `--cafe-fond` ; une copie qui remplace tout caractère non
19
+ ASCII vise `--caf-fond`, une variable absente, sans erreur.
20
+
15
21
  ## Preuve
16
22
 
17
23
  `ucm check`, section tokens. Relecture : aucune valeur littérale à la place
18
- d'une référence.
24
+ d'une référence, et aucune projection de nom qui s'écarte de
25
+ `tokenCssVariable`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ucm-kit/cli",
3
- "version": "0.1.38",
3
+ "version": "0.1.40",
4
4
  "description": "La ligne de commande UCM : initialiser un repository, lister ce qu'il doit couvrir.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -29,6 +29,9 @@
29
29
  "test": "node scripts/run-tests.cjs"
30
30
  },
31
31
  "dependencies": {
32
- "@ucm-kit/core": "0.1.34"
32
+ "@ucm-kit/core": "0.1.36"
33
+ },
34
+ "devDependencies": {
35
+ "yaml": "^2.9.1"
33
36
  }
34
37
  }
package/src/guide.mjs CHANGED
@@ -46,6 +46,7 @@ const FICHIERS_EPINGLES = [
46
46
  ".agents/skills/ucm-implementer/SKILL.md",
47
47
  ".claude/skills/ucm-implementer/SKILL.md",
48
48
  ".github/workflows/ucm.yml",
49
+ ".gitlab/ucm.gitlab-ci.yml",
49
50
  ];
50
51
 
51
52
  /** Les catalogues de second niveau, par partie de vue. */
package/src/init.mjs CHANGED
@@ -23,6 +23,7 @@
23
23
  * comment nommer ses fichiers d'implémentation, au lieu de porter un `.tsx`
24
24
  * faux dès le jour de son installation.
25
25
  */
26
+ import { execFileSync } from "node:child_process";
26
27
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
27
28
  import { dirname, join } from "node:path";
28
29
 
@@ -30,6 +31,7 @@ import {
30
31
  CONFIGURATION_PAR_DEFAUT,
31
32
  MOTIF_IMPLEMENTATION_PAR_DEFAUT,
32
33
  NOM_CONFIGURATION,
34
+ estCheminDuRepository,
33
35
  } from "@ucm-kit/core/format";
34
36
  import { lireConfiguration } from "@ucm-kit/core/lecteurs";
35
37
 
@@ -50,18 +52,14 @@ const OPTIONS_DE_DOSSIER = { "--components": "components", "--tokens": "tokens"
50
52
  const NOM_FICHIER_TOKENS = CONFIGURATION_PAR_DEFAUT.tokens.split("/").pop();
51
53
 
52
54
  /**
53
- * Un chemin acceptable dans la configuration : relatif, en `/`, sans segment
54
- * qui remonte. La garde est ici et pas dans la grammaire du kit : celle-ci
55
- * décrit ce qu'un `ucm.config.json` déjà écrit a le droit de contenir, et la
56
- * durcir changerait le format. Ce qu'une commande accepte de taper au clavier
57
- * est une autre question, et c'est celle-là qui se pose ici.
55
+ * Le chemin tapé, écrit comme la grammaire du kit l'accepte, ou `null`.
56
+ *
57
+ * Le clavier tolère `\` et des barres obliques de bord ; le fichier écrit n'en
58
+ * garde aucune, et la grammaire décide du reste.
58
59
  */
59
60
  function cheminAcceptable(valeur) {
60
61
  const normalise = valeur.trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
61
- if (!normalise) return null;
62
- const segments = normalise.split("/");
63
- if (segments.some((segment) => !segment || segment === "." || segment === "..")) return null;
64
- return segments.join("/");
62
+ return estCheminDuRepository(normalise) ? normalise : null;
65
63
  }
66
64
 
67
65
  /**
@@ -81,6 +79,7 @@ function cheminAcceptable(valeur) {
81
79
  export function lireArgumentsInit(arguments_) {
82
80
  const chemins = {};
83
81
  let sansAgents = false;
82
+ let forge;
84
83
 
85
84
  for (let i = 0; i < arguments_.length; i += 1) {
86
85
  const argument = arguments_[i];
@@ -88,6 +87,15 @@ export function lireArgumentsInit(arguments_) {
88
87
  sansAgents = true;
89
88
  continue;
90
89
  }
90
+ if (argument === "--forge") {
91
+ const valeur = arguments_[i + 1];
92
+ if (!FORGES.includes(valeur)) {
93
+ return { erreur: `--forge attend github ou gitlab${valeur === undefined ? "." : ` : ${valeur} n'en est pas une.`}` };
94
+ }
95
+ forge = valeur;
96
+ i += 1;
97
+ continue;
98
+ }
91
99
  const cle = OPTIONS_DE_DOSSIER[argument];
92
100
  if (!cle && argument !== "--implementation") {
93
101
  return { erreur: `Argument inconnu : ${argument}` };
@@ -123,7 +131,45 @@ export function lireArgumentsInit(arguments_) {
123
131
  chemins[cle] = cle === "tokens" ? `${resolu}/${NOM_FICHIER_TOKENS}` : resolu;
124
132
  }
125
133
 
126
- return { chemins, sansAgents };
134
+ return { chemins, sansAgents, forge };
135
+ }
136
+
137
+ const FORGES = ["github", "gitlab"];
138
+
139
+ /** Le fichier qu'`init` écrit pour GitLab, et que `.gitlab-ci.yml` inclut. */
140
+ export const CHEMIN_CI_GITLAB = ".gitlab/ucm.gitlab-ci.yml";
141
+
142
+ /** L'URL du remote `origin`, ou `null` sans git ni remote. */
143
+ function remoteOrigin(racine) {
144
+ try {
145
+ return execFileSync("git", ["remote", "get-url", "origin"], { cwd: racine, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+
151
+ /** L'hôte d'une URL de remote, en HTTPS, SSH ou forme `git@hôte:chemin`. */
152
+ function hoteDuRemote(url) {
153
+ return /^(?:[a-z][a-z+]*:\/\/)?(?:[^@/]+@)?([^/:]+)/i.exec(url)?.[1]?.toLowerCase() ?? null;
154
+ }
155
+
156
+ /**
157
+ * La forge dont `init` écrit la CI, et le signal qui l'a désignée.
158
+ *
159
+ * Ordre : l'option, l'hôte du remote `origin`, la présence de `.gitlab-ci.yml`,
160
+ * puis GitHub. Le compte rendu nomme le signal : une forge devinée en silence
161
+ * écrirait une CI que la forge réelle ne lance jamais, et rien ne le dirait.
162
+ * Un hôte qui commence par `gitlab.` désigne une instance GitLab
163
+ * auto-hébergée, que le fichier écrit sait joindre par `CI_API_V4_URL`.
164
+ */
165
+ export function forgeDuRepository(racine, { forge, git = remoteOrigin } = {}) {
166
+ if (forge) return { nom: forge, signal: "l'option --forge" };
167
+ const url = git(racine);
168
+ const hote = url ? hoteDuRemote(url) : null;
169
+ if (hote === "github.com") return { nom: "github", signal: `l'hôte du remote origin, ${hote}` };
170
+ if (hote === "gitlab.com" || hote?.startsWith("gitlab.")) return { nom: "gitlab", signal: `l'hôte du remote origin, ${hote}` };
171
+ if (existsSync(join(racine, ".gitlab-ci.yml"))) return { nom: "gitlab", signal: "la présence de .gitlab-ci.yml" };
172
+ return { nom: "github", signal: "aucun signal, GitHub par défaut" };
127
173
  }
128
174
 
129
175
  /** La version de `@ucm-kit/cli`, lue dans son propre `package.json`. */
@@ -149,7 +195,7 @@ function versionDuPaquet() {
149
195
  * présents, le rappel se tait : trois lignes réclamées pour rien sont trois
150
196
  * lignes qu'on apprend à sauter.
151
197
  */
152
- function fichiers(version, chemins, { agents = true, gabarits = [] } = {}) {
198
+ function fichiers(version, chemins, { agents = true, gabarits = [], forge = "github" } = {}) {
153
199
  return [
154
200
  {
155
201
  chemin: NOM_CONFIGURATION,
@@ -209,10 +255,17 @@ function fichiers(version, chemins, { agents = true, gabarits = [] } = {}) {
209
255
  marqueurs: ["ci-report.md"],
210
256
  rappel: "ajoutez-y `ci-report.md`. `ucm check --report` le réécrit à chaque exécution ; commité, il montrerait le verdict d'un contrôle passé, pas celui du code en cours.",
211
257
  },
212
- {
213
- chemin: ".github/workflows/ucm.yml",
214
- contenu: workflow(version),
215
- },
258
+ ...(forge === "gitlab"
259
+ ? [
260
+ { chemin: CHEMIN_CI_GITLAB, contenu: workflowGitlab(version) },
261
+ {
262
+ chemin: ".gitlab-ci.yml",
263
+ contenu: `include:\n - local: ${CHEMIN_CI_GITLAB}\n`,
264
+ marqueurs: [CHEMIN_CI_GITLAB],
265
+ rappel: `ajoutez \`- local: ${CHEMIN_CI_GITLAB}\` à sa liste \`include:\`. Sans cette ligne, le job ucm ne tourne jamais et aucune merge request n'est contrôlée.`,
266
+ },
267
+ ]
268
+ : [{ chemin: ".github/workflows/ucm.yml", contenu: workflow(version) }]),
216
269
  ...(agents
217
270
  ? [
218
271
  { chemin: ".agents/skills/ucm-implementer/SKILL.md", contenu: relais(version) },
@@ -351,6 +404,14 @@ function lignesRestantes(racine, version, configuration) {
351
404
  * « le rapport manque ». Le premier décrit sa chaîne de construction, qu'un
352
405
  * repo Swift n'a pas. Le second est universel : une pull request refusée sans
353
406
  * un mot laisse le designer sans recours.
407
+ *
408
+ * **Le job qui exécute le code du repository n'écrit nulle part.** `npm ci`
409
+ * lance les scripts d'installation des dépendances, et un paquet compromis
410
+ * lirait le jeton du job, même hors de l'environnement. Le commentaire part
411
+ * donc d'un second job, sans checkout ni npm, qui reçoit le rapport en
412
+ * artefact. L'auteur d'une branche du repository peut réécrire ce fichier :
413
+ * la séparation ne borne que ce qu'une dépendance obtient. Une fourche reçoit
414
+ * de GitHub un jeton en lecture seule, et son commentaire échoue.
354
415
  */
355
416
  function workflow(version) {
356
417
  const commande = `npx --yes @ucm-kit/cli@${version} check --report ci-report.md`;
@@ -361,6 +422,10 @@ function workflow(version) {
361
422
  "# designer qui valide un export : il n'ouvre pas les logs de la CI. Toute",
362
423
  "# étape qui refuse une fusion doit donc lui laisser un message.",
363
424
  "#",
425
+ "# Le job `contrats` exécute le code du repository et ses dépendances : il",
426
+ "# ne porte aucun droit d'écriture. Seul `commentaire`, qui n'exécute rien",
427
+ "# du repository, écrit sur la pull request.",
428
+ "#",
364
429
  "# Écrit par `ucm init`. Adaptez-le : il ne sera jamais réécrit par-dessus.",
365
430
  "name: ucm",
366
431
  "",
@@ -369,17 +434,15 @@ function workflow(version) {
369
434
  " branches: [main]",
370
435
  " pull_request:",
371
436
  "",
372
- "# Nécessaire pour publier le diagnostic en commentaire de pull request.",
373
437
  "permissions:",
374
438
  " contents: read",
375
- " pull-requests: write",
376
439
  "",
377
440
  "jobs:",
378
441
  " contrats:",
379
442
  " runs-on: ubuntu-latest",
380
443
  " steps:",
381
444
  " # Le job exécute le code de la pull request : il n'a aucune raison de",
382
- " # garder un jeton git utilisable. Le commentaire passe par GITHUB_TOKEN.",
445
+ " # garder un jeton git utilisable.",
383
446
  " - uses: actions/checkout@v4",
384
447
  " with:",
385
448
  " persist-credentials: false",
@@ -428,21 +491,167 @@ function workflow(version) {
428
491
  " **Action attendue :** un développeur doit ouvrir [l'exécution de la CI]($RUN_URL) pour en connaître la raison.",
429
492
  " EOF",
430
493
  "",
431
- " # `always()` car l'essentiel est justement de commenter les échecs.",
494
+ " # Le rapport passe au job `commentaire`. Une dépendance a pu le",
495
+ " # réécrire : il part en corps de commentaire, jamais en commande.",
496
+ " - name: Transmettre le rapport",
497
+ " if: always() && github.event_name == 'pull_request'",
498
+ " uses: actions/upload-artifact@v4",
499
+ " with:",
500
+ " name: ucm-rapport",
501
+ " path: ci-report.md",
502
+ " retention-days: 1",
503
+ "",
504
+ " commentaire:",
505
+ " needs: contrats",
506
+ " # `!cancelled()` et non `always()` : un run annulé ne commente pas.",
507
+ " if: ${{ !cancelled() && github.event_name == 'pull_request' }}",
508
+ " runs-on: ubuntu-latest",
509
+ " permissions:",
510
+ " pull-requests: write",
511
+ " steps:",
512
+ " - uses: actions/download-artifact@v4",
513
+ " with:",
514
+ " name: ucm-rapport",
515
+ "",
432
516
  " - name: Publier le diagnostic sur la pull request",
433
- " if: always() && github.event_name == 'pull_request' && hashFiles('ci-report.md') != ''",
434
517
  " env:",
435
518
  " GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}",
436
519
  " NUMERO: ${{ github.event.number }}",
437
520
  " # --edit-last met à jour le commentaire précédent au lieu d'en empiler",
438
521
  " # un nouveau à chaque push ; s'il n'en existe pas encore, on en crée un.",
439
522
  " run: |",
440
- ' gh pr comment "$NUMERO" --body-file ci-report.md --edit-last \\',
441
- ' || gh pr comment "$NUMERO" --body-file ci-report.md',
523
+ ' gh pr comment "$NUMERO" -R "$GITHUB_REPOSITORY" --body-file ci-report.md --edit-last \\',
524
+ ' || gh pr comment "$NUMERO" -R "$GITHUB_REPOSITORY" --body-file ci-report.md',
442
525
  "",
443
526
  ].join("\n");
444
527
  }
445
528
 
529
+ /**
530
+ * Le contrôle pour GitLab, dans un fichier que `.gitlab-ci.yml` inclut.
531
+ *
532
+ * **Deux jobs, aucune clé globale.** Ni `workflow`, ni `image`, ni `variables`,
533
+ * ni `stages` : un fichier inclus qui en déclarerait changerait les pipelines
534
+ * de tous les jobs du projet. Chaque job porte ses propres règles.
535
+ *
536
+ * **Le job qui installe les dépendances ne publie pas la note.** Une variable
537
+ * CI/CD non protégée entre dans l'environnement de tous les jobs, et un script
538
+ * d'installation la lirait. `ucm` la retire avant `npm ci`, ce qui ne vaut que
539
+ * pour les exécuteurs qui posent les variables dans le script ; `ucm-rapport`
540
+ * publie sans clone, depuis un dossier vide, sans script d'installation. Qui
541
+ * pousse une branche peut réécrire ce fichier et lire la variable : seul le
542
+ * rôle du compte qui porte le jeton borne ce qu'il en tire.
543
+ *
544
+ * **La note ne refuse jamais une fusion.** `ucm-rapport` tourne après un échec
545
+ * de `ucm`, et `allow_failure` garde le pipeline de la couleur du contrôle
546
+ * quand GitLab refuse le jeton : le rapport reste dans les artefacts.
547
+ */
548
+ function workflowGitlab(version) {
549
+ const cli = `npx --yes @ucm-kit/cli@${version}`;
550
+ return [
551
+ "# Contrôle des contrats UCM, inclus par .gitlab-ci.yml.",
552
+ "#",
553
+ "# Le rapport publié en note de la merge request est le seul message que",
554
+ "# reçoit le designer qui valide un export : il n'ouvre pas les journaux de",
555
+ "# la CI. Toute étape qui refuse une fusion doit donc lui laisser un message.",
556
+ "#",
557
+ "# Ce fichier ne déclare que deux jobs et aucune clé globale : les autres jobs",
558
+ "# du projet gardent leurs règles. Les deux jobs prennent le stage `test`.",
559
+ "#",
560
+ "# Un job rouge ne bloque la fusion que si « Pipelines must succeed » est",
561
+ "# coché dans Settings > Merge requests. La note demande la variable",
562
+ "# UCM_GITLAB_TOKEN, masquée et non protégée. Tout pipeline d'une branche du",
563
+ "# projet la lit : son jeton, de scope api, appartient à un compte de rôle",
564
+ "# Reporter sur ce seul projet.",
565
+ "#",
566
+ "# Écrit par `ucm init`. Adaptez-le : il ne sera jamais réécrit par-dessus.",
567
+ "ucm:",
568
+ " image: node:22",
569
+ " variables:",
570
+ " # Le diff avec la base délimite les états informatifs du rapport.",
571
+ ' GIT_DEPTH: "0"',
572
+ " rules:",
573
+ ' - if: $CI_PIPELINE_SOURCE == "merge_request_event"',
574
+ " - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH",
575
+ " script:",
576
+ " # Les scripts d'installation ne reçoivent pas le jeton de la note.",
577
+ " - unset UCM_GITLAB_TOKEN",
578
+ " # Un adaptateur appartient à la stack du repository. Sans lockfile, le",
579
+ " # noyau portable reste seul.",
580
+ " - if [ -f package-lock.json ]; then npm ci; fi",
581
+ " - |",
582
+ ' if [ -n "$CI_MERGE_REQUEST_DIFF_BASE_SHA" ]; then',
583
+ ` ${cli} check --report ci-report.md --base "$CI_MERGE_REQUEST_DIFF_BASE_SHA"`,
584
+ " else",
585
+ ` ${cli} check --report ci-report.md`,
586
+ " fi",
587
+ " artifacts:",
588
+ " when: always",
589
+ " paths:",
590
+ " - ci-report.md",
591
+ "",
592
+ "ucm-rapport:",
593
+ " image: node:22",
594
+ " needs:",
595
+ " - job: ucm",
596
+ " artifacts: true",
597
+ " rules:",
598
+ ' - if: $CI_PIPELINE_SOURCE == "merge_request_event"',
599
+ " when: always",
600
+ " # Un jeton refusé ne rend pas rouge un pipeline dont les contrats sont verts.",
601
+ " allow_failure: true",
602
+ " variables:",
603
+ " # Aucun clone : ni .npmrc ni node_modules du repository.",
604
+ " GIT_STRATEGY: none",
605
+ ' NPM_CONFIG_IGNORE_SCRIPTS: "true"',
606
+ " script:",
607
+ " # Filet : sans rapport, `ucm` s'est arrêté avant le contrôle (clone,",
608
+ " # installation, plantage).",
609
+ " - |",
610
+ " if [ ! -f ci-report.md ]; then",
611
+ " printf '%s\\n\\n%s\\n\\n%s\\n' \\",
612
+ " \"## ❌ La vérification n'a pas pu rendre son diagnostic\" \\",
613
+ " \"Les contrôles se sont arrêtés avant d'avoir pu analyser cet export : le rapport habituel n'a pas été produit. **Votre design n'est pas en cause** et réexporter depuis Figma n'y changerait rien.\" \\",
614
+ " \"**Action attendue :** un développeur doit ouvrir [le pipeline de la CI]($CI_PIPELINE_URL) pour en connaître la raison.\" \\",
615
+ " > ci-report.md",
616
+ " fi",
617
+ " # Depuis un dossier vide, npx ne lit ni configuration ni paquet laissés",
618
+ " # par un job précédent sur le runner.",
619
+ " - cd \"$(mktemp -d)\"",
620
+ ` - ${cli} rapport-gitlab --projet "$CI_PROJECT_ID" --merge-request "$CI_MERGE_REQUEST_IID" --fichier "$CI_PROJECT_DIR/ci-report.md" --api "$CI_API_V4_URL"`,
621
+ "",
622
+ ].join("\n");
623
+ }
624
+
625
+ /**
626
+ * Les lignes qu'`init` ne peut pas écrire pour GitLab : des réglages du projet,
627
+ * et un `stages:` qui refuserait le job.
628
+ */
629
+ function lignesGitlab(racine) {
630
+ const lignes = [
631
+ {
632
+ fichier: "Settings > CI/CD > Variables",
633
+ ligne: "créez `UCM_GITLAB_TOKEN`, masquée et non protégée, avec un jeton de scope api d'un compte de service membre de ce seul projet, au rôle Reporter, ou un jeton d'accès de projet au rôle Reporter si l'offre le permet. Sans elle, le rapport n'est pas publié sur la merge request. Non protégée, parce que les branches d'export ne le sont pas ; tout pipeline d'une branche la lit, et le rôle Reporter borne ce qu'on en tire à lire et commenter.",
634
+ },
635
+ {
636
+ fichier: "Settings > Merge requests",
637
+ ligne: "cochez « Pipelines must succeed ». Sans cette case, un rapport rouge annonce une fusion bloquée qui ne l'est pas.",
638
+ },
639
+ ];
640
+ try {
641
+ const ci = readFileSync(join(racine, ".gitlab-ci.yml"), "utf8");
642
+ const stages = /^stages:([^\n]*(?:\n[ \t]+[^\n]*|\n-[^\n]*)*)/m.exec(ci);
643
+ if (stages && !/\btest\b/.test(stages[1])) {
644
+ lignes.push({
645
+ fichier: ".gitlab-ci.yml",
646
+ ligne: "ajoutez `test` à `stages:`. Le job ucm s'y range, et GitLab refuse un pipeline dont un job vise un stage absent.",
647
+ });
648
+ }
649
+ } catch {
650
+ // Sans .gitlab-ci.yml, celui qu'`init` écrit ne déclare aucun stage.
651
+ }
652
+ return lignes;
653
+ }
654
+
446
655
  /**
447
656
  * Écrit ce qui manque, et rend le compte rendu de ce qui a été fait.
448
657
  *
@@ -456,13 +665,18 @@ export function init(racine, {
456
665
  sansAgents = false,
457
666
  adaptateur = null,
458
667
  erreurAdaptateur = null,
668
+ forge: forgeDemandee,
669
+ git,
459
670
  } = {}) {
460
671
  const version = versionDuPaquet();
461
672
  const aEcrire = [];
462
673
  const deja = [];
463
674
  const { gabarits, erreur: erreurGabarits } = sansAgents ? { gabarits: [], erreur: null } : gabaritsDe(adaptateur);
675
+ // Lue avant toute écriture : le `.gitlab-ci.yml` qu'`init` écrirait ne doit
676
+ // pas devenir le signal qui désigne GitLab.
677
+ const forge = forgeDuRepository(racine, { forge: forgeDemandee, git });
464
678
 
465
- for (const fichier of fichiers(version, chemins, { agents: !sansAgents, gabarits })) {
679
+ for (const fichier of fichiers(version, chemins, { agents: !sansAgents, gabarits, forge: forge.nom })) {
466
680
  const cible = join(racine, fichier.chemin);
467
681
  if (existsSync(cible)) deja.push({ ...fichier, cible });
468
682
  else aEcrire.push({ ...fichier, cible });
@@ -500,19 +714,23 @@ export function init(racine, {
500
714
  ? { ...CONFIGURATION_PAR_DEFAUT, ...chemins }
501
715
  : null,
502
716
  version,
717
+ forge,
503
718
  agents: !sansAgents,
504
719
  // `absent` quand aucun adaptateur n'est installé, le message quand il n'a pas pu servir.
505
720
  adaptateur: erreurAdaptateur
506
721
  ? { erreur: erreurAdaptateur?.message ?? String(erreurAdaptateur) }
507
722
  : erreurGabarits ? { erreur: erreurGabarits } : adaptateur ? "trouve" : "absent",
508
723
  nodeJs: existsSync(join(racine, "package.json")),
509
- lignes: lignesRestantes(
510
- racine,
511
- version,
512
- aEcrire.some((f) => f.chemin === NOM_CONFIGURATION)
513
- ? { ...CONFIGURATION_PAR_DEFAUT, ...chemins }
514
- : lireConfiguration(racine).configuration,
515
- ),
724
+ lignes: [
725
+ ...lignesRestantes(
726
+ racine,
727
+ version,
728
+ aEcrire.some((f) => f.chemin === NOM_CONFIGURATION)
729
+ ? { ...CONFIGURATION_PAR_DEFAUT, ...chemins }
730
+ : lireConfiguration(racine).configuration,
731
+ ),
732
+ ...(forge.nom === "gitlab" ? lignesGitlab(racine) : []),
733
+ ],
516
734
  };
517
735
  }
518
736
 
@@ -549,6 +767,7 @@ export function rendreInit({
549
767
  optionsIgnorees = false,
550
768
  chemins = null,
551
769
  version,
770
+ forge = null,
552
771
  agents = false,
553
772
  adaptateur = "absent",
554
773
  nodeJs = false,
@@ -572,6 +791,10 @@ export function rendreInit({
572
791
  ? "Rien à faire : ce repository est déjà installé."
573
792
  : "Aucun fichier à écrire : ce repository est déjà installé.",
574
793
  );
794
+ if (forge) {
795
+ lignes.push(`CI écrite pour ${forge.nom === "gitlab" ? "GitLab" : "GitHub"}, d'après ${forge.signal}. `
796
+ + "L'option `--forge github` ou `--forge gitlab` en choisit une autre.");
797
+ }
575
798
 
576
799
  if (optionsIgnorees) {
577
800
  lignes.push("");
@@ -0,0 +1,152 @@
1
+ /**
2
+ * `ucm rapport-gitlab` : publie le rapport de `ucm check` en note d'une merge
3
+ * request GitLab, et remplace au push suivant la note qu'il a déjà écrite.
4
+ *
5
+ * La commande existe parce que l'image `node:22` d'un job GitLab n'a ni `glab`
6
+ * ni `jq`, et qu'un script recopié dans le YAML du repository ne se teste pas.
7
+ *
8
+ * **Le jeton se lit dans `UCM_GITLAB_TOKEN`, jamais dans un argument**, et
9
+ * n'apparaît dans aucune sortie : le journal d'un job se lit par tout membre
10
+ * du projet. Sans jeton, la commande le dit et sort en 0, parce que le rapport
11
+ * reste dans les artefacts du job et que le contrôle, lui, a déjà rendu son
12
+ * verdict.
13
+ *
14
+ * **Seule la note de ce compte portant le marqueur est remplacée.** Une note
15
+ * d'un autre compte qui recopie le marqueur reste intacte : la remplacer
16
+ * écraserait le texte d'un humain.
17
+ */
18
+ import { readFileSync } from "node:fs";
19
+ import { resolve } from "node:path";
20
+
21
+ export const MARQUEUR_RAPPORT = "<!-- ucm-rapport -->";
22
+
23
+ const API_PAR_DEFAUT = "https://gitlab.com/api/v4";
24
+
25
+ const USAGE = "ucm rapport-gitlab --projet <id> --merge-request <iid> --fichier <chemin> [--api <url>]";
26
+
27
+ const OPTIONS = { "--projet": "projet", "--merge-request": "mergeRequest", "--fichier": "fichier", "--api": "api" };
28
+
29
+ /** Lit les arguments ; rend `erreur` pour une invocation fautive. */
30
+ export function lireArgumentsRapport(arguments_) {
31
+ const valeurs = { api: API_PAR_DEFAUT };
32
+ for (let i = 0; i < arguments_.length; i += 1) {
33
+ const cle = OPTIONS[arguments_[i]];
34
+ if (!cle) return { erreur: `Argument inconnu : ${arguments_[i]}` };
35
+ const valeur = arguments_[i + 1];
36
+ if (valeur === undefined || valeur.startsWith("--") || valeur === "") {
37
+ return { erreur: `${arguments_[i]} attend une valeur.` };
38
+ }
39
+ valeurs[cle] = valeur;
40
+ i += 1;
41
+ }
42
+ for (const [option, cle] of Object.entries(OPTIONS)) {
43
+ if (valeurs[cle] === undefined) return { erreur: `${option} est obligatoire.` };
44
+ }
45
+ if (!/^https:\/\//.test(valeurs.api)) return { erreur: `--api attend une adresse https : ${valeurs.api} n'en est pas une.` };
46
+ return { valeurs: { ...valeurs, api: valeurs.api.replace(/\/+$/, "") } };
47
+ }
48
+
49
+ /** Une réponse d'API refusée, avec son statut. */
50
+ class RefusGitlab extends Error {
51
+ constructor(statut, geste) {
52
+ super(geste);
53
+ this.statut = statut;
54
+ }
55
+ }
56
+
57
+ /** Le geste qu'un statut demande, écrit pour la personne qui lit le journal du job. */
58
+ function gesteDuStatut(statut, action) {
59
+ if (statut === 401) {
60
+ return `GitLab refuse le jeton de UCM_GITLAB_TOKEN (401) en voulant ${action}. `
61
+ + "Un mainteneur du projet doit créer un nouveau jeton de scope api, puis remplacer la valeur de cette variable.";
62
+ }
63
+ if (statut === 403) {
64
+ return `Le jeton de UCM_GITLAB_TOKEN n'a pas le droit de ${action} (403). `
65
+ + "Un mainteneur du projet doit lui donner le scope api et le rôle Reporter sur ce projet.";
66
+ }
67
+ if (statut === 404) {
68
+ return `GitLab ne trouve pas la merge request en voulant ${action} (404). `
69
+ + "Vérifiez --projet et --merge-request, et que le jeton a accès à ce projet.";
70
+ }
71
+ return `GitLab a répondu ${statut} en voulant ${action}. Relancez le job ; si la réponse ne change pas, un développeur doit la regarder.`;
72
+ }
73
+
74
+ /**
75
+ * Publie ou remplace la note du rapport.
76
+ *
77
+ * Codes : 0 note écrite ou jeton absent, 1 refus de GitLab ou rapport
78
+ * illisible, 2 invocation fautive.
79
+ */
80
+ export async function rapportGitlab(arguments_, {
81
+ racine = process.cwd(),
82
+ env = process.env,
83
+ fetch: requete = globalThis.fetch,
84
+ ecrire = console.log,
85
+ alerter = console.error,
86
+ } = {}) {
87
+ const { valeurs, erreur } = lireArgumentsRapport(arguments_);
88
+ if (erreur) {
89
+ alerter(`${erreur}\n\n${USAGE}`);
90
+ return 2;
91
+ }
92
+
93
+ const jeton = env.UCM_GITLAB_TOKEN?.trim();
94
+ if (!jeton) {
95
+ ecrire("UCM_GITLAB_TOKEN est absente : le rapport n'est pas publié sur la merge request. "
96
+ + "Il reste dans les artefacts du job. Pour le publier, un mainteneur du projet doit créer "
97
+ + "cette variable, masquée et non protégée, avec un jeton de scope api d'un compte au rôle Reporter sur ce projet.");
98
+ return 0;
99
+ }
100
+
101
+ let rapport;
102
+ try {
103
+ rapport = readFileSync(resolve(racine, valeurs.fichier), "utf8");
104
+ } catch (erreurLecture) {
105
+ alerter(`Le rapport ${valeurs.fichier} ne se lit pas (${erreurLecture?.code ?? erreurLecture?.message}) : aucune note n'est publiée.`);
106
+ return 1;
107
+ }
108
+ const corps = `${MARQUEUR_RAPPORT}\n${rapport}`;
109
+ const projet = encodeURIComponent(valeurs.projet);
110
+ const notes = `${valeurs.api}/projects/${projet}/merge_requests/${encodeURIComponent(valeurs.mergeRequest)}/notes`;
111
+
112
+ async function appeler(url, action, init = {}) {
113
+ let reponse;
114
+ try {
115
+ reponse = await requete(url, {
116
+ ...init,
117
+ headers: { "PRIVATE-TOKEN": jeton, "Content-Type": "application/json" },
118
+ });
119
+ } catch (panne) {
120
+ throw new RefusGitlab(null, `La requête vers GitLab n'a pas abouti en voulant ${action} (${panne?.message ?? panne}). Relancez le job.`);
121
+ }
122
+ if (!reponse.ok) throw new RefusGitlab(reponse.status, gesteDuStatut(reponse.status, action));
123
+ return reponse;
124
+ }
125
+
126
+ try {
127
+ const compte = await (await appeler(`${valeurs.api}/user`, "lire le compte du jeton")).json();
128
+
129
+ let existante = null;
130
+ let page = "1";
131
+ while (page && !existante) {
132
+ const reponse = await appeler(`${notes}?per_page=100&sort=asc&page=${page}`, "lire les notes de la merge request");
133
+ const lues = await reponse.json();
134
+ existante = lues.find((note) => !note.system && note.author?.id === compte.id
135
+ && typeof note.body === "string" && note.body.includes(MARQUEUR_RAPPORT)) ?? null;
136
+ page = reponse.headers.get("x-next-page");
137
+ }
138
+
139
+ if (existante) {
140
+ await appeler(`${notes}/${existante.id}`, "remplacer la note du rapport", { method: "PUT", body: JSON.stringify({ body: corps }) });
141
+ ecrire(`Rapport remplacé dans la note ${existante.id} de la merge request !${valeurs.mergeRequest}.`);
142
+ } else {
143
+ await appeler(notes, "écrire la note du rapport", { method: "POST", body: JSON.stringify({ body: corps }) });
144
+ ecrire(`Rapport publié en note de la merge request !${valeurs.mergeRequest}.`);
145
+ }
146
+ return 0;
147
+ } catch (refus) {
148
+ if (!(refus instanceof RefusGitlab)) throw refus;
149
+ alerter(refus.message);
150
+ return 1;
151
+ }
152
+ }
package/src/ucm.mjs CHANGED
@@ -16,6 +16,7 @@ import { check } from "./check.mjs";
16
16
  import { guide } from "./guide.mjs";
17
17
  import { iconesDuRepository, rendreIcones } from "./icons.mjs";
18
18
  import { init, lireArgumentsInit, rendreInit } from "./init.mjs";
19
+ import { rapportGitlab } from "./rapport-gitlab.mjs";
19
20
  import { tokensCss } from "./tokens-css.mjs";
20
21
 
21
22
  /** Le verdict de tests qu'un orchestrateur de stack peut transmettre au CLI. */
@@ -44,15 +45,19 @@ const AIDE = `ucm — la ligne de commande UCM
44
45
  ucm tokens css écrit la feuille CSS des tokens et de leurs modes
45
46
  ucm aides liste les aides à l'implémentation et leur origine
46
47
  ucm guide imprime ce qu'un agent lit avant d'implémenter un contrat
48
+ ucm rapport-gitlab publie le rapport en note d'une merge request GitLab
47
49
  ucm --help affiche cette aide
48
50
 
49
- ucm init [--components <dossier>] [--tokens <dossier>] [--implementation <motif>] [--sans-agents]
51
+ ucm init [--components <dossier>] [--tokens <dossier>] [--implementation <motif>] [--sans-agents] [--forge github|gitlab]
50
52
  --components dossier sous lequel les contrats sont rangés
51
53
  --tokens dossier qui reçoit tokens.json
52
54
  --implementation où vit l'implémentation d'un contrat, {dir} et {id}
53
55
  pour son dossier et son identifiant
54
56
  --sans-agents n'écrit ni les relais d'agent, ni .ucm/conventions.md,
55
57
  ni les gabarits
58
+ --forge la forge dont la CI est écrite ; sans elle, l'hôte du
59
+ remote origin, puis la présence de .gitlab-ci.yml
60
+ décident, et GitHub sinon
56
61
  Les trois n'agissent qu'à la première installation : ucm init n'écrase
57
62
  jamais un ucm.config.json existant.
58
63
 
@@ -75,6 +80,14 @@ const AIDE = `ucm — la ligne de commande UCM
75
80
  <contrat> le fichier .contract.json à implémenter
76
81
  --out écrit le guide dans ce fichier plutôt que dans le terminal
77
82
 
83
+ ucm rapport-gitlab --projet <id> --merge-request <iid> --fichier <chemin> [--api <url>]
84
+ --projet l'identifiant ou le chemin du projet GitLab
85
+ --merge-request le numéro de la merge request dans ce projet
86
+ --fichier le rapport écrit par ucm check --report
87
+ --api l'API GitLab, https://gitlab.com/api/v4 par défaut
88
+ Le jeton se lit dans UCM_GITLAB_TOKEN. Sans lui, la commande le dit et
89
+ sort en 0.
90
+
78
91
  Codes de sortie : 0 tout est passé, 1 des contrôles ont échoué, 2 l'invocation
79
92
  ou la configuration est fautive.`;
80
93
 
@@ -108,10 +121,10 @@ function executerCommande(arguments_, {
108
121
  }
109
122
 
110
123
  if (commande === "init") {
111
- const { chemins, sansAgents, erreur } = lireArgumentsInit(arguments_.slice(1));
124
+ const { chemins, sansAgents, forge, erreur } = lireArgumentsInit(arguments_.slice(1));
112
125
  if (erreur) {
113
126
  const alerter = sorties.alerter ?? console.error;
114
- alerter(`${erreur}\n\nucm init [--components <dossier>] [--tokens <dossier>] [--implementation <motif>] [--sans-agents]`);
127
+ alerter(`${erreur}\n\nucm init [--components <dossier>] [--tokens <dossier>] [--implementation <motif>] [--sans-agents] [--forge github|gitlab]`);
115
128
  return 2;
116
129
  }
117
130
  // Un adaptateur qui ne se charge pas prive le repository de ses gabarits,
@@ -119,7 +132,7 @@ function executerCommande(arguments_, {
119
132
  return chargerAdaptateur(racine)
120
133
  .then((adaptateur) => ({ adaptateur }), (erreurAdaptateur) => ({ erreurAdaptateur }))
121
134
  .then((chargement) => {
122
- ecrire(rendreInit(init(racine, { chemins, sansAgents, ...chargement })));
135
+ ecrire(rendreInit(init(racine, { chemins, sansAgents, forge, git: sorties.git, ...chargement })));
123
136
  return 0;
124
137
  });
125
138
  }
@@ -168,6 +181,16 @@ function executerCommande(arguments_, {
168
181
  return guide(arguments_.slice(1), { racine, ecrire, alerter: sorties.alerter ?? console.error });
169
182
  }
170
183
 
184
+ if (commande === "rapport-gitlab") {
185
+ return rapportGitlab(arguments_.slice(1), {
186
+ racine,
187
+ env,
188
+ fetch: sorties.fetch,
189
+ ecrire,
190
+ alerter: sorties.alerter ?? console.error,
191
+ });
192
+ }
193
+
171
194
  if (commande === "icons") {
172
195
  const { configuration, erreur } = lireConfiguration(racine);
173
196
  if (erreur) {