@mriekki/project-forge 1.0.0 → 2.0.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.
package/src/cli.mjs CHANGED
@@ -1,150 +1,150 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { execFileSync } from 'node:child_process';
4
- import readline from 'node:readline/promises';
5
- import { stdin as input, stdout as output } from 'node:process';
6
- import { applyProfile, checkProfile, loadProjectForgeBaseline, planProfile } from './engine.mjs';
7
- import { loadPackageData } from './package-data.mjs';
8
-
9
- function parseArgs(argv) {
10
- const options = { acceptedRetired: new Map() };
11
- const positional = [];
12
- for (let i = 0; i < argv.length; i += 1) {
13
- const arg = argv[i];
14
- if (arg === '--help' || arg === '-h') options.help = true;
15
- else if (arg === '--apply' || arg === '--yes') options.apply = true;
16
- else if (arg === '--root') options.root = argv[++i];
17
- else if (arg === '--profile') options.profile = argv[++i];
18
- else if (arg === '--consumer') options.consumer = argv[++i];
19
- else if (arg === '--consumer-baseline') options.consumerBaseline = argv[++i];
20
- else if (arg === '--accept-retired') {
21
- const value = argv[++i] ?? '';
22
- const index = value.indexOf(':');
23
- if (index <= 0) throw new Error('--accept-retired must use component:path');
24
- const component = value.slice(0, index);
25
- const retiredPath = value.slice(index + 1);
26
- if (!options.acceptedRetired.has(component)) options.acceptedRetired.set(component, new Set());
27
- options.acceptedRetired.get(component).add(retiredPath);
28
- } else if (arg.startsWith('-')) throw new Error(`Unknown option: ${arg}`);
29
- else positional.push(arg);
30
- }
31
- return { command: positional[0] ?? 'help', options };
32
- }
33
-
34
- function inferConsumer(root) {
35
- try {
36
- const origin = execFileSync('git', ['-C', root, 'config', '--get', 'remote.origin.url'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
37
- if (origin) {
38
- const normalized = origin.replace(/\\/g, '/').replace(/\.git$/, '');
39
- const match = normalized.match(/[:/]([^/:]+\/[^/]+)$/);
40
- if (match) return match[1].split('/').pop();
41
- }
42
- } catch {}
43
- return path.basename(root);
44
- }
45
-
46
- function printPlan(plan) {
47
- console.log(`Project Forge profile: ${plan.profileName}`);
48
- for (const component of plan.plans) {
49
- console.log(`\n${component.componentId.toUpperCase()} ${component.component.commit}`);
50
- for (const row of component.rows) console.log(`${row.state.padEnd(20)} ${row.path}`);
51
- for (const retired of component.retired) console.log(`${retired.state.padEnd(20)} ${retired.path}`);
52
- }
53
- console.log(`\nUnsafe drift/conflicts: ${plan.unsafe.length}`);
54
- for (const item of plan.unsafe) console.log(` - ${item.component}: ${item.state}: ${item.path}`);
55
- }
56
-
57
- async function shouldApply(options) {
58
- if (options.apply) return true;
59
- if (!input.isTTY || !output.isTTY) return false;
60
- const rl = readline.createInterface({ input, output });
61
- try {
62
- const answer = (await rl.question('Apply this safe Project Forge asset plan? [y/N] ')).trim().toLowerCase();
63
- return answer === 'y' || answer === 'yes';
64
- } finally {
65
- rl.close();
66
- }
67
- }
68
-
69
- function usage(command) {
70
- const commandUsage = {
71
- install: 'project-forge install [--root PATH] [--profile NAME] [--apply|--yes] [--consumer NAME] [--consumer-baseline LABEL] [--accept-retired component:path]',
72
- update: 'project-forge update [--root PATH] [--profile NAME] [--apply|--yes] [--accept-retired component:path]',
73
- status: 'project-forge status [--root PATH] [--profile NAME]',
74
- check: 'project-forge check [--root PATH] [--profile NAME]',
75
- version: 'project-forge version'
76
- };
77
-
78
- if (commandUsage[command]) {
79
- console.log(`@mriekki/project-forge\n\nUsage:\n ${commandUsage[command]}\n`);
80
- return;
81
- }
82
-
83
- console.log(`@mriekki/project-forge\n\nCommands:\n install Preview/install bundled Project Forge assets\n update Preview/update to this package's bundled Project Forge assets\n status Show installed umbrella/component provenance\n check Verify managed files and baselines exactly match this package\n version Show package version\n\nCommon options:\n --root PATH\n --profile greenfield-project\n --apply | --yes\n --consumer NAME\n --consumer-baseline LABEL\n --accept-retired core:path\n -h, --help\n`);
84
- }
85
-
86
- export async function run(argv = process.argv.slice(2), packageData = loadPackageData()) {
87
- const { command, options } = parseArgs(argv);
88
- if (command === 'help') { usage(); return 0; }
89
- if (options.help) {
90
- if (!['install', 'update', 'status', 'check', 'version'].includes(command)) throw new Error(`Unknown command: ${command}`);
91
- usage(command);
92
- return 0;
93
- }
94
- if (command === 'version') { console.log(`${packageData.pkg.name} ${packageData.pkg.version}`); return 0; }
95
- const root = path.resolve(options.root ?? process.cwd());
96
- if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) throw new Error(`Repository root not found: ${root}`);
97
- const installed = loadProjectForgeBaseline(root);
98
- const profile = options.profile ?? installed.profile ?? packageData.assets.defaultProfile;
99
-
100
- if (command === 'status') {
101
- if (!Object.keys(installed).length) {
102
- console.log(`Project Forge: not installed\nAvailable package: ${packageData.pkg.name}@${packageData.pkg.version}\nProfile: ${profile}`);
103
- return 0;
104
- }
105
- console.log(`Project Forge package: ${installed.package}@${installed.version}`);
106
- console.log(`Available package: ${packageData.pkg.name}@${packageData.pkg.version}`);
107
- console.log(`Profile: ${installed.profile}`);
108
- for (const [name, component] of Object.entries(installed.components ?? {})) {
109
- console.log(`${name}: ${component.version ? component.version + ' @ ' : ''}${component.commit}`);
110
- }
111
- return 0;
112
- }
113
-
114
- if (command === 'check') {
115
- const result = checkProfile(packageData, profile, root);
116
- console.log(`Project Forge package baseline current: ${result.projectForgeCurrent ? 'yes' : 'no'}`);
117
- for (const component of result.plan.plans) {
118
- const clean = component.metadataCurrent && component.rows.every((row) => row.state === 'SAME') && component.retired.length === 0;
119
- console.log(`${component.componentId}: ${clean ? 'PASS' : 'STALE OR DRIFTED'}`);
120
- }
121
- console.log(`Project Forge check: ${result.clean ? 'PASS' : 'STALE OR DRIFTED'}`);
122
- return result.clean ? 0 : 1;
123
- }
124
-
125
- if (!['install', 'update'].includes(command)) throw new Error(`Unknown command: ${command}`);
126
- if (command === 'install' && Object.keys(installed).length) throw new Error('PROJECT_FORGE_BASELINE.json already exists; use update instead of install');
127
- if (command === 'update' && !Object.keys(installed).length) throw new Error('PROJECT_FORGE_BASELINE.json is missing; use install first');
128
- if (installed.profile && installed.profile !== profile) throw new Error(`Installed Project Forge profile is ${installed.profile}; refusing implicit profile change to ${profile}`);
129
-
130
- const plan = planProfile(packageData, profile, root, options.acceptedRetired);
131
- printPlan(plan);
132
- if (plan.unsafe.length) {
133
- console.log('\nRefusing apply. Resolve drift/conflicts and preview again. No managed files were changed.');
134
- return 2;
135
- }
136
- const apply = await shouldApply(options);
137
- if (!apply) {
138
- console.log('\nPreview only. Re-run with --apply, or run interactively and approve the prompt.');
139
- return 0;
140
- }
141
- const baselineConsumers = [...new Set(plan.plans.map((item) => item.baseline.consumer).filter(Boolean))];
142
- const baselineLabels = [...new Set(plan.plans.map((item) => item.baseline.consumerBaseline).filter(Boolean))];
143
- if (baselineConsumers.length > 1) throw new Error(`Component baselines disagree on consumer identity: ${baselineConsumers.join(', ')}`);
144
- if (baselineLabels.length > 1) throw new Error(`Component baselines disagree on consumer baseline: ${baselineLabels.join(', ')}`);
145
- const consumer = options.consumer ?? installed.consumer ?? baselineConsumers[0] ?? inferConsumer(root);
146
- const consumerBaseline = options.consumerBaseline ?? installed.consumerBaseline ?? baselineLabels[0] ?? `${packageData.pkg.name}@${packageData.pkg.version}`;
147
- applyProfile(packageData, plan, root, consumer, consumerBaseline);
148
- console.log(`\nProject Forge ${command}: PASS (${packageData.pkg.name}@${packageData.pkg.version})`);
149
- return 0;
150
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { execFileSync } from 'node:child_process';
4
+ import readline from 'node:readline/promises';
5
+ import { stdin as input, stdout as output } from 'node:process';
6
+ import { applyProfile, checkProfile, loadProjectForgeBaseline, planProfile } from './engine.mjs';
7
+ import { loadPackageData } from './package-data.mjs';
8
+
9
+ function parseArgs(argv) {
10
+ const options = { acceptedRetired: new Map() };
11
+ const positional = [];
12
+ for (let i = 0; i < argv.length; i += 1) {
13
+ const arg = argv[i];
14
+ if (arg === '--help' || arg === '-h') options.help = true;
15
+ else if (arg === '--apply' || arg === '--yes') options.apply = true;
16
+ else if (arg === '--root') options.root = argv[++i];
17
+ else if (arg === '--profile') options.profile = argv[++i];
18
+ else if (arg === '--consumer') options.consumer = argv[++i];
19
+ else if (arg === '--consumer-baseline') options.consumerBaseline = argv[++i];
20
+ else if (arg === '--accept-retired') {
21
+ const value = argv[++i] ?? '';
22
+ const index = value.indexOf(':');
23
+ if (index <= 0) throw new Error('--accept-retired must use component:path');
24
+ const component = value.slice(0, index);
25
+ const retiredPath = value.slice(index + 1);
26
+ if (!options.acceptedRetired.has(component)) options.acceptedRetired.set(component, new Set());
27
+ options.acceptedRetired.get(component).add(retiredPath);
28
+ } else if (arg.startsWith('-')) throw new Error(`Unknown option: ${arg}`);
29
+ else positional.push(arg);
30
+ }
31
+ return { command: positional[0] ?? 'help', options };
32
+ }
33
+
34
+ function inferConsumer(root) {
35
+ try {
36
+ const origin = execFileSync('git', ['-C', root, 'config', '--get', 'remote.origin.url'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
37
+ if (origin) {
38
+ const normalized = origin.replace(/\\/g, '/').replace(/\.git$/, '');
39
+ const match = normalized.match(/[:/]([^/:]+\/[^/]+)$/);
40
+ if (match) return match[1].split('/').pop();
41
+ }
42
+ } catch {}
43
+ return path.basename(root);
44
+ }
45
+
46
+ function printPlan(plan) {
47
+ console.log(`Project Forge profile: ${plan.profileName}`);
48
+ for (const component of plan.plans) {
49
+ console.log(`\n${component.componentId.toUpperCase()} ${component.component.commit}`);
50
+ for (const row of component.rows) console.log(`${row.state.padEnd(20)} ${row.path}`);
51
+ for (const retired of component.retired) console.log(`${retired.state.padEnd(20)} ${retired.path}`);
52
+ }
53
+ console.log(`\nUnsafe drift/conflicts: ${plan.unsafe.length}`);
54
+ for (const item of plan.unsafe) console.log(` - ${item.component}: ${item.state}: ${item.path}`);
55
+ }
56
+
57
+ async function shouldApply(options) {
58
+ if (options.apply) return true;
59
+ if (!input.isTTY || !output.isTTY) return false;
60
+ const rl = readline.createInterface({ input, output });
61
+ try {
62
+ const answer = (await rl.question('Apply this safe Project Forge asset plan? [y/N] ')).trim().toLowerCase();
63
+ return answer === 'y' || answer === 'yes';
64
+ } finally {
65
+ rl.close();
66
+ }
67
+ }
68
+
69
+ function usage(command) {
70
+ const commandUsage = {
71
+ install: 'project-forge install [--root PATH] [--profile NAME] [--apply|--yes] [--consumer NAME] [--consumer-baseline LABEL] [--accept-retired component:path]',
72
+ update: 'project-forge update [--root PATH] [--profile NAME] [--apply|--yes] [--accept-retired component:path]',
73
+ status: 'project-forge status [--root PATH] [--profile NAME]',
74
+ check: 'project-forge check [--root PATH] [--profile NAME]',
75
+ version: 'project-forge version'
76
+ };
77
+
78
+ if (commandUsage[command]) {
79
+ console.log(`@mriekki/project-forge\n\nUsage:\n ${commandUsage[command]}\n`);
80
+ return;
81
+ }
82
+
83
+ console.log(`@mriekki/project-forge\n\nCommands:\n install Preview/install bundled Project Forge assets\n update Preview/update to this package's bundled Project Forge assets\n status Show installed umbrella/component provenance\n check Verify managed files and baselines exactly match this package\n version Show package version\n\nCommon options:\n --root PATH\n --profile greenfield-project\n --apply | --yes\n --consumer NAME\n --consumer-baseline LABEL\n --accept-retired core:path\n -h, --help\n`);
84
+ }
85
+
86
+ export async function run(argv = process.argv.slice(2), packageData = loadPackageData()) {
87
+ const { command, options } = parseArgs(argv);
88
+ if (command === 'help') { usage(); return 0; }
89
+ if (options.help) {
90
+ if (!['install', 'update', 'status', 'check', 'version'].includes(command)) throw new Error(`Unknown command: ${command}`);
91
+ usage(command);
92
+ return 0;
93
+ }
94
+ if (command === 'version') { console.log(`${packageData.pkg.name} ${packageData.pkg.version}`); return 0; }
95
+ const root = path.resolve(options.root ?? process.cwd());
96
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) throw new Error(`Repository root not found: ${root}`);
97
+ const installed = loadProjectForgeBaseline(root);
98
+ const profile = options.profile ?? installed.profile ?? packageData.assets.defaultProfile;
99
+
100
+ if (command === 'status') {
101
+ if (!Object.keys(installed).length) {
102
+ console.log(`Project Forge: not installed\nAvailable package: ${packageData.pkg.name}@${packageData.pkg.version}\nProfile: ${profile}`);
103
+ return 0;
104
+ }
105
+ console.log(`Project Forge package: ${installed.package}@${installed.version}`);
106
+ console.log(`Available package: ${packageData.pkg.name}@${packageData.pkg.version}`);
107
+ console.log(`Profile: ${installed.profile}`);
108
+ for (const [name, component] of Object.entries(installed.components ?? {})) {
109
+ console.log(`${name}: ${component.version ? component.version + ' @ ' : ''}${component.commit}`);
110
+ }
111
+ return 0;
112
+ }
113
+
114
+ if (command === 'check') {
115
+ const result = checkProfile(packageData, profile, root);
116
+ console.log(`Project Forge package baseline current: ${result.projectForgeCurrent ? 'yes' : 'no'}`);
117
+ for (const component of result.plan.plans) {
118
+ const clean = component.metadataCurrent && component.rows.every((row) => row.state === 'SAME') && component.retired.length === 0;
119
+ console.log(`${component.componentId}: ${clean ? 'PASS' : 'STALE OR DRIFTED'}`);
120
+ }
121
+ console.log(`Project Forge check: ${result.clean ? 'PASS' : 'STALE OR DRIFTED'}`);
122
+ return result.clean ? 0 : 1;
123
+ }
124
+
125
+ if (!['install', 'update'].includes(command)) throw new Error(`Unknown command: ${command}`);
126
+ if (command === 'install' && Object.keys(installed).length) throw new Error('PROJECT_FORGE_BASELINE.json already exists; use update instead of install');
127
+ if (command === 'update' && !Object.keys(installed).length) throw new Error('PROJECT_FORGE_BASELINE.json is missing; use install first');
128
+ if (installed.profile && installed.profile !== profile) throw new Error(`Installed Project Forge profile is ${installed.profile}; refusing implicit profile change to ${profile}`);
129
+
130
+ const plan = planProfile(packageData, profile, root, options.acceptedRetired);
131
+ printPlan(plan);
132
+ if (plan.unsafe.length) {
133
+ console.log('\nRefusing apply. Resolve drift/conflicts and preview again. No managed files were changed.');
134
+ return 2;
135
+ }
136
+ const apply = await shouldApply(options);
137
+ if (!apply) {
138
+ console.log('\nPreview only. Re-run with --apply, or run interactively and approve the prompt.');
139
+ return 0;
140
+ }
141
+ const baselineConsumers = [...new Set(plan.plans.map((item) => item.baseline.consumer).filter(Boolean))];
142
+ const baselineLabels = [...new Set(plan.plans.map((item) => item.baseline.consumerBaseline).filter(Boolean))];
143
+ if (baselineConsumers.length > 1) throw new Error(`Component baselines disagree on consumer identity: ${baselineConsumers.join(', ')}`);
144
+ if (baselineLabels.length > 1) throw new Error(`Component baselines disagree on consumer baseline: ${baselineLabels.join(', ')}`);
145
+ const consumer = options.consumer ?? installed.consumer ?? baselineConsumers[0] ?? inferConsumer(root);
146
+ const consumerBaseline = options.consumerBaseline ?? installed.consumerBaseline ?? baselineLabels[0] ?? `${packageData.pkg.name}@${packageData.pkg.version}`;
147
+ applyProfile(packageData, plan, root, consumer, consumerBaseline);
148
+ console.log(`\nProject Forge ${command}: PASS (${packageData.pkg.name}@${packageData.pkg.version})`);
149
+ return 0;
150
+ }