@simplix-boot/cli 0.0.0-stage → 1.3.1

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.
Files changed (55) hide show
  1. package/LICENSE +25 -0
  2. package/LICENSE_KO +28 -0
  3. package/README.ko.md +82 -0
  4. package/README.md +81 -2
  5. package/bin/simplix-boot.js +6 -0
  6. package/package.json +45 -4
  7. package/src/cli.js +103 -0
  8. package/src/commands/config.js +129 -0
  9. package/src/commands/generate.js +291 -0
  10. package/src/commands/generated.js +125 -0
  11. package/src/commands/init.js +41 -0
  12. package/src/commands/promote.js +172 -0
  13. package/src/commands/templates.js +100 -0
  14. package/src/commands/version.js +134 -0
  15. package/src/lib/analysis/fields.js +217 -0
  16. package/src/lib/analysis/imports.js +76 -0
  17. package/src/lib/analysis/structure.js +193 -0
  18. package/src/lib/analysis/types.js +94 -0
  19. package/src/lib/args.js +69 -0
  20. package/src/lib/comment-extractor.js +141 -0
  21. package/src/lib/config/fields.js +321 -0
  22. package/src/lib/config/parents.js +108 -0
  23. package/src/lib/config/paths.js +156 -0
  24. package/src/lib/config/yml.js +61 -0
  25. package/src/lib/console.js +83 -0
  26. package/src/lib/controller-name.js +33 -0
  27. package/src/lib/entity-analyzer.js +49 -0
  28. package/src/lib/entity-type-resolver.js +80 -0
  29. package/src/lib/entity-type.js +35 -0
  30. package/src/lib/errors.js +17 -0
  31. package/src/lib/export-config.js +74 -0
  32. package/src/lib/file-utils.js +77 -0
  33. package/src/lib/generate/file-plan.js +155 -0
  34. package/src/lib/generate/search-fields.js +111 -0
  35. package/src/lib/generate/settings.js +111 -0
  36. package/src/lib/generate/support-classes.js +47 -0
  37. package/src/lib/generate/template-vars.js +183 -0
  38. package/src/lib/git-utils.js +18 -0
  39. package/src/lib/name-field.js +42 -0
  40. package/src/lib/project.js +121 -0
  41. package/src/lib/promote-files.js +132 -0
  42. package/src/lib/rendered-output.js +13 -0
  43. package/src/lib/search-operators.js +87 -0
  44. package/src/lib/templates.js +50 -0
  45. package/src/lib/tracked-render.js +200 -0
  46. package/src/lib/version-check.js +195 -0
  47. package/src/lib/version-utils.js +97 -0
  48. package/templates/controller/rest/EntityRestController.java.template +517 -0
  49. package/templates/controller/web/EntityWebController.java.template +211 -0
  50. package/templates/dto/EntityDTOs.java.template +981 -0
  51. package/templates/repository/EntityRepository.java.template +78 -0
  52. package/templates/service/EntityService.java.template +790 -0
  53. package/templates/service/EntityTreeService.java.template +352 -0
  54. package/templates/test/EntityServiceTest.java.template +937 -0
  55. package/templates/test/EntityTreeServiceTest.java.template +842 -0
@@ -0,0 +1,132 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { resolveControllerName } from './controller-name.js';
4
+ import { CliError } from './errors.js';
5
+
6
+ function resolvePath(template, modulePath) {
7
+ if (!template) throw new Error('Path template is undefined');
8
+ if (!modulePath) throw new Error('Module path is undefined');
9
+ return template.replace('{modulePath}', modulePath.replace(/\//g, path.sep));
10
+ }
11
+
12
+ function generatedBase(config) {
13
+ return config.target.generatedBasePath || config.target.basePath;
14
+ }
15
+
16
+ function generatedTestBase(config) {
17
+ return (
18
+ config.target.testGeneratedBasePath ||
19
+ config.target.testBasePath ||
20
+ generatedBase(config).replace('/main/', '/test/')
21
+ );
22
+ }
23
+
24
+ /**
25
+ * Every file promote moves for one entity: where the generator renders it and where it lands in
26
+ * the module. The tree service and its test are listed only when the render produced them.
27
+ *
28
+ * @param {object} target
29
+ * @param {string} target.root the project root
30
+ * @param {object} target.config the parsed `.simplix/generator-simplix.json`
31
+ * @param {string} target.entityName the entity class name
32
+ * @param {object} target.entityConfig the parsed entity yml, which carries `modulePath`
33
+ * @param {string} target.moduleName the target module under the module root (`admin/jobs`)
34
+ * @returns {{ name: string, src: string, dest: string }[]}
35
+ */
36
+ export function promoteFiles({ root, config, entityName, entityConfig, moduleName }) {
37
+ const modulePath = entityConfig?.modulePath;
38
+ if (!modulePath) throw new CliError(`modulePath not found in ${entityName}.yml`);
39
+ if (!config.target?.targetPath) throw new CliError('target.targetPath not found in generator-simplix.json');
40
+ const moduleRoot = config.promote?.moduleRoot || 'modules';
41
+ const packagePath = config.target.basePackage.replace(/\./g, '/');
42
+ const main = (target, fileName) => ({
43
+ src: path.join(root, generatedBase(config), resolvePath(target, modulePath), fileName),
44
+ dest: path.join(
45
+ root,
46
+ moduleRoot,
47
+ moduleName,
48
+ 'src/main/java',
49
+ packagePath,
50
+ resolvePath(target, modulePath),
51
+ fileName
52
+ ),
53
+ });
54
+ const test = (target, fileName) => ({
55
+ src: path.join(root, generatedTestBase(config), resolvePath(target, modulePath), fileName),
56
+ dest: path.join(
57
+ root,
58
+ moduleRoot,
59
+ moduleName,
60
+ 'src/test/java',
61
+ packagePath,
62
+ resolvePath(target, modulePath),
63
+ fileName
64
+ ),
65
+ });
66
+ const { targetPath, testTargetPath } = config.target;
67
+ const files = [];
68
+ if (targetPath.service) files.push({ name: 'Service', ...main(targetPath.service, `${entityName}Service.java`) });
69
+ if (targetPath.controllerRest) {
70
+ const controller = `${resolveControllerName(entityName, entityConfig)}.java`;
71
+ files.push({ name: 'Controller', ...main(targetPath.controllerRest, controller) });
72
+ }
73
+
74
+ if (targetPath.dto) files.push({ name: 'DTOs', ...main(targetPath.dto, `${entityName}DTOs.java`) });
75
+ if (testTargetPath?.serviceTest) {
76
+ files.push({ name: 'Service Test', ...test(testTargetPath.serviceTest, `${entityName}ServiceTest.java`) });
77
+ }
78
+
79
+ if (targetPath.service) {
80
+ const tree = main(targetPath.service, `${entityName}TreeService.java`);
81
+ if (fs.existsSync(tree.src) || fs.existsSync(tree.dest)) {
82
+ files.push({ name: 'TreeService', ...tree });
83
+ if (testTargetPath?.serviceTest) {
84
+ const treeTest = test(testTargetPath.serviceTest, `${entityName}TreeServiceTest.java`);
85
+ if (fs.existsSync(treeTest.src) || fs.existsSync(treeTest.dest)) {
86
+ files.push({ name: 'TreeService Test', ...treeTest });
87
+ }
88
+ }
89
+ }
90
+ }
91
+
92
+ return files;
93
+ }
94
+
95
+ /**
96
+ * The modules under the module root: every directory holding a `src/` tree, named by its path
97
+ * below the root (`admin/jobs`).
98
+ */
99
+ export function listModules(root, config) {
100
+ const moduleRoot = path.join(root, config.promote?.moduleRoot || 'modules');
101
+ const found = [];
102
+ const walk = (dir, depth) => {
103
+ if (depth > 4 || !fs.existsSync(dir)) return;
104
+ if (fs.existsSync(path.join(dir, 'src'))) {
105
+ found.push(path.relative(moduleRoot, dir).split(path.sep).join('/'));
106
+ return;
107
+ }
108
+
109
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
110
+ if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'build') {
111
+ walk(path.join(dir, entry.name), depth + 1);
112
+ }
113
+ }
114
+ };
115
+
116
+ walk(moduleRoot, 0);
117
+ return found.sort();
118
+ }
119
+
120
+ /**
121
+ * The module an entity was promoted into: the one module holding any of its promoted files.
122
+ *
123
+ * @returns {string|undefined} the module name, or undefined when none holds a file
124
+ * @throws {Error} when more than one module holds its files
125
+ */
126
+ export function findPromotedModule(root, config, entityName, entityConfig) {
127
+ const hits = listModules(root, config).filter(moduleName =>
128
+ promoteFiles({ root, config, entityName, entityConfig, moduleName }).some(file => fs.existsSync(file.dest))
129
+ );
130
+ if (hits.length > 1) throw new CliError(`${entityName} has promoted files in more than one module: ${hits.join(', ')}`);
131
+ return hits[0];
132
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Tidies a rendered template before it is written.
3
+ *
4
+ * <p>A scriptlet line indented with the code around it renders as a line holding only that
5
+ * indentation, so every line loses its trailing spaces and tabs, and a run of blank lines
6
+ * collapses to one, so the generated file matches what a formatter would leave.
7
+ *
8
+ * @param {string} rendered the template output
9
+ * @returns {string} the output without trailing whitespace or repeated blank lines
10
+ */
11
+ export function tidyRenderedOutput(rendered) {
12
+ return rendered.replace(/[ \t]+$/gm, '').replace(/\n{3,}/g, '\n\n');
13
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Default search operators per Java type, shared by `config` (which writes them into a new yml)
3
+ * and `entity` (which falls back to them for an embedded id field the yml does not mention).
4
+ *
5
+ * A temporal field offers the inclusive pair plus `between`. The frontend's date range filter
6
+ * writes `<field>.greaterThanOrEqualTo` and `<field>.lessThanOrEqualTo`; a field declaring only
7
+ * the exclusive `greaterThan` / `lessThan` refuses that request as an invalid parameter, so every
8
+ * ranged read of the list fails. The exclusive pair stays available by writing it in the yml.
9
+ */
10
+
11
+ const TEMPORAL_TYPES = Object.freeze([
12
+ 'Instant',
13
+ 'LocalDate',
14
+ 'LocalTime',
15
+ 'LocalDateTime',
16
+ 'OffsetDateTime',
17
+ 'ZonedDateTime',
18
+ ]);
19
+
20
+ const NUMERIC_TYPES = Object.freeze(['Integer', 'Long', 'Double', 'BigDecimal']);
21
+
22
+ /**
23
+ * Types whose column cannot be a sort key. The paging query aggregates the sort column as
24
+ * `max(<column>)` and PostgreSQL has no `max(boolean)`, so a boolean `@SearchableField` declared
25
+ * `sortable = true` answers 500 the moment anybody sorts by it, and puts the sort arrow in the
26
+ * list header that triggers it.
27
+ */
28
+ const UNSORTABLE_TYPES = Object.freeze(['boolean', 'Boolean']);
29
+
30
+ /**
31
+ * @param {string} type a simple Java type name
32
+ * @returns {boolean} whether the type holds a point in time, a date, or a wall-clock time
33
+ */
34
+ export function isTemporalType(type) {
35
+ return TEMPORAL_TYPES.includes(type);
36
+ }
37
+
38
+ /**
39
+ * @param {string} type a simple Java type name, primitive spellings included
40
+ * @returns {boolean} whether a search field of that type may be generated with `sortable = true`
41
+ */
42
+ export function isSortableSearchType(type) {
43
+ return !UNSORTABLE_TYPES.includes(type);
44
+ }
45
+
46
+ /**
47
+ * @param {string} type a simple Java type name
48
+ * @returns {string[]} the yml searchOperators a field of that type starts with
49
+ */
50
+ export function defaultSearchOperators(type) {
51
+ if (type === 'String') {
52
+ return ['equals', 'contains'];
53
+ }
54
+
55
+ if (NUMERIC_TYPES.includes(type)) {
56
+ return ['equals', 'greaterThan', 'lessThan'];
57
+ }
58
+
59
+ if (isTemporalType(type)) {
60
+ return ['between', 'greaterThanOrEqual', 'lessThanOrEqual'];
61
+ }
62
+
63
+ return ['equals'];
64
+ }
65
+
66
+ const OPERATOR_CONSTANTS = Object.freeze({
67
+ greaterThanOrEqual: 'GREATER_THAN_OR_EQUAL_TO',
68
+ greaterThanOrEquals: 'GREATER_THAN_OR_EQUAL_TO',
69
+ lessThanOrEqual: 'LESS_THAN_OR_EQUAL_TO',
70
+ lessThanOrEquals: 'LESS_THAN_OR_EQUAL_TO',
71
+ });
72
+
73
+ /**
74
+ * Converts one yml searchOperators entry to its SearchOperator enum constant. The yml names are
75
+ * camelCase; the constants are UPPER_SNAKE, with the inclusive comparisons spelled
76
+ * `..._OR_EQUAL_TO`.
77
+ *
78
+ * @param {string} operator a yml operator name such as `greaterThanOrEqual` or `isNull`
79
+ * @returns {string} the SearchOperator constant name
80
+ */
81
+ export function toSearchOperatorConstant(operator) {
82
+ if (OPERATOR_CONSTANTS[operator]) {
83
+ return OPERATOR_CONSTANTS[operator];
84
+ }
85
+
86
+ return operator.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase();
87
+ }
@@ -0,0 +1,50 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { SIMPLIX_DIR } from './project.js';
5
+
6
+ /** The templates the CLI ships, used for every template a project does not provide itself. */
7
+ export const BUILT_IN_TEMPLATE_DIR = fileURLToPath(new URL('../../templates', import.meta.url));
8
+
9
+ /** Where a project keeps the templates that replace the built-in ones, under its root. */
10
+ export function projectTemplateDir(root) {
11
+ return path.join(root, SIMPLIX_DIR, 'templates');
12
+ }
13
+
14
+ /**
15
+ * Finds a template by its path relative to a template directory. The project's own copy under
16
+ * `.simplix/templates` wins; the built-in template of the same relative path is used otherwise.
17
+ *
18
+ * @param {string} root the project root
19
+ * @param {string} relativePath the template's path, such as `service/EntityService.java.template`
20
+ * @returns {{ path: string, origin: 'project' | 'built-in' } | undefined} the template, or
21
+ * undefined when neither the project nor the CLI has one
22
+ */
23
+ export function locateTemplate(root, relativePath) {
24
+ const own = path.join(projectTemplateDir(root), relativePath);
25
+ if (fs.existsSync(own)) return { path: own, origin: 'project' };
26
+
27
+ const builtIn = path.join(BUILT_IN_TEMPLATE_DIR, relativePath);
28
+ if (fs.existsSync(builtIn)) return { path: builtIn, origin: 'built-in' };
29
+
30
+ return undefined;
31
+ }
32
+
33
+ /**
34
+ * Every built-in template, by its path relative to the template directory, sorted.
35
+ *
36
+ * @returns {string[]}
37
+ */
38
+ export function listBuiltInTemplates() {
39
+ const found = [];
40
+ const walk = dir => {
41
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
42
+ const full = path.join(dir, entry.name);
43
+ if (entry.isDirectory()) walk(full);
44
+ else if (entry.name.endsWith('.template')) found.push(path.relative(BUILT_IN_TEMPLATE_DIR, full).split(path.sep).join('/'));
45
+ }
46
+ };
47
+
48
+ if (fs.existsSync(BUILT_IN_TEMPLATE_DIR)) walk(BUILT_IN_TEMPLATE_DIR);
49
+ return found.sort();
50
+ }
@@ -0,0 +1,200 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import crypto from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ /** The marker line every promoted file opens with. */
8
+ export const GENERATED_MARKER = '@simplix-generated';
9
+
10
+ /** The line under the marker carrying the render fingerprint and the command that laid it down. */
11
+ export const RENDER_MARKER = '@simplix-render';
12
+
13
+ /**
14
+ * The committed folder that holds, per promoted file, the exact render promote last wrote for it.
15
+ *
16
+ * <p>That render is the merge base the next promote reads an edited file against. It lives in the
17
+ * project, so a fresh clone merges exactly as the machine that promoted.
18
+ */
19
+ export const BASE_DIR = path.join('.simplix', 'bases');
20
+
21
+ /** Where a conflicting promote writes its merge with markers; inside the git-ignored tree. */
22
+ export const CONFLICT_DIR = path.join('generated', 'conflicts');
23
+
24
+ /**
25
+ * The fingerprint of one render, over everything but the fingerprint line itself.
26
+ *
27
+ * @param {string} source the file's content
28
+ * @returns {string} twelve hex characters
29
+ */
30
+ export function renderFingerprint(source) {
31
+ const withoutStamp = source
32
+ .split('\n')
33
+ .filter(line => !line.includes(RENDER_MARKER))
34
+ .join('\n');
35
+ return crypto.createHash('sha256').update(withoutStamp).digest('hex').slice(0, 12);
36
+ }
37
+
38
+ /**
39
+ * Puts the marker and the fingerprint line on top of a fresh render.
40
+ *
41
+ * @param {string} render the generator's output, unstamped
42
+ * @param {string} origin the command arguments that reproduce the render
43
+ * @returns {string} the stamped render
44
+ */
45
+ export function stampRender(render, origin) {
46
+ const body = stripStamp(render);
47
+ const marked = `// ${GENERATED_MARKER}\n${body}`;
48
+ return `// ${GENERATED_MARKER}\n// ${RENDER_MARKER} ${renderFingerprint(marked)} ${origin}\n${body}`;
49
+ }
50
+
51
+ /** The content without the marker and fingerprint lines. */
52
+ export function stripStamp(source) {
53
+ return source
54
+ .split('\n')
55
+ .filter(line => !line.includes(RENDER_MARKER) && !line.includes(GENERATED_MARKER))
56
+ .join('\n');
57
+ }
58
+
59
+ /**
60
+ * Gives an edited file the stamp lines of a render, so it reads as laid down from that render and
61
+ * keeps every edit.
62
+ */
63
+ export function carryStamp(held, render) {
64
+ const stamp = render.split('\n').filter(line => line.includes(GENERATED_MARKER) || line.includes(RENDER_MARKER));
65
+ return [...stamp, stripStamp(held)].join('\n');
66
+ }
67
+
68
+ /** The fingerprint recorded in a file's stamp line, or undefined. */
69
+ export function recordedFingerprint(held) {
70
+ const line = held.split('\n').find(one => one.includes(RENDER_MARKER));
71
+ if (line === undefined) return undefined;
72
+ return new RegExp(`${RENDER_MARKER}\\s+([0-9a-f]{12})`).exec(line)?.[1];
73
+ }
74
+
75
+ /** The command arguments recorded after the fingerprint, or undefined. */
76
+ export function recordedOrigin(held) {
77
+ const line = held.split('\n').find(one => one.includes(RENDER_MARKER));
78
+ if (line === undefined) return undefined;
79
+ return new RegExp(`${RENDER_MARKER}\\s+[0-9a-f]{12}\\s+(.+)$`).exec(line)?.[1]?.trim();
80
+ }
81
+
82
+ /** Whether a file still holds exactly the render it was stamped as. */
83
+ export function isUntouched(held) {
84
+ const recorded = recordedFingerprint(held);
85
+ return recorded !== undefined && recorded === renderFingerprint(held);
86
+ }
87
+
88
+ /** Where the stored base of a promoted file lives, under the project root. */
89
+ export function basePathFor(root, filePath) {
90
+ return path.join(root, BASE_DIR, path.relative(root, path.resolve(root, filePath)));
91
+ }
92
+
93
+ /** The stored base of a promoted file, or undefined when none was recorded. */
94
+ export function readBase(root, filePath) {
95
+ const at = basePathFor(root, filePath);
96
+ return fs.existsSync(at) ? fs.readFileSync(at, 'utf8') : undefined;
97
+ }
98
+
99
+ /** Stores a stamped render as the merge base of a promoted file. */
100
+ export function recordBase(root, filePath, render) {
101
+ writeWithDir(basePathFor(root, filePath), render);
102
+ }
103
+
104
+ function writeWithDir(filePath, content) {
105
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
106
+ fs.writeFileSync(filePath, content);
107
+ }
108
+
109
+ /**
110
+ * A three-way merge of `ours` and `theirs` against `base`, through `git merge-file`.
111
+ *
112
+ * @returns {{ text: string, hunks: string[] }} the merge and each conflicting region with markers
113
+ */
114
+ export function mergeThreeWay(base, ours, theirs) {
115
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'simplix-merge-'));
116
+ try {
117
+ const [o, b, t] = ['edited', 'base', 'template'].map(name => path.join(dir, name));
118
+ fs.writeFileSync(o, ours);
119
+ fs.writeFileSync(b, base);
120
+ fs.writeFileSync(t, theirs);
121
+ let text;
122
+ try {
123
+ text = execFileSync('git', ['merge-file', '-p', '-L', 'edited', '-L', 'base', '-L', 'template', o, b, t], {
124
+ encoding: 'utf8',
125
+ maxBuffer: 64 * 1024 * 1024,
126
+ });
127
+ } catch (err) {
128
+ // A positive exit status is the number of conflicts, and stdout still holds the merge.
129
+ if (typeof err.status !== 'number' || err.status < 0 || typeof err.stdout !== 'string') throw err;
130
+ text = err.stdout;
131
+ }
132
+
133
+ const hunks = [...text.matchAll(/^<<<<<<< edited\n[\s\S]*?^>>>>>>> template\n?/gm)].map(m => m[0]);
134
+ return { text, hunks };
135
+ } finally {
136
+ fs.rmSync(dir, { recursive: true, force: true });
137
+ }
138
+ }
139
+
140
+ /**
141
+ * What a promote of one fresh render into one file comes to, without writing anything.
142
+ *
143
+ * - `written`: absent or untouched, so the fresh render goes in as it is
144
+ * - `merged`: edited, and the template change merges into the edits without a conflict
145
+ * - `current`: edited, and the merge changes nothing
146
+ * - `conflict`: edited, and the template change collides with the edits
147
+ * - `no-base`: edited, and no stored base exists to merge against
148
+ * - `removed`: absent while a base is stored, so it was deleted after it was laid down and stays deleted
149
+ *
150
+ * @param {string} root the project root
151
+ * @param {string} filePath the promoted file
152
+ * @param {string} stamped the fresh render, stamped
153
+ * @returns {{ outcome: string, text?: string, hunks?: string[] }}
154
+ */
155
+ export function planTracked(root, filePath, stamped) {
156
+ if (!fs.existsSync(filePath)) {
157
+ return readBase(root, filePath) === undefined ? { outcome: 'written', text: stamped } : { outcome: 'removed' };
158
+ }
159
+
160
+ const ours = fs.readFileSync(filePath, 'utf8');
161
+ if (isUntouched(ours)) return { outcome: 'written', text: stamped };
162
+ let base = readBase(root, filePath);
163
+ if (base === undefined && recordedFingerprint(ours) === recordedFingerprint(stamped)) base = stamped;
164
+ if (base === undefined) return { outcome: 'no-base' };
165
+ // The stamp lines name the render a file was read against and are not content: every side takes
166
+ // the fresh render's, so a fingerprint that moved never collides with one an edit carried.
167
+ const { text, hunks } = mergeThreeWay(carryStamp(base, stamped), carryStamp(ours, stamped), stamped);
168
+ if (hunks.length > 0) return { outcome: 'conflict', text, hunks };
169
+ if (text === ours || text === carryStamp(ours, stamped)) return { outcome: 'current', text: ours };
170
+ return { outcome: 'merged', text };
171
+ }
172
+
173
+ /**
174
+ * Writes one fresh render into a promoted file under the tracked-render rule: laid down when absent,
175
+ * rewritten while untouched, left deleted once removed, merged three-way into the edits once somebody has edited it. A conflict
176
+ * never overwrites the file; its merge with markers goes to {@link CONFLICT_DIR}.
177
+ *
178
+ * @returns {{ outcome: string, report?: string, hunks?: string[] }}
179
+ */
180
+ export function writeTracked(root, filePath, stamped) {
181
+ const plan = planTracked(root, filePath, stamped);
182
+ switch (plan.outcome) {
183
+ case 'written':
184
+ case 'merged':
185
+ writeWithDir(filePath, plan.text);
186
+ recordBase(root, filePath, stamped);
187
+ return { outcome: plan.outcome };
188
+ case 'current':
189
+ recordBase(root, filePath, stamped);
190
+ return { outcome: 'current' };
191
+ case 'conflict': {
192
+ const report = path.join(root, CONFLICT_DIR, `${path.relative(root, path.resolve(root, filePath))}.conflict`);
193
+ writeWithDir(report, plan.text);
194
+ return { outcome: 'conflict', report, hunks: plan.hunks };
195
+ }
196
+
197
+ default:
198
+ return { outcome: plan.outcome };
199
+ }
200
+ }
@@ -0,0 +1,195 @@
1
+ import fs from 'node:fs';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { style, symbols } from './console.js';
4
+ import { CliError } from './errors.js';
5
+ import { CONFIG_FILE_NAME } from './project.js';
6
+ import {
7
+ compareReleaseVersions,
8
+ getGeneratorPackageName,
9
+ getGeneratorVersion,
10
+ getReleaseTag,
11
+ isSnapshotVersion,
12
+ toReleaseVersion,
13
+ } from './version-utils.js';
14
+
15
+ const NPM_BIN = process.platform === 'win32' ? 'npm.cmd' : 'npm';
16
+ const NPM_LOOKUP_TIMEOUT_MS = 15000;
17
+
18
+ /**
19
+ * Version of the CLI this project is built against, as recorded in
20
+ * generator-simplix.json under `generator.version`. Null when not recorded.
21
+ */
22
+ export function readRequiredVersion(config) {
23
+ const recorded = config?.generator?.version;
24
+ return typeof recorded === 'string' && recorded.trim() !== '' ? recorded.trim() : null;
25
+ }
26
+
27
+ const GENERATOR_VERSION_FIELD = /("generator"\s*:\s*\{[^{}]*?"version"\s*:\s*)"[^"]*"/;
28
+ const GENERATOR_BLOCK_OPEN = /"generator"\s*:\s*\{/;
29
+
30
+ /**
31
+ * Write `generator.version` into generator-simplix.json.
32
+ * The surrounding text is preserved byte for byte so recording a version never
33
+ * reformats a configuration file the project maintains by hand.
34
+ */
35
+ export function recordGeneratorVersion(configPath, version) {
36
+ const raw = fs.readFileSync(configPath, 'utf8');
37
+
38
+ if (GENERATOR_VERSION_FIELD.test(raw)) {
39
+ fs.writeFileSync(configPath, raw.replace(GENERATOR_VERSION_FIELD, `$1"${version}"`));
40
+ return;
41
+ }
42
+
43
+ if (GENERATOR_BLOCK_OPEN.test(raw)) {
44
+ fs.writeFileSync(
45
+ configPath,
46
+ raw.replace(GENERATOR_BLOCK_OPEN, match => `${match}\n "version": "${version}",`)
47
+ );
48
+ return;
49
+ }
50
+
51
+ const objectOpen = raw.indexOf('{');
52
+ if (objectOpen === -1) {
53
+ throw new CliError(`${CONFIG_FILE_NAME} is not a JSON object`);
54
+ }
55
+
56
+ const inserted = `${raw.slice(0, objectOpen + 1)}\n "generator": {\n "version": "${version}"\n },${raw.slice(objectOpen + 1)}`;
57
+ fs.writeFileSync(configPath, inserted);
58
+ }
59
+
60
+ /**
61
+ * Latest version of this build's release line published to the npm registry, or null when the
62
+ * registry cannot be reached or the line has never been published.
63
+ */
64
+ export function fetchLatestPublishedVersion(packageName = getGeneratorPackageName(), releaseTag = getReleaseTag()) {
65
+ let output;
66
+ try {
67
+ output = execFileSync(NPM_BIN, ['view', `${packageName}@${releaseTag}`, 'version'], {
68
+ encoding: 'utf8',
69
+ stdio: ['ignore', 'pipe', 'ignore'],
70
+ timeout: NPM_LOOKUP_TIMEOUT_MS,
71
+ });
72
+ } catch (error) {
73
+ // npm exits non-zero for an unpublished package and an unreachable registry, is killed at the
74
+ // timeout, and is absent on a machine without it. Each of those is "no answer".
75
+ if (typeof error.status === 'number' || error.signal || error.code === 'ENOENT' || error.code === 'ETIMEDOUT') {
76
+ return null;
77
+ }
78
+
79
+ throw error;
80
+ }
81
+
82
+ const version = output.trim();
83
+ return version === '' ? null : version;
84
+ }
85
+
86
+ /**
87
+ * Install a published version globally. Output streams to the terminal so the
88
+ * caller sees npm's own progress and failures.
89
+ */
90
+ export function installGeneratorVersion(version, packageName = getGeneratorPackageName()) {
91
+ execFileSync(NPM_BIN, ['install', '-g', `${packageName}@${version}`], { stdio: 'inherit' });
92
+ }
93
+
94
+ /**
95
+ * Refuse to generate when the running CLI is older than the version the
96
+ * project is built against. Templates and configuration keys move together,
97
+ * so an older CLI silently produces code the project no longer expects.
98
+ *
99
+ * A newer CLI is allowed and only reports the drift, and a project that
100
+ * records no version is left alone beyond a one-line notice.
101
+ *
102
+ * @param {object} check
103
+ * @param {object} [check.config] the parsed project configuration
104
+ * @param {(message: string) => void} check.log where the notices go
105
+ * @param {boolean} [check.skip] whether the check is skipped for this run
106
+ * @throws {CliError} when the running CLI is older than the project requires
107
+ */
108
+ export function assertGeneratorVersion({ config, log, skip = false }) {
109
+ if (skip) {
110
+ return;
111
+ }
112
+
113
+ const current = getGeneratorVersion();
114
+ const required = readRequiredVersion(config);
115
+
116
+ if (!required) {
117
+ log(
118
+ `${symbols.info} This project records no generator version. Run ${style.cyan('simplix-boot version --write')} to pin it to ${toReleaseVersion(current)}.`
119
+ );
120
+ return;
121
+ }
122
+
123
+ const comparison = compareReleaseVersions(current, required);
124
+
125
+ if (comparison === null) {
126
+ log(`${symbols.warning} Cannot compare generator version ${current} with the required version ${required}.`);
127
+ return;
128
+ }
129
+
130
+ if (comparison > 0) {
131
+ log(
132
+ `${symbols.warning} Generator ${current} is newer than the version this project records (${required}). Run ${style.cyan('simplix-boot version --write')} to update it.`
133
+ );
134
+ return;
135
+ }
136
+
137
+ if (comparison === 0) {
138
+ return;
139
+ }
140
+
141
+ const packageName = getGeneratorPackageName();
142
+ const latest = fetchLatestPublishedVersion(packageName);
143
+ const target = latest && compareReleaseVersions(latest, required) >= 0 ? latest : required;
144
+
145
+ throw new CliError(
146
+ [
147
+ `Generator ${style.red(current)} is older than the version this project requires (${style.cyan(required)}).`,
148
+ ` latest on npm: ${latest ? style.cyan(latest) : `${style.yellow('lookup failed')}: check the registry connection`}`,
149
+ ` update: ${style.cyan(`npm install -g ${packageName}@${target}`)}`,
150
+ ` or: ${style.cyan('simplix-boot version --update')}`,
151
+ ` skip: rerun with ${style.cyan('--skip-version-check')}`,
152
+ ].join('\n')
153
+ );
154
+ }
155
+
156
+ function describeStatus(current, required) {
157
+ if (required === null) {
158
+ return 'unrecorded';
159
+ }
160
+
161
+ const comparison = compareReleaseVersions(current, required);
162
+
163
+ if (comparison === null) {
164
+ return 'unknown';
165
+ }
166
+
167
+ if (comparison < 0) {
168
+ return 'outdated';
169
+ }
170
+
171
+ if (comparison > 0) {
172
+ return 'ahead';
173
+ }
174
+
175
+ return 'match';
176
+ }
177
+
178
+ /**
179
+ * Current / required / latest triple, for reporting and for machine-readable
180
+ * output. `latest` is only looked up when `includeLatest` is set, because the
181
+ * lookup costs a registry round trip.
182
+ */
183
+ export function collectVersionStatus({ config, includeLatest = false }) {
184
+ const current = getGeneratorVersion();
185
+ const required = readRequiredVersion(config);
186
+
187
+ return {
188
+ packageName: getGeneratorPackageName(),
189
+ current,
190
+ snapshot: isSnapshotVersion(current),
191
+ required,
192
+ latest: includeLatest ? fetchLatestPublishedVersion() : null,
193
+ status: describeStatus(current, required),
194
+ };
195
+ }