praxo-cli 0.0.0-stage → 0.1.0-rc.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.
- package/LICENSE +21 -0
- package/README.md +195 -2
- package/dist/app.js +75 -0
- package/dist/bin.js +21 -0
- package/dist/cli/commands/ai.command.js +189 -0
- package/dist/cli/commands/cmd.command.js +265 -0
- package/dist/cli/commands/completion.command.js +334 -0
- package/dist/cli/commands/config.command.js +27 -0
- package/dist/cli/commands/decision.command.js +287 -0
- package/dist/cli/commands/doctor.command.js +45 -0
- package/dist/cli/commands/project.command.js +24 -0
- package/dist/cli/commands/search.command.js +59 -0
- package/dist/cli/commands/sync.command.js +122 -0
- package/dist/cli/commands/transfer.command.js +148 -0
- package/dist/cli/index.js +156 -0
- package/dist/cli/output.js +133 -0
- package/dist/cli/prompts.js +68 -0
- package/dist/features/ai/client.js +238 -0
- package/dist/features/ai/output.js +7 -0
- package/dist/features/ai/providers.js +52 -0
- package/dist/features/ai/schemas.js +43 -0
- package/dist/features/ai/service.js +183 -0
- package/dist/features/commands/executor.js +54 -0
- package/dist/features/commands/repository.js +61 -0
- package/dist/features/commands/safety.js +154 -0
- package/dist/features/commands/service.js +254 -0
- package/dist/features/commands/template.js +153 -0
- package/dist/features/decisions/repository.js +53 -0
- package/dist/features/decisions/service.js +209 -0
- package/dist/features/decisions/stats.js +84 -0
- package/dist/features/decisions/status.js +7 -0
- package/dist/features/projects/repository.js +51 -0
- package/dist/features/projects/service.js +74 -0
- package/dist/features/sync/git.js +207 -0
- package/dist/features/sync/merge.js +194 -0
- package/dist/features/sync/repository.js +151 -0
- package/dist/features/sync/sanitizer.js +21 -0
- package/dist/features/sync/service.js +199 -0
- package/dist/features/sync/snapshot.js +230 -0
- package/dist/infrastructure/credentials/store.js +105 -0
- package/dist/infrastructure/database/client.js +41 -0
- package/dist/infrastructure/database/migrate.js +102 -0
- package/dist/infrastructure/database/schema.js +138 -0
- package/dist/infrastructure/git/detector.js +48 -0
- package/dist/shared/clipboard.js +19 -0
- package/dist/shared/config.js +163 -0
- package/dist/shared/doctor.js +47 -0
- package/dist/shared/errors.js +19 -0
- package/dist/shared/global-search.js +51 -0
- package/dist/shared/input.js +37 -0
- package/dist/shared/links.js +48 -0
- package/dist/shared/paths.js +14 -0
- package/dist/shared/query.js +10 -0
- package/dist/shared/redaction.js +54 -0
- package/dist/shared/search.js +39 -0
- package/dist/shared/sync-metadata.js +7 -0
- package/dist/shared/tags.js +91 -0
- package/dist/shared/transfer/archive.js +197 -0
- package/dist/shared/transfer/markdown.js +53 -0
- package/dist/shared/transfer/service.js +278 -0
- package/dist/tui/Workspace.js +121 -0
- package/dist/tui/components/AiPanel.js +200 -0
- package/dist/tui/components/Catalog.js +47 -0
- package/dist/tui/components/Confirm.js +28 -0
- package/dist/tui/components/Form.js +113 -0
- package/dist/tui/components/HelpModal.js +44 -0
- package/dist/tui/components/Inspection.js +28 -0
- package/dist/tui/components/KeyHints.js +7 -0
- package/dist/tui/components/SearchInput.js +31 -0
- package/dist/tui/components/SyncPanel.js +93 -0
- package/dist/tui/index.js +18 -0
- package/dist/tui/screens/Commands.js +383 -0
- package/dist/tui/screens/DecisionForms.js +117 -0
- package/dist/tui/screens/Decisions.js +260 -0
- package/dist/tui/screens/Lookup.js +96 -0
- package/dist/tui/theme.js +47 -0
- package/drizzle/0000_initial.sql +105 -0
- package/drizzle/0001_v11_sync.sql +117 -0
- package/drizzle/meta/0000_snapshot.json +735 -0
- package/drizzle/meta/0001_snapshot.json +867 -0
- package/drizzle/meta/_journal.json +20 -0
- package/package.json +77 -4
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { Option } from 'commander';
|
|
2
|
+
import { parseAssignments } from '../../features/commands/template.js';
|
|
3
|
+
import { AppError } from '../../shared/errors.js';
|
|
4
|
+
import { canPrompt, collect, formatTable, limit, output, outputList } from '../output.js';
|
|
5
|
+
import { confirmRemoval, confirmRun, field, prompt, requirePrompt } from '../prompts.js';
|
|
6
|
+
/** 注册命令列表与搜索共用的查询过滤选项。 */
|
|
7
|
+
function queryOptions(command) {
|
|
8
|
+
return command
|
|
9
|
+
.option('-t, --type <type>', 'Filter by command type')
|
|
10
|
+
.addOption(new Option('--tier <tier>', 'Filter by priority tier').choices(['hot', 'normal']))
|
|
11
|
+
.option('--sos', 'Only show SOS emergency commands')
|
|
12
|
+
.addOption(new Option('--scope <scope>', 'Filter by visibility scope').choices([
|
|
13
|
+
'global',
|
|
14
|
+
'project',
|
|
15
|
+
'all',
|
|
16
|
+
]))
|
|
17
|
+
.option('-p, --project <id>', 'Filter by project ID or "current"')
|
|
18
|
+
.option('--tag <tag>', 'Filter by tag (repeatable)', collect, [])
|
|
19
|
+
.addOption(new Option('--sort <mode>', 'Sort order').choices(['smart', 'recent', 'used', 'name']))
|
|
20
|
+
.option('-L, --limit <n>', 'Maximum number of results to return')
|
|
21
|
+
.option('--json', 'Output JSON');
|
|
22
|
+
}
|
|
23
|
+
function rowCells(item) {
|
|
24
|
+
return [
|
|
25
|
+
item.id,
|
|
26
|
+
item.name,
|
|
27
|
+
item.type,
|
|
28
|
+
[item.tier, item.sos ? 'SOS' : ''].filter(Boolean).join('/'),
|
|
29
|
+
item.projectName ?? 'Global',
|
|
30
|
+
];
|
|
31
|
+
}
|
|
32
|
+
function displayRow(item) {
|
|
33
|
+
return rowCells(item).join('\t');
|
|
34
|
+
}
|
|
35
|
+
function displayDetail(item) {
|
|
36
|
+
return [
|
|
37
|
+
displayRow(item),
|
|
38
|
+
item.template,
|
|
39
|
+
item.note,
|
|
40
|
+
'Tags: ' + (item.tags.join(', ') || '—'),
|
|
41
|
+
'Uses: ' + item.count + ' (' + item.copyCount + ' copied, ' + item.runCount + ' executed)',
|
|
42
|
+
]
|
|
43
|
+
.filter(Boolean)
|
|
44
|
+
.join('\n');
|
|
45
|
+
}
|
|
46
|
+
function showList(app, options, query) {
|
|
47
|
+
const { tag, json, limit: count, ...filter } = options;
|
|
48
|
+
const rows = app.commands.list({ ...filter, tags: tag, limit: limit(count) }, query);
|
|
49
|
+
outputList(rows, json, () => formatTable(['ID', 'Name', 'Type', 'Priority', 'Scope'], rows.map(rowCells)), 'No matching commands.');
|
|
50
|
+
}
|
|
51
|
+
/** 注册命令新增与编辑共用的字段选项。 */
|
|
52
|
+
function commandFields(command, edit = false) {
|
|
53
|
+
const result = command
|
|
54
|
+
.option('-n, --name <name>', 'Command display name')
|
|
55
|
+
.option('-t, --type <type>', 'Command category/type')
|
|
56
|
+
.addOption(new Option('--tier <tier>', 'Priority tier').choices(['hot', 'normal']))
|
|
57
|
+
.option('--sos', 'Mark as an SOS emergency command')
|
|
58
|
+
.option('--danger', 'Mark as a high-risk command')
|
|
59
|
+
.option('--note <text>', 'Usage note or description')
|
|
60
|
+
.addOption(new Option('--scope <scope>', 'Visibility scope').choices(edit ? ['global', 'project'] : ['auto', 'global', 'project']))
|
|
61
|
+
.option('-p, --project <id>', 'Bind to a project ID or "current"');
|
|
62
|
+
const extended = edit
|
|
63
|
+
? result
|
|
64
|
+
.option('--template <template>', 'Updated command template')
|
|
65
|
+
.option('--no-sos', 'Clear the SOS flag')
|
|
66
|
+
.option('--no-danger', 'Clear the high-risk flag')
|
|
67
|
+
: result.option('--tag <tag>', 'Attach a tag (repeatable)', collect, []);
|
|
68
|
+
return extended.option('--json', 'Output JSON');
|
|
69
|
+
}
|
|
70
|
+
async function add(app, template, options) {
|
|
71
|
+
const { tag, json, ...input } = options;
|
|
72
|
+
if (template === undefined) {
|
|
73
|
+
requirePrompt('Supply a command template, for example: pxo command add "git status".');
|
|
74
|
+
const result = await prompt(async (ask) => ({
|
|
75
|
+
template: await ask('Command template: '),
|
|
76
|
+
name: input.name ?? (await field(ask, 'Name (optional)', '')),
|
|
77
|
+
note: input.note ?? (await field(ask, 'Description (optional)', '')),
|
|
78
|
+
type: input.type ?? (await field(ask, 'Type (optional)', 'custom')),
|
|
79
|
+
}));
|
|
80
|
+
template = result.template;
|
|
81
|
+
Object.assign(input, result);
|
|
82
|
+
}
|
|
83
|
+
const record = app.commands.create({ ...input, template, tags: tag });
|
|
84
|
+
output(record, json, () => 'Added ' + displayRow(record));
|
|
85
|
+
}
|
|
86
|
+
async function edit(app, id, options) {
|
|
87
|
+
const { json, ...patch } = options;
|
|
88
|
+
const record = app.commands.show(id);
|
|
89
|
+
let updates = patch;
|
|
90
|
+
if (!Object.values(updates).some((value) => value !== undefined)) {
|
|
91
|
+
requirePrompt('Pass at least one field to update, for example --name.');
|
|
92
|
+
updates = await prompt(async (ask) => ({
|
|
93
|
+
name: await field(ask, 'Name', record.name),
|
|
94
|
+
template: await field(ask, 'Template', record.template),
|
|
95
|
+
note: await field(ask, 'Description', record.note),
|
|
96
|
+
type: await field(ask, 'Type', record.type),
|
|
97
|
+
}));
|
|
98
|
+
if (Object.values(updates).every((value) => value === undefined)) {
|
|
99
|
+
output({ id, updated: false, record }, json, () => 'No changes.');
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const updated = app.commands.edit(id, updates);
|
|
104
|
+
output(updated, json, () => 'Updated ' + displayRow(updated));
|
|
105
|
+
}
|
|
106
|
+
async function choose(app, selector, ask) {
|
|
107
|
+
const rows = app.commands.match(selector);
|
|
108
|
+
if (rows.length === 1)
|
|
109
|
+
return rows[0];
|
|
110
|
+
if (!ask) {
|
|
111
|
+
throw new AppError(2, 'Multiple commands match. Run pxo command search and pass a command ID.');
|
|
112
|
+
}
|
|
113
|
+
const shown = rows.slice(0, 20);
|
|
114
|
+
shown.forEach((row, index) => process.stderr.write(String(index + 1) + ') ' + displayRow(row) + '\n'));
|
|
115
|
+
const answer = (await ask('Choose a command number, or press Enter to cancel: ')).trim();
|
|
116
|
+
if (!answer)
|
|
117
|
+
throw new AppError(130, 'Selection cancelled.');
|
|
118
|
+
const selected = /^\d+$/u.test(answer) ? shown[Number(answer) - 1] : undefined;
|
|
119
|
+
if (!selected)
|
|
120
|
+
throw new AppError(2, 'Choose a number from the displayed results.');
|
|
121
|
+
return selected;
|
|
122
|
+
}
|
|
123
|
+
function displayedPlan(plan) {
|
|
124
|
+
const vector = 'executable' in plan.risk
|
|
125
|
+
? '\nArguments: ' + JSON.stringify([plan.risk.executable, ...plan.risk.args])
|
|
126
|
+
: '';
|
|
127
|
+
return plan.text + '\nRisk: ' + plan.risk.kind + '. ' + plan.risk.reason + vector;
|
|
128
|
+
}
|
|
129
|
+
async function use(app, action, selector, options) {
|
|
130
|
+
const values = parseAssignments(options.var);
|
|
131
|
+
const interaction = canPrompt(options.prompt === false || options.noPrompt === true);
|
|
132
|
+
async function perform(ask) {
|
|
133
|
+
const { id } = await choose(app, selector, ask);
|
|
134
|
+
const missing = app.commands.variables(id, values);
|
|
135
|
+
if (ask) {
|
|
136
|
+
for (const key of missing)
|
|
137
|
+
values.set(key, await ask(key + ': '));
|
|
138
|
+
}
|
|
139
|
+
if (action === 'copy') {
|
|
140
|
+
const text = await app.commands.copy(id, values);
|
|
141
|
+
output({ id, text, copied: true }, options.json, () => 'Copied command.');
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const plan = app.commands.prepare(id, values);
|
|
145
|
+
if (options.dryRun) {
|
|
146
|
+
output({ id, text: plan.text, risk: plan.risk }, options.json, () => displayedPlan(plan));
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
let approval = 'unattended';
|
|
150
|
+
if (plan.risk.kind === 'high') {
|
|
151
|
+
if (!ask) {
|
|
152
|
+
throw new AppError(4, 'High-risk commands require an interactive terminal and typed confirmation.');
|
|
153
|
+
}
|
|
154
|
+
process.stderr.write(displayedPlan(plan) + '\n');
|
|
155
|
+
approval = await confirmRun(ask, true, plan.risk.reason);
|
|
156
|
+
}
|
|
157
|
+
else if (plan.risk.kind === 'ordinary' && !options.yes) {
|
|
158
|
+
if (!ask) {
|
|
159
|
+
throw new AppError(4, 'Pass --yes to confirm ordinary execution in non-interactive mode.');
|
|
160
|
+
}
|
|
161
|
+
process.stderr.write(displayedPlan(plan) + '\n');
|
|
162
|
+
approval = await confirmRun(ask, false, plan.risk.reason);
|
|
163
|
+
}
|
|
164
|
+
return { id, plan, approval };
|
|
165
|
+
}
|
|
166
|
+
// 关闭 readline 后再交出终端,让子进程可以自行读取键盘输入。
|
|
167
|
+
const ready = interaction ? await prompt(perform) : await perform();
|
|
168
|
+
if (ready) {
|
|
169
|
+
const result = await app.commands.run(ready.id, values, ready.approval, ready.plan);
|
|
170
|
+
if (result.kind === 'copied')
|
|
171
|
+
process.stderr.write(result.reason + ' Copied command.\n');
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/** 注册 `pxo command`(别名 `cmd`/`c`)命令组。 */
|
|
175
|
+
export function registerCommands(program, withApp) {
|
|
176
|
+
const commands = program
|
|
177
|
+
.command('command')
|
|
178
|
+
.aliases(['cmd', 'c'])
|
|
179
|
+
.description('Manage saved commands');
|
|
180
|
+
queryOptions(commands.command('list').alias('ls').description('List saved commands')).action((options) => withApp((app) => showList(app, options)));
|
|
181
|
+
queryOptions(commands.command('search <query>').alias('s').description('Search saved commands')).action((query, options) => withApp((app) => showList(app, options, query)));
|
|
182
|
+
commands
|
|
183
|
+
.command('show <id>')
|
|
184
|
+
.description('Show command details')
|
|
185
|
+
.option('--json', 'Output JSON')
|
|
186
|
+
.action((id, options) => withApp((app) => {
|
|
187
|
+
const row = app.commands.show(id);
|
|
188
|
+
output(row, options.json, () => displayDetail(row));
|
|
189
|
+
}));
|
|
190
|
+
commandFields(commands.command('add [template]').description('Add a new command')).action((template, options) => withApp((app) => add(app, template, options)));
|
|
191
|
+
commandFields(commands.command('edit <id>').description('Edit a saved command'), true).action((id, options) => withApp((app) => edit(app, id, options)));
|
|
192
|
+
commands
|
|
193
|
+
.command('remove <id>')
|
|
194
|
+
.alias('rm')
|
|
195
|
+
.description('Delete a saved command')
|
|
196
|
+
.option('-y, --yes', 'Skip deletion confirmation')
|
|
197
|
+
.option('--json', 'Output JSON')
|
|
198
|
+
.action((id, options) => withApp(async (app) => {
|
|
199
|
+
const row = app.commands.show(id);
|
|
200
|
+
await confirmRemoval(row.name, options.yes);
|
|
201
|
+
app.commands.remove(id);
|
|
202
|
+
output({ id, deleted: true }, options.json, () => 'Deleted command ' + id + '.');
|
|
203
|
+
}));
|
|
204
|
+
commands
|
|
205
|
+
.command('render <id>')
|
|
206
|
+
.description('Render a command template with variables')
|
|
207
|
+
.option('--var <key=value>', 'Assign a template variable (repeatable)', collect, [])
|
|
208
|
+
.option('--json', 'Output JSON')
|
|
209
|
+
.action((id, options) => withApp((app) => {
|
|
210
|
+
const text = app.commands.render(id, parseAssignments(options.var));
|
|
211
|
+
output({ id, text }, options.json, () => text);
|
|
212
|
+
}));
|
|
213
|
+
for (const action of ['copy', 'run']) {
|
|
214
|
+
const command = commands
|
|
215
|
+
.command(action + ' <id-or-query>')
|
|
216
|
+
.description(action === 'copy' ? 'Render and copy a command to clipboard' : 'Safely execute a command')
|
|
217
|
+
.option('--var <key=value>', 'Assign a template variable (repeatable)', collect, [])
|
|
218
|
+
.addOption(new Option('--no-prompt', 'Disable interactive prompts').hideHelp());
|
|
219
|
+
if (action === 'copy') {
|
|
220
|
+
command.alias('cp').option('--json', 'Output JSON');
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
command
|
|
224
|
+
.option('--dry-run', 'Preview rendered command and risk without executing')
|
|
225
|
+
.option('-y, --yes', 'Confirm ordinary execution without prompting')
|
|
226
|
+
.option('--json', 'Output JSON (supported with --dry-run)');
|
|
227
|
+
}
|
|
228
|
+
command.action((selector, options) => withApp((app) => use(app, action, selector, options), options.dryRun ? 'preview' : 'write'));
|
|
229
|
+
}
|
|
230
|
+
const tag = commands.command('tag').description('Manage command tags');
|
|
231
|
+
for (const action of ['add', 'remove']) {
|
|
232
|
+
const sub = tag
|
|
233
|
+
.command(action + ' <id> <tag>')
|
|
234
|
+
.description(action === 'add' ? 'Attach a tag to a command' : 'Detach a tag from a command')
|
|
235
|
+
.option('--json', 'Output JSON');
|
|
236
|
+
if (action === 'remove')
|
|
237
|
+
sub.alias('rm');
|
|
238
|
+
sub.action((id, name, options) => withApp((app) => {
|
|
239
|
+
const row = app.commands.tag(id, action, name);
|
|
240
|
+
output({ id, tags: row.tags }, options.json, () => row.tags.join(', '));
|
|
241
|
+
}));
|
|
242
|
+
}
|
|
243
|
+
return commands;
|
|
244
|
+
}
|
|
245
|
+
/** 注册顶层快捷命令 `pxo add`(等价 `pxo command add`)。 */
|
|
246
|
+
export function registerCommandAddShortcut(program, withApp) {
|
|
247
|
+
return commandFields(program
|
|
248
|
+
.command('add [template]')
|
|
249
|
+
.description('Quickly add a command (shortcut for command add)')).action((template, options) => withApp((app) => add(app, template, options)));
|
|
250
|
+
}
|
|
251
|
+
/** 注册顶层 `pxo tag` 命令组。 */
|
|
252
|
+
export function registerTag(program, withApp) {
|
|
253
|
+
const tag = program.command('tag').description('Inspect tags across commands and decisions');
|
|
254
|
+
tag
|
|
255
|
+
.command('list')
|
|
256
|
+
.alias('ls')
|
|
257
|
+
.description('List tags and usage counts')
|
|
258
|
+
.addOption(new Option('--sort <mode>', 'Sort order').choices(['name', 'usage']))
|
|
259
|
+
.option('--json', 'Output JSON')
|
|
260
|
+
.action((options) => withApp((app) => {
|
|
261
|
+
const rows = app.tags.list(options.sort);
|
|
262
|
+
outputList(rows, options.json, () => formatTable(['Tag', 'Count'], rows.map((row) => [row.name, String(row.count)])), 'No tags.');
|
|
263
|
+
}));
|
|
264
|
+
return tag;
|
|
265
|
+
}
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import { Argument } from 'commander';
|
|
2
|
+
/** 从 Commander 命令树提取可补全的子命令、别名与可见选项结构。 */
|
|
3
|
+
function collectTree(command) {
|
|
4
|
+
const options = command.options
|
|
5
|
+
.filter((option) => !option.hidden)
|
|
6
|
+
.map((option) => ({
|
|
7
|
+
short: option.short,
|
|
8
|
+
long: option.long,
|
|
9
|
+
flags: [option.short, option.long].filter((flag) => Boolean(flag)),
|
|
10
|
+
takesValue: Boolean(option.required || option.optional),
|
|
11
|
+
description: option.description || '',
|
|
12
|
+
}));
|
|
13
|
+
const subcommands = command.commands
|
|
14
|
+
.filter((sub) => sub.name() !== 'help')
|
|
15
|
+
.map((sub) => collectTree(sub));
|
|
16
|
+
return {
|
|
17
|
+
name: command.name(),
|
|
18
|
+
names: [command.name(), ...command.aliases()],
|
|
19
|
+
description: command.description() || '',
|
|
20
|
+
options,
|
|
21
|
+
subcommands,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** 收集命令树中所有需要参数值的选项标志,避免把选项值误判为子命令名。 */
|
|
25
|
+
function collectValueFlags(node, target = new Set()) {
|
|
26
|
+
for (const opt of node.options) {
|
|
27
|
+
if (opt.takesValue) {
|
|
28
|
+
for (const flag of opt.flags)
|
|
29
|
+
target.add(flag);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
for (const sub of node.subcommands)
|
|
33
|
+
collectValueFlags(sub, target);
|
|
34
|
+
return [...target].sort();
|
|
35
|
+
}
|
|
36
|
+
/** 扁平化命令树,返回每条命令路径(含别名路径)对应的子命令与选项补全词表。 */
|
|
37
|
+
function flattenPaths(node, prefix = []) {
|
|
38
|
+
const subWords = node.subcommands.flatMap((sub) => sub.names);
|
|
39
|
+
const optWords = node.options.flatMap((opt) => opt.flags);
|
|
40
|
+
const current = [{ path: prefix, words: [...subWords, ...optWords] }];
|
|
41
|
+
const nested = node.subcommands.flatMap((sub) => sub.names.flatMap((name) => flattenPaths(sub, [...prefix, name])));
|
|
42
|
+
return [...current, ...nested];
|
|
43
|
+
}
|
|
44
|
+
/** 递归收集规范路径(按主命令名)与别名映射,用于 Fish 多层级补全。 */
|
|
45
|
+
function collectCanonical(node, prefix = []) {
|
|
46
|
+
const path = prefix.join(' ');
|
|
47
|
+
const nodes = [{ path, node }];
|
|
48
|
+
const transitions = [];
|
|
49
|
+
for (const sub of node.subcommands) {
|
|
50
|
+
const nextPrefix = [...prefix, sub.name];
|
|
51
|
+
const nextPath = nextPrefix.join(' ');
|
|
52
|
+
for (const token of sub.names) {
|
|
53
|
+
transitions.push({ from: path, token, to: nextPath });
|
|
54
|
+
}
|
|
55
|
+
const child = collectCanonical(sub, nextPrefix);
|
|
56
|
+
nodes.push(...child.nodes);
|
|
57
|
+
transitions.push(...child.transitions);
|
|
58
|
+
}
|
|
59
|
+
return { nodes, transitions };
|
|
60
|
+
}
|
|
61
|
+
function escapeSingle(value) {
|
|
62
|
+
return value.replace(/'/gu, "'\\''");
|
|
63
|
+
}
|
|
64
|
+
function bashScript(tree) {
|
|
65
|
+
const entries = flattenPaths(tree);
|
|
66
|
+
const valueFlags = collectValueFlags(tree);
|
|
67
|
+
const validKeys = entries
|
|
68
|
+
.map(({ path }) => path.join(' '))
|
|
69
|
+
.filter(Boolean)
|
|
70
|
+
.map((key) => `"${key}"`)
|
|
71
|
+
.join('|');
|
|
72
|
+
const cases = entries
|
|
73
|
+
.map(({ path, words }) => {
|
|
74
|
+
const key = path.join(' ') || '__root__';
|
|
75
|
+
return ` "${key}")\n COMPREPLY=( $(compgen -W "${words.join(' ')}" -- "$cur") )\n return 0\n ;;`;
|
|
76
|
+
})
|
|
77
|
+
.join('\n');
|
|
78
|
+
const flagPattern = valueFlags.join('|');
|
|
79
|
+
return [
|
|
80
|
+
'# Bash completion for pxo',
|
|
81
|
+
'# Load with: eval "$(pxo completion bash)"',
|
|
82
|
+
'_pxo_completions() {',
|
|
83
|
+
' local cur="${COMP_WORDS[COMP_CWORD]}"',
|
|
84
|
+
' local path=""',
|
|
85
|
+
' local skip_next=0',
|
|
86
|
+
' local i word candidate',
|
|
87
|
+
' for ((i = 1; i < COMP_CWORD; i++)); do',
|
|
88
|
+
' word="${COMP_WORDS[i]}"',
|
|
89
|
+
' if ((skip_next)); then',
|
|
90
|
+
' skip_next=0',
|
|
91
|
+
' continue',
|
|
92
|
+
' fi',
|
|
93
|
+
' case "$word" in',
|
|
94
|
+
...(flagPattern
|
|
95
|
+
? [` ${flagPattern})\n skip_next=1\n continue\n ;;`]
|
|
96
|
+
: []),
|
|
97
|
+
' -*)',
|
|
98
|
+
' continue',
|
|
99
|
+
' ;;',
|
|
100
|
+
' esac',
|
|
101
|
+
' candidate="${path:+$path }$word"',
|
|
102
|
+
' case "$candidate" in',
|
|
103
|
+
...(validKeys ? [` ${validKeys})\n path="$candidate"\n ;;`] : []),
|
|
104
|
+
' esac',
|
|
105
|
+
' done',
|
|
106
|
+
' if ((skip_next)); then',
|
|
107
|
+
' COMPREPLY=()',
|
|
108
|
+
' return 0',
|
|
109
|
+
' fi',
|
|
110
|
+
' case "${path:-__root__}" in',
|
|
111
|
+
cases,
|
|
112
|
+
' esac',
|
|
113
|
+
'}',
|
|
114
|
+
'complete -F _pxo_completions pxo',
|
|
115
|
+
'',
|
|
116
|
+
].join('\n');
|
|
117
|
+
}
|
|
118
|
+
function zshScript(tree) {
|
|
119
|
+
const entries = flattenPaths(tree);
|
|
120
|
+
const valueFlags = collectValueFlags(tree);
|
|
121
|
+
const validKeys = entries
|
|
122
|
+
.map(({ path }) => path.join(' '))
|
|
123
|
+
.filter(Boolean)
|
|
124
|
+
.map((key) => `'${escapeSingle(key)}'`)
|
|
125
|
+
.join('|');
|
|
126
|
+
const cases = entries
|
|
127
|
+
.map(({ path, words }) => {
|
|
128
|
+
const key = path.join(' ') || '__root__';
|
|
129
|
+
const quoted = words.map((w) => `'${escapeSingle(w)}'`).join(' ');
|
|
130
|
+
return ` "${key}")\n reply=(${quoted})\n ;;`;
|
|
131
|
+
})
|
|
132
|
+
.join('\n');
|
|
133
|
+
const flagPattern = valueFlags.map((flag) => `'${escapeSingle(flag)}'`).join('|');
|
|
134
|
+
return [
|
|
135
|
+
'#compdef pxo',
|
|
136
|
+
'# Zsh completion for pxo',
|
|
137
|
+
'# Load with: eval "$(pxo completion zsh)"',
|
|
138
|
+
'_pxo() {',
|
|
139
|
+
' local -a reply',
|
|
140
|
+
' local path=""',
|
|
141
|
+
' local skip_next=0',
|
|
142
|
+
' local i word candidate',
|
|
143
|
+
' for ((i = 2; i < CURRENT; i++)); do',
|
|
144
|
+
' word="${words[i]}"',
|
|
145
|
+
' if ((skip_next)); then',
|
|
146
|
+
' skip_next=0',
|
|
147
|
+
' continue',
|
|
148
|
+
' fi',
|
|
149
|
+
' case "$word" in',
|
|
150
|
+
...(flagPattern
|
|
151
|
+
? [` ${flagPattern})\n skip_next=1\n continue\n ;;`]
|
|
152
|
+
: []),
|
|
153
|
+
' -*)',
|
|
154
|
+
' continue',
|
|
155
|
+
' ;;',
|
|
156
|
+
' esac',
|
|
157
|
+
' candidate="${path:+$path }$word"',
|
|
158
|
+
' case "$candidate" in',
|
|
159
|
+
...(validKeys ? [` ${validKeys})\n path="$candidate"\n ;;`] : []),
|
|
160
|
+
' esac',
|
|
161
|
+
' done',
|
|
162
|
+
' if ((skip_next)); then',
|
|
163
|
+
' return 0',
|
|
164
|
+
' fi',
|
|
165
|
+
' case "${path:-__root__}" in',
|
|
166
|
+
cases,
|
|
167
|
+
' esac',
|
|
168
|
+
' compadd -a reply',
|
|
169
|
+
'}',
|
|
170
|
+
'compdef _pxo pxo',
|
|
171
|
+
'',
|
|
172
|
+
].join('\n');
|
|
173
|
+
}
|
|
174
|
+
function fishScript(tree) {
|
|
175
|
+
const valueFlags = collectValueFlags(tree);
|
|
176
|
+
const { nodes, transitions } = collectCanonical(tree);
|
|
177
|
+
const grouped = new Map();
|
|
178
|
+
for (const tr of transitions) {
|
|
179
|
+
const bucket = grouped.get(tr.from) ?? [];
|
|
180
|
+
const existing = bucket.find((item) => item.to === tr.to);
|
|
181
|
+
if (existing)
|
|
182
|
+
existing.tokens.push(tr.token);
|
|
183
|
+
else
|
|
184
|
+
bucket.push({ tokens: [tr.token], to: tr.to });
|
|
185
|
+
grouped.set(tr.from, bucket);
|
|
186
|
+
}
|
|
187
|
+
const switchLines = [];
|
|
188
|
+
for (const [from, items] of grouped) {
|
|
189
|
+
const keyExpr = from ? `${from} ` : '';
|
|
190
|
+
for (const item of items) {
|
|
191
|
+
const patterns = item.tokens.map((token) => `'${escapeSingle(keyExpr + token)}'`).join(' ');
|
|
192
|
+
switchLines.push(` case ${patterns}`, ` set path '${escapeSingle(item.to)}'`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const lines = [
|
|
196
|
+
'# Fish completion for pxo',
|
|
197
|
+
'# Load with: pxo completion fish | source',
|
|
198
|
+
'function __pxo_path',
|
|
199
|
+
' set -l tokens (commandline -opc)',
|
|
200
|
+
' set -e tokens[1]',
|
|
201
|
+
' set -l path ""',
|
|
202
|
+
' set -l skip 0',
|
|
203
|
+
' for word in $tokens',
|
|
204
|
+
' if test $skip -eq 1',
|
|
205
|
+
' set skip 0',
|
|
206
|
+
' continue',
|
|
207
|
+
' end',
|
|
208
|
+
' switch $word',
|
|
209
|
+
...(valueFlags.length
|
|
210
|
+
? [
|
|
211
|
+
` case ${valueFlags.map((flag) => `'${escapeSingle(flag)}'`).join(' ')}`,
|
|
212
|
+
' set skip 1',
|
|
213
|
+
' continue',
|
|
214
|
+
]
|
|
215
|
+
: []),
|
|
216
|
+
" case '-*'",
|
|
217
|
+
' continue',
|
|
218
|
+
' end',
|
|
219
|
+
' set -l candidate (test -n "$path"; and echo "$path $word"; or echo "$word")',
|
|
220
|
+
' switch $candidate',
|
|
221
|
+
...switchLines,
|
|
222
|
+
' end',
|
|
223
|
+
' end',
|
|
224
|
+
' if test $skip -eq 1',
|
|
225
|
+
' echo __expect_value__',
|
|
226
|
+
' return',
|
|
227
|
+
' end',
|
|
228
|
+
' if test -z "$path"',
|
|
229
|
+
' echo __root__',
|
|
230
|
+
' else',
|
|
231
|
+
' echo $path',
|
|
232
|
+
' end',
|
|
233
|
+
'end',
|
|
234
|
+
'complete -c pxo -f',
|
|
235
|
+
];
|
|
236
|
+
for (const { path, node } of nodes) {
|
|
237
|
+
const target = path || '__root__';
|
|
238
|
+
const cond = `test (__pxo_path) = "${target}"`;
|
|
239
|
+
for (const sub of node.subcommands) {
|
|
240
|
+
const desc = escapeSingle(sub.description);
|
|
241
|
+
for (const name of sub.names) {
|
|
242
|
+
lines.push(`complete -c pxo -n '${cond}' -a '${escapeSingle(name)}' -d '${desc}'`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
for (const opt of node.options) {
|
|
246
|
+
const desc = escapeSingle(opt.description);
|
|
247
|
+
const parts = [`complete -c pxo -n '${cond}'`];
|
|
248
|
+
if (opt.short)
|
|
249
|
+
parts.push(`-s '${escapeSingle(opt.short.slice(1))}'`);
|
|
250
|
+
if (opt.long)
|
|
251
|
+
parts.push(`-l '${escapeSingle(opt.long.slice(2))}'`);
|
|
252
|
+
if (opt.takesValue)
|
|
253
|
+
parts.push('-r');
|
|
254
|
+
parts.push(`-d '${desc}'`);
|
|
255
|
+
lines.push(parts.join(' '));
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return lines.join('\n') + '\n';
|
|
259
|
+
}
|
|
260
|
+
function powershellScript(tree) {
|
|
261
|
+
const entries = flattenPaths(tree);
|
|
262
|
+
const valueFlags = collectValueFlags(tree);
|
|
263
|
+
const mapLines = entries.map(({ path, words }) => {
|
|
264
|
+
const key = path.join(' ') || '__root__';
|
|
265
|
+
const list = words.map((w) => `'${w.replace(/'/gu, "''")}'`).join(', ');
|
|
266
|
+
return ` '${key}' = @(${list})`;
|
|
267
|
+
});
|
|
268
|
+
const valueFlagList = valueFlags.map((f) => `'${f.replace(/'/gu, "''")}'`).join(', ');
|
|
269
|
+
return [
|
|
270
|
+
'# PowerShell completion for pxo',
|
|
271
|
+
'# Load with: pxo completion powershell | Out-String | Invoke-Expression',
|
|
272
|
+
'Register-ArgumentCompleter -Native -CommandName pxo -ScriptBlock {',
|
|
273
|
+
' param($wordToComplete, $commandAst, $cursorPosition)',
|
|
274
|
+
' $tokens = $commandAst.CommandElements | Select-Object -Skip 1 | ForEach-Object { $_.Extent.Text }',
|
|
275
|
+
` $valueFlags = @(${valueFlagList})`,
|
|
276
|
+
' $table = @{',
|
|
277
|
+
...mapLines,
|
|
278
|
+
' }',
|
|
279
|
+
' $path = ""',
|
|
280
|
+
' $skipNext = $false',
|
|
281
|
+
' foreach ($token in $tokens) {',
|
|
282
|
+
' if ($token -eq $wordToComplete) { break }',
|
|
283
|
+
' if ($skipNext) {',
|
|
284
|
+
' $skipNext = $false',
|
|
285
|
+
' continue',
|
|
286
|
+
' }',
|
|
287
|
+
' if ($valueFlags -contains $token) {',
|
|
288
|
+
' $skipNext = $true',
|
|
289
|
+
' continue',
|
|
290
|
+
' }',
|
|
291
|
+
" if ($token.StartsWith('-')) { continue }",
|
|
292
|
+
' $candidate = if ($path) { "$path $token" } else { $token }',
|
|
293
|
+
' if ($table.ContainsKey($candidate)) { $path = $candidate }',
|
|
294
|
+
' }',
|
|
295
|
+
' if ($skipNext) { return }',
|
|
296
|
+
" $key = if ($path) { $path } else { '__root__' }",
|
|
297
|
+
' if ($table.ContainsKey($key)) {',
|
|
298
|
+
' $table[$key] | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {',
|
|
299
|
+
" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)",
|
|
300
|
+
' }',
|
|
301
|
+
' }',
|
|
302
|
+
'}',
|
|
303
|
+
'',
|
|
304
|
+
].join('\n');
|
|
305
|
+
}
|
|
306
|
+
/** 生成指定 Shell 的自动补全脚本。 */
|
|
307
|
+
export function buildCompletion(program, shell) {
|
|
308
|
+
const tree = collectTree(program);
|
|
309
|
+
if (shell === 'bash')
|
|
310
|
+
return bashScript(tree);
|
|
311
|
+
if (shell === 'zsh')
|
|
312
|
+
return zshScript(tree);
|
|
313
|
+
if (shell === 'fish')
|
|
314
|
+
return fishScript(tree);
|
|
315
|
+
return powershellScript(tree);
|
|
316
|
+
}
|
|
317
|
+
/** 注册 `pxo completion <shell>` 命令。 */
|
|
318
|
+
export function registerCompletion(program) {
|
|
319
|
+
return program
|
|
320
|
+
.command('completion')
|
|
321
|
+
.description('Generate shell completion script')
|
|
322
|
+
.addArgument(new Argument('<shell>', 'Target shell').choices(['bash', 'zsh', 'fish', 'powershell']))
|
|
323
|
+
.addHelpText('after', [
|
|
324
|
+
'',
|
|
325
|
+
'Examples:',
|
|
326
|
+
' eval "$(pxo completion bash)"',
|
|
327
|
+
' eval "$(pxo completion zsh)"',
|
|
328
|
+
' pxo completion fish | source',
|
|
329
|
+
' pxo completion powershell | Out-String | Invoke-Expression',
|
|
330
|
+
].join('\n'))
|
|
331
|
+
.action((shell) => {
|
|
332
|
+
process.stdout.write(buildCompletion(program, shell));
|
|
333
|
+
});
|
|
334
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { configService, instancePaths } from '../../shared/config.js';
|
|
2
|
+
import { databasePath } from '../../shared/paths.js';
|
|
3
|
+
import { formatTable, output } from '../output.js';
|
|
4
|
+
/** 注册 `pxo config` 本地配置查看命令组。 */
|
|
5
|
+
export function registerConfig(program) {
|
|
6
|
+
const config = program
|
|
7
|
+
.command('config')
|
|
8
|
+
.description('Inspect local configuration and paths')
|
|
9
|
+
.addHelpText('after', '\nTo update settings, run `pxo sync init` for GitHub sync or `pxo ai config` for AI providers.');
|
|
10
|
+
config
|
|
11
|
+
.command('show')
|
|
12
|
+
.description('Show current local configuration')
|
|
13
|
+
.option('--json', 'Output JSON')
|
|
14
|
+
.action(({ json }) => {
|
|
15
|
+
const settings = configService(instancePaths(databasePath())).read();
|
|
16
|
+
output(settings, json, () => JSON.stringify(settings, null, 2));
|
|
17
|
+
});
|
|
18
|
+
config
|
|
19
|
+
.command('path')
|
|
20
|
+
.description('Show database, config, and cache locations')
|
|
21
|
+
.option('--json', 'Output JSON')
|
|
22
|
+
.action(({ json }) => {
|
|
23
|
+
const paths = instancePaths(databasePath());
|
|
24
|
+
output(paths, json, () => formatTable(['Key', 'Path'], Object.entries(paths).map(([name, value]) => [name, value])));
|
|
25
|
+
});
|
|
26
|
+
return config;
|
|
27
|
+
}
|