@roomi-fields/grillhouse 0.27.0 → 0.28.0

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.
@@ -30,6 +30,7 @@
30
30
  // languages. No migration yet.
31
31
  // - Its share of the update (./mise-a-jour.mjs, `miseAJour`): the template of a project of cargo
32
32
  // (`templates/cargo/`) and its test scripts.
33
+ // - The skeleton of a new crate (./squelette.mjs, `squelette`), which `grillhouse paquet` writes.
33
34
  import { readFileSync } from 'node:fs';
34
35
  import path from 'node:path';
35
36
  import { fileURLToPath } from 'node:url';
@@ -46,6 +47,7 @@ import {
46
47
  import { elementsDuLot } from './elements-du-lot.mjs';
47
48
  import { enRetard, entreesDeLIndex, SORTIE } from './index-interfaces.mjs';
48
49
  import { miseAJour } from './mise-a-jour.mjs';
50
+ import { squelette } from './squelette.mjs';
49
51
  import { CACHE } from './sccache.mjs';
50
52
  import { touches } from './touches.mjs';
51
53
  import { verdict } from './verdict.mjs';
@@ -120,4 +122,5 @@ export default {
120
122
  gardes: () => GARDES.map(({ script, args }) => [script, ...args]),
121
123
  migrations: [],
122
124
  miseAJour,
125
+ squelette,
123
126
  };
@@ -0,0 +1,111 @@
1
+ // The skeleton of a new crate of the module cargo, the demand `squelette` of the join
2
+ // (scripts/jointure.d.ts), which `grillhouse paquet` writes (scripts/paquet.mjs), as `cargo new
3
+ // --lib` writes one and adds it to the members of the workspace: no behaviour, no test.
4
+ //
5
+ // - Its files: its Cargo.toml (its name, the folder's; each field of `[workspace.package]` the
6
+ // workspace holds inherited, `<champ>.workspace = true`, as `cargo new` inherits them in a
7
+ // workspace, else its version 0.1.0 and its edition 2021; `[lints] workspace = true` when the
8
+ // workspace has `[workspace.lints]`); `src/lib.rs`, a library without code; `tests/.gitkeep`, its
9
+ // folder of tests by the interface. Cargo needs no configuration of its own for the tests
10
+ // (nextest, the frame's profile) nor for the typing (`cargo check`, clippy).
11
+ // - The workspace: the root Cargo.toml receives the crate's path in `members` of `[workspace]`,
12
+ // written in its text, the rest of the file as it was; a root without `members` receives the
13
+ // key, a root package without `[workspace]` the table, and a project without a root Cargo.toml a
14
+ // virtual workspace. A member or a pattern that covers the path leaves it as it is.
15
+ // - The lock of the versions: `cargo update --workspace`, at the root, which brings Cargo.lock in
16
+ // line with the members alone.
17
+ // - The manifest is read with smol-toml, the tool of this module (`outils`), loaded at the call.
18
+ import { existsSync, readFileSync } from 'node:fs';
19
+ import { createRequire } from 'node:module';
20
+ import path from 'node:path';
21
+
22
+ const require = createRequire(import.meta.url);
23
+
24
+ // The fields of a package cargo inherits from `[workspace.package]`, in the order `cargo new`
25
+ // writes them.
26
+ const HERITES = [
27
+ 'version',
28
+ 'edition',
29
+ 'rust-version',
30
+ 'authors',
31
+ 'description',
32
+ 'documentation',
33
+ 'readme',
34
+ 'homepage',
35
+ 'repository',
36
+ 'license',
37
+ 'license-file',
38
+ 'keywords',
39
+ 'categories',
40
+ 'publish',
41
+ ];
42
+
43
+ // The text <texte> of a root Cargo.toml with <chemin> added to `members` of `[workspace]`.
44
+ function ajouterLeMembre(texte, chemin) {
45
+ const entree = JSON.stringify(chemin);
46
+ const lignes = texte.split('\n');
47
+ const debut = lignes.findIndex(l => /^\s*\[workspace\]\s*(#.*)?$/.test(l));
48
+ if (debut < 0) {
49
+ const fin = texte.endsWith('\n') ? '' : '\n';
50
+ return `${texte}${fin}\n[workspace]\nmembers = [${entree}]\n`;
51
+ }
52
+ let fin = lignes.findIndex((l, i) => i > debut && /^\s*\[/.test(l));
53
+ if (fin < 0) {
54
+ fin = lignes.length;
55
+ }
56
+ const section = lignes.slice(debut + 1, fin).join('\n');
57
+ const m = /^(\s*members\s*=\s*\[)([\s\S]*?)(\])/m.exec(section);
58
+ let nouvelle;
59
+ if (!m) {
60
+ nouvelle = `members = [${entree}]\n${section}`;
61
+ } else if (m[2].includes('\n')) {
62
+ const corps = m[2].replace(/\s*$/, '');
63
+ const virgule = corps.trim() === '' || corps.trim().endsWith(',') ? '' : ',';
64
+ nouvelle = section.replace(m[0], `${m[1]}${corps}${virgule}\n ${entree},\n${m[3]}`);
65
+ } else {
66
+ const corps = m[2].trim().replace(/,$/, '');
67
+ nouvelle = section.replace(m[0], `${m[1]}${corps ? `${corps}, ` : ''}${entree}${m[3]}`);
68
+ }
69
+ return [...lignes.slice(0, debut + 1), nouvelle, ...lignes.slice(fin)].join('\n');
70
+ }
71
+
72
+ /** @type {import('../../jointure.js').Langage['squelette']} */
73
+ export function squelette(racine, { chemin }) {
74
+ const nom = path.posix.basename(chemin);
75
+ const f = path.join(racine, 'Cargo.toml');
76
+ const texte = existsSync(f) ? readFileSync(f, 'utf8') : null;
77
+ const espace = texte === null ? null : (require('smol-toml').parse(texte).workspace ?? null);
78
+ const herites = HERITES.filter(c => espace?.package?.[c] !== undefined);
79
+ const paquet = [
80
+ '[package]',
81
+ `name = ${JSON.stringify(nom)}`,
82
+ ...(herites.includes('version') ? [] : ['version = "0.1.0"']),
83
+ ...(herites.includes('edition') ? [] : ['edition = "2021"']),
84
+ ...herites.map(c => `${c}.workspace = true`),
85
+ ...(espace?.lints ? ['', '[lints]', 'workspace = true'] : []),
86
+ '',
87
+ '[dependencies]',
88
+ '',
89
+ ].join('\n');
90
+ const fichiers = {
91
+ [`${chemin}/Cargo.toml`]: paquet,
92
+ [`${chemin}/src/lib.rs`]: `//! The crate ${nom}: its interface, docs/INTERFACE.md, says what it offers.\n`,
93
+ [`${chemin}/tests/.gitkeep`]: '',
94
+ };
95
+ const membres = Array.isArray(espace?.members) ? espace.members : [];
96
+ const couvert = membres.some(m => typeof m === 'string' && path.matchesGlob(chemin, m));
97
+ let entree = null;
98
+ if (texte === null) {
99
+ entree = {
100
+ fichier: 'Cargo.toml',
101
+ texte: `[workspace]\nmembers = [${JSON.stringify(chemin)}]\nresolver = "2"\n`,
102
+ };
103
+ } else if (!couvert) {
104
+ entree = { fichier: 'Cargo.toml', texte: ajouterLeMembre(texte, chemin) };
105
+ }
106
+ return {
107
+ fichiers,
108
+ espace: entree,
109
+ verrouiller: { commande: 'cargo', args: ['update', '--workspace'], dossier: '.' },
110
+ };
111
+ }
@@ -27,6 +27,7 @@
27
27
  // No migration yet.
28
28
  // - Its share of the update (./mise-a-jour.mjs): the template `templates/python/`, its test
29
29
  // scripts, the generator of the index and the installation of uv.
30
+ // - The skeleton of a new package (./squelette.mjs, `squelette`), which `grillhouse paquet` writes.
30
31
  import { readFileSync } from 'node:fs';
31
32
  import path from 'node:path';
32
33
  import { fileURLToPath } from 'node:url';
@@ -43,6 +44,7 @@ import {
43
44
  import { enRetard, SORTIE } from './index-interfaces.mjs';
44
45
  import { elementsDuLot, touches } from './lot.mjs';
45
46
  import { miseAJour } from './mise-a-jour.mjs';
47
+ import { squelette } from './squelette.mjs';
46
48
  import { verdict } from './verdict.mjs';
47
49
 
48
50
  const ici = nom => path.join(path.dirname(fileURLToPath(import.meta.url)), nom);
@@ -91,4 +93,5 @@ export default {
91
93
  gardes: () => GARDES.map(({ script, args }) => [script, ...args]),
92
94
  migrations: [],
93
95
  miseAJour,
96
+ squelette,
94
97
  };
@@ -0,0 +1,66 @@
1
+ // The skeleton of a new package of the module python, the demand `squelette` of the join
2
+ // (scripts/jointure.d.ts), which `grillhouse paquet` writes (scripts/paquet.mjs), as `uv init`
3
+ // writes one: no behaviour, no test.
4
+ //
5
+ // - Its files: its pyproject.toml (PEP 621: its name, the folder's, its version 0.1.0, the Python
6
+ // it requires, no dependency; its group `test` of `[dependency-groups]`, PEP 735, pytest, which
7
+ // the module runs by `uv run --group test pytest`; the configuration of pytest,
8
+ // `[tool.pytest.ini_options]`, its tests under `tests/` and its code importable from `src/`, as
9
+ // uv's layout of a library has it); `src/<module>/__init__.py`, the module named after the
10
+ // package (`-` read `_`), without code; `tests/.gitkeep`, its folder of tests. The typing is
11
+ // `python -m compileall`, which needs no configuration. No build system: uv neither builds nor
12
+ // installs the package to run its tests.
13
+ // - The workspace: a root pyproject.toml whose `[tool.uv.workspace]` names its `members` receives
14
+ // the package's path there, as `uv init` adds a project under a workspace to its members; without
15
+ // one, the package is its own project of uv, as the module plays each package (./commandes.mjs).
16
+ // - The lock of the versions: `uv lock`, at the workspace's root, else in the package.
17
+ import { existsSync, readFileSync } from 'node:fs';
18
+ import { createRequire } from 'node:module';
19
+ import path from 'node:path';
20
+
21
+ const require = createRequire(import.meta.url);
22
+
23
+ /** @type {import('../../jointure.js').Langage['squelette']} */
24
+ export function squelette(racine, { chemin }) {
25
+ const nom = path.posix.basename(chemin);
26
+ const module = nom.replace(/-/g, '_');
27
+ const manifeste = [
28
+ '[project]',
29
+ `name = ${JSON.stringify(nom)}`,
30
+ 'version = "0.1.0"',
31
+ 'requires-python = ">=3.12"',
32
+ 'dependencies = []',
33
+ '',
34
+ '[dependency-groups]',
35
+ 'test = ["pytest>=8"]',
36
+ '',
37
+ '[tool.pytest.ini_options]',
38
+ 'testpaths = ["tests"]',
39
+ 'pythonpath = ["src"]',
40
+ '',
41
+ ].join('\n');
42
+ const fichiers = {
43
+ [`${chemin}/pyproject.toml`]: manifeste,
44
+ [`${chemin}/src/${module}/__init__.py`]: `"""The package ${nom}: its interface, docs/INTERFACE.md, says what it offers."""\n`,
45
+ [`${chemin}/tests/.gitkeep`]: '',
46
+ };
47
+ const f = path.join(racine, 'pyproject.toml');
48
+ const texte = existsSync(f) ? readFileSync(f, 'utf8') : null;
49
+ const espace =
50
+ texte === null ? null : (require('smol-toml').parse(texte).tool?.uv?.workspace ?? null);
51
+ const membres = Array.isArray(espace?.members) ? espace.members : null;
52
+ let entree = null;
53
+ if (membres && !membres.some(m => typeof m === 'string' && path.matchesGlob(chemin, m))) {
54
+ const m = /^(\s*members\s*=\s*\[)([\s\S]*?)(\])/m.exec(
55
+ texte.slice(texte.search(/^\s*\[tool\.uv\.workspace\]/m))
56
+ );
57
+ const corps = m[2].replace(/\s*$/, '').replace(/,$/, '');
58
+ const ajout = `${m[1]}${corps.trim() ? `${corps}, ` : ''}${JSON.stringify(chemin)}${m[3]}`;
59
+ entree = { fichier: 'pyproject.toml', texte: texte.replace(m[0], ajout) };
60
+ }
61
+ return {
62
+ fichiers,
63
+ espace: entree,
64
+ verrouiller: { commande: 'uv', args: ['lock'], dossier: membres ? '.' : chemin },
65
+ };
66
+ }
@@ -9,7 +9,9 @@
9
9
  // other option replaces the frame's at its first level, as the `extends` of dependency-cruiser does.
10
10
  //
11
11
  // npx grillhouse frontieres refuses a stale configuration, then runs dependency-cruiser
12
- // npx grillhouse frontieres --ecrire writes the configuration
12
+ // npx grillhouse frontieres --ecrire writes the configuration, and `.dependency-cruiser.projet.cjs`
13
+ // empty when the project has none, so that knip resolves
14
+ // the require of the configuration (grillhouse-b32)
13
15
  //
14
16
  // The rules: no cycle; a package reaches another by its name, never by a path into its tree; a
15
17
  // module of `src/` reaches another by its entry (`index`); the code of `src/` imports no test; the
@@ -46,6 +48,13 @@ import { CODE, horsCadre } from '../../paquets.mjs';
46
48
  import { trancher } from '../../dette.mjs';
47
49
 
48
50
  export const CONFIGURATION = '.dependency-cruiser.cjs';
51
+ // The project's own rules and options, which the configuration requires, and their text when
52
+ // `--ecrire` writes them for a project that has none.
53
+ const REGLES_DU_PROJET = '.dependency-cruiser.projet.cjs';
54
+ const REGLES_VIDES = `// The project's own rules and options of dependency-cruiser, which the generated
55
+ // ${CONFIGURATION} reads (\`npx grillhouse frontieres\`); written empty once, the project's own after.
56
+ module.exports = {};
57
+ `;
49
58
  export const RACINES = ['src', 'packages'];
50
59
  /** The test files, as a pattern of a path from the repository's root. */
51
60
  export const TESTS = '(^|/)(test|tests|__tests__)/|[.](test|spec)[.][a-z]+$';
@@ -391,6 +400,10 @@ function frontieres(racine, args) {
391
400
  const cible = path.join(racine, CONFIGURATION);
392
401
  if (args.includes('--ecrire')) {
393
402
  writeFileSync(cible, attendu);
403
+ const propres = path.join(racine, REGLES_DU_PROJET);
404
+ if (!existsSync(propres)) {
405
+ writeFileSync(propres, REGLES_VIDES);
406
+ }
394
407
  return 0;
395
408
  }
396
409
  const present = existsSync(cible) ? readFileSync(cible, 'utf8') : '';
@@ -45,6 +45,7 @@
45
45
  // - No binary of the machine (`binaires`); what its tools write in a project, `.turbo`
46
46
  // (`ignorer`); its share of the update (./mise-a-jour.mjs, `miseAJour`): the tests by Vitest,
47
47
  // the frame's package declared, the typing, the turbo.json, and the generators.
48
+ // - The skeleton of a new package (./squelette.mjs, `squelette`), which `grillhouse paquet` writes.
48
49
  import { spawnSync } from 'node:child_process';
49
50
  import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
50
51
  import { createRequire } from 'node:module';
@@ -59,6 +60,7 @@ import { estUnTest, manifestes } from './regle-des-tests.mjs';
59
60
  import { SCRIPT_DES_TESTS } from './script-des-tests.mjs';
60
61
  import { verdict } from './verdict.mjs';
61
62
  import { miseAJour } from './mise-a-jour.mjs';
63
+ import { squelette } from './squelette.mjs';
62
64
  import * as configVitest from './migrations/0.23.0-config-vitest.mjs';
63
65
  import * as nomsDeclaresInutilises from './migrations/0.24.4-noms-declares-inutilises.mjs';
64
66
  import * as lignesMalFormees from './migrations/0.24.6-lignes-mal-formees.mjs';
@@ -330,4 +332,5 @@ export default {
330
332
  cheminsDesTests,
331
333
  ],
332
334
  miseAJour: miseAJour(joueDesTests),
335
+ squelette,
333
336
  };
@@ -0,0 +1,120 @@
1
+ // The skeleton of a new package of the module typescript, the demand `squelette` of the join
2
+ // (scripts/jointure.d.ts), which `grillhouse paquet` writes (scripts/paquet.mjs), as `nx g
3
+ // @nx/js:lib` and `turbo gen workspace` write one: no behaviour, no test.
4
+ //
5
+ // - A package of TypeScript lives under `packages/<nom>`, where the module finds its components
6
+ // (./composants.mjs); another path is refused, named.
7
+ // - Its files: its package.json (its name, the root's scope before the folder's name when the root's
8
+ // name has one, as Nx names a library after the workspace's scope; private; an ES module; its
9
+ // script `test:unit`, which makes it a package that plays tests, and the tools of its tests and
10
+ // of its typing the root does not declare, TypeScript, Vitest and Node's types, at the versions of
11
+ // the module's template); its tsconfig.json, which types its sources, its tests and its
12
+ // configuration, nothing emitted; its vitest.config.ts, the frame's base configuration by its
13
+ // name, which passes while the package has no test yet, as the configuration of a library that
14
+ // Nx generates (`passWithNoTests`); `src/index.ts`, an empty module; `tests/.gitkeep`, its folder
15
+ // of tests. The update gives it its script `typecheck` and the frame's package in its
16
+ // devDependencies (./mise-a-jour.mjs).
17
+ // - The workspace: the root package.json receives the package's path in its `workspaces` (created
18
+ // when the root has none), unless a pattern there covers it already.
19
+ // - The lock of the versions: `npm install`, at the root.
20
+ import { existsSync, readFileSync } from 'node:fs';
21
+ import path from 'node:path';
22
+
23
+ const CHAMPS = ['dependencies', 'devDependencies', 'optionalDependencies'];
24
+ // The tools of a package's tests and of its typing, at the versions of the module's template.
25
+ const OUTILS_DU_PAQUET = ['@types/node', 'typescript', 'vitest'];
26
+
27
+ const lireJson = f => (existsSync(f) ? JSON.parse(readFileSync(f, 'utf8')) : null);
28
+ const json = v => `${JSON.stringify(v, null, 2)}\n`;
29
+
30
+ const TSCONFIG = {
31
+ compilerOptions: {
32
+ target: 'ES2022',
33
+ lib: ['ES2022'],
34
+ module: 'Node16',
35
+ moduleResolution: 'Node16',
36
+ resolveJsonModule: true,
37
+ noEmit: true,
38
+ esModuleInterop: true,
39
+ forceConsistentCasingInFileNames: true,
40
+ isolatedModules: true,
41
+ strict: true,
42
+ noUnusedLocals: true,
43
+ noUnusedParameters: true,
44
+ noImplicitReturns: true,
45
+ noFallthroughCasesInSwitch: true,
46
+ noUncheckedIndexedAccess: true,
47
+ skipLibCheck: true,
48
+ },
49
+ include: ['src/**/*', 'tests/**/*', '*.ts'],
50
+ exclude: ['node_modules', 'dist'],
51
+ };
52
+
53
+ const VITEST = `import { defineConfig, mergeConfig } from 'vitest/config';
54
+ import base from '@roomi-fields/grillhouse/vitest-config';
55
+
56
+ // The tests of the package: the frame's base configuration, by its name, extended with what is the
57
+ // package's own. It passes while the package has no test yet, as the configuration of a library
58
+ // that Nx generates; its first test plays as any other.
59
+ export default mergeConfig(
60
+ base,
61
+ defineConfig({
62
+ test: {
63
+ include: ['src/**/*.{test,spec}.{ts,js,mjs}', 'tests/**/*.{test,spec}.{ts,js,mjs}'],
64
+ passWithNoTests: true,
65
+ },
66
+ })
67
+ );
68
+ `;
69
+
70
+ /** @type {import('../../jointure.js').Langage['squelette']} */
71
+ export function squelette(racine, { chemin, modele }) {
72
+ if (!/^packages\/[^/]+$/.test(chemin)) {
73
+ throw new Error(
74
+ `${chemin} : un paquet typescript vit sous packages/<nom>, où le module trouve ses composants.`
75
+ );
76
+ }
77
+ const racinePkg = lireJson(path.join(racine, 'package.json')) ?? {};
78
+ const nom = path.posix.basename(chemin);
79
+ const portee = /^(@[^/]+)\//.exec(String(racinePkg.name ?? ''))?.[1];
80
+ const declare = n => CHAMPS.some(c => racinePkg[c]?.[n] !== undefined);
81
+ const versions = modele.devDependencies ?? {};
82
+ const devDependencies = Object.fromEntries(
83
+ OUTILS_DU_PAQUET.filter(n => !declare(n) && typeof versions[n] === 'string').map(n => [
84
+ n,
85
+ versions[n],
86
+ ])
87
+ );
88
+ const pkg = {
89
+ name: portee ? `${portee}/${nom}` : nom,
90
+ version: '0.0.0',
91
+ private: true,
92
+ type: 'module',
93
+ scripts: { 'test:unit': 'vitest run' },
94
+ ...(Object.keys(devDependencies).length ? { devDependencies } : {}),
95
+ };
96
+ const fichiers = {
97
+ [`${chemin}/package.json`]: json(pkg),
98
+ [`${chemin}/tsconfig.json`]: json(TSCONFIG),
99
+ [`${chemin}/vitest.config.ts`]: VITEST,
100
+ [`${chemin}/src/index.ts`]: `// The entry of the package ${nom}: its interface, docs/INTERFACE.md, says what it exports.\nexport {};\n`,
101
+ [`${chemin}/tests/.gitkeep`]: '',
102
+ };
103
+ const espaces = Array.isArray(racinePkg.workspaces)
104
+ ? racinePkg.workspaces
105
+ : (racinePkg.workspaces?.packages ?? null);
106
+ const couvert = (espaces ?? []).some(
107
+ m => typeof m === 'string' && !m.startsWith('!') && path.matchesGlob(chemin, m)
108
+ );
109
+ let espace = null;
110
+ if (!couvert) {
111
+ const p = { ...racinePkg };
112
+ if (Array.isArray(p.workspaces) || p.workspaces === undefined) {
113
+ p.workspaces = [...(p.workspaces ?? []), chemin];
114
+ } else {
115
+ p.workspaces = { ...p.workspaces, packages: [...(p.workspaces.packages ?? []), chemin] };
116
+ }
117
+ espace = { fichier: 'package.json', texte: json(p) };
118
+ }
119
+ return { fichiers, espace, verrouiller: { commande: 'npm', args: ['install'], dossier: '.' } };
120
+ }
@@ -50,7 +50,7 @@ function langageDeLInterface(dossier) {
50
50
  if (!existsSync(f)) {
51
51
  return null;
52
52
  }
53
- const m = readFileSync(f, 'utf8').match(/^\*\*Langage\*\*\s*:\s*(.+)$/m);
53
+ const m = readFileSync(f, 'utf8').match(/^\*\*Langu?age\*\*\s*:\s*(.+)$/m);
54
54
  return m ? langageDeLaCellule(m[1]) || null : null;
55
55
  }
56
56
 
@@ -0,0 +1,261 @@
1
+ #!/usr/bin/env node
2
+ // The creation of a package, out of the circuit: the third of the four times of a package's birth
3
+ // (the common charter, « La naissance d'un paquet »: the grill, the writing of its row and its
4
+ // documents, this command, then a ticket of code), as the generators of Nx (`nx g @nx/js:lib`,
5
+ // after `nx add` installs the tools of its plugin), `turbo gen workspace` and `cargo new --lib`
6
+ // added to the members of the workspace write one. A skeleton has neither behaviour nor test: it
7
+ // does not pass by the circuit, which works on a package that exists.
8
+ //
9
+ // npx grillhouse paquet <chemin> from the root of the project, <chemin> from it
10
+ //
11
+ // - The row first: a row of a table of the components of docs/ARCHITECTURE.md
12
+ // (./tableau-des-composants.mjs) names <chemin> when one name of its cell of the names is the
13
+ // path, or else the folder's name, as the guard of the languages reads a component; a row that
14
+ // names the path itself comes first. Refused, by its name, and nothing written: a path no row
15
+ // names; a row whose cell of the column « Langage » is empty; a language out of the frame's
16
+ // list; a folder that already holds the manifest of its language (`manifeste` of its module). A
17
+ // folder that holds docs/ alone, the documents of the second time, is accepted, as `cargo init`
18
+ // takes a folder without its Cargo.toml.
19
+ // - The skeleton: the module of the row's language gives the files of the package and the entry
20
+ // of the workspace (`squelette`, scripts/jointure.d.ts), the versions of its tools from its
21
+ // template (`miseAJour.gabarit`); the documents of the package, docs/CADRE.md and
22
+ // docs/INTERFACE.md, come from the frame's template of a package (`templates/paquet/`), its name
23
+ // and its language written in. Each file absent is written, a file present stays; the manifest
24
+ // of the workspace receives the entry. The command commits nothing: the second and the third
25
+ // times enter one commit, after a green verification.
26
+ // - The tools of the language, as `nx add` installs them before the first generator: the share
27
+ // of the update of each declared language (`mettreAJour` of ./grillhouse-maj.mjs: its tools at
28
+ // its template's versions, its scripts, its files, `turbo.json` for typescript), then `npm
29
+ // install` when the update asks it, the module's command that locks the versions of the new
30
+ // package (`verrouiller`), the binaries of the declared languages (`installerBinaires`), and the
31
+ // generators (`regenerer`), those of the package's language whatever files the project holds:
32
+ // the first package of a language receives its boundaries' configuration and its index.
33
+ // - The report: each file written, then the lines of the update; on the error stream, each
34
+ // command that fails, named with its output. The exit code: 0; 1 for a refusal (⛔ and its
35
+ // reason) or a command that fails; 2 for the usage.
36
+ import { spawnSync } from 'node:child_process';
37
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
38
+ import path from 'node:path';
39
+ import { pathToFileURL } from 'node:url';
40
+ import { CADRE } from './cadre.mjs';
41
+ import {
42
+ aInstaller,
43
+ installerBinaires,
44
+ mettreAJour,
45
+ rapport,
46
+ regenerer,
47
+ } from './grillhouse-maj.mjs';
48
+ import { LANGAGES, langage } from './langages.mjs';
49
+ import {
50
+ ARCHITECTURE,
51
+ colonneDesNoms,
52
+ COLONNE,
53
+ langageDeLaCellule,
54
+ nomme,
55
+ nomsDe,
56
+ tableauxDesComposants,
57
+ } from './tableau-des-composants.mjs';
58
+
59
+ /** The frame's template of the documents of a package, from the frame's files. */
60
+ export const GABARIT_DU_PAQUET = 'templates/paquet';
61
+ const DOCUMENTS = ['docs/CADRE.md', 'docs/INTERFACE.md'];
62
+
63
+ /** A refusal of the command, its message the reason. */
64
+ export class Refus extends Error {}
65
+
66
+ // <chemin> from the root of the project at <racine>, `/` its separator, without `./` nor a
67
+ // trailing `/`; refused out of the project or at its root.
68
+ function normaliser(racine, chemin) {
69
+ const rel = path.relative(racine, path.resolve(racine, chemin)).split(path.sep).join('/');
70
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
71
+ throw new Refus(`${chemin} : un paquet vit dans un dossier du projet, sous sa racine.`);
72
+ }
73
+ return rel;
74
+ }
75
+
76
+ /**
77
+ * The row of the tables of the components of the project at <racine> that names the package at
78
+ * <rel> (from the root): `{ ligne, langage }`, `ligne` its number in docs/ARCHITECTURE.md, `langage`
79
+ * its cell of the column « Langage » (empty for none); null when no row names it.
80
+ * @param {string} racine
81
+ * @param {string} rel
82
+ */
83
+ export function ligneDuPaquet(racine, rel) {
84
+ const virtuel = { dossier: path.join(racine, rel), nom: path.posix.basename(rel), paquet: null };
85
+ const trouvees = tableauxDesComposants(racine).flatMap(t => {
86
+ const colonne = colonneDesNoms(t.lignes, [virtuel], racine, t.colonne);
87
+ return colonne < 0
88
+ ? []
89
+ : t.lignes
90
+ .filter(l => nomme(nomsDe(l.cellules[colonne]), virtuel, racine))
91
+ .map(l => ({
92
+ exacte: nomsDe(l.cellules[colonne]).includes(rel),
93
+ ligne: l.index + 1,
94
+ langage: langageDeLaCellule(l.cellules[t.colonne]),
95
+ }));
96
+ });
97
+ const l = trouvees.find(x => x.exacte) ?? trouvees[0];
98
+ return l ? { ligne: l.ligne, langage: l.langage } : null;
99
+ }
100
+
101
+ const lireJson = f => (existsSync(f) ? JSON.parse(readFileSync(f, 'utf8')) : {});
102
+
103
+ /**
104
+ * The plan of the package at <chemin> of the project at <racine>, nothing written: `{ chemin,
105
+ * langage, fichiers, espace, verrouiller }`, `fichiers` the skeleton of its language and its
106
+ * documents (path from the root → text), `espace` the manifest of the workspace with its entry
107
+ * (null when it holds it), `verrouiller` the command that locks its versions. Throws a Refus, by
108
+ * its name, for a path no row names, a row without language, a language out of the frame's list,
109
+ * or a folder that holds the manifest of its language.
110
+ * @param {string} racine the root of the project
111
+ * @param {string} chemin the package's folder, from the root
112
+ * @param {{ source?: string }} [o] the frame's files (CADRE)
113
+ */
114
+ export function planDuPaquet(racine, chemin, { source = CADRE } = {}) {
115
+ const rel = normaliser(racine, chemin);
116
+ const l = ligneDuPaquet(racine, rel);
117
+ if (!l) {
118
+ throw new Refus(
119
+ `${rel} : aucune ligne d'un tableau des composants de ${ARCHITECTURE} ne le nomme ; le grill tranche le paquet, puis sa ligne s'y écrit avec son langage (colonne « ${COLONNE} »), avant la commande.`
120
+ );
121
+ }
122
+ const ou = `${ARCHITECTURE}:${l.ligne}`;
123
+ if (!l.langage) {
124
+ throw new Refus(
125
+ `${rel} : sa ligne (${ou}) ne nomme pas son langage ; la colonne « ${COLONNE} » le déclare (les langages du cadre : ${Object.keys(LANGAGES).join(', ')}).`
126
+ );
127
+ }
128
+ if (!Object.hasOwn(LANGAGES, l.langage)) {
129
+ throw new Refus(
130
+ `${rel} : langage inconnu du cadre, ${l.langage} (${ou}) ; les langages du cadre : ${Object.keys(LANGAGES).join(', ')}.`
131
+ );
132
+ }
133
+ const m = langage(l.langage);
134
+ if (existsSync(path.join(racine, rel, m.manifeste))) {
135
+ throw new Refus(
136
+ `${rel} : le dossier porte déjà son ${m.manifeste} ; le paquet existe, un ticket de code le travaille par le circuit.`
137
+ );
138
+ }
139
+ const modele = lireJson(path.join(source, m.miseAJour.gabarit, 'package.json'));
140
+ let s;
141
+ try {
142
+ s = m.squelette(racine, { chemin: rel, modele });
143
+ } catch (e) {
144
+ throw new Refus(e.message);
145
+ }
146
+ const nom = path.posix.basename(rel);
147
+ const documents = Object.fromEntries(
148
+ DOCUMENTS.map(d => [
149
+ `${rel}/${d}`,
150
+ readFileSync(path.join(source, GABARIT_DU_PAQUET, d), 'utf8')
151
+ .replaceAll('<nom>', nom)
152
+ .replaceAll('<langage>', l.langage),
153
+ ])
154
+ );
155
+ return {
156
+ chemin: rel,
157
+ langage: m,
158
+ fichiers: { ...s.fichiers, ...documents },
159
+ espace: s.espace,
160
+ verrouiller: s.verrouiller,
161
+ };
162
+ }
163
+
164
+ /**
165
+ * Writes the plan <plan> (`planDuPaquet`) in the project at <racine>: each file absent, then the
166
+ * manifest of the workspace. Returns the files written, from the root.
167
+ * @param {string} racine
168
+ * @param {ReturnType<typeof planDuPaquet>} plan
169
+ */
170
+ export function ecrireLePaquet(racine, plan) {
171
+ const ecrits = [];
172
+ for (const [f, texte] of Object.entries(plan.fichiers)) {
173
+ const abs = path.join(racine, f);
174
+ if (existsSync(abs)) {
175
+ continue;
176
+ }
177
+ mkdirSync(path.dirname(abs), { recursive: true });
178
+ writeFileSync(abs, texte);
179
+ ecrits.push(f);
180
+ }
181
+ if (plan.espace) {
182
+ writeFileSync(path.join(racine, plan.espace.fichier), plan.espace.texte);
183
+ ecrits.push(plan.espace.fichier);
184
+ }
185
+ return ecrits;
186
+ }
187
+
188
+ // Runs <commande> <args> in <dossier>, its output this process's error stream; its code.
189
+ const lancer = (commande, args, dossier) =>
190
+ spawnSync(commande, args, { cwd: dossier, stdio: ['ignore', 2, 2] }).status ?? 1;
191
+
192
+ /**
193
+ * Creates the package at <chemin> of the project at <racine>: its plan written, then the tools of
194
+ * its language (see the header). Returns `{ ecrits, lignes, echecs }`: the files written, the
195
+ * lines of the report, the lines of each command that fails. Throws a Refus as `planDuPaquet`.
196
+ * @param {string} racine
197
+ * @param {string} chemin
198
+ * @param {{ source?: string, executer?: (commande: string, args: string[], dossier: string) => number }} [o]
199
+ */
200
+ export function creerPaquet(racine, chemin, { source = CADRE, executer = lancer } = {}) {
201
+ const plan = planDuPaquet(racine, chemin, { source });
202
+ const ecrits = ecrireLePaquet(racine, plan);
203
+ const b = mettreAJour(racine, source);
204
+ const echecs = [];
205
+ const vus = new Set();
206
+ const jouer = (commande, args, dossier) => {
207
+ const cle = JSON.stringify([commande, ...args, dossier]);
208
+ if (vus.has(cle)) {
209
+ return;
210
+ }
211
+ vus.add(cle);
212
+ const code = executer(commande, args, path.join(racine, dossier));
213
+ if (code !== 0) {
214
+ echecs.push(
215
+ `\`${[commande, ...args].join(' ')}\` (${dossier}) échoue, code ${code} ; lance-le, puis \`npx grillhouse maj\`.`
216
+ );
217
+ }
218
+ };
219
+ if (aInstaller(b)) {
220
+ jouer('npm', ['install'], '.');
221
+ }
222
+ const v = plan.verrouiller;
223
+ jouer(v.commande, v.args, v.dossier);
224
+ const binaires = installerBinaires(racine);
225
+ echecs.push(...binaires.lignes, ...regenerer(racine, { langage: plan.langage.nom }));
226
+ const lignes = rapport(b)
227
+ .split('\n')
228
+ .filter(Boolean)
229
+ .concat(
230
+ binaires.installes.length ? [`Binaires installés : ${binaires.installes.join(', ')}.`] : []
231
+ );
232
+ return { ecrits, lignes, echecs };
233
+ }
234
+
235
+ const USAGE =
236
+ 'Usage : npx grillhouse paquet <chemin> crée le paquet que sa ligne de docs/ARCHITECTURE.md déclare\n';
237
+
238
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
239
+ const args = process.argv.slice(2);
240
+ if (args.length !== 1 || args[0].startsWith('-')) {
241
+ process.stderr.write(USAGE);
242
+ process.exitCode = 2;
243
+ } else {
244
+ try {
245
+ const { ecrits, lignes, echecs } = creerPaquet(process.cwd(), args[0]);
246
+ process.stdout.write(
247
+ `Paquet ${args[0]} : ${ecrits.join(', ') || 'aucun fichier'} écrits ; rien n'est commité.\n${lignes.map(l => `${l}\n`).join('')}`
248
+ );
249
+ for (const l of echecs) {
250
+ process.stderr.write(`${l}\n`);
251
+ }
252
+ process.exitCode = echecs.length ? 1 : 0;
253
+ } catch (e) {
254
+ if (!(e instanceof Refus)) {
255
+ throw e;
256
+ }
257
+ process.stderr.write(`⛔ ${e.message}\n`);
258
+ process.exitCode = 1;
259
+ }
260
+ }
261
+ }