wpops 0.1.1 → 0.3.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/bin/wpops.js CHANGED
@@ -1,14 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from 'node:fs';
3
- import { loadEnv, listSites } from '../lib/env.js';
4
- import { buildConfig, createClient, WpError } from '../lib/client.js';
2
+ import { existsSync, readFileSync, writeFileSync, rmSync, renameSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { loadEnv, listSites, configHome } from '../lib/env.js';
5
+ import { WpError } from '../lib/client.js';
6
+ import { UsageError } from '../lib/errors.js';
5
7
  import { parseArgs, isMutation } from '../lib/args.js';
6
8
  import { installSkill } from '../lib/skill.js';
7
- import * as cmd from '../lib/commands.js';
8
-
9
- function printJson(value) {
10
- console.log(JSON.stringify(value, null, 2));
11
- }
9
+ import { configureOutput } from '../lib/util.js';
10
+ import { runOne } from '../lib/run.js';
11
+ import { generalHelp, groupHelp, commandsJson, usageHint } from '../lib/help.js';
12
+ import { completionWords, groupByName } from '../lib/spec.js';
13
+ import { setup } from '../lib/commands.js';
12
14
 
13
15
  function version() {
14
16
  try {
@@ -18,68 +20,6 @@ function version() {
18
20
  }
19
21
  }
20
22
 
21
- function printHelp() {
22
- console.log(`wpops —— WordPress REST 操作工具
23
-
24
- 用法: wpops [--site 名字 | --all] <组> <动作> [参数] [--flags]
25
-
26
- --version / -v 显示版本
27
-
28
- setup 交互式配置一个站点(写入 sites/<名字>.env 并体检)
29
- doctor 连接与权限体检(先跑这个)
30
- me 当前用户与能力
31
- sites 列出已配置的站点
32
- install-skill 把内置 skill 装到 agent 发现目录
33
-
34
- posts list|get|create|update|delete ...
35
- pages list|get|create|update|delete ...
36
- media list|get|upload|update|delete ...
37
- plugins list|install|activate|deactivate ...
38
- themes list|activate ...
39
- categories list|get|create|update|delete ...
40
- tags list|get|create|update|delete ...
41
- comments list|get|update|delete ...
42
- users list|get|create|update|delete|me ...
43
- raw <METHOD> <path> [--data JSON] 任意端点兜底
44
-
45
- 多站点:
46
- --site <名字> / -s <名字> 对 sites/<名字>.env 执行
47
- --all / -a 对所有已配置站点批量执行(写操作需 --yes)
48
-
49
- 安全:
50
- --dry-run 只预览不执行(写操作)
51
- --yes / -y --all 写操作的确认开关
52
-
53
- 常用参数:
54
- --per-page N · --page N 分页(REST 上限 100)
55
- --status <s> 状态(posts/comments 等)
56
- --search <s> · --orderby <f> · --order <asc|desc>
57
- --categories 1,2 · --tags 3,4 分类/标签 ID(过滤或设置)
58
- --author <id> · --after <日期> · --before <日期>
59
- --title/--content/--from-file 标题/正文
60
- --slug <s> · --excerpt <s> 别名 / 摘要
61
- --featured-media <id> 特色图
62
- --alt <文本> · --caption <文本> 媒体替代文本 / 说明
63
- --name/--parent/--description 分类/标签字段
64
- --username/--email/--role 用户字段
65
- --force 彻底删除 / 危险操作确认
66
- --data <JSON> raw 的请求体
67
- --json 输出原始 JSON
68
-
69
- 示例:
70
- wpops doctor
71
- wpops -s blog-a posts list --per-page 5 --orderby date --order desc
72
- wpops posts list --categories 3,7
73
- wpops posts update 12 --from-file ./post.md --status draft
74
- wpops media update 44 --alt "配图"
75
- wpops categories list
76
- wpops comments list --status hold
77
- wpops --all posts list
78
- wpops --all plugins list
79
- wpops --all posts delete 5 --dry-run
80
- wpops plugins install wp-super-cache --activate`);
81
- }
82
-
83
23
  function printSites() {
84
24
  const sites = listSites();
85
25
  if (!sites.length) {
@@ -100,221 +40,210 @@ function printSites() {
100
40
  }
101
41
  }
102
42
 
103
- async function runOne(site, group, action, rest, flags, showHeader) {
104
- const cfg = buildConfig(loadEnv(site));
105
- const client = createClient(cfg);
43
+ // ------------------------------------------------------------------ sites 管理
44
+
45
+ const SENSITIVE = /PASSWORD|SECRET|TOKEN|KEY/i;
106
46
 
107
- if (showHeader) {
108
- console.log(`\n=== ${site || '(default)'} — ${cfg.url || '(未配置 WP_URL)'} ===`);
47
+ function sitesCommand(action, rest) {
48
+ const dir = join(configHome(), 'sites');
49
+ switch (action) {
50
+ case undefined:
51
+ case 'list':
52
+ return printSites();
53
+ case 'show': {
54
+ const name = rest[0];
55
+ if (!name) throw new Error('sites show 需要站点名');
56
+ const env = loadEnv(name);
57
+ console.log(`站点 ${name}:`);
58
+ for (const [key, value] of Object.entries(env)) {
59
+ console.log(` ${key}=${SENSITIVE.test(key) ? '***' : value}`);
60
+ }
61
+ return;
62
+ }
63
+ case 'rm': {
64
+ const name = rest[0];
65
+ if (!name) throw new Error('sites rm 需要站点名');
66
+ const file = join(dir, `${name}.env`);
67
+ if (!existsSync(file)) throw new Error(`找不到站点配置 ${file}`);
68
+ rmSync(file);
69
+ console.log(`✓ 已删除站点配置 ${name}`);
70
+ return;
71
+ }
72
+ case 'rename': {
73
+ const [from, to] = rest;
74
+ if (!from || !to) throw new Error('sites rename 需要 <旧名> <新名>');
75
+ const src = join(dir, `${from}.env`);
76
+ const dst = join(dir, `${to}.env`);
77
+ if (!existsSync(src)) throw new Error(`找不到站点配置 ${src}`);
78
+ if (existsSync(dst)) throw new Error(`目标已存在 ${dst}`);
79
+ renameSync(src, dst);
80
+ console.log(`✓ 已重命名站点 ${from} → ${to}`);
81
+ return;
82
+ }
83
+ default:
84
+ throw new Error(`sites 未知子命令:${action}(list|show|rm|rename)`);
109
85
  }
86
+ }
110
87
 
111
- const needFirst = (what) => {
112
- const value = rest[0];
113
- if (!value) throw new Error(`${what} 需要一个参数`);
114
- return value;
115
- };
88
+ // ------------------------------------------------------------------ 输出包装
116
89
 
117
- const content = async (type) => {
118
- switch (action) {
119
- case undefined:
120
- case 'list':
121
- return cmd.listContent(client, type, flags);
122
- case 'get':
123
- return cmd.getContent(client, type, needFirst('get'), flags);
124
- case 'create':
125
- case 'new':
126
- return cmd.createContent(client, type, flags);
127
- case 'update':
128
- case 'edit':
129
- return cmd.updateContent(client, type, needFirst('update'), flags);
130
- case 'delete':
131
- case 'rm':
132
- return cmd.deleteContent(client, type, needFirst('delete'), flags);
133
- default:
134
- throw new Error(`${type} 未知子命令:${action}`);
90
+ /** 统一处理 --quiet / --output:抑制或把命令的人类可读输出写入文件。 */
91
+ async function withOutput(flags, fn) {
92
+ const lines = [];
93
+ const originalLog = console.log;
94
+ if (flags.quiet) console.log = () => {};
95
+ else if (flags.output) console.log = (...args) => lines.push(args.join(' '));
96
+ try {
97
+ return await fn();
98
+ } finally {
99
+ console.log = originalLog;
100
+ if (!flags.quiet && flags.output && lines.length) {
101
+ const file = resolve(String(flags.output));
102
+ writeFileSync(file, lines.join('\n') + '\n', 'utf8');
103
+ originalLog(`✓ 输出已写入 ${file}`);
135
104
  }
136
- };
105
+ }
106
+ }
137
107
 
138
- const taxonomy = async (tax) => {
139
- switch (action) {
140
- case undefined:
141
- case 'list':
142
- return cmd.listTaxonomy(client, tax, flags);
143
- case 'get':
144
- return cmd.getTaxonomy(client, tax, needFirst('get'));
145
- case 'create':
146
- case 'new':
147
- return cmd.createTaxonomy(client, tax, flags);
148
- case 'update':
149
- case 'edit':
150
- return cmd.updateTaxonomy(client, tax, needFirst('update'), flags);
151
- case 'delete':
152
- case 'rm':
153
- return cmd.deleteTaxonomy(client, tax, needFirst('delete'), flags);
154
- default:
155
- throw new Error(`${tax} 未知子命令:${action}`);
156
- }
157
- };
108
+ // ------------------------------------------------------------------ 用法错误
158
109
 
159
- switch (group) {
160
- case 'doctor':
161
- return cmd.doctor(client, cfg, flags);
162
- case 'me':
163
- return cmd.me(client, flags);
164
- case 'posts':
165
- case 'post':
166
- return content('posts');
167
- case 'pages':
168
- case 'page':
169
- return content('pages');
170
- case 'media':
171
- switch (action) {
172
- case undefined:
173
- case 'list':
174
- return cmd.listMedia(client, flags);
175
- case 'get':
176
- return cmd.getMedia(client, needFirst('get'), flags);
177
- case 'upload':
178
- return cmd.uploadMedia(client, needFirst('upload 需要文件路径'), flags);
179
- case 'update':
180
- case 'edit':
181
- return cmd.updateMedia(client, needFirst('update'), flags);
182
- case 'delete':
183
- case 'rm':
184
- return cmd.deleteMedia(client, needFirst('delete'), flags);
185
- default:
186
- throw new Error(`media 未知子命令:${action}`);
187
- }
188
- case 'plugins':
189
- case 'plugin':
190
- switch (action) {
191
- case undefined:
192
- case 'list':
193
- return cmd.listPlugins(client, flags);
194
- case 'install':
195
- if (!rest[0]) {
196
- throw new Error('plugins install 需要 wordpress.org 插件别名,例如 wpops plugins install akismet');
197
- }
198
- return cmd.installPlugin(client, rest[0], flags);
199
- case 'activate':
200
- return cmd.setPluginStatus(client, needFirst('activate'), true, flags);
201
- case 'deactivate':
202
- return cmd.setPluginStatus(client, needFirst('deactivate'), false, flags);
203
- default:
204
- throw new Error(`plugins 未知子命令:${action}`);
205
- }
206
- case 'themes':
207
- case 'theme':
208
- switch (action) {
209
- case undefined:
210
- case 'list':
211
- return cmd.listThemes(client, flags);
212
- case 'activate':
213
- case 'switch':
214
- return cmd.activateTheme(client, needFirst('activate'), flags);
215
- default:
216
- throw new Error(`themes 未知子命令:${action}`);
217
- }
218
- case 'categories':
219
- case 'category':
220
- return taxonomy('categories');
221
- case 'tags':
222
- case 'tag':
223
- return taxonomy('tags');
224
- case 'comments':
225
- case 'comment':
226
- switch (action) {
227
- case undefined:
228
- case 'list':
229
- return cmd.listComments(client, flags);
230
- case 'get':
231
- return cmd.getComment(client, needFirst('get'));
232
- case 'update':
233
- case 'edit':
234
- return cmd.updateComment(client, needFirst('update'), flags);
235
- case 'delete':
236
- case 'rm':
237
- return cmd.deleteComment(client, needFirst('delete'), flags);
238
- default:
239
- throw new Error(`comments 未知子命令:${action}`);
240
- }
241
- case 'users':
242
- case 'user':
243
- switch (action) {
244
- case undefined:
245
- case 'list':
246
- return cmd.listUsers(client, flags);
247
- case 'me':
248
- return cmd.me(client, flags);
249
- case 'get':
250
- return cmd.getUser(client, needFirst('get'));
251
- case 'create':
252
- case 'new':
253
- return cmd.createUser(client, flags);
254
- case 'update':
255
- case 'edit':
256
- return cmd.updateUser(client, needFirst('update'), flags);
257
- case 'delete':
258
- case 'rm':
259
- return cmd.deleteUser(client, needFirst('delete'), flags);
260
- default:
261
- throw new Error(`users 未知子命令:${action}`);
262
- }
263
- case 'raw':
264
- if (!action || !rest[0]) throw new Error('raw 用法:wpops raw <METHOD> <path> [--data JSON]');
265
- return cmd.raw(client, action, rest[0], flags);
110
+ /** 用法错误:stderr 打印「消息 + 精简用法 + --help 提示」,退出码 2(与运行期错误的 1 区分)。 */
111
+ function reportUsageError(err, group, action) {
112
+ console.error(`✗ ${err.message}`);
113
+ const lines = usageHint(group, action);
114
+ if (lines.length) {
115
+ console.error('用法:');
116
+ for (const line of lines) console.error(` ${line}`);
117
+ }
118
+ if (group && groupByName(group)) {
119
+ console.error(`提示:wpops ${group} --help 查看完整用法`);
120
+ } else {
121
+ console.error('提示:wpops help 查看全部命令');
122
+ }
123
+ process.exitCode = 2;
124
+ }
125
+
126
+ // ------------------------------------------------------------------ completion
127
+
128
+ function printCompletion(shell) {
129
+ const words = completionWords(['help']).join(' ');
130
+ switch (shell || 'bash') {
131
+ case 'bash':
132
+ console.log(`# wpops bash completion(用法:eval "$(wpops completion bash)")\n_wpops() {\n local cur="\${COMP_WORDS[COMP_CWORD]}"\n COMPREPLY=( $(compgen -W "${words}" -- "$cur") )\n}\ncomplete -F _wpops wpops`);
133
+ return;
134
+ case 'zsh':
135
+ console.log(`# wpops zsh completion(用法:eval "$(wpops completion zsh)")\n_wpops() { compadd ${words} }\ncompdef _wpops wpops`);
136
+ return;
137
+ case 'fish':
138
+ console.log(`# wpops fish completion(用法:wpops completion fish | source)\ncomplete -c wpops -f -a "${words}"`);
139
+ return;
140
+ case 'powershell':
141
+ console.log(`# wpops PowerShell completion(用法:wpops completion powershell | Out-String | Invoke-Expression)\nRegister-ArgumentCompleter -Native -CommandName wpops -ScriptBlock {\n param($wordToComplete)\n "${words}".Split(' ') | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }\n}`);
142
+ return;
266
143
  default:
267
- throw new Error(`未知命令:${group}(运行 wpops help 查看用法)`);
144
+ throw new Error('completion 支持:bash|zsh|fish|powershell');
268
145
  }
269
146
  }
270
147
 
148
+ // ------------------------------------------------------------------ main
149
+
271
150
  async function main() {
272
151
  const { positionals, flags } = parseArgs(process.argv.slice(2));
273
152
  const [group, action, ...rest] = positionals;
274
153
 
154
+ configureOutput(flags);
155
+ if (flags.paginate) flags['all-pages'] = true;
156
+ if (flags.csv || flags.table || flags.fields) flags.json = true;
157
+
275
158
  if (flags.version) {
276
159
  console.log(version());
277
160
  return;
278
161
  }
162
+
163
+ // help:wpops / wpops help [组] [动作] / wpops <组> [动作] --help
279
164
  if (!group || group === 'help' || flags.help) {
280
- printHelp();
165
+ const helpGroup = group === 'help' ? action : group;
166
+ const helpAction = group === 'help' ? rest[0] : action;
167
+ if (helpGroup) {
168
+ const text = groupHelp(helpGroup, helpAction);
169
+ if (!text) {
170
+ console.error(`未知命令组:${helpGroup}(运行 wpops help 查看全部)`);
171
+ process.exitCode = 1;
172
+ return;
173
+ }
174
+ console.log(text);
175
+ return;
176
+ }
177
+ console.log(generalHelp(version()));
281
178
  return;
282
179
  }
180
+
283
181
  if (group === 'sites') {
284
- printSites();
182
+ await withOutput(flags, () => sitesCommand(action, rest));
285
183
  return;
286
184
  }
287
185
  if (group === 'setup') {
288
- await cmd.setup(flags);
186
+ await setup(flags);
289
187
  return;
290
188
  }
291
189
  if (group === 'install-skill') {
292
- const dirs = installSkill();
293
- if (!dirs.length) {
294
- console.log('未安装 skill(可能已存在同名目录被跳过,或用 WPOPS_SKIP_SKILL 禁用)。');
295
- } else {
296
- for (const dir of dirs) console.log(`✓ skill 已安装到 ${dir}`);
297
- }
190
+ await withOutput(flags, () => {
191
+ const dirs = installSkill();
192
+ if (!dirs.length) {
193
+ console.log('未安装 skill(可能已存在同名目录被跳过,或用 WPOPS_SKIP_SKILL 禁用)。');
194
+ } else {
195
+ for (const dir of dirs) console.log(`✓ skill 已安装到 ${dir}`);
196
+ }
197
+ });
198
+ return;
199
+ }
200
+ if (group === 'completion') {
201
+ await withOutput(flags, () => printCompletion(action));
298
202
  return;
299
203
  }
204
+ if (group === 'commands') {
205
+ await withOutput(flags, () => console.log(commandsJson(version())));
206
+ return;
207
+ }
208
+
209
+ const single = flags.site || process.env.WPOPS_SITE || null;
210
+ const named = flags.site && String(flags.site).includes(',')
211
+ ? String(flags.site).split(',').map((s) => s.trim()).filter(Boolean)
212
+ : [];
300
213
 
301
- const site = flags.site || process.env.WPOPS_SITE || null;
302
- const mutating = isMutation(group, action);
214
+ let targets = null;
215
+ if (flags.all) targets = listSites();
216
+ else if (named.length) targets = named.map((name) => ({ name, label: name }));
303
217
 
304
- if (flags.all) {
305
- const targets = listSites();
218
+ if (targets) {
306
219
  if (!targets.length) throw new Error('还没有配置任何站点');
307
- if (mutating && !flags.yes && !flags['dry-run']) {
308
- throw new Error('--all 会作用于所有站点。写操作请加 --yes 确认,或先用 --dry-run 预览。');
220
+ if (isMutation(group, action) && !flags.yes && !flags['dry-run']) {
221
+ reportUsageError(
222
+ new UsageError('批量执行会作用于多个站点。写操作请加 --yes 确认,或先用 --dry-run 预览。', { group, action }),
223
+ group,
224
+ action,
225
+ );
226
+ return;
309
227
  }
310
228
  let failures = 0;
311
- for (const target of targets) {
312
- try {
313
- await runOne(target.name, group, action, rest, flags, true);
314
- } catch (err) {
315
- failures++;
316
- console.error(`✗ [${target.label}] ${err.message}`);
229
+ let usageError = null;
230
+ await withOutput(flags, async () => {
231
+ for (const target of targets) {
232
+ try {
233
+ await runOne(target.name, group, action, rest, flags, true);
234
+ } catch (err) {
235
+ if (err instanceof UsageError) {
236
+ usageError = err; // 用法与站点无关:立即中止,不逐站重复
237
+ return;
238
+ }
239
+ failures++;
240
+ console.error(`✗ [${target.label}] ${err.message}`);
241
+ }
317
242
  }
243
+ });
244
+ if (usageError) {
245
+ reportUsageError(usageError, usageError.group || group, usageError.action ?? action);
246
+ return;
318
247
  }
319
248
  if (failures) {
320
249
  console.error(`\n完成:${failures}/${targets.length} 个站点出错。`);
@@ -323,10 +252,23 @@ async function main() {
323
252
  return;
324
253
  }
325
254
 
326
- await runOne(site, group, action, rest, flags, false);
255
+ try {
256
+ await withOutput(flags, () => runOne(single, group, action, rest, flags, false));
257
+ } catch (err) {
258
+ if (err instanceof UsageError) {
259
+ reportUsageError(err, err.group || group, err.action ?? action);
260
+ return;
261
+ }
262
+ throw err;
263
+ }
327
264
  }
328
265
 
329
266
  main().catch((err) => {
267
+ if (err instanceof UsageError) {
268
+ console.error(`✗ ${err.message}`);
269
+ console.error('提示:wpops help 查看全部命令');
270
+ process.exit(2);
271
+ }
330
272
  if (err instanceof WpError) {
331
273
  console.error(`✗ ${err.message}`);
332
274
  if (err.code) console.error(` 代码:${err.code}`);
@@ -0,0 +1,51 @@
1
+ // Abilities API 命令(/wp-json/wp-abilities/v1/abilities)。
2
+ // 需要站点安装并启用 Abilities API 插件。
3
+ import { printJson, dry, parseJson } from './util.js';
4
+
5
+ const ABILITIES = '/wp-json/wp-abilities/v1/abilities';
6
+
7
+ /** 端点可能返回数组、{ abilities: [...] } 或按名字索引的对象,统一成数组。 */
8
+ function asList(data) {
9
+ if (Array.isArray(data)) return data;
10
+ if (Array.isArray(data?.abilities)) return data.abilities;
11
+ if (data && typeof data === 'object') return Object.values(data);
12
+ return [];
13
+ }
14
+
15
+ /** 列表:GET /abilities。字段可能缺失,逐项容错。 */
16
+ export async function listAbilities(client, flags) {
17
+ const { data } = await client.request('GET', ABILITIES);
18
+ if (flags.json) return printJson(data);
19
+ const items = asList(data);
20
+ console.log(`Abilities ${items.length} 个:`);
21
+ for (const item of items) {
22
+ const name = item?.name ?? item?.id ?? '?';
23
+ const label = item?.label ?? '';
24
+ const description = item?.description ?? '';
25
+ console.log(` ${name} ${label} ${description}`);
26
+ }
27
+ }
28
+
29
+ /** 详情:GET /abilities/{name}。 */
30
+ export async function getAbility(client, name, flags) {
31
+ const { data } = await client.request('GET', `${ABILITIES}/${encodeURIComponent(name)}`);
32
+ if (flags.json) return printJson(data);
33
+ console.log(`${data?.name ?? name} ${data?.label ?? ''}`);
34
+ if (data?.description) console.log(` 描述:${data.description}`);
35
+ if (data?.input_schema) console.log(` 输入:${JSON.stringify(data.input_schema)}`);
36
+ if (data?.output_schema) console.log(` 输出:${JSON.stringify(data.output_schema)}`);
37
+ }
38
+
39
+ /**
40
+ * 运行:POST /abilities/{name}/run。
41
+ * body 来自 --input 或 --data(JSON 字符串),都没有则 {}。
42
+ */
43
+ export async function runAbility(client, name, flags) {
44
+ const raw = flags.input !== undefined ? flags.input : flags.data;
45
+ const body = raw !== undefined ? parseJson(raw) : {};
46
+ if (flags['dry-run']) return dry(`运行 Ability ${name} ${JSON.stringify(body)}`);
47
+ const { data } = await client.request('POST', `${ABILITIES}/${encodeURIComponent(name)}/run`, { body });
48
+ if (flags.json) return printJson(data);
49
+ console.log(`✓ 已运行 ${name}`);
50
+ console.log(JSON.stringify(data, null, 2));
51
+ }
@@ -0,0 +1,39 @@
1
+ // 用户应用密码(/wp-json/wp/v2/users/<user|me>/application-passwords)。
2
+ // 创建是唯一会返回明文 password 的接口,该字段只在此处打印一次。
3
+ import { printJson, dry } from './util.js';
4
+ import { UsageError } from './errors.js';
5
+
6
+ function appPasswordsPath(user) {
7
+ return `/wp-json/wp/v2/users/${user || 'me'}/application-passwords`;
8
+ }
9
+
10
+ export async function listAppPasswords(client, user, flags) {
11
+ const base = appPasswordsPath(user);
12
+ const { data } = await client.request('GET', base);
13
+ if (flags.json) return printJson(data);
14
+ console.log(`应用密码 ${data.length} 个:`);
15
+ for (const p of data) {
16
+ console.log(` ${p.uuid} ${p.name} ${p.last_used ?? '—'} ${p.created ?? '—'}`);
17
+ }
18
+ }
19
+
20
+ export async function createAppPassword(client, user, flags) {
21
+ if (flags.name === undefined) throw new UsageError('创建应用密码需要 --name');
22
+ const body = { name: String(flags.name) };
23
+ if (flags['app-id'] !== undefined) body.app_id = String(flags['app-id']);
24
+ const base = appPasswordsPath(user);
25
+ if (flags['dry-run']) return dry(`创建应用密码 ${body.name}`);
26
+ const { data } = await client.request('POST', base, { body });
27
+ if (flags.json) return printJson(data);
28
+ console.log(`${data.uuid} ${data.name}`);
29
+ console.log(`password: ${data.password}`);
30
+ }
31
+
32
+ export async function deleteAppPassword(client, user, uuid, flags) {
33
+ const base = appPasswordsPath(user);
34
+ if (flags['dry-run']) return dry(`删除应用密码 ${uuid}`);
35
+ if (!flags.force) throw new UsageError('删除应用密码需要 --force(不可撤销)');
36
+ const { data } = await client.request('DELETE', `${base}/${uuid}`);
37
+ if (flags.json) return printJson(data);
38
+ console.log(data.deleted ? `✓ 已删除应用密码 ${uuid}` : `? 应用密码 ${uuid} 未删除`);
39
+ }
package/lib/args.js CHANGED
@@ -1,5 +1,8 @@
1
1
  // 已知的布尔开关:遇到它们不吞下一个参数,避免 `--json -s a` 把 -s 当值。
2
- const BOOLEAN_FLAGS = new Set(['json', 'force', 'activate', 'dry-run', 'yes', 'all', 'help', 'version']);
2
+ const BOOLEAN_FLAGS = new Set([
3
+ 'json', 'force', 'activate', 'dry-run', 'yes', 'all', 'help', 'version',
4
+ 'csv', 'table', 'quiet', 'verbose', 'all-pages', 'paginate', 'auto-add',
5
+ ]);
3
6
 
4
7
  /** 解析命令行。支持 --flag value、--flag=value、布尔 --flag、以及 -s/-a/-h/-y。 */
5
8
  export function parseArgs(argv) {
@@ -53,37 +56,5 @@ export function parseArgs(argv) {
53
56
  return { positionals, flags };
54
57
  }
55
58
 
56
- const CONTENT_MUTATIONS = new Set(['create', 'new', 'update', 'edit', 'delete', 'rm']);
57
-
58
- /** 判断命令是否会修改站点数据(用于 --all 护栏与 --dry-run 提示)。 */
59
- export function isMutation(group, action) {
60
- const act = action || '';
61
- switch (group) {
62
- case 'posts':
63
- case 'post':
64
- case 'pages':
65
- case 'page':
66
- case 'categories':
67
- case 'category':
68
- case 'tags':
69
- case 'tag':
70
- return CONTENT_MUTATIONS.has(act);
71
- case 'media':
72
- return ['upload', 'update', 'edit', 'delete', 'rm'].includes(act);
73
- case 'plugins':
74
- case 'plugin':
75
- return ['install', 'activate', 'deactivate'].includes(act);
76
- case 'themes':
77
- case 'theme':
78
- return ['activate', 'switch'].includes(act);
79
- case 'comments':
80
- case 'comment':
81
- return ['update', 'edit', 'delete', 'rm'].includes(act);
82
- case 'users':
83
- return ['create', 'update', 'edit', 'delete', 'rm'].includes(act);
84
- case 'raw':
85
- return !['GET', 'HEAD', 'OPTIONS'].includes(act.toUpperCase());
86
- default:
87
- return false;
88
- }
89
- }
59
+ // 写操作判定统一来自 lib/spec.js(单一事实来源),这里只做转发。
60
+ export { isMutation, groupByName } from './spec.js';