@llman-sdd/cli 0.8.2 → 0.10.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/package.json +2 -2
- package/src/cli-shared.ts +214 -45
- package/src/commands/archive.ts +61 -58
- package/src/commands/change.ts +321 -210
- package/src/commands/config.ts +35 -29
- package/src/commands/context.ts +67 -41
- package/src/commands/graph.ts +33 -21
- package/src/commands/index.ts +28 -18
- package/src/commands/init.ts +41 -11
- package/src/commands/list.ts +24 -18
- package/src/commands/project.ts +168 -78
- package/src/commands/review.ts +27 -26
- package/src/commands/self.ts +156 -0
- package/src/commands/show.ts +73 -37
- package/src/commands/spec.ts +155 -126
- package/src/commands/validate.ts +153 -89
- package/src/io.ts +7 -0
- package/src/main.ts +55 -50
- package/src/program.ts +83 -0
- package/src/progress.ts +14 -6
package/src/commands/project.ts
CHANGED
|
@@ -2,20 +2,71 @@ import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from '
|
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
|
|
4
4
|
import {
|
|
5
|
+
DEFAULT_LOCALE,
|
|
5
6
|
buildReqRegistry,
|
|
6
|
-
|
|
7
|
-
|
|
7
|
+
compareVersions,
|
|
8
|
+
isValidVersion,
|
|
8
9
|
migrateNoteFor,
|
|
9
10
|
migrateOverviewFor,
|
|
10
11
|
migrationOverviewLines,
|
|
11
12
|
migrationPrompt,
|
|
12
|
-
|
|
13
|
+
knownMigrationVersions,
|
|
14
|
+
parseVersionExpr,
|
|
13
15
|
planDedupe,
|
|
14
16
|
stripLegacyHeaderLines,
|
|
15
17
|
} from '@llman-sdd/core';
|
|
16
18
|
import type { Command } from 'commander';
|
|
17
19
|
|
|
18
|
-
import {
|
|
20
|
+
import {
|
|
21
|
+
CliError,
|
|
22
|
+
addSpecDirOption,
|
|
23
|
+
loadCliConfig,
|
|
24
|
+
loadRootSpecEntries,
|
|
25
|
+
type CliContext,
|
|
26
|
+
resolveRootSpecsDir,
|
|
27
|
+
} from '../cli-shared.ts';
|
|
28
|
+
|
|
29
|
+
interface MigrateOptions {
|
|
30
|
+
kind?: string;
|
|
31
|
+
fromVersion?: string;
|
|
32
|
+
toVersion?: string;
|
|
33
|
+
versionExpr?: string;
|
|
34
|
+
dryRun?: boolean;
|
|
35
|
+
directory?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Resolve the playbook range from --from-version/--to-version or the
|
|
39
|
+
* deprecated --version-expr (r100): conflict → ERROR, missing half → ERROR,
|
|
40
|
+
* malformed version → ERROR, from >= to → ERROR. Returns null when no
|
|
41
|
+
* selector was given at all (caller prints usage). */
|
|
42
|
+
function resolvePromptRange(options: MigrateOptions): {
|
|
43
|
+
from: string;
|
|
44
|
+
to: string;
|
|
45
|
+
viaExpr: boolean;
|
|
46
|
+
} | null {
|
|
47
|
+
const hasNew = options.fromVersion !== undefined || options.toVersion !== undefined;
|
|
48
|
+
if (options.versionExpr !== undefined && hasNew) {
|
|
49
|
+
throw new CliError(
|
|
50
|
+
'--version-expr is deprecated and conflicts with --from-version/--to-version; pass only the new flags',
|
|
51
|
+
2,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
if (options.versionExpr !== undefined) {
|
|
55
|
+
const parsed = parseVersionExpr(options.versionExpr);
|
|
56
|
+
if (parsed === null) {
|
|
57
|
+
throw new CliError(
|
|
58
|
+
`invalid --version-expr: ${options.versionExpr} (expected '<from>-><to>', e.g. '0.7.5->0.8.0')`,
|
|
59
|
+
2,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
return { ...parsed, viaExpr: true };
|
|
63
|
+
}
|
|
64
|
+
if (!hasNew) return null;
|
|
65
|
+
if (options.fromVersion === undefined || options.toVersion === undefined) {
|
|
66
|
+
throw new CliError('--from-version and --to-version must be given together (x.y.z)', 2);
|
|
67
|
+
}
|
|
68
|
+
return { from: options.fromVersion, to: options.toVersion, viaExpr: false };
|
|
69
|
+
}
|
|
19
70
|
|
|
20
71
|
function collectFeatureFiles(paths: string[]): string[] {
|
|
21
72
|
const out: string[] = [];
|
|
@@ -31,27 +82,35 @@ function collectFeatureFiles(paths: string[]): string[] {
|
|
|
31
82
|
return out;
|
|
32
83
|
}
|
|
33
84
|
|
|
34
|
-
export function registerProject(program: Command): void {
|
|
85
|
+
export function registerProject(program: Command, ctx: CliContext): void {
|
|
35
86
|
const project = program.command('project').description('Project management commands');
|
|
36
87
|
|
|
37
|
-
project
|
|
88
|
+
const dedupe = project
|
|
38
89
|
.command('dedupe-req-ids')
|
|
39
90
|
.description('Remap globally duplicated req ids (report with --dry-run)')
|
|
40
91
|
.option('--dry-run', 'report the remap plan without writing')
|
|
41
|
-
.action((options: { dryRun?: boolean }) => {
|
|
92
|
+
.action((options: { dryRun?: boolean; directory?: string }) => {
|
|
42
93
|
// dedupe registry covers requirement handles (`@req` on 规则: headers) only;
|
|
43
94
|
// duplicates follow the occurrence model (同文件内共用或跨文件均算)
|
|
44
|
-
|
|
95
|
+
// r115: the instance root (--directory, else the nearest at or above cwd)
|
|
96
|
+
// scopes the registry AND the write plan — never the launch dir alone.
|
|
97
|
+
const entries = loadRootSpecEntries(options.directory, ctx.io);
|
|
45
98
|
const { duplicates } = buildReqRegistry(entries);
|
|
46
99
|
if (duplicates.length === 0) {
|
|
47
100
|
console.log('No colliding req_id values in llmanspec/specs.');
|
|
48
101
|
return;
|
|
49
102
|
}
|
|
50
|
-
const io =
|
|
103
|
+
const io = ctx.io;
|
|
51
104
|
// r43: --dry-run is zero-side-effect — plan only, never write.
|
|
52
|
-
const plan = planDedupe(
|
|
53
|
-
|
|
54
|
-
|
|
105
|
+
const plan = planDedupe(
|
|
106
|
+
entries,
|
|
107
|
+
io,
|
|
108
|
+
resolveRootSpecsDir(options.directory, ctx.io),
|
|
109
|
+
duplicates,
|
|
110
|
+
{
|
|
111
|
+
apply: !options.dryRun,
|
|
112
|
+
},
|
|
113
|
+
);
|
|
55
114
|
// predecessor output: `{cap}: {from} → {to}` per remap (prefix in dry-run) + count line.
|
|
56
115
|
for (const item of plan) {
|
|
57
116
|
const cap = item.remapFile.replace(/^.*specs\//u, '').replace(/\.feature$/u, '');
|
|
@@ -60,90 +119,121 @@ export function registerProject(program: Command): void {
|
|
|
60
119
|
}
|
|
61
120
|
console.log(`${plan.length} remapping(s)${options.dryRun ? ' (dry-run)' : ''}`);
|
|
62
121
|
});
|
|
122
|
+
addSpecDirOption(dedupe);
|
|
63
123
|
|
|
64
|
-
project
|
|
124
|
+
const migrate = project
|
|
65
125
|
.command('migrate')
|
|
66
126
|
.description(
|
|
67
127
|
'Migration hub: legacy collaboration notes, versioned agent playbooks, spec-header strip',
|
|
68
128
|
)
|
|
69
129
|
.argument('[action]', 'prompt | strip-legacy-headers')
|
|
70
130
|
.option('--kind <kind>', 'legacy collaboration notes: toon2features | specs-flatten')
|
|
71
|
-
.option('--version
|
|
131
|
+
.option('--from-version <version>', 'migration playbook range start, exclusive (x.y.z)')
|
|
132
|
+
.option('--to-version <version>', 'migration playbook range end, inclusive (x.y.z)')
|
|
133
|
+
.option(
|
|
134
|
+
'--version-expr <expr>',
|
|
135
|
+
"deprecated — use --from-version/--to-version instead (e.g. '0.7.5->0.8.0')",
|
|
136
|
+
)
|
|
72
137
|
.option('--dry-run', 'strip-legacy-headers: report affected files without writing')
|
|
73
|
-
.action(
|
|
74
|
-
(
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
`unknown migration: ${expr} (known: ${knownMigrationIds().join(', ')})`,
|
|
100
|
-
);
|
|
101
|
-
}
|
|
102
|
-
console.log(migrationPrompt(migration));
|
|
138
|
+
.action((action: string | undefined, options: MigrateOptions) => {
|
|
139
|
+
// T36: version-range flags without an action are a usage error (rc 2),
|
|
140
|
+
// not a silent no-op — the error names the action that consumes them.
|
|
141
|
+
// `--kind` alone stays the legacy no-action form (overview / kind note).
|
|
142
|
+
if (
|
|
143
|
+
action === undefined &&
|
|
144
|
+
(options.versionExpr !== undefined ||
|
|
145
|
+
options.fromVersion !== undefined ||
|
|
146
|
+
options.toVersion !== undefined)
|
|
147
|
+
) {
|
|
148
|
+
throw new CliError(
|
|
149
|
+
'project migrate range flags require the prompt action (llman-sdd project migrate prompt)',
|
|
150
|
+
2,
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
const locale = loadCliConfig()?.locale ?? DEFAULT_LOCALE;
|
|
154
|
+
if (action === 'prompt') {
|
|
155
|
+
const range = resolvePromptRange(options);
|
|
156
|
+
if (range === null) {
|
|
157
|
+
console.log(
|
|
158
|
+
[
|
|
159
|
+
'Migration playbook range is required.',
|
|
160
|
+
`Known migrations: ${knownMigrationVersions().join(', ')}`,
|
|
161
|
+
'Usage: llman-sdd project migrate prompt --from-version <from> --to-version <to>',
|
|
162
|
+
].join('\n'),
|
|
163
|
+
);
|
|
103
164
|
return;
|
|
104
165
|
}
|
|
105
|
-
|
|
106
|
-
if (
|
|
107
|
-
throw new CliError(
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
let touched = 0;
|
|
111
|
-
let removed = 0;
|
|
112
|
-
for (const file of targets) {
|
|
113
|
-
const source = readFileSync(file, 'utf8');
|
|
114
|
-
const result = stripLegacyHeaderLines(source);
|
|
115
|
-
if (result.removed === 0) continue;
|
|
116
|
-
touched++;
|
|
117
|
-
removed += result.removed;
|
|
118
|
-
console.log(
|
|
119
|
-
`[strip] ${file}: ${result.removed} line(s)${options.dryRun === true ? ' (dry-run)' : ''}`,
|
|
166
|
+
for (const v of [range.from, range.to]) {
|
|
167
|
+
if (!isValidVersion(v)) {
|
|
168
|
+
throw new CliError(
|
|
169
|
+
`invalid version '${v}': expected x.y.z (e.g. 0.9.0), got '${v}'`,
|
|
170
|
+
2,
|
|
120
171
|
);
|
|
121
|
-
if (options.dryRun !== true) writeFileSync(file, result.content, 'utf8');
|
|
122
172
|
}
|
|
123
|
-
const mode = options.dryRun === true ? ' (dry-run)' : '';
|
|
124
|
-
console.log(
|
|
125
|
-
`strip-legacy-headers: ${touched} file(s), ${removed} line(s) removed${mode}`,
|
|
126
|
-
);
|
|
127
|
-
console.log('next: re-run `llman-sdd init --update` to refresh skills and templates');
|
|
128
|
-
return;
|
|
129
173
|
}
|
|
130
|
-
if (
|
|
174
|
+
if (compareVersions(range.from, range.to) >= 0) {
|
|
131
175
|
throw new CliError(
|
|
132
|
-
`
|
|
176
|
+
`invalid range: --from-version (${range.from}) must be less than --to-version (${range.to})`,
|
|
177
|
+
2,
|
|
133
178
|
);
|
|
134
179
|
}
|
|
135
|
-
if (
|
|
136
|
-
console.
|
|
137
|
-
|
|
138
|
-
|
|
180
|
+
if (range.viaExpr) {
|
|
181
|
+
console.error(
|
|
182
|
+
'[WARNING] --version-expr is deprecated; use --from-version/--to-version instead.',
|
|
183
|
+
);
|
|
139
184
|
}
|
|
140
|
-
|
|
141
|
-
|
|
185
|
+
console.log(migrationPrompt(range.from, range.to));
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (action === 'strip-legacy-headers') {
|
|
189
|
+
if (
|
|
190
|
+
options.kind !== undefined ||
|
|
191
|
+
options.versionExpr !== undefined ||
|
|
192
|
+
options.fromVersion !== undefined ||
|
|
193
|
+
options.toVersion !== undefined
|
|
194
|
+
) {
|
|
142
195
|
throw new CliError(
|
|
143
|
-
|
|
196
|
+
'strip-legacy-headers takes no --kind/--version-expr/--from-version/--to-version',
|
|
144
197
|
);
|
|
145
198
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
199
|
+
const targets = collectFeatureFiles([resolveRootSpecsDir(options.directory, ctx.io)]);
|
|
200
|
+
let touched = 0;
|
|
201
|
+
let removed = 0;
|
|
202
|
+
for (const file of targets) {
|
|
203
|
+
const source = readFileSync(file, 'utf8');
|
|
204
|
+
const result = stripLegacyHeaderLines(source);
|
|
205
|
+
if (result.removed === 0) continue;
|
|
206
|
+
touched++;
|
|
207
|
+
removed += result.removed;
|
|
208
|
+
console.log(
|
|
209
|
+
`[strip] ${file}: ${result.removed} line(s)${options.dryRun === true ? ' (dry-run)' : ''}`,
|
|
210
|
+
);
|
|
211
|
+
if (options.dryRun !== true) writeFileSync(file, result.content, 'utf8');
|
|
212
|
+
}
|
|
213
|
+
const mode = options.dryRun === true ? ' (dry-run)' : '';
|
|
214
|
+
console.log(`strip-legacy-headers: ${touched} file(s), ${removed} line(s) removed${mode}`);
|
|
215
|
+
console.log('next: re-run `llman-sdd init --update` to refresh skills and templates');
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (action !== undefined) {
|
|
219
|
+
throw new CliError(
|
|
220
|
+
`unknown migrate action: ${action} (expected: prompt | strip-legacy-headers)`,
|
|
221
|
+
2,
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
if (options.kind === undefined) {
|
|
225
|
+
console.log(migrateOverviewFor(locale));
|
|
226
|
+
console.log(migrationOverviewLines().join('\n'));
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const note = migrateNoteFor(options.kind, locale);
|
|
230
|
+
if (note === null) {
|
|
231
|
+
throw new CliError(
|
|
232
|
+
`unknown migration kind: ${options.kind} (expected: toon2features | specs-flatten)`,
|
|
233
|
+
2,
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
console.log(note);
|
|
237
|
+
});
|
|
238
|
+
addSpecDirOption(migrate);
|
|
149
239
|
}
|
package/src/commands/review.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { join } from 'node:path';
|
|
|
4
4
|
import {
|
|
5
5
|
buildReview,
|
|
6
6
|
collectChanges,
|
|
7
|
-
|
|
7
|
+
discoverSpecs,
|
|
8
8
|
renderReviewHtml,
|
|
9
9
|
specIdOf,
|
|
10
10
|
TEMPLATES_ROOT,
|
|
@@ -13,23 +13,24 @@ import type { Command } from 'commander';
|
|
|
13
13
|
|
|
14
14
|
import {
|
|
15
15
|
addReportOutputOptions,
|
|
16
|
+
addSpecDirOption,
|
|
16
17
|
CliError,
|
|
17
18
|
cliMaxScanDepth,
|
|
19
|
+
emitReport,
|
|
18
20
|
exitWith,
|
|
19
|
-
|
|
20
|
-
loadSpecEntries,
|
|
21
|
-
newIo,
|
|
22
|
-
resolveOutMode,
|
|
21
|
+
resolveCommandRoot,
|
|
23
22
|
templateIo,
|
|
23
|
+
type CliContext,
|
|
24
24
|
} from '../cli-shared.ts';
|
|
25
25
|
|
|
26
|
-
export function registerReview(program: Command): void {
|
|
26
|
+
export function registerReview(program: Command, ctx: CliContext): void {
|
|
27
27
|
const review = program
|
|
28
28
|
.command('review')
|
|
29
29
|
.description('Aggregate review: unbound signals plus a validate sweep');
|
|
30
30
|
|
|
31
31
|
review.option('--capability <capability>', 'restrict the sweep to one capability/spec id');
|
|
32
32
|
addReportOutputOptions(review);
|
|
33
|
+
addSpecDirOption(review);
|
|
33
34
|
review
|
|
34
35
|
.option('--export-html <path>', 'write a self-contained HTML report')
|
|
35
36
|
.action(
|
|
@@ -39,41 +40,41 @@ export function registerReview(program: Command): void {
|
|
|
39
40
|
compactJson?: boolean;
|
|
40
41
|
output?: string;
|
|
41
42
|
exportHtml?: string;
|
|
43
|
+
directory?: string;
|
|
42
44
|
}) => {
|
|
43
|
-
const io =
|
|
44
|
-
const
|
|
45
|
+
const io = ctx.io;
|
|
46
|
+
const root = resolveCommandRoot(ctx, options.directory);
|
|
47
|
+
const entries = discoverSpecs(join(root, 'llmanspec', 'specs'), ctx.io);
|
|
45
48
|
if (options.capability !== undefined) {
|
|
46
49
|
const known = new Set(entries.map((e) => specIdOf(e)));
|
|
47
50
|
if (!known.has(options.capability)) {
|
|
48
51
|
throw new CliError(`capability \`${options.capability}\` not found`);
|
|
49
52
|
}
|
|
50
53
|
}
|
|
51
|
-
const activeChanges = collectChanges(
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const now = new Date();
|
|
56
|
-
const result = buildReview(
|
|
54
|
+
const activeChanges = collectChanges(
|
|
55
|
+
io,
|
|
56
|
+
resolveCommandRoot(ctx, options.directory),
|
|
57
|
+
new Date(),
|
|
57
58
|
{
|
|
58
|
-
|
|
59
|
-
boundChangeCount: activeChanges.filter((c) => c.hasBinding).length,
|
|
60
|
-
activeChanges,
|
|
61
|
-
capability: options.capability,
|
|
62
|
-
checkTransitions: Boolean(loadCliConfig()?.specs?.check_transitions),
|
|
59
|
+
maxScanDepth: cliMaxScanDepth(program),
|
|
63
60
|
},
|
|
64
|
-
io,
|
|
65
61
|
);
|
|
62
|
+
// B17: 墙钟由 CLI 注入,core 不直读 new Date()
|
|
63
|
+
const now = new Date();
|
|
64
|
+
const result = buildReview({
|
|
65
|
+
entries,
|
|
66
|
+
boundChangeCount: activeChanges.filter((c) => c.hasBinding).length,
|
|
67
|
+
activeChanges,
|
|
68
|
+
capability: options.capability,
|
|
69
|
+
});
|
|
66
70
|
if (options.exportHtml !== undefined) {
|
|
67
71
|
const template = templateIo.readText(join(TEMPLATES_ROOT, 'shared', 'review.html'));
|
|
68
72
|
writeFileSync(options.exportHtml, renderReviewHtml(template, result, now));
|
|
69
73
|
console.log(`wrote ${options.exportHtml}`);
|
|
70
74
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
} else {
|
|
75
|
-
console.log(result.lines.join('\n'));
|
|
76
|
-
}
|
|
75
|
+
emitReport({ signals: result.signals, summary: result.summary }, options, () =>
|
|
76
|
+
result.lines.join('\n'),
|
|
77
|
+
);
|
|
77
78
|
if (result.exitCode !== 0) exitWith(result.exitCode);
|
|
78
79
|
},
|
|
79
80
|
);
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
4
|
+
/**
|
|
5
|
+
* `self` command group (completion capability r110-r112): shell-completion
|
|
6
|
+
* generation from the live commander tree and marker-idempotent rc install
|
|
7
|
+
* with a confirmation gate. Terminal interaction stays in this CLI adapter
|
|
8
|
+
* (core owns only pure text transforms), per the AGENTS interaction rule.
|
|
9
|
+
*/
|
|
10
|
+
import { createInterface } from 'node:readline';
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
COMPLETION_BIN,
|
|
14
|
+
COMPLETION_SHELLS,
|
|
15
|
+
completionBlock,
|
|
16
|
+
isCompletionShell,
|
|
17
|
+
renderCompletionScript,
|
|
18
|
+
resolveBashRc,
|
|
19
|
+
upsertCompletionBlock,
|
|
20
|
+
type CompletionCommandSpec,
|
|
21
|
+
type CompletionShell,
|
|
22
|
+
} from '@llman-sdd/core';
|
|
23
|
+
import { type Command } from 'commander';
|
|
24
|
+
|
|
25
|
+
import { CliError, type CliContext } from '../cli-shared.ts';
|
|
26
|
+
|
|
27
|
+
/** Extract the completion IR from the live commander tree — no second manifest. */
|
|
28
|
+
export function extractCompletionSpec(program: Command): CompletionCommandSpec {
|
|
29
|
+
const walk = (cmd: Command): CompletionCommandSpec => ({
|
|
30
|
+
name: cmd.name(),
|
|
31
|
+
flags: cmd.options.map((o) => o.long).filter((f): f is string => typeof f === 'string'),
|
|
32
|
+
subcommands: cmd.commands
|
|
33
|
+
.filter((c) => (c as unknown as { hidden?: boolean }).hidden !== true)
|
|
34
|
+
.map(walk),
|
|
35
|
+
});
|
|
36
|
+
return walk(program);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function completionSnippet(shell: CompletionShell): string {
|
|
40
|
+
switch (shell) {
|
|
41
|
+
case 'bash':
|
|
42
|
+
case 'zsh':
|
|
43
|
+
return `source <(${COMPLETION_BIN} self completion --shell ${shell})`;
|
|
44
|
+
case 'fish':
|
|
45
|
+
return `${COMPLETION_BIN} self completion --shell fish | source`;
|
|
46
|
+
case 'powershell':
|
|
47
|
+
return `${COMPLETION_BIN} self completion --shell powershell | Out-String | Invoke-Expression`;
|
|
48
|
+
case 'elvish':
|
|
49
|
+
return `eval (${COMPLETION_BIN} self completion --shell elvish)`;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** rc/profile target for one shell (r111). Bash keeps the 3-step fallback chain. */
|
|
54
|
+
export function resolveRcPath(shell: CompletionShell, home: string): string {
|
|
55
|
+
switch (shell) {
|
|
56
|
+
case 'bash':
|
|
57
|
+
return resolveBashRc(home, (p) => existsSync(p));
|
|
58
|
+
case 'zsh':
|
|
59
|
+
return join(home, '.zshrc');
|
|
60
|
+
case 'fish':
|
|
61
|
+
return join(home, '.config', 'fish', 'config.fish');
|
|
62
|
+
case 'powershell':
|
|
63
|
+
return resolvePowerShellProfile(home);
|
|
64
|
+
case 'elvish':
|
|
65
|
+
return join(home, '.elvish', 'rc.elv');
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function resolvePowerShellProfile(home: string): string {
|
|
70
|
+
const envProfile = process.env.PROFILE?.trim();
|
|
71
|
+
if (envProfile !== undefined && envProfile !== '') {
|
|
72
|
+
const absolute = isAbsolute(envProfile) ? resolve(envProfile) : resolve(envProfile);
|
|
73
|
+
const homeAbs = resolve(home);
|
|
74
|
+
if (absolute === homeAbs || absolute.startsWith(homeAbs + sep)) return absolute;
|
|
75
|
+
throw new CliError(`powershell profile resolves outside home: ${absolute}`, 2);
|
|
76
|
+
}
|
|
77
|
+
return join(home, '.config', 'powershell', 'Microsoft.PowerShell_profile.ps1');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Confirmation gate (r112): TTY prompt, `-y` bypass, non-interactive → refuse. */
|
|
81
|
+
export async function confirmInstall(
|
|
82
|
+
rcPath: string,
|
|
83
|
+
yes: boolean,
|
|
84
|
+
deps: { isInteractive?: () => boolean; prompt?: (text: string) => Promise<string> } = {},
|
|
85
|
+
): Promise<boolean> {
|
|
86
|
+
if (yes) return true;
|
|
87
|
+
const isInteractive = deps.isInteractive ?? (() => process.stdin.isTTY === true);
|
|
88
|
+
const prompt =
|
|
89
|
+
deps.prompt ??
|
|
90
|
+
((text: string) =>
|
|
91
|
+
new Promise<string>((resolvePrompt) => {
|
|
92
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
93
|
+
rl.question(text, (answer) => {
|
|
94
|
+
rl.close();
|
|
95
|
+
resolvePrompt(answer);
|
|
96
|
+
});
|
|
97
|
+
}));
|
|
98
|
+
if (!isInteractive()) return false;
|
|
99
|
+
const answer = await prompt(`Install ${COMPLETION_BIN} completion block into ${rcPath}? [y/N] `);
|
|
100
|
+
return /^y(?:es)?$/iu.test(answer.trim());
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface InstallDeps {
|
|
104
|
+
/** Injectable home (tests); defaults to os.homedir() — Bun's homedir()
|
|
105
|
+
* ignores in-process process.env.HOME writes, so tests MUST inject. */
|
|
106
|
+
home?: string;
|
|
107
|
+
isInteractive?: () => boolean;
|
|
108
|
+
prompt?: (text: string) => Promise<string>;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function runInstall(
|
|
112
|
+
shell: CompletionShell,
|
|
113
|
+
yes: boolean,
|
|
114
|
+
deps: InstallDeps = {},
|
|
115
|
+
): Promise<void> {
|
|
116
|
+
const home = deps.home ?? homedir();
|
|
117
|
+
const rcPath = resolveRcPath(shell, home);
|
|
118
|
+
const confirmed = await confirmInstall(rcPath, yes, {
|
|
119
|
+
isInteractive: deps.isInteractive,
|
|
120
|
+
prompt: deps.prompt,
|
|
121
|
+
});
|
|
122
|
+
if (!confirmed) {
|
|
123
|
+
throw new CliError(`non-interactive session without --yes — refusing to write ${rcPath}`, 2);
|
|
124
|
+
}
|
|
125
|
+
const existing = existsSync(rcPath) ? readFileSync(rcPath, 'utf8') : '';
|
|
126
|
+
const snippet = completionSnippet(shell);
|
|
127
|
+
const { content } = upsertCompletionBlock(existing, snippet);
|
|
128
|
+
mkdirSync(dirname(rcPath), { recursive: true });
|
|
129
|
+
writeFileSync(rcPath, content);
|
|
130
|
+
console.log(completionBlock(snippet));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function registerSelf(program: Command, _ctx: CliContext): void {
|
|
134
|
+
const self = program.command('self').description('Self-inspection surface (shell completion)');
|
|
135
|
+
|
|
136
|
+
self
|
|
137
|
+
.command('completion')
|
|
138
|
+
.description('Generate or install shell completions (generation prints to stdout)')
|
|
139
|
+
.requiredOption('--shell <shell>', `target shell (${COMPLETION_SHELLS.join('|')})`)
|
|
140
|
+
.option('--install', 'install the marker-wrapped snippet block into the shell rc/profile')
|
|
141
|
+
.option('-y, --yes', 'skip the confirmation prompt (only meaningful with --install)')
|
|
142
|
+
.action(async (options: { shell: string; install?: boolean; yes?: boolean }) => {
|
|
143
|
+
const shell = options.shell.toLowerCase();
|
|
144
|
+
if (!isCompletionShell(shell)) {
|
|
145
|
+
throw new CliError(
|
|
146
|
+
`unknown shell "${options.shell}" — legal values: ${COMPLETION_SHELLS.join(', ')}`,
|
|
147
|
+
2,
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
if (options.install === true) {
|
|
151
|
+
await runInstall(shell, options.yes === true);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
process.stdout.write(renderCompletionScript(extractCompletionSpec(program), shell));
|
|
155
|
+
});
|
|
156
|
+
}
|