ylcwf 0.0.0-stage → 0.2.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/CHANGELOG.md +115 -0
- package/LICENSE +21 -0
- package/README.md +375 -2
- package/dist/index.js +4211 -0
- package/index.js +3 -0
- package/package.json +132 -4
- package/ui-dist/assets/index-BMzLPxJZ.css +2 -0
- package/ui-dist/assets/index-Duh_DcAy.js +80 -0
- package/ui-dist/favicon.svg +57 -0
- package/ui-dist/index.html +15 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,4211 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import { appendFileSync, chmodSync, closeSync, copyFileSync, existsSync as external_node_fs_existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
3
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
4
|
+
import { basename, dirname, extname, isAbsolute, join as external_node_path_join, resolve, sep } from "node:path";
|
|
5
|
+
import { isMap, isSeq, parseDocument } from "yaml";
|
|
6
|
+
import { homedir, tmpdir as external_node_os_tmpdir } from "node:os";
|
|
7
|
+
import picocolors from "picocolors";
|
|
8
|
+
import { randomBytes } from "node:crypto";
|
|
9
|
+
import { createServer } from "node:net";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { createServer as external_node_http_createServer } from "node:http";
|
|
12
|
+
import * as __rspack_external__clack_prompts_d2d5c36d from "@clack/prompts";
|
|
13
|
+
const errors_EXIT = {
|
|
14
|
+
OK: 0,
|
|
15
|
+
INVALID: 1,
|
|
16
|
+
USAGE: 2,
|
|
17
|
+
NOT_FOUND: 3
|
|
18
|
+
};
|
|
19
|
+
class errors_CliError extends Error {
|
|
20
|
+
exitCode;
|
|
21
|
+
constructor(message, exitCode){
|
|
22
|
+
super(message);
|
|
23
|
+
this.name = 'CliError';
|
|
24
|
+
this.exitCode = exitCode;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function printJson(value) {
|
|
28
|
+
writeFileSync(process.stdout.fd, `${JSON.stringify(value, null, 2)}\n`);
|
|
29
|
+
}
|
|
30
|
+
function printLine(text = '') {
|
|
31
|
+
writeFileSync(process.stdout.fd, `${text}\n`);
|
|
32
|
+
}
|
|
33
|
+
function printError(text) {
|
|
34
|
+
writeFileSync(process.stderr.fd, `${text}\n`);
|
|
35
|
+
}
|
|
36
|
+
const CONFIG_DIR = external_node_path_join(homedir(), '.ylcwf');
|
|
37
|
+
const DEFAULT_CONFIG_PATH = external_node_path_join(CONFIG_DIR, 'config.yaml');
|
|
38
|
+
function paths_resolveConfigPath(explicit) {
|
|
39
|
+
const fromFlag = explicit?.trim();
|
|
40
|
+
if (void 0 !== fromFlag && fromFlag.length > 0) return isAbsolute(fromFlag) ? fromFlag : resolve(process.cwd(), fromFlag);
|
|
41
|
+
const fromEnv = process.env['YLCWF_CONFIG']?.trim();
|
|
42
|
+
if (void 0 !== fromEnv && fromEnv.length > 0) return isAbsolute(fromEnv) ? fromEnv : resolve(process.cwd(), fromEnv);
|
|
43
|
+
return DEFAULT_CONFIG_PATH;
|
|
44
|
+
}
|
|
45
|
+
function serveTokenPath() {
|
|
46
|
+
return external_node_path_join(CONFIG_DIR, 'serve.token');
|
|
47
|
+
}
|
|
48
|
+
function historyPath() {
|
|
49
|
+
return external_node_path_join(CONFIG_DIR, 'history', 'task-actions.jsonl');
|
|
50
|
+
}
|
|
51
|
+
const DEFAULT_DOCS_REMOTE = 'https://code.seevin.com/tools/iteration-task-repo';
|
|
52
|
+
function managedReposDir() {
|
|
53
|
+
return external_node_path_join(CONFIG_DIR, 'repos');
|
|
54
|
+
}
|
|
55
|
+
function backupsDir(configPath) {
|
|
56
|
+
return external_node_path_join(dirname(configPath), 'backups');
|
|
57
|
+
}
|
|
58
|
+
const DASH_PATTERN = /[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D_-]+/g;
|
|
59
|
+
function normalizeName(input) {
|
|
60
|
+
return input.normalize('NFKC').replace(/\s+/g, '').replace(DASH_PATTERN, '-').replace(/^-+/, '').replace(/-+$/, '').toLowerCase();
|
|
61
|
+
}
|
|
62
|
+
function editDistance(a, b) {
|
|
63
|
+
if (a === b) return 0;
|
|
64
|
+
if (0 === a.length) return b.length;
|
|
65
|
+
if (0 === b.length) return a.length;
|
|
66
|
+
let previous = Array.from({
|
|
67
|
+
length: b.length + 1
|
|
68
|
+
}, (_, index)=>index);
|
|
69
|
+
for(let i = 1; i <= a.length; i += 1){
|
|
70
|
+
const current = [
|
|
71
|
+
i
|
|
72
|
+
];
|
|
73
|
+
for(let j = 1; j <= b.length; j += 1){
|
|
74
|
+
const cost = a.charAt(i - 1) === b.charAt(j - 1) ? 0 : 1;
|
|
75
|
+
const deletion = (previous[j] ?? 0) + 1;
|
|
76
|
+
const insertion = (current[j - 1] ?? 0) + 1;
|
|
77
|
+
const substitution = (previous[j - 1] ?? 0) + cost;
|
|
78
|
+
current[j] = Math.min(deletion, insertion, substitution);
|
|
79
|
+
}
|
|
80
|
+
previous = current;
|
|
81
|
+
}
|
|
82
|
+
return previous[b.length] ?? 0;
|
|
83
|
+
}
|
|
84
|
+
function utils_isRecord(value) {
|
|
85
|
+
return 'object' == typeof value && null !== value && !Array.isArray(value);
|
|
86
|
+
}
|
|
87
|
+
function isStringArray(value) {
|
|
88
|
+
return Array.isArray(value) && value.every((item)=>'string' == typeof item);
|
|
89
|
+
}
|
|
90
|
+
function parsePathList(input) {
|
|
91
|
+
return input.split(/[,,;;]/).map((item)=>item.trim()).filter((item)=>item.length > 0);
|
|
92
|
+
}
|
|
93
|
+
const ROLES = [
|
|
94
|
+
'frontend',
|
|
95
|
+
'backend',
|
|
96
|
+
'fullstack'
|
|
97
|
+
];
|
|
98
|
+
const SIDES = [
|
|
99
|
+
'frontend',
|
|
100
|
+
'backend'
|
|
101
|
+
];
|
|
102
|
+
const MODES = [
|
|
103
|
+
'developer',
|
|
104
|
+
'stakeholder'
|
|
105
|
+
];
|
|
106
|
+
const TOP_LEVEL_KEYS = new Set([
|
|
107
|
+
'profile',
|
|
108
|
+
'docs',
|
|
109
|
+
'terminals'
|
|
110
|
+
]);
|
|
111
|
+
const PROFILE_KEYS = new Set([
|
|
112
|
+
'developer',
|
|
113
|
+
'role',
|
|
114
|
+
'mode'
|
|
115
|
+
]);
|
|
116
|
+
const DOCS_KEYS = new Set([
|
|
117
|
+
'root',
|
|
118
|
+
'remote'
|
|
119
|
+
]);
|
|
120
|
+
const TERMINAL_KEYS = new Set([
|
|
121
|
+
'aliases',
|
|
122
|
+
'repos'
|
|
123
|
+
]);
|
|
124
|
+
const REPO_KEYS = new Set(SIDES);
|
|
125
|
+
const DEVELOPER_PATTERN = /^[a-z][a-z0-9]*$/;
|
|
126
|
+
function isRole(value) {
|
|
127
|
+
return 'string' == typeof value && ROLES.some((role)=>role === value);
|
|
128
|
+
}
|
|
129
|
+
function isMode(value) {
|
|
130
|
+
return 'string' == typeof value && MODES.some((mode)=>mode === value);
|
|
131
|
+
}
|
|
132
|
+
function schema_error(code, message, where) {
|
|
133
|
+
return {
|
|
134
|
+
level: 'error',
|
|
135
|
+
code,
|
|
136
|
+
message,
|
|
137
|
+
...void 0 === where ? {} : {
|
|
138
|
+
where
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
function warning(code, message, where) {
|
|
143
|
+
return {
|
|
144
|
+
level: 'warning',
|
|
145
|
+
code,
|
|
146
|
+
message,
|
|
147
|
+
...void 0 === where ? {} : {
|
|
148
|
+
where
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function unknownKeys(value, allowed, where) {
|
|
153
|
+
return Object.keys(value).filter((key)=>!allowed.has(key)).map((key)=>schema_error('UNKNOWN_KEY', `未知字段「${key}」,允许的字段为:${[
|
|
154
|
+
...allowed
|
|
155
|
+
].join(', ')}`, where));
|
|
156
|
+
}
|
|
157
|
+
function checkAbsolutePath(value, where, issues, required) {
|
|
158
|
+
if (null === value) {
|
|
159
|
+
if (required) issues.push(schema_error('FIELD_REQUIRED', '该字段不能为空', where));
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
if ('string' != typeof value || 0 === value.trim().length) {
|
|
163
|
+
issues.push(schema_error('FIELD_TYPE', '必须是绝对路径字符串', where));
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
if (!isAbsolute(value)) {
|
|
167
|
+
issues.push(schema_error('PATH_NOT_ABSOLUTE', `必须是绝对路径:${value}`, where));
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
return value;
|
|
171
|
+
}
|
|
172
|
+
function parseProfile(raw, options, issues) {
|
|
173
|
+
if (!utils_isRecord(raw)) {
|
|
174
|
+
issues.push(schema_error('PROFILE_TYPE', 'profile 必须是对象', 'profile'));
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
issues.push(...unknownKeys(raw, PROFILE_KEYS, 'profile'));
|
|
178
|
+
const incomplete = true === options.allowIncomplete;
|
|
179
|
+
let valid = true;
|
|
180
|
+
const modeRaw = raw['mode'];
|
|
181
|
+
let mode = 'developer';
|
|
182
|
+
if (void 0 !== modeRaw) if (isMode(modeRaw)) mode = modeRaw;
|
|
183
|
+
else {
|
|
184
|
+
issues.push(schema_error('MODE_INVALID', `使用模式必须是 ${MODES.join(' / ')} 之一:${String(modeRaw)}`, 'profile.mode'));
|
|
185
|
+
valid = false;
|
|
186
|
+
}
|
|
187
|
+
const developerRequired = 'developer' === mode;
|
|
188
|
+
const developerRaw = raw['developer'];
|
|
189
|
+
let developer = '';
|
|
190
|
+
if (void 0 === developerRaw || 'string' == typeof developerRaw && '' === developerRaw.trim()) {
|
|
191
|
+
if (!incomplete && developerRequired) {
|
|
192
|
+
issues.push(schema_error('FIELD_REQUIRED', 'profile.developer 未配置(干系人可不填)', 'profile.developer'));
|
|
193
|
+
valid = false;
|
|
194
|
+
}
|
|
195
|
+
} else if ('string' == typeof developerRaw && DEVELOPER_PATTERN.test(developerRaw)) developer = developerRaw;
|
|
196
|
+
else {
|
|
197
|
+
issues.push(schema_error('DEVELOPER_INVALID', `开发者标识必须是小写字母开头的字母数字串:${String(developerRaw)}`, 'profile.developer'));
|
|
198
|
+
valid = false;
|
|
199
|
+
}
|
|
200
|
+
const roleRaw = raw['role'];
|
|
201
|
+
let role = 'frontend';
|
|
202
|
+
if (void 0 === roleRaw) {
|
|
203
|
+
if (!incomplete && developerRequired) {
|
|
204
|
+
issues.push(schema_error('FIELD_REQUIRED', 'profile.role 未配置', 'profile.role'));
|
|
205
|
+
valid = false;
|
|
206
|
+
}
|
|
207
|
+
} else if (isRole(roleRaw)) role = roleRaw;
|
|
208
|
+
else {
|
|
209
|
+
issues.push(schema_error('ROLE_INVALID', `角色必须是 ${ROLES.join(' / ')} 之一:${String(roleRaw)}`, 'profile.role'));
|
|
210
|
+
valid = false;
|
|
211
|
+
}
|
|
212
|
+
if (!valid) return null;
|
|
213
|
+
return {
|
|
214
|
+
developer,
|
|
215
|
+
role,
|
|
216
|
+
mode
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
function parseDocs(raw, options, issues) {
|
|
220
|
+
if (!utils_isRecord(raw)) {
|
|
221
|
+
issues.push(schema_error('DOCS_TYPE', 'docs 必须是对象', 'docs'));
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
issues.push(...unknownKeys(raw, DOCS_KEYS, 'docs'));
|
|
225
|
+
let root = '';
|
|
226
|
+
const rootRaw = raw['root'];
|
|
227
|
+
if (void 0 === rootRaw || 'string' == typeof rootRaw && '' === rootRaw.trim()) {
|
|
228
|
+
if (true !== options.allowIncomplete) {
|
|
229
|
+
issues.push(schema_error('FIELD_REQUIRED', 'docs.root 未配置', 'docs.root'));
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
} else {
|
|
233
|
+
const parsed = checkAbsolutePath(rootRaw, 'docs.root', issues, true);
|
|
234
|
+
if (null === parsed) return null;
|
|
235
|
+
root = parsed;
|
|
236
|
+
}
|
|
237
|
+
let remote = null;
|
|
238
|
+
const remoteRaw = raw['remote'];
|
|
239
|
+
if (null != remoteRaw) {
|
|
240
|
+
if ('string' != typeof remoteRaw || 0 === remoteRaw.trim().length) {
|
|
241
|
+
issues.push(schema_error('REMOTE_INVALID', 'docs.remote 必须是非空字符串', 'docs.remote'));
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
const trimmed = remoteRaw.trim();
|
|
245
|
+
const looksLikeGit = /^(https?:\/\/|ssh:\/\/|git@)/.test(trimmed);
|
|
246
|
+
if (!looksLikeGit) {
|
|
247
|
+
issues.push(schema_error('REMOTE_INVALID', `docs.remote 不是合法的仓库地址:${trimmed}`, 'docs.remote'));
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
remote = trimmed;
|
|
251
|
+
}
|
|
252
|
+
return {
|
|
253
|
+
root,
|
|
254
|
+
remote
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
function parseRepos(raw, where, issues) {
|
|
258
|
+
if (!utils_isRecord(raw)) {
|
|
259
|
+
issues.push(schema_error('REPOS_TYPE', 'repos 必须是对象', where));
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
issues.push(...unknownKeys(raw, REPO_KEYS, where));
|
|
263
|
+
const repos = {
|
|
264
|
+
frontend: [],
|
|
265
|
+
backend: []
|
|
266
|
+
};
|
|
267
|
+
let valid = true;
|
|
268
|
+
for (const side of SIDES){
|
|
269
|
+
const value = raw[side];
|
|
270
|
+
const whereSide = `${where}.${side}`;
|
|
271
|
+
if (null == value) continue;
|
|
272
|
+
if (!Array.isArray(value)) {
|
|
273
|
+
issues.push(schema_error('REPOS_NOT_ARRAY', '该端仓库必须是路径数组,例如 ["/path/to/repo"]', whereSide));
|
|
274
|
+
valid = false;
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
const seen = new Set();
|
|
278
|
+
for (const item of value){
|
|
279
|
+
if ('string' != typeof item || 0 === item.trim().length) {
|
|
280
|
+
issues.push(schema_error('REPO_PATH_TYPE', '仓库路径必须是非空字符串', whereSide));
|
|
281
|
+
valid = false;
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
if (!isAbsolute(item)) {
|
|
285
|
+
issues.push(schema_error('PATH_NOT_ABSOLUTE', `仓库路径必须是绝对路径:${item}`, whereSide));
|
|
286
|
+
valid = false;
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
if (seen.has(item)) {
|
|
290
|
+
issues.push(schema_error('REPO_DUPLICATE', `同一端存在重复仓库路径:${item}`, whereSide));
|
|
291
|
+
valid = false;
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
seen.add(item);
|
|
295
|
+
repos[side].push(item);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return valid ? repos : null;
|
|
299
|
+
}
|
|
300
|
+
function parseTerminals(raw, issues) {
|
|
301
|
+
if (!utils_isRecord(raw)) {
|
|
302
|
+
issues.push(schema_error('TERMINALS_TYPE', 'terminals 必须是对象', 'terminals'));
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
const terminals = {};
|
|
306
|
+
let valid = true;
|
|
307
|
+
for (const [name, value] of Object.entries(raw)){
|
|
308
|
+
const where = `terminals.${name}`;
|
|
309
|
+
if (name.includes('.')) {
|
|
310
|
+
issues.push(schema_error('TERMINAL_KEY_DOT', `终端名不能包含「.」:${name}`, where));
|
|
311
|
+
valid = false;
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
if (0 === name.trim().length) {
|
|
315
|
+
issues.push(schema_error('TERMINAL_KEY_EMPTY', '终端名不能为空', 'terminals'));
|
|
316
|
+
valid = false;
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
if (!utils_isRecord(value)) {
|
|
320
|
+
issues.push(schema_error('TERMINAL_TYPE', '终端配置必须是对象', where));
|
|
321
|
+
valid = false;
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
issues.push(...unknownKeys(value, TERMINAL_KEYS, where));
|
|
325
|
+
const aliasesRaw = value['aliases'];
|
|
326
|
+
let aliases = [];
|
|
327
|
+
if (void 0 !== aliasesRaw) if (isStringArray(aliasesRaw)) aliases = aliasesRaw.map((alias)=>alias.trim()).filter((alias)=>alias.length > 0);
|
|
328
|
+
else {
|
|
329
|
+
issues.push(schema_error('ALIASES_TYPE', 'aliases 必须是字符串数组', `${where}.aliases`));
|
|
330
|
+
valid = false;
|
|
331
|
+
}
|
|
332
|
+
const repos = parseRepos(value['repos'], `${where}.repos`, issues);
|
|
333
|
+
if (null === repos) {
|
|
334
|
+
valid = false;
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
terminals[name] = {
|
|
338
|
+
aliases,
|
|
339
|
+
repos
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
return valid ? terminals : null;
|
|
343
|
+
}
|
|
344
|
+
function checkTerminalIdentity(terminals) {
|
|
345
|
+
const issues = [];
|
|
346
|
+
const seen = new Map();
|
|
347
|
+
for (const [name, terminal] of Object.entries(terminals)){
|
|
348
|
+
if (name.includes('.') || 0 === name.trim().length) continue;
|
|
349
|
+
const normalizedKey = normalizeName(name);
|
|
350
|
+
const existingKey = seen.get(normalizedKey);
|
|
351
|
+
if (void 0 !== existingKey) issues.push(schema_error('TERMINAL_DUPLICATE', `终端名「${name}」与「${existingKey}」归一化后重复(${normalizedKey}),请改名或合并`, `terminals.${name}`));
|
|
352
|
+
else seen.set(normalizedKey, name);
|
|
353
|
+
}
|
|
354
|
+
for (const [name, terminal] of Object.entries(terminals))for (const alias of terminal.aliases){
|
|
355
|
+
const normalizedAlias = normalizeName(alias);
|
|
356
|
+
if (normalizedAlias === normalizeName(name)) {
|
|
357
|
+
issues.push(warning('ALIAS_REDUNDANT', `别名「${alias}」归一化后与终端名相同,可删除(空格/全角/大小写差异已由归一化覆盖)`, `terminals.${name}.aliases`));
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
const existing = seen.get(normalizedAlias);
|
|
361
|
+
if (void 0 !== existing) issues.push(schema_error('ALIAS_CONFLICT', `别名「${alias}」与「${existing}」冲突(归一化后为 ${normalizedAlias})`, `terminals.${name}.aliases`));
|
|
362
|
+
else seen.set(normalizedAlias, `${name}(别名)`);
|
|
363
|
+
}
|
|
364
|
+
return issues;
|
|
365
|
+
}
|
|
366
|
+
function checkFsOfDocs(config, issues) {
|
|
367
|
+
const { root } = config.docs;
|
|
368
|
+
if ('' === root) return;
|
|
369
|
+
if (!external_node_fs_existsSync(root)) return void issues.push(schema_error('DOCS_ROOT_MISSING', `文档仓库不存在:${root}`, 'docs.root'));
|
|
370
|
+
if (!statSync(root).isDirectory()) return void issues.push(schema_error('DOCS_ROOT_NOT_DIR', `文档仓库不是目录:${root}`, 'docs.root'));
|
|
371
|
+
if (!external_node_fs_existsSync(external_node_path_join(root, 'skills', 'iteration-task-docs', 'SKILL.md'))) issues.push(schema_error('DOCS_ROOT_NO_SKILL', `文档仓库缺少 skills/iteration-task-docs/SKILL.md:${root}`, 'docs.root'));
|
|
372
|
+
}
|
|
373
|
+
function checkFsOfTerminals(config, issues) {
|
|
374
|
+
const pathOwners = new Map();
|
|
375
|
+
for (const [name, terminal] of Object.entries(config.terminals))for (const side of SIDES){
|
|
376
|
+
const targets = terminal.repos[side];
|
|
377
|
+
const where = `terminals.${name}.repos.${side}`;
|
|
378
|
+
if (0 === targets.length) {
|
|
379
|
+
if ('fullstack' === config.profile.role) issues.push(warning('SIDE_NOT_CONFIGURED', `角色为 fullstack,但「${name}」未配置 ${side} 仓库`, where));
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
for (const target of targets){
|
|
383
|
+
if (!external_node_fs_existsSync(target)) {
|
|
384
|
+
issues.push(schema_error('REPO_PATH_MISSING', `仓库路径不存在:${target}`, where));
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
if (!statSync(target).isDirectory()) {
|
|
388
|
+
issues.push(schema_error('REPO_PATH_NOT_DIR', `仓库路径不是目录:${target}`, where));
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
if (!external_node_fs_existsSync(external_node_path_join(target, '.git'))) issues.push(warning('REPO_NOT_GIT', `路径不是 git 仓库:${target}`, where));
|
|
392
|
+
const entry = pathOwners.get(`${side}:${target}`) ?? {
|
|
393
|
+
side,
|
|
394
|
+
target,
|
|
395
|
+
owners: []
|
|
396
|
+
};
|
|
397
|
+
entry.owners.push(name);
|
|
398
|
+
pathOwners.set(`${side}:${target}`, entry);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
for (const entry of pathOwners.values())if (!(entry.owners.length < 2)) issues.push(warning('REPO_PATH_SHARED', `${entry.side} 仓库路径被多个终端复用:${entry.target}(${entry.owners.join('、')})`, 'terminals'));
|
|
402
|
+
}
|
|
403
|
+
function checkConfig(raw, options = {}) {
|
|
404
|
+
const issues = [];
|
|
405
|
+
if (!utils_isRecord(raw)) return {
|
|
406
|
+
config: null,
|
|
407
|
+
issues: [
|
|
408
|
+
schema_error('CONFIG_ROOT', '配置文件根节点必须是对象')
|
|
409
|
+
]
|
|
410
|
+
};
|
|
411
|
+
const normalized = {
|
|
412
|
+
...raw
|
|
413
|
+
};
|
|
414
|
+
delete normalized['schemaVersion'];
|
|
415
|
+
issues.push(...unknownKeys(normalized, TOP_LEVEL_KEYS, 'root'));
|
|
416
|
+
const profile = parseProfile(normalized['profile'], options, issues);
|
|
417
|
+
const docs = parseDocs(normalized['docs'], options, issues);
|
|
418
|
+
const terminals = parseTerminals(normalized['terminals'] ?? {}, issues);
|
|
419
|
+
if (null === profile || null === docs || null === terminals) return {
|
|
420
|
+
config: null,
|
|
421
|
+
issues
|
|
422
|
+
};
|
|
423
|
+
const config = {
|
|
424
|
+
profile,
|
|
425
|
+
docs,
|
|
426
|
+
terminals
|
|
427
|
+
};
|
|
428
|
+
issues.push(...checkTerminalIdentity(terminals));
|
|
429
|
+
if (true === options.checkFs) {
|
|
430
|
+
checkFsOfDocs(config, issues);
|
|
431
|
+
checkFsOfTerminals(config, issues);
|
|
432
|
+
}
|
|
433
|
+
return {
|
|
434
|
+
config,
|
|
435
|
+
issues
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
function hasError(issues) {
|
|
439
|
+
return issues.some((issue)=>'error' === issue.level);
|
|
440
|
+
}
|
|
441
|
+
function formatIssue(issue) {
|
|
442
|
+
const tag = 'error' === issue.level ? picocolors.red('✗ error') : picocolors.yellow('! warning');
|
|
443
|
+
const where = void 0 === issue.where ? '' : picocolors.dim(` [${issue.where}]`);
|
|
444
|
+
return `${tag} ${issue.code}${where} ${issue.message}`;
|
|
445
|
+
}
|
|
446
|
+
function formatIssues(issues, emptyText = '未发现问题') {
|
|
447
|
+
if (0 === issues.length) return picocolors.green(`✓ ${emptyText}`);
|
|
448
|
+
return issues.map(formatIssue).join('\n');
|
|
449
|
+
}
|
|
450
|
+
function countIssues(issues) {
|
|
451
|
+
let errors = 0;
|
|
452
|
+
let warnings = 0;
|
|
453
|
+
for (const issue of issues)if ('error' === issue.level) errors += 1;
|
|
454
|
+
else warnings += 1;
|
|
455
|
+
return {
|
|
456
|
+
errors,
|
|
457
|
+
warnings
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
function existsMark(exists) {
|
|
461
|
+
return exists ? picocolors.green('✓') : picocolors.red('✗');
|
|
462
|
+
}
|
|
463
|
+
function isProcessAlive(pid) {
|
|
464
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
465
|
+
try {
|
|
466
|
+
process.kill(pid, 0);
|
|
467
|
+
return true;
|
|
468
|
+
} catch (error) {
|
|
469
|
+
const code = error.code;
|
|
470
|
+
return 'EPERM' === code;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
function isStale(lockPath, staleMs) {
|
|
474
|
+
try {
|
|
475
|
+
const info = statSync(lockPath);
|
|
476
|
+
if (Date.now() - info.mtimeMs > staleMs) return true;
|
|
477
|
+
const raw = readFileSync(lockPath, 'utf8').trim();
|
|
478
|
+
const pid = Number.parseInt(raw.split(/\s+/)[0] ?? '', 10);
|
|
479
|
+
if (!Number.isFinite(pid)) return true;
|
|
480
|
+
return !isProcessAlive(pid);
|
|
481
|
+
} catch {
|
|
482
|
+
return true;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
486
|
+
const DEFAULT_STALE_MS = 30000;
|
|
487
|
+
const DEFAULT_RETRY_MS = 50;
|
|
488
|
+
function sleepSync(ms) {
|
|
489
|
+
const shared = new SharedArrayBuffer(4);
|
|
490
|
+
Atomics.wait(new Int32Array(shared), 0, 0, ms);
|
|
491
|
+
}
|
|
492
|
+
function withConfigLock(configPath, run, options = {}) {
|
|
493
|
+
const lockPath = `${configPath}.lock`;
|
|
494
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
495
|
+
const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
|
|
496
|
+
const retryMs = options.retryMs ?? DEFAULT_RETRY_MS;
|
|
497
|
+
const deadline = Date.now() + timeoutMs;
|
|
498
|
+
let fd = null;
|
|
499
|
+
for(;;)try {
|
|
500
|
+
fd = openSync(lockPath, 'wx');
|
|
501
|
+
writeSync(fd, `${process.pid} ${new Date().toISOString()}\n`);
|
|
502
|
+
break;
|
|
503
|
+
} catch (error) {
|
|
504
|
+
const code = error.code;
|
|
505
|
+
if ('EEXIST' !== code) throw error;
|
|
506
|
+
if (isStale(lockPath, staleMs)) {
|
|
507
|
+
try {
|
|
508
|
+
unlinkSync(lockPath);
|
|
509
|
+
} catch {}
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
if (Date.now() >= deadline) throw new errors_CliError(`配置文件正被其他进程写入:${lockPath}\n请等待当前操作完成,或删除该锁文件后重试`, errors_EXIT.INVALID);
|
|
513
|
+
sleepSync(retryMs);
|
|
514
|
+
}
|
|
515
|
+
try {
|
|
516
|
+
return run();
|
|
517
|
+
} finally{
|
|
518
|
+
if (null !== fd) try {
|
|
519
|
+
closeSync(fd);
|
|
520
|
+
} catch {}
|
|
521
|
+
if (external_node_fs_existsSync(lockPath)) try {
|
|
522
|
+
unlinkSync(lockPath);
|
|
523
|
+
} catch {}
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
const MAX_BACKUPS = 10;
|
|
527
|
+
const TEMPLATE = `# ylcwf 配置
|
|
528
|
+
# 由 ylcwf CLI 管理;手改后请运行 \`ylcwf doctor\` 校验。
|
|
529
|
+
|
|
530
|
+
profile:
|
|
531
|
+
developer: ''
|
|
532
|
+
role: frontend
|
|
533
|
+
|
|
534
|
+
docs:
|
|
535
|
+
root: ''
|
|
536
|
+
|
|
537
|
+
terminals: {}
|
|
538
|
+
`;
|
|
539
|
+
function createEmptyDocument() {
|
|
540
|
+
return parseDocument(TEMPLATE);
|
|
541
|
+
}
|
|
542
|
+
function loadConfig(explicit) {
|
|
543
|
+
const path = paths_resolveConfigPath(explicit);
|
|
544
|
+
if (!external_node_fs_existsSync(path)) return {
|
|
545
|
+
path,
|
|
546
|
+
exists: false,
|
|
547
|
+
doc: null,
|
|
548
|
+
raw: null,
|
|
549
|
+
config: null,
|
|
550
|
+
issues: []
|
|
551
|
+
};
|
|
552
|
+
const text = readFileSync(path, 'utf8');
|
|
553
|
+
const doc = parseDocument(text);
|
|
554
|
+
if (doc.errors.length > 0) {
|
|
555
|
+
const detail = doc.errors.map((item)=>item.message).join('\n');
|
|
556
|
+
throw new errors_CliError(`配置文件 YAML 语法错误:${path}\n${detail}`, errors_EXIT.INVALID);
|
|
557
|
+
}
|
|
558
|
+
const raw = doc.toJS();
|
|
559
|
+
const checked = checkConfig(raw, {
|
|
560
|
+
allowIncomplete: true
|
|
561
|
+
});
|
|
562
|
+
return {
|
|
563
|
+
path,
|
|
564
|
+
exists: true,
|
|
565
|
+
doc,
|
|
566
|
+
raw,
|
|
567
|
+
config: checked.config,
|
|
568
|
+
issues: checked.issues
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
function requireConfig(explicit) {
|
|
572
|
+
const loaded = loadConfig(explicit);
|
|
573
|
+
if (!loaded.exists || null === loaded.doc) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
|
|
574
|
+
if (null === loaded.config) throw new errors_CliError(`配置结构不合法:${loaded.path}\n${formatIssues(loaded.issues)}`, errors_EXIT.INVALID);
|
|
575
|
+
return {
|
|
576
|
+
path: loaded.path,
|
|
577
|
+
doc: loaded.doc,
|
|
578
|
+
config: loaded.config,
|
|
579
|
+
issues: loaded.issues
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
function obtainDocument(explicit) {
|
|
583
|
+
const loaded = loadConfig(explicit);
|
|
584
|
+
if (null !== loaded.doc) return {
|
|
585
|
+
path: loaded.path,
|
|
586
|
+
doc: loaded.doc
|
|
587
|
+
};
|
|
588
|
+
return {
|
|
589
|
+
path: loaded.path,
|
|
590
|
+
doc: parseDocument(TEMPLATE)
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
function assertWritable(doc, path) {
|
|
594
|
+
const raw = doc.toJS();
|
|
595
|
+
const checked = checkConfig(raw, {
|
|
596
|
+
allowIncomplete: true
|
|
597
|
+
});
|
|
598
|
+
if (null === checked.config || checked.issues.some((issue)=>'error' === issue.level)) throw new errors_CliError(`配置校验失败,已取消写入:${path}\n${formatIssues(checked.issues)}`, errors_EXIT.INVALID);
|
|
599
|
+
return checked.config;
|
|
600
|
+
}
|
|
601
|
+
function toBlockStyle(node) {
|
|
602
|
+
if (isMap(node)) {
|
|
603
|
+
if (node.items.length > 0) node.flow = false;
|
|
604
|
+
for (const pair of node.items){
|
|
605
|
+
toBlockStyle(pair.key);
|
|
606
|
+
toBlockStyle(pair.value);
|
|
607
|
+
}
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
if (isSeq(node)) {
|
|
611
|
+
if (node.items.length > 0) node.flow = false;
|
|
612
|
+
for (const item of node.items)toBlockStyle(item);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
function saveDocument(doc, target) {
|
|
616
|
+
mkdirSync(dirname(target), {
|
|
617
|
+
recursive: true
|
|
618
|
+
});
|
|
619
|
+
doc.deleteIn([
|
|
620
|
+
'schemaVersion'
|
|
621
|
+
]);
|
|
622
|
+
toBlockStyle(doc.contents);
|
|
623
|
+
const text = doc.toString({
|
|
624
|
+
lineWidth: 0
|
|
625
|
+
});
|
|
626
|
+
withConfigLock(target, ()=>{
|
|
627
|
+
if (external_node_fs_existsSync(target)) backup(target);
|
|
628
|
+
const tmp = `${target}.tmp-${process.pid}`;
|
|
629
|
+
writeFileSync(tmp, text, 'utf8');
|
|
630
|
+
renameSync(tmp, target);
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
function backup(target) {
|
|
634
|
+
const dir = backupsDir(target);
|
|
635
|
+
mkdirSync(dir, {
|
|
636
|
+
recursive: true
|
|
637
|
+
});
|
|
638
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
639
|
+
let destination = external_node_path_join(dir, `config-${stamp}.yaml`);
|
|
640
|
+
let index = 1;
|
|
641
|
+
while(external_node_fs_existsSync(destination)){
|
|
642
|
+
destination = external_node_path_join(dir, `config-${stamp}-${index}.yaml`);
|
|
643
|
+
index += 1;
|
|
644
|
+
}
|
|
645
|
+
copyFileSync(target, destination);
|
|
646
|
+
const files = readdirSync(dir).filter((name)=>name.startsWith('config-') && name.endsWith('.yaml')).sort();
|
|
647
|
+
const stale = files.slice(0, Math.max(0, files.length - MAX_BACKUPS));
|
|
648
|
+
for (const name of stale)unlinkSync(`${dir}/${name}`);
|
|
649
|
+
}
|
|
650
|
+
function parseDotPath(input) {
|
|
651
|
+
const parts = input.split('.').map((part)=>part.trim());
|
|
652
|
+
if (0 === parts.length || parts.some((part)=>0 === part.length)) throw new errors_CliError(`路径不合法:${input}(应形如 docs.role)`, errors_EXIT.USAGE);
|
|
653
|
+
return parts;
|
|
654
|
+
}
|
|
655
|
+
function getIn(root, path) {
|
|
656
|
+
let current = root;
|
|
657
|
+
for (const key of path){
|
|
658
|
+
if (!utils_isRecord(current)) return;
|
|
659
|
+
if (!Object.hasOwn(current, key)) return;
|
|
660
|
+
current = current[key];
|
|
661
|
+
}
|
|
662
|
+
return current;
|
|
663
|
+
}
|
|
664
|
+
function renderScalar(value) {
|
|
665
|
+
if ('string' == typeof value) return value;
|
|
666
|
+
if (null === value) return 'null';
|
|
667
|
+
return JSON.stringify(value);
|
|
668
|
+
}
|
|
669
|
+
function bail() {
|
|
670
|
+
__rspack_external__clack_prompts_d2d5c36d.cancel('已取消');
|
|
671
|
+
process.exit(errors_EXIT.OK);
|
|
672
|
+
}
|
|
673
|
+
async function askText(message, placeholder, validate, defaultValue = '') {
|
|
674
|
+
const answer = await __rspack_external__clack_prompts_d2d5c36d.text({
|
|
675
|
+
message,
|
|
676
|
+
placeholder,
|
|
677
|
+
defaultValue,
|
|
678
|
+
validate
|
|
679
|
+
});
|
|
680
|
+
if (__rspack_external__clack_prompts_d2d5c36d.isCancel(answer)) bail();
|
|
681
|
+
return answer;
|
|
682
|
+
}
|
|
683
|
+
async function askConfirm(message, initialValue) {
|
|
684
|
+
const answer = await __rspack_external__clack_prompts_d2d5c36d.confirm({
|
|
685
|
+
message,
|
|
686
|
+
initialValue
|
|
687
|
+
});
|
|
688
|
+
if (__rspack_external__clack_prompts_d2d5c36d.isCancel(answer)) bail();
|
|
689
|
+
return answer;
|
|
690
|
+
}
|
|
691
|
+
function validateExistingDir(value) {
|
|
692
|
+
const trimmed = (value ?? '').trim();
|
|
693
|
+
if (0 === trimmed.length) return '不能为空';
|
|
694
|
+
if (!isAbsolute(trimmed)) return '必须是绝对路径';
|
|
695
|
+
if (!external_node_fs_existsSync(trimmed)) return '路径不存在';
|
|
696
|
+
if (!statSync(trimmed).isDirectory()) return '不是目录';
|
|
697
|
+
}
|
|
698
|
+
function validateDeveloper(value) {
|
|
699
|
+
if (!/^[a-z][a-z0-9]*$/.test((value ?? '').trim())) return '必须是小写字母开头的字母数字串(姓名小写全拼)';
|
|
700
|
+
}
|
|
701
|
+
function splitAliases(value) {
|
|
702
|
+
return value.split(',').map((item)=>item.trim()).filter((item)=>item.length > 0);
|
|
703
|
+
}
|
|
704
|
+
function validatePathList(value) {
|
|
705
|
+
const raw = (value ?? '').trim();
|
|
706
|
+
if (0 === raw.length) return;
|
|
707
|
+
for (const part of parsePathList(raw)){
|
|
708
|
+
const message = validateExistingDir(part);
|
|
709
|
+
if (void 0 !== message) return `${part}:${message}`;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
function detectGitRemote(root) {
|
|
713
|
+
try {
|
|
714
|
+
const out = execFileSync('git', [
|
|
715
|
+
'-C',
|
|
716
|
+
root,
|
|
717
|
+
'remote',
|
|
718
|
+
'get-url',
|
|
719
|
+
'origin'
|
|
720
|
+
], {
|
|
721
|
+
encoding: 'utf8',
|
|
722
|
+
timeout: 5000
|
|
723
|
+
}).trim();
|
|
724
|
+
return out.length > 0 ? out : null;
|
|
725
|
+
} catch {
|
|
726
|
+
return null;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
function validateRemote(value) {
|
|
730
|
+
const trimmed = (value ?? '').trim();
|
|
731
|
+
if (0 === trimmed.length) return '不能为空';
|
|
732
|
+
if (!/^(https?:\/\/|ssh:\/\/|git@)/.test(trimmed)) return '必须是 https:// 或 git@ 形式的地址';
|
|
733
|
+
}
|
|
734
|
+
async function runInit(options) {
|
|
735
|
+
if (true !== process.stdin.isTTY) throw new errors_CliError('init 需要交互式终端;无 TTY 时请改用:ylcwf set / ylcwf terminal add', errors_EXIT.USAGE);
|
|
736
|
+
const configPath = paths_resolveConfigPath(options.config);
|
|
737
|
+
const existing = loadConfig(options.config);
|
|
738
|
+
if (existing.exists && true !== options.force) {
|
|
739
|
+
const proceed = await askConfirm(`配置已存在(${configPath}),继续将覆盖全部字段。是否继续?`, false);
|
|
740
|
+
if (!proceed) return void __rspack_external__clack_prompts_d2d5c36d.cancel('已取消');
|
|
741
|
+
}
|
|
742
|
+
__rspack_external__clack_prompts_d2d5c36d.intro(`ylcwf 初始化 → ${configPath}`);
|
|
743
|
+
const doc = createEmptyDocument();
|
|
744
|
+
const mode = await __rspack_external__clack_prompts_d2d5c36d.select({
|
|
745
|
+
message: '使用模式',
|
|
746
|
+
options: [
|
|
747
|
+
{
|
|
748
|
+
value: 'developer',
|
|
749
|
+
label: '开发者(全功能:配置 + 迭代看板)'
|
|
750
|
+
},
|
|
751
|
+
{
|
|
752
|
+
value: 'stakeholder',
|
|
753
|
+
label: '干系人(产品 / 项目经理 / 测试,只看迭代看板)'
|
|
754
|
+
}
|
|
755
|
+
],
|
|
756
|
+
initialValue: 'developer'
|
|
757
|
+
});
|
|
758
|
+
if (__rspack_external__clack_prompts_d2d5c36d.isCancel(mode)) bail();
|
|
759
|
+
doc.setIn([
|
|
760
|
+
'profile',
|
|
761
|
+
'mode'
|
|
762
|
+
], mode);
|
|
763
|
+
if ('developer' === mode) {
|
|
764
|
+
const developer = await askText('开发者标识(姓名小写全拼)', 'yourname', validateDeveloper);
|
|
765
|
+
doc.setIn([
|
|
766
|
+
'profile',
|
|
767
|
+
'developer'
|
|
768
|
+
], developer.trim());
|
|
769
|
+
const role = await __rspack_external__clack_prompts_d2d5c36d.select({
|
|
770
|
+
message: '默认角色',
|
|
771
|
+
options: [
|
|
772
|
+
{
|
|
773
|
+
value: 'frontend',
|
|
774
|
+
label: '前端'
|
|
775
|
+
},
|
|
776
|
+
{
|
|
777
|
+
value: 'backend',
|
|
778
|
+
label: '后端'
|
|
779
|
+
},
|
|
780
|
+
{
|
|
781
|
+
value: 'fullstack',
|
|
782
|
+
label: '全栈(前端 + 后端)'
|
|
783
|
+
}
|
|
784
|
+
],
|
|
785
|
+
initialValue: 'frontend'
|
|
786
|
+
});
|
|
787
|
+
if (__rspack_external__clack_prompts_d2d5c36d.isCancel(role)) bail();
|
|
788
|
+
doc.setIn([
|
|
789
|
+
'profile',
|
|
790
|
+
'role'
|
|
791
|
+
], role);
|
|
792
|
+
const root = await askText('迭代任务文档仓库绝对路径', '/Users/you/develop/iteration-task-repo', validateExistingDir);
|
|
793
|
+
doc.setIn([
|
|
794
|
+
'docs',
|
|
795
|
+
'root'
|
|
796
|
+
], root.trim());
|
|
797
|
+
doc.setIn([
|
|
798
|
+
'docs',
|
|
799
|
+
'remote'
|
|
800
|
+
], detectGitRemote(root.trim()) ?? DEFAULT_DOCS_REMOTE);
|
|
801
|
+
__rspack_external__clack_prompts_d2d5c36d.log.info('接下来逐项录入终端 → 本地仓库映射;终端名留空即结束。每端多个仓库用逗号或分号分隔。');
|
|
802
|
+
let index = 0;
|
|
803
|
+
for(;;){
|
|
804
|
+
index += 1;
|
|
805
|
+
const name = await askText(`终端 #${index}:PRD 中的终端名(留空结束)`, '示例终端-A', ()=>void 0);
|
|
806
|
+
const trimmedName = name.trim();
|
|
807
|
+
if (0 === trimmedName.length) break;
|
|
808
|
+
if (void 0 !== getIn(doc.toJS(), [
|
|
809
|
+
'terminals',
|
|
810
|
+
trimmedName
|
|
811
|
+
])) {
|
|
812
|
+
__rspack_external__clack_prompts_d2d5c36d.log.warn(`终端「${trimmedName}」已存在,跳过`);
|
|
813
|
+
index -= 1;
|
|
814
|
+
continue;
|
|
815
|
+
}
|
|
816
|
+
const aliases = await askText('别名(逗号分隔,可留空)', '别名1, 别名2', ()=>void 0);
|
|
817
|
+
const frontendRaw = await askText('前端仓库绝对路径(多个用逗号或分号分隔,可留空)', '/Users/you/develop/ylc/xxx', validatePathList);
|
|
818
|
+
const backendRaw = await askText('后端仓库绝对路径(多个用逗号或分号分隔,可留空)', '/Users/you/develop/java/xxx', validatePathList);
|
|
819
|
+
doc.setIn([
|
|
820
|
+
'terminals',
|
|
821
|
+
trimmedName
|
|
822
|
+
], {
|
|
823
|
+
aliases: splitAliases(aliases),
|
|
824
|
+
repos: {
|
|
825
|
+
frontend: parsePathList(frontendRaw),
|
|
826
|
+
backend: parsePathList(backendRaw)
|
|
827
|
+
}
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
} else {
|
|
831
|
+
doc.setIn([
|
|
832
|
+
'profile',
|
|
833
|
+
'developer'
|
|
834
|
+
], '');
|
|
835
|
+
const remote = await askText('文档仓库远程地址', DEFAULT_DOCS_REMOTE, validateRemote);
|
|
836
|
+
doc.setIn([
|
|
837
|
+
'docs',
|
|
838
|
+
'remote'
|
|
839
|
+
], remote.trim());
|
|
840
|
+
__rspack_external__clack_prompts_d2d5c36d.log.info('干系人模式不配置本地路径:打开工作台后会自动准备只读副本。');
|
|
841
|
+
}
|
|
842
|
+
assertWritable(doc, configPath);
|
|
843
|
+
saveDocument(doc, configPath);
|
|
844
|
+
__rspack_external__clack_prompts_d2d5c36d.outro(`已写入 ${configPath}\n下一步:ylcwf doctor 校验,ylcwf show 查看;后续追加仓库用 ylcwf terminal repo add`);
|
|
845
|
+
printLine('');
|
|
846
|
+
}
|
|
847
|
+
function registerInit(program) {
|
|
848
|
+
program.command('init').description('交互式首次配置(逐项引导)').option('-c, --config <path>', '指定配置文件路径').option('--force', '已存在时直接覆盖,不再确认').action(async (options)=>{
|
|
849
|
+
await runInit(options);
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
const ANSI_PATTERN = new RegExp('\\u001B\\[[0-9;]*m', 'g');
|
|
853
|
+
function displayWidth(text) {
|
|
854
|
+
let width = 0;
|
|
855
|
+
for (const char of text.replace(ANSI_PATTERN, '')){
|
|
856
|
+
const code = char.codePointAt(0) ?? 0;
|
|
857
|
+
if (code >= 0x1f300 && code <= 0x1faff) {
|
|
858
|
+
width += 2;
|
|
859
|
+
continue;
|
|
860
|
+
}
|
|
861
|
+
width += isWide(char) ? 2 : 1;
|
|
862
|
+
}
|
|
863
|
+
return width;
|
|
864
|
+
}
|
|
865
|
+
function isWide(char) {
|
|
866
|
+
const code = char.codePointAt(0) ?? 0;
|
|
867
|
+
return code >= 0x1100 && code <= 0x115f || code >= 0x2e80 && code <= 0x303e || code >= 0x3041 && code <= 0x33ff || code >= 0x3400 && code <= 0x4dbf || code >= 0x4e00 && code <= 0x9fff || code >= 0xa000 && code <= 0xa4cf || code >= 0xac00 && code <= 0xd7a3 || code >= 0xf900 && code <= 0xfaff || code >= 0xfe30 && code <= 0xfe4f || code >= 0xff00 && code <= 0xff60 || code >= 0xffe0 && code <= 0xffe6;
|
|
868
|
+
}
|
|
869
|
+
function padCell(cell, width) {
|
|
870
|
+
const visible = displayWidth(cell);
|
|
871
|
+
return visible >= width ? cell : cell + ' '.repeat(width - visible);
|
|
872
|
+
}
|
|
873
|
+
function renderTable(headers, rows) {
|
|
874
|
+
headers.length;
|
|
875
|
+
const widths = headers.map((header, index)=>Math.max(displayWidth(header), ...rows.map((row)=>displayWidth(row[index] ?? ''))));
|
|
876
|
+
const formatRow = (cells, padLast)=>cells.map((cell, index)=>{
|
|
877
|
+
const width = widths[index] ?? 0;
|
|
878
|
+
return padLast || index < cells.length - 1 ? padCell(cell, width) : cell;
|
|
879
|
+
}).join(' ').trimEnd();
|
|
880
|
+
const separator = widths.map((width)=>'─'.repeat(width)).join(' ');
|
|
881
|
+
return [
|
|
882
|
+
formatRow(headers, true),
|
|
883
|
+
separator,
|
|
884
|
+
...rows.map((row)=>formatRow(row, false))
|
|
885
|
+
];
|
|
886
|
+
}
|
|
887
|
+
function parseFormat(value) {
|
|
888
|
+
if (void 0 === value || 'human' === value) return 'human';
|
|
889
|
+
if ('json' === value) return 'json';
|
|
890
|
+
throw new errors_CliError(`不支持的输出格式:${value}(可选 human / json)`, errors_EXIT.USAGE);
|
|
891
|
+
}
|
|
892
|
+
const ROLE_LABEL = {
|
|
893
|
+
frontend: '前端',
|
|
894
|
+
backend: '后端',
|
|
895
|
+
fullstack: '全栈(前端 + 后端)'
|
|
896
|
+
};
|
|
897
|
+
const MODE_LABEL = {
|
|
898
|
+
developer: '开发者(全功能)',
|
|
899
|
+
stakeholder: '干系人(只看文档看板)'
|
|
900
|
+
};
|
|
901
|
+
const SIDE_LABEL = {
|
|
902
|
+
frontend: '前端',
|
|
903
|
+
backend: '后端'
|
|
904
|
+
};
|
|
905
|
+
function showConfig(explicit, format) {
|
|
906
|
+
const loaded = loadConfig(explicit);
|
|
907
|
+
if (!loaded.exists) {
|
|
908
|
+
if ('json' === format) return void printJson({
|
|
909
|
+
configPath: loaded.path,
|
|
910
|
+
exists: false,
|
|
911
|
+
config: null,
|
|
912
|
+
issues: []
|
|
913
|
+
});
|
|
914
|
+
printLine(`配置文件 ${loaded.path} ${existsMark(false)}(未初始化)`);
|
|
915
|
+
printLine('');
|
|
916
|
+
printLine('运行 `ylcwf init` 完成首次配置,或 `ylcwf set <path> <value>` 精确修改。');
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
const checked = checkConfig(loaded.raw, {
|
|
920
|
+
checkFs: true
|
|
921
|
+
});
|
|
922
|
+
if ('json' === format) return void printJson({
|
|
923
|
+
configPath: loaded.path,
|
|
924
|
+
exists: true,
|
|
925
|
+
config: checked.config,
|
|
926
|
+
issues: checked.issues
|
|
927
|
+
});
|
|
928
|
+
renderHuman(loaded.path, checked.config, checked.issues);
|
|
929
|
+
}
|
|
930
|
+
function renderHuman(path, config, issues) {
|
|
931
|
+
const { errors, warnings } = countIssues(issues);
|
|
932
|
+
if (null === config) {
|
|
933
|
+
printLine(renderTable([
|
|
934
|
+
'项',
|
|
935
|
+
'值'
|
|
936
|
+
], [
|
|
937
|
+
[
|
|
938
|
+
'配置文件',
|
|
939
|
+
`${path} ${existsMark(true)}`
|
|
940
|
+
],
|
|
941
|
+
[
|
|
942
|
+
'结构',
|
|
943
|
+
picocolors.red('不合法,无法读取有效字段')
|
|
944
|
+
]
|
|
945
|
+
]).join('\n'));
|
|
946
|
+
printLine('');
|
|
947
|
+
printLine(formatIssues(issues));
|
|
948
|
+
printHint();
|
|
949
|
+
return;
|
|
950
|
+
}
|
|
951
|
+
printLine(renderTable([
|
|
952
|
+
'项',
|
|
953
|
+
'值'
|
|
954
|
+
], [
|
|
955
|
+
[
|
|
956
|
+
'配置文件',
|
|
957
|
+
`${path} ${existsMark(true)}`
|
|
958
|
+
],
|
|
959
|
+
[
|
|
960
|
+
'文档仓库',
|
|
961
|
+
`${config.docs.root} ${existsMark(external_node_fs_existsSync(config.docs.root))}`
|
|
962
|
+
],
|
|
963
|
+
[
|
|
964
|
+
'远程地址',
|
|
965
|
+
config.docs.remote ?? picocolors.dim('(内置默认值)')
|
|
966
|
+
],
|
|
967
|
+
[
|
|
968
|
+
'开发者标识',
|
|
969
|
+
config.profile.developer
|
|
970
|
+
],
|
|
971
|
+
[
|
|
972
|
+
'默认角色',
|
|
973
|
+
ROLE_LABEL[config.profile.role]
|
|
974
|
+
],
|
|
975
|
+
[
|
|
976
|
+
'使用模式',
|
|
977
|
+
MODE_LABEL[config.profile.mode]
|
|
978
|
+
]
|
|
979
|
+
]).join('\n'));
|
|
980
|
+
const names = Object.keys(config.terminals);
|
|
981
|
+
printLine('');
|
|
982
|
+
printLine(`PRD终端-本地仓库映射表(${names.length})`);
|
|
983
|
+
if (0 === names.length) printLine(picocolors.dim(' (空)运行 ylcwf terminal add <终端名> --frontend <路径> 添加'));
|
|
984
|
+
else {
|
|
985
|
+
const rows = [];
|
|
986
|
+
for (const name of names){
|
|
987
|
+
const terminal = config.terminals[name];
|
|
988
|
+
if (void 0 === terminal) continue;
|
|
989
|
+
const aliases = 0 === terminal.aliases.length ? '—' : terminal.aliases.join('、');
|
|
990
|
+
let printedName = false;
|
|
991
|
+
for (const side of SIDES){
|
|
992
|
+
const targets = terminal.repos[side];
|
|
993
|
+
if (0 === targets.length) {
|
|
994
|
+
rows.push([
|
|
995
|
+
printedName ? '' : name,
|
|
996
|
+
printedName ? '' : aliases,
|
|
997
|
+
SIDE_LABEL[side],
|
|
998
|
+
'—',
|
|
999
|
+
picocolors.dim('未配置')
|
|
1000
|
+
]);
|
|
1001
|
+
printedName = true;
|
|
1002
|
+
continue;
|
|
1003
|
+
}
|
|
1004
|
+
targets.forEach((target, index)=>{
|
|
1005
|
+
rows.push([
|
|
1006
|
+
printedName ? '' : name,
|
|
1007
|
+
printedName ? '' : aliases,
|
|
1008
|
+
0 === index ? SIDE_LABEL[side] : '',
|
|
1009
|
+
target,
|
|
1010
|
+
existsMark(external_node_fs_existsSync(target))
|
|
1011
|
+
]);
|
|
1012
|
+
printedName = true;
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
printLine(renderTable([
|
|
1017
|
+
'终端',
|
|
1018
|
+
'别名',
|
|
1019
|
+
'端',
|
|
1020
|
+
'本地仓库',
|
|
1021
|
+
'状态'
|
|
1022
|
+
], rows).join('\n'));
|
|
1023
|
+
}
|
|
1024
|
+
printLine('');
|
|
1025
|
+
if (0 === errors && 0 === warnings) printLine(formatIssues([]));
|
|
1026
|
+
else {
|
|
1027
|
+
printLine(`问题(error ${errors} / warning ${warnings})`);
|
|
1028
|
+
printLine(formatIssues(issues));
|
|
1029
|
+
}
|
|
1030
|
+
printHint();
|
|
1031
|
+
}
|
|
1032
|
+
function printHint() {
|
|
1033
|
+
printLine('');
|
|
1034
|
+
printLine(picocolors.dim('更多命令:ylcwf --help | 健康检查:ylcwf doctor | 首次配置:ylcwf init'));
|
|
1035
|
+
}
|
|
1036
|
+
function registerShow(program) {
|
|
1037
|
+
program.command('show').description('查看当前配置(带路径存在性检查)').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
|
|
1038
|
+
showConfig(options.config, parseFormat(options.format));
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
function runGet(dotPath, options) {
|
|
1042
|
+
const format = parseFormat(options.format);
|
|
1043
|
+
const ready = requireConfig(options.config);
|
|
1044
|
+
const path = parseDotPath(dotPath);
|
|
1045
|
+
const value = getIn(ready.config, path);
|
|
1046
|
+
if (void 0 === value) throw new errors_CliError(`配置项不存在:${dotPath}`, errors_EXIT.NOT_FOUND);
|
|
1047
|
+
if ('json' === format) return void printJson({
|
|
1048
|
+
path: dotPath,
|
|
1049
|
+
value
|
|
1050
|
+
});
|
|
1051
|
+
printLine(renderScalar(value));
|
|
1052
|
+
}
|
|
1053
|
+
function registerGet(program) {
|
|
1054
|
+
program.command('get <dotPath>').description('读取配置项,输出裸值(机器接口)').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((dotPath, options)=>{
|
|
1055
|
+
runGet(dotPath, options);
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
const ROLE_SET = new Set(ROLES);
|
|
1059
|
+
const MODE_SET = new Set(MODES);
|
|
1060
|
+
const SIDE_SET = new Set(SIDES);
|
|
1061
|
+
function assertSettable(path) {
|
|
1062
|
+
const [first, second, third, fourth] = path;
|
|
1063
|
+
if (2 === path.length && 'docs' === first && ('root' === second || 'remote' === second)) return;
|
|
1064
|
+
if (2 === path.length && 'profile' === first && ('developer' === second || 'role' === second || 'mode' === second)) return;
|
|
1065
|
+
if (4 === path.length && 'terminals' === first && void 0 !== second && 'repos' === third && void 0 !== fourth && SIDE_SET.has(fourth)) return;
|
|
1066
|
+
if (3 === path.length && 'terminals' === first && void 0 !== second && 'aliases' === third) return;
|
|
1067
|
+
throw new errors_CliError(`不支持通过 set 修改该路径:${path.join('.')}\n允许:docs.root / docs.remote / profile.developer / profile.role / profile.mode / terminals.<终端>.aliases / terminals.<终端>.repos.frontend|backend\n终端的新增与删除请用:ylcwf terminal add | rm`, errors_EXIT.USAGE);
|
|
1068
|
+
}
|
|
1069
|
+
function coerceValue(path, raw) {
|
|
1070
|
+
const key = path[path.length - 1];
|
|
1071
|
+
const trimmed = raw.trim();
|
|
1072
|
+
if ('root' === key) {
|
|
1073
|
+
if (!isAbsolute(trimmed)) throw new errors_CliError(`文档仓库必须是绝对路径:${raw}`, errors_EXIT.USAGE);
|
|
1074
|
+
return trimmed;
|
|
1075
|
+
}
|
|
1076
|
+
if ('remote' === key) {
|
|
1077
|
+
const looksLikeGit = /^(https?:\/\/|ssh:\/\/|git@)/.test(trimmed);
|
|
1078
|
+
if (!looksLikeGit) throw new errors_CliError(`远程地址不合法:${raw}`, errors_EXIT.USAGE);
|
|
1079
|
+
return trimmed;
|
|
1080
|
+
}
|
|
1081
|
+
if ('developer' === key) {
|
|
1082
|
+
if (!/^[a-z][a-z0-9]*$/.test(trimmed)) throw new errors_CliError(`开发者标识必须是小写字母开头的字母数字串:${raw}`, errors_EXIT.USAGE);
|
|
1083
|
+
return trimmed;
|
|
1084
|
+
}
|
|
1085
|
+
if ('role' === key) {
|
|
1086
|
+
if (!ROLE_SET.has(trimmed)) throw new errors_CliError(`角色必须是 ${ROLES.join(' / ')} 之一:${raw}`, errors_EXIT.USAGE);
|
|
1087
|
+
return trimmed;
|
|
1088
|
+
}
|
|
1089
|
+
if ('mode' === key) {
|
|
1090
|
+
if (!MODE_SET.has(trimmed)) throw new errors_CliError(`使用模式必须是 ${MODES.join(' / ')} 之一:${raw}`, errors_EXIT.USAGE);
|
|
1091
|
+
return trimmed;
|
|
1092
|
+
}
|
|
1093
|
+
if ('aliases' === key) return trimmed.split(',').map((item)=>item.trim()).filter((item)=>item.length > 0);
|
|
1094
|
+
if ('frontend' === key || 'backend' === key) {
|
|
1095
|
+
const parts = parsePathList(trimmed);
|
|
1096
|
+
for (const part of parts)if (!isAbsolute(part)) throw new errors_CliError(`仓库路径必须是绝对路径:${part}`, errors_EXIT.USAGE);
|
|
1097
|
+
return parts;
|
|
1098
|
+
}
|
|
1099
|
+
return raw;
|
|
1100
|
+
}
|
|
1101
|
+
function runSet(dotPath, rawValue, options) {
|
|
1102
|
+
const format = parseFormat(options.format);
|
|
1103
|
+
const path = parseDotPath(dotPath);
|
|
1104
|
+
assertSettable(path);
|
|
1105
|
+
const value = coerceValue(path, rawValue);
|
|
1106
|
+
const { path: configPath, doc } = obtainDocument(options.config);
|
|
1107
|
+
const before = doc.toJS();
|
|
1108
|
+
doc.setIn([
|
|
1109
|
+
...path
|
|
1110
|
+
], value);
|
|
1111
|
+
assertWritable(doc, configPath);
|
|
1112
|
+
const previous = getIn(before, path);
|
|
1113
|
+
const next = getIn(doc.toJS(), path);
|
|
1114
|
+
if (true === options.dryRun) {
|
|
1115
|
+
if ('json' === format) return void printJson({
|
|
1116
|
+
dryRun: true,
|
|
1117
|
+
path: dotPath,
|
|
1118
|
+
previous: previous ?? null,
|
|
1119
|
+
next: next ?? null
|
|
1120
|
+
});
|
|
1121
|
+
printLine(`(dry-run) ${dotPath}: ${renderScalar(previous)} → ${renderScalar(next)}`);
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
saveDocument(doc, configPath);
|
|
1125
|
+
if ('json' === format) return void printJson({
|
|
1126
|
+
saved: true,
|
|
1127
|
+
configPath,
|
|
1128
|
+
path: dotPath,
|
|
1129
|
+
previous: previous ?? null,
|
|
1130
|
+
next: next ?? null
|
|
1131
|
+
});
|
|
1132
|
+
printLine(`已更新 ${dotPath}: ${renderScalar(previous)} → ${renderScalar(next)}`);
|
|
1133
|
+
printLine(`配置文件:${configPath}`);
|
|
1134
|
+
}
|
|
1135
|
+
function registerSet(program) {
|
|
1136
|
+
program.command('set <dotPath> <value>').description('精确修改配置项(校验通过才写入)').option('-c, --config <path>', '指定配置文件路径').option('--dry-run', '只显示变更,不写入').option('--format <format>', '输出格式:human | json', 'human').action((dotPath, value, options)=>{
|
|
1137
|
+
runSet(dotPath, value, options);
|
|
1138
|
+
});
|
|
1139
|
+
}
|
|
1140
|
+
function terminal_matched(config, name, kind) {
|
|
1141
|
+
const entry = config.terminals[name] ?? null;
|
|
1142
|
+
return {
|
|
1143
|
+
input: name,
|
|
1144
|
+
matched: null !== entry,
|
|
1145
|
+
matchedBy: null === entry ? null : kind,
|
|
1146
|
+
terminal: null === entry ? null : name,
|
|
1147
|
+
entry,
|
|
1148
|
+
candidates: []
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
const SUGGEST_DISTANCE = 3;
|
|
1152
|
+
function suggest(config, target) {
|
|
1153
|
+
if (0 === target.length) return [];
|
|
1154
|
+
const scored = [];
|
|
1155
|
+
for (const [name, entry] of Object.entries(config.terminals)){
|
|
1156
|
+
const pool = [
|
|
1157
|
+
normalizeName(name),
|
|
1158
|
+
...entry.aliases.map((alias)=>normalizeName(alias))
|
|
1159
|
+
].filter((item)=>item.length > 0);
|
|
1160
|
+
let best = 1 / 0;
|
|
1161
|
+
for (const candidate of pool){
|
|
1162
|
+
if (candidate.includes(target) || target.includes(candidate)) {
|
|
1163
|
+
best = Math.min(best, 1);
|
|
1164
|
+
continue;
|
|
1165
|
+
}
|
|
1166
|
+
best = Math.min(best, editDistance(candidate, target));
|
|
1167
|
+
}
|
|
1168
|
+
if (best <= SUGGEST_DISTANCE) scored.push({
|
|
1169
|
+
name,
|
|
1170
|
+
score: best
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
return scored.sort((left, right)=>left.score - right.score).slice(0, 3).map((item)=>item.name);
|
|
1174
|
+
}
|
|
1175
|
+
function resolveTerminalName(terminals, input) {
|
|
1176
|
+
const raw = input.trim();
|
|
1177
|
+
const names = Object.keys(terminals);
|
|
1178
|
+
const target = normalizeName(raw);
|
|
1179
|
+
const wrap = (name, matchedBy)=>({
|
|
1180
|
+
input: raw,
|
|
1181
|
+
name,
|
|
1182
|
+
matchedBy,
|
|
1183
|
+
candidates: []
|
|
1184
|
+
});
|
|
1185
|
+
if (Object.hasOwn(terminals, raw)) return wrap(raw, 'exact');
|
|
1186
|
+
for (const name of names)if (terminals[name]?.aliases.includes(raw) === true) return wrap(name, 'alias');
|
|
1187
|
+
if (target.length > 0) {
|
|
1188
|
+
const byKey = names.find((name)=>normalizeName(name) === target);
|
|
1189
|
+
if (void 0 !== byKey) return wrap(byKey, 'normalized');
|
|
1190
|
+
for (const name of names)if (terminals[name]?.aliases.some((alias)=>normalizeName(alias) === target) === true) return wrap(name, 'normalized');
|
|
1191
|
+
}
|
|
1192
|
+
return {
|
|
1193
|
+
input: raw,
|
|
1194
|
+
name: null,
|
|
1195
|
+
matchedBy: null,
|
|
1196
|
+
candidates: suggest({
|
|
1197
|
+
terminals
|
|
1198
|
+
}, target)
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
function resolveTerminal(config, input) {
|
|
1202
|
+
const match = resolveTerminalName(config.terminals, input);
|
|
1203
|
+
if (null === match.name) return {
|
|
1204
|
+
input: match.input,
|
|
1205
|
+
matched: false,
|
|
1206
|
+
matchedBy: null,
|
|
1207
|
+
terminal: null,
|
|
1208
|
+
entry: null,
|
|
1209
|
+
candidates: match.candidates
|
|
1210
|
+
};
|
|
1211
|
+
return terminal_matched(config, match.name, match.matchedBy ?? 'exact');
|
|
1212
|
+
}
|
|
1213
|
+
function resolveKey(terminals, input) {
|
|
1214
|
+
const match = resolveTerminalName(terminals, input);
|
|
1215
|
+
if (null !== match.name) return match.name;
|
|
1216
|
+
const hint = 0 === match.candidates.length ? '' : `\n最接近:${match.candidates.join('、')}`;
|
|
1217
|
+
throw new errors_CliError(`终端不存在:${input.trim()}${hint}\n查看全部:ylcwf terminal list`, errors_EXIT.NOT_FOUND);
|
|
1218
|
+
}
|
|
1219
|
+
function readTerminals(doc) {
|
|
1220
|
+
const raw = doc.toJS();
|
|
1221
|
+
const section = getIn(raw, [
|
|
1222
|
+
'terminals'
|
|
1223
|
+
]);
|
|
1224
|
+
return 'object' == typeof section && null !== section ? section : {};
|
|
1225
|
+
}
|
|
1226
|
+
const terminal_SIDE_LABEL = {
|
|
1227
|
+
frontend: '前端',
|
|
1228
|
+
backend: '后端'
|
|
1229
|
+
};
|
|
1230
|
+
function collect(value, previous) {
|
|
1231
|
+
return [
|
|
1232
|
+
...previous,
|
|
1233
|
+
value
|
|
1234
|
+
];
|
|
1235
|
+
}
|
|
1236
|
+
function assertAbsolute(value, field) {
|
|
1237
|
+
const trimmed = value.trim();
|
|
1238
|
+
if (0 === trimmed.length) throw new errors_CliError(`${field} 不能为空`, errors_EXIT.USAGE);
|
|
1239
|
+
if (!isAbsolute(trimmed)) throw new errors_CliError(`${field} 必须是绝对路径:${value}`, errors_EXIT.USAGE);
|
|
1240
|
+
return trimmed;
|
|
1241
|
+
}
|
|
1242
|
+
function parseSide(value) {
|
|
1243
|
+
const trimmed = value?.trim();
|
|
1244
|
+
if (void 0 === trimmed || 0 === trimmed.length) throw new errors_CliError('必须指定 --side frontend|backend', errors_EXIT.USAGE);
|
|
1245
|
+
if ('frontend' === trimmed || 'backend' === trimmed) return trimmed;
|
|
1246
|
+
throw new errors_CliError(`--side 必须是 frontend / backend:${trimmed}`, errors_EXIT.USAGE);
|
|
1247
|
+
}
|
|
1248
|
+
function terminal_splitAliases(value) {
|
|
1249
|
+
const trimmed = value?.trim() ?? '';
|
|
1250
|
+
if (0 === trimmed.length) return [];
|
|
1251
|
+
return trimmed.split(',').map((item)=>item.trim()).filter((item)=>item.length > 0);
|
|
1252
|
+
}
|
|
1253
|
+
function readSideList(doc, key, side) {
|
|
1254
|
+
const value = getIn(doc.toJS(), [
|
|
1255
|
+
'terminals',
|
|
1256
|
+
key,
|
|
1257
|
+
'repos',
|
|
1258
|
+
side
|
|
1259
|
+
]);
|
|
1260
|
+
if (!Array.isArray(value)) return [];
|
|
1261
|
+
return value.filter((item)=>'string' == typeof item);
|
|
1262
|
+
}
|
|
1263
|
+
function runTerminalList(options) {
|
|
1264
|
+
const format = parseFormat(options.format);
|
|
1265
|
+
const ready = requireConfig(options.config);
|
|
1266
|
+
if ('json' === format) return void printJson({
|
|
1267
|
+
configPath: ready.path,
|
|
1268
|
+
terminals: ready.config.terminals
|
|
1269
|
+
});
|
|
1270
|
+
const names = Object.keys(ready.config.terminals);
|
|
1271
|
+
if (0 === names.length) return void printLine('(空)运行 `ylcwf terminal add <终端名> --frontend <路径>` 添加');
|
|
1272
|
+
for (const name of names){
|
|
1273
|
+
const terminal = ready.config.terminals[name];
|
|
1274
|
+
if (void 0 === terminal) continue;
|
|
1275
|
+
const aliases = 0 === terminal.aliases.length ? '(无)' : terminal.aliases.join('、');
|
|
1276
|
+
printLine(`${name} 别名:${aliases}`);
|
|
1277
|
+
for (const side of SIDES){
|
|
1278
|
+
const targets = terminal.repos[side];
|
|
1279
|
+
if (0 === targets.length) {
|
|
1280
|
+
printLine(` ${terminal_SIDE_LABEL[side]} (未配置)`);
|
|
1281
|
+
continue;
|
|
1282
|
+
}
|
|
1283
|
+
targets.forEach((target, index)=>{
|
|
1284
|
+
const mark = external_node_fs_existsSync(target) ? picocolors.green(' ✓') : picocolors.red(' ✗');
|
|
1285
|
+
const label = 0 === index ? terminal_SIDE_LABEL[side] : ' '.repeat(terminal_SIDE_LABEL[side].length);
|
|
1286
|
+
printLine(` ${label} ${target}${mark}`);
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
function runTerminalAdd(key, options) {
|
|
1292
|
+
const trimmedKey = key.trim();
|
|
1293
|
+
if (0 === trimmedKey.length) throw new errors_CliError('终端名不能为空', errors_EXIT.USAGE);
|
|
1294
|
+
if (trimmedKey.includes('.')) throw new errors_CliError('终端名不能包含「.」(与配置路径语法冲突)', errors_EXIT.USAGE);
|
|
1295
|
+
const { path: configPath, doc } = obtainDocument(options.config);
|
|
1296
|
+
if (void 0 !== getIn(doc.toJS(), [
|
|
1297
|
+
'terminals',
|
|
1298
|
+
trimmedKey
|
|
1299
|
+
])) throw new errors_CliError(`终端已存在:${trimmedKey}\n修改请用:ylcwf terminal repo add|rm,或 terminal set --aliases`, errors_EXIT.USAGE);
|
|
1300
|
+
doc.setIn([
|
|
1301
|
+
'terminals',
|
|
1302
|
+
trimmedKey
|
|
1303
|
+
], {
|
|
1304
|
+
aliases: options.alias ?? [],
|
|
1305
|
+
repos: {
|
|
1306
|
+
frontend: (options.frontend ?? []).map((item)=>assertAbsolute(item, '--frontend')),
|
|
1307
|
+
backend: (options.backend ?? []).map((item)=>assertAbsolute(item, '--backend'))
|
|
1308
|
+
}
|
|
1309
|
+
});
|
|
1310
|
+
assertWritable(doc, configPath);
|
|
1311
|
+
saveDocument(doc, configPath);
|
|
1312
|
+
printLine(`已添加终端:${trimmedKey}`);
|
|
1313
|
+
printLine(`配置文件:${configPath}`);
|
|
1314
|
+
}
|
|
1315
|
+
function runTerminalSetAliases(key, options) {
|
|
1316
|
+
const trimmedKey = key.trim();
|
|
1317
|
+
const { path: configPath, doc } = obtainDocument(options.config);
|
|
1318
|
+
const resolvedKey = resolveKey(readTerminals(doc), trimmedKey);
|
|
1319
|
+
if (void 0 === options.aliases) throw new errors_CliError('需要指定 --aliases(逗号分隔,整体替换)', errors_EXIT.USAGE);
|
|
1320
|
+
doc.setIn([
|
|
1321
|
+
'terminals',
|
|
1322
|
+
resolvedKey,
|
|
1323
|
+
'aliases'
|
|
1324
|
+
], terminal_splitAliases(options.aliases));
|
|
1325
|
+
assertWritable(doc, configPath);
|
|
1326
|
+
saveDocument(doc, configPath);
|
|
1327
|
+
printLine(`已更新终端别名:${resolvedKey}`);
|
|
1328
|
+
printLine(`配置文件:${configPath}`);
|
|
1329
|
+
}
|
|
1330
|
+
function runTerminalRepoAdd(key, options) {
|
|
1331
|
+
const trimmedKey = key.trim();
|
|
1332
|
+
const side = parseSide(options.side);
|
|
1333
|
+
const target = assertAbsolute(options.path ?? '', '--path');
|
|
1334
|
+
const { path: configPath, doc } = obtainDocument(options.config);
|
|
1335
|
+
const resolvedKey = resolveKey(readTerminals(doc), trimmedKey);
|
|
1336
|
+
if (resolvedKey !== trimmedKey) printLine(`(按别名匹配到终端:${resolvedKey})`);
|
|
1337
|
+
const list = readSideList(doc, resolvedKey, side);
|
|
1338
|
+
if (list.includes(target)) throw new errors_CliError(`${side} 端已存在该仓库:${target}`, errors_EXIT.USAGE);
|
|
1339
|
+
doc.setIn([
|
|
1340
|
+
'terminals',
|
|
1341
|
+
resolvedKey,
|
|
1342
|
+
'repos',
|
|
1343
|
+
side
|
|
1344
|
+
], [
|
|
1345
|
+
...list,
|
|
1346
|
+
target
|
|
1347
|
+
]);
|
|
1348
|
+
assertWritable(doc, configPath);
|
|
1349
|
+
saveDocument(doc, configPath);
|
|
1350
|
+
printLine(`已为「${resolvedKey}」的 ${side} 端添加仓库:${target}(共 ${list.length + 1} 个)`);
|
|
1351
|
+
}
|
|
1352
|
+
function runTerminalRepoRemove(key, options) {
|
|
1353
|
+
const trimmedKey = key.trim();
|
|
1354
|
+
const side = parseSide(options.side);
|
|
1355
|
+
const target = assertAbsolute(options.path ?? '', '--path');
|
|
1356
|
+
const { path: configPath, doc } = obtainDocument(options.config);
|
|
1357
|
+
const resolvedKey = resolveKey(readTerminals(doc), trimmedKey);
|
|
1358
|
+
const list = readSideList(doc, resolvedKey, side);
|
|
1359
|
+
if (0 === list.length) throw new errors_CliError(`终端「${resolvedKey}」的 ${side} 端没有仓库`, errors_EXIT.NOT_FOUND);
|
|
1360
|
+
if (!list.includes(target)) throw new errors_CliError(`${side} 端不存在该仓库:${target}\n现有:\n${list.map((item, index)=>` ${index + 1}) ${item}`).join('\n')}`, errors_EXIT.NOT_FOUND);
|
|
1361
|
+
const next = list.filter((item)=>item !== target);
|
|
1362
|
+
doc.setIn([
|
|
1363
|
+
'terminals',
|
|
1364
|
+
resolvedKey,
|
|
1365
|
+
'repos',
|
|
1366
|
+
side
|
|
1367
|
+
], next);
|
|
1368
|
+
assertWritable(doc, configPath);
|
|
1369
|
+
saveDocument(doc, configPath);
|
|
1370
|
+
printLine(`已移除「${resolvedKey}」的 ${side} 端仓库:${target}(剩余 ${next.length} 个)`);
|
|
1371
|
+
}
|
|
1372
|
+
function runTerminalRepoList(key, options) {
|
|
1373
|
+
const trimmedKey = key.trim();
|
|
1374
|
+
const format = parseFormat(options.format);
|
|
1375
|
+
const ready = requireConfig(options.config);
|
|
1376
|
+
const resolvedKey = resolveKey(ready.config.terminals, trimmedKey);
|
|
1377
|
+
const terminal = ready.config.terminals[resolvedKey];
|
|
1378
|
+
if (void 0 === terminal) throw new errors_CliError(`终端不存在:${resolvedKey}`, errors_EXIT.NOT_FOUND);
|
|
1379
|
+
const sides = void 0 === options.side ? [
|
|
1380
|
+
...SIDES
|
|
1381
|
+
] : [
|
|
1382
|
+
parseSide(options.side)
|
|
1383
|
+
];
|
|
1384
|
+
if ('json' === format) {
|
|
1385
|
+
const payload = {};
|
|
1386
|
+
for (const side of sides)payload[side] = terminal.repos[side];
|
|
1387
|
+
printJson({
|
|
1388
|
+
terminal: resolvedKey,
|
|
1389
|
+
repos: payload
|
|
1390
|
+
});
|
|
1391
|
+
return;
|
|
1392
|
+
}
|
|
1393
|
+
for (const side of sides){
|
|
1394
|
+
const targets = terminal.repos[side];
|
|
1395
|
+
if (0 === targets.length) {
|
|
1396
|
+
printLine(`${side}(未配置)`);
|
|
1397
|
+
continue;
|
|
1398
|
+
}
|
|
1399
|
+
targets.forEach((target, index)=>{
|
|
1400
|
+
printLine(`${side} ${index + 1}) ${target}${external_node_fs_existsSync(target) ? '' : ' (路径不存在)'}`);
|
|
1401
|
+
});
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
async function runTerminalRemove(key, options) {
|
|
1405
|
+
const trimmedKey = key.trim();
|
|
1406
|
+
const ready = requireConfig(options.config);
|
|
1407
|
+
const resolvedKey = resolveKey(ready.config.terminals, trimmedKey);
|
|
1408
|
+
if (true !== options.yes) {
|
|
1409
|
+
if (true !== process.stdin.isTTY) throw new errors_CliError('非交互环境删除终端需要显式加 --yes', errors_EXIT.USAGE);
|
|
1410
|
+
const { confirm } = await import("@clack/prompts");
|
|
1411
|
+
const answer = await confirm({
|
|
1412
|
+
message: `确认删除终端「${resolvedKey}」?`,
|
|
1413
|
+
initialValue: false
|
|
1414
|
+
});
|
|
1415
|
+
if (true !== answer) return void printLine('已取消');
|
|
1416
|
+
}
|
|
1417
|
+
ready.doc.deleteIn([
|
|
1418
|
+
'terminals',
|
|
1419
|
+
resolvedKey
|
|
1420
|
+
]);
|
|
1421
|
+
assertWritable(ready.doc, ready.path);
|
|
1422
|
+
saveDocument(ready.doc, ready.path);
|
|
1423
|
+
printLine(`已删除终端:${resolvedKey}`);
|
|
1424
|
+
}
|
|
1425
|
+
function registerTerminal(program) {
|
|
1426
|
+
const terminal = program.command('terminal').description('维护 PRD 终端 → 本地仓库映射');
|
|
1427
|
+
terminal.command('list').description('列出全部终端').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
|
|
1428
|
+
runTerminalList(options);
|
|
1429
|
+
});
|
|
1430
|
+
terminal.command('add <key>').description('新增终端(终端名用 PRD 中的取值,可为中文)').option('-c, --config <path>', '指定配置文件路径').option('--frontend <path>', '前端仓库绝对路径,可重复', collect, []).option('--backend <path>', '后端仓库绝对路径,可重复', collect, []).option('--alias <name>', '别名,可重复', collect, []).action((key, options)=>{
|
|
1431
|
+
runTerminalAdd(key, options);
|
|
1432
|
+
});
|
|
1433
|
+
terminal.command('set <key>').description('修改终端别名(仓库增删用 terminal repo)').option('-c, --config <path>', '指定配置文件路径').option('--aliases <list>', '别名,逗号分隔(整体替换)').action((key, options)=>{
|
|
1434
|
+
runTerminalSetAliases(key, options);
|
|
1435
|
+
});
|
|
1436
|
+
terminal.command('rm <key>').description('删除终端').option('-c, --config <path>', '指定配置文件路径').option('--yes', '跳过确认').action(async (key, options)=>{
|
|
1437
|
+
await runTerminalRemove(key, options);
|
|
1438
|
+
});
|
|
1439
|
+
const repo = terminal.command('repo').description('维护单个终端某一端的仓库列表');
|
|
1440
|
+
repo.command('list <key>').description('列出仓库').option('-c, --config <path>', '指定配置文件路径').option('--side <side>', '限定端口:frontend | backend').option('--format <format>', '输出格式:human | json', 'human').action((key, options)=>{
|
|
1441
|
+
runTerminalRepoList(key, options);
|
|
1442
|
+
});
|
|
1443
|
+
repo.command('add <key>').description('为某一端追加仓库').option('-c, --config <path>', '指定配置文件路径').option('--side <side>', '端口:frontend | backend').option('--path <path>', '仓库绝对路径').action((key, options)=>{
|
|
1444
|
+
runTerminalRepoAdd(key, options);
|
|
1445
|
+
});
|
|
1446
|
+
repo.command('rm <key>').description('从某一端移除仓库').option('-c, --config <path>', '指定配置文件路径').option('--side <side>', '端口:frontend | backend').option('--path <path>', '仓库绝对路径').action((key, options)=>{
|
|
1447
|
+
runTerminalRepoRemove(key, options);
|
|
1448
|
+
});
|
|
1449
|
+
}
|
|
1450
|
+
const SAFE_SEGMENT = /^[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
|
|
1451
|
+
function safeSegment(value, label) {
|
|
1452
|
+
const trimmed = value.trim();
|
|
1453
|
+
if (!SAFE_SEGMENT.test(trimmed) || '.' === trimmed || '..' === trimmed) throw new errors_CliError(`${label} 不合法:${value}`, errors_EXIT.USAGE);
|
|
1454
|
+
return trimmed;
|
|
1455
|
+
}
|
|
1456
|
+
const ACTION_META = {
|
|
1457
|
+
start: {
|
|
1458
|
+
label: '开始实施',
|
|
1459
|
+
from: '未开始',
|
|
1460
|
+
to: '进行中'
|
|
1461
|
+
},
|
|
1462
|
+
submit: {
|
|
1463
|
+
label: '提交验收',
|
|
1464
|
+
from: '进行中',
|
|
1465
|
+
to: '待验收'
|
|
1466
|
+
},
|
|
1467
|
+
accept: {
|
|
1468
|
+
label: '验收通过',
|
|
1469
|
+
from: '待验收',
|
|
1470
|
+
to: '已完成'
|
|
1471
|
+
},
|
|
1472
|
+
reject: {
|
|
1473
|
+
label: '验收驳回',
|
|
1474
|
+
from: '待验收',
|
|
1475
|
+
to: '进行中'
|
|
1476
|
+
}
|
|
1477
|
+
};
|
|
1478
|
+
function appendHistory(entry) {
|
|
1479
|
+
try {
|
|
1480
|
+
const target = historyPath();
|
|
1481
|
+
mkdirSync(dirname(target), {
|
|
1482
|
+
recursive: true
|
|
1483
|
+
});
|
|
1484
|
+
appendFileSync(target, `${JSON.stringify({
|
|
1485
|
+
at: new Date().toISOString(),
|
|
1486
|
+
...entry
|
|
1487
|
+
})}\n`, 'utf8');
|
|
1488
|
+
} catch {}
|
|
1489
|
+
}
|
|
1490
|
+
function readTaskHistory(options) {
|
|
1491
|
+
const target = historyPath();
|
|
1492
|
+
if (!external_node_fs_existsSync(target)) return [];
|
|
1493
|
+
const limit = options.limit ?? 5;
|
|
1494
|
+
const lines = readFileSync(target, 'utf8').trim().split('\n').filter((line)=>line.length > 0);
|
|
1495
|
+
const entries = [];
|
|
1496
|
+
for(let index = lines.length - 1; index >= 0 && entries.length < limit; index -= 1){
|
|
1497
|
+
const line = lines[index];
|
|
1498
|
+
if (void 0 !== line) try {
|
|
1499
|
+
const parsed = JSON.parse(line);
|
|
1500
|
+
if (parsed.iteration.toLowerCase() !== options.iteration.toLowerCase()) continue;
|
|
1501
|
+
if (parsed.developer !== options.developer) continue;
|
|
1502
|
+
if (void 0 !== options.taskId && parsed.taskId !== options.taskId) continue;
|
|
1503
|
+
entries.push(parsed);
|
|
1504
|
+
} catch {
|
|
1505
|
+
continue;
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
return entries;
|
|
1509
|
+
}
|
|
1510
|
+
const TASK_HEADERS = {
|
|
1511
|
+
id: '任务编号',
|
|
1512
|
+
requirement: '关联需求编号',
|
|
1513
|
+
selfTest: 'AI自测状态',
|
|
1514
|
+
acceptance: '开发人工验收',
|
|
1515
|
+
status: '任务状态'
|
|
1516
|
+
};
|
|
1517
|
+
const REQUIREMENT_HEADERS = {
|
|
1518
|
+
id: '需求编号',
|
|
1519
|
+
status: '开发状态',
|
|
1520
|
+
progress: '开发进度(%)'
|
|
1521
|
+
};
|
|
1522
|
+
function columnIndex(headerCells, name) {
|
|
1523
|
+
const index = headerCells.findIndex((cell)=>cell.trim() === name);
|
|
1524
|
+
if (index < 0) throw new errors_CliError(`表格缺少列「${name}」,无法安全写入`, errors_EXIT.INVALID);
|
|
1525
|
+
return index;
|
|
1526
|
+
}
|
|
1527
|
+
function splitRow(line) {
|
|
1528
|
+
const trimmed = line.trim();
|
|
1529
|
+
const inner = trimmed.startsWith('|') ? trimmed.slice(1) : trimmed;
|
|
1530
|
+
const withoutTail = inner.endsWith('|') ? inner.slice(0, -1) : inner;
|
|
1531
|
+
return withoutTail.split('|').map((cell)=>cell.trim());
|
|
1532
|
+
}
|
|
1533
|
+
function joinRow(cells) {
|
|
1534
|
+
return `| ${cells.join(' | ')} |`;
|
|
1535
|
+
}
|
|
1536
|
+
function canSubmit(selfTest) {
|
|
1537
|
+
const text = selfTest.trim();
|
|
1538
|
+
return '通过' === text || text.startsWith('免测');
|
|
1539
|
+
}
|
|
1540
|
+
function sectionRange(lines, heading) {
|
|
1541
|
+
const start = lines.findIndex((line)=>line.trim() === heading);
|
|
1542
|
+
if (start < 0) throw new errors_CliError(`文档缺少章节「${heading}」,无法安全写入`, errors_EXIT.INVALID);
|
|
1543
|
+
let end = lines.length;
|
|
1544
|
+
for(let index = start + 1; index < lines.length; index += 1){
|
|
1545
|
+
const line = lines[index] ?? '';
|
|
1546
|
+
if (/^##\s+/.test(line) || /^#\s+/.test(line)) {
|
|
1547
|
+
end = index;
|
|
1548
|
+
break;
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
return [
|
|
1552
|
+
start,
|
|
1553
|
+
end
|
|
1554
|
+
];
|
|
1555
|
+
}
|
|
1556
|
+
function parseTaskRows(lines) {
|
|
1557
|
+
const [start, end] = sectionRange(lines, '## 三、任务清单');
|
|
1558
|
+
let header = null;
|
|
1559
|
+
const rows = [];
|
|
1560
|
+
for(let index = start; index < end; index += 1){
|
|
1561
|
+
const line = lines[index] ?? '';
|
|
1562
|
+
if (!line.trim().startsWith('|')) continue;
|
|
1563
|
+
const cells = splitRow(line);
|
|
1564
|
+
if (null === header) {
|
|
1565
|
+
if (cells.includes(TASK_HEADERS.id)) header = cells;
|
|
1566
|
+
continue;
|
|
1567
|
+
}
|
|
1568
|
+
if (cells.every((cell)=>/^:?-{2,}:?$/.test(cell))) continue;
|
|
1569
|
+
const taskId = cells[columnIndex(header, TASK_HEADERS.id)] ?? '';
|
|
1570
|
+
if (/^#\d{3,6}-T\d+$/.test(taskId)) rows.push({
|
|
1571
|
+
index,
|
|
1572
|
+
cells,
|
|
1573
|
+
taskId,
|
|
1574
|
+
status: cells[columnIndex(header, TASK_HEADERS.status)] ?? '',
|
|
1575
|
+
acceptance: cells[columnIndex(header, TASK_HEADERS.acceptance)] ?? '',
|
|
1576
|
+
selfTest: cells[columnIndex(header, TASK_HEADERS.selfTest)] ?? '',
|
|
1577
|
+
requirementId: cells[columnIndex(header, TASK_HEADERS.requirement)] ?? ''
|
|
1578
|
+
});
|
|
1579
|
+
}
|
|
1580
|
+
if (null === header) throw new errors_CliError('未找到任务清单表头,无法安全写入', errors_EXIT.INVALID);
|
|
1581
|
+
return {
|
|
1582
|
+
header,
|
|
1583
|
+
rows
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
function parseRequirementRows(lines) {
|
|
1587
|
+
const [start, end] = sectionRange(lines, '## 二、需求清单');
|
|
1588
|
+
let header = null;
|
|
1589
|
+
const rows = [];
|
|
1590
|
+
for(let index = start; index < end; index += 1){
|
|
1591
|
+
const line = lines[index] ?? '';
|
|
1592
|
+
if (!line.trim().startsWith('|')) continue;
|
|
1593
|
+
const cells = splitRow(line);
|
|
1594
|
+
if (null === header) {
|
|
1595
|
+
if (cells.includes(REQUIREMENT_HEADERS.id)) header = cells;
|
|
1596
|
+
continue;
|
|
1597
|
+
}
|
|
1598
|
+
if (cells.every((cell)=>/^:?-{2,}:?$/.test(cell))) continue;
|
|
1599
|
+
const id = cells[columnIndex(header, REQUIREMENT_HEADERS.id)] ?? '';
|
|
1600
|
+
if (/^#\d{3,6}$/.test(id)) rows.push({
|
|
1601
|
+
index,
|
|
1602
|
+
cells,
|
|
1603
|
+
id
|
|
1604
|
+
});
|
|
1605
|
+
}
|
|
1606
|
+
if (null === header) throw new errors_CliError('未找到需求清单表头,无法安全写入', errors_EXIT.INVALID);
|
|
1607
|
+
return {
|
|
1608
|
+
header,
|
|
1609
|
+
rows
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
function aggregateRequirementStatus(statuses) {
|
|
1613
|
+
if (0 === statuses.length) return '未开始';
|
|
1614
|
+
if (statuses.every((status)=>'未开始' === status)) return '未开始';
|
|
1615
|
+
if (statuses.every((status)=>'已完成' === status)) return '已完成';
|
|
1616
|
+
return '进行中';
|
|
1617
|
+
}
|
|
1618
|
+
function updateDetailBlock(lines, taskId, updates) {
|
|
1619
|
+
const headingIndex = lines.findIndex((line)=>line.trim().startsWith(`### [${taskId}]`));
|
|
1620
|
+
if (headingIndex < 0) throw new errors_CliError(`任务 ${taskId} 缺少第四章详情区块,无法同步状态`, errors_EXIT.INVALID);
|
|
1621
|
+
let end = lines.length;
|
|
1622
|
+
for(let index = headingIndex + 1; index < lines.length; index += 1)if (/^###\s+/.test(lines[index] ?? '') || /^##\s+/.test(lines[index] ?? '')) {
|
|
1623
|
+
end = index;
|
|
1624
|
+
break;
|
|
1625
|
+
}
|
|
1626
|
+
const next = [
|
|
1627
|
+
...lines
|
|
1628
|
+
];
|
|
1629
|
+
for(let index = headingIndex; index < end; index += 1){
|
|
1630
|
+
const line = lines[index] ?? '';
|
|
1631
|
+
const match = /^(\s*-\s+\*\*(.+?)\*\*\s*[::]\s*)(.*)$/.exec(line);
|
|
1632
|
+
if (null === match) continue;
|
|
1633
|
+
const field = match[2] ?? '';
|
|
1634
|
+
const replacement = updates[field];
|
|
1635
|
+
if (void 0 !== replacement) next[index] = `${match[1] ?? ''}${replacement}`;
|
|
1636
|
+
}
|
|
1637
|
+
return next;
|
|
1638
|
+
}
|
|
1639
|
+
function loadDoc(docsRoot, iterationRaw, developerRaw) {
|
|
1640
|
+
const iteration = safeSegment(iterationRaw, '迭代目录');
|
|
1641
|
+
const developer = safeSegment(developerRaw, '开发者标识');
|
|
1642
|
+
const file = external_node_path_join(docsRoot, iteration, `${developer}.md`);
|
|
1643
|
+
if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${iteration}/${developer}.md`, errors_EXIT.NOT_FOUND);
|
|
1644
|
+
const mtime = statSync(file).mtimeMs;
|
|
1645
|
+
const original = readFileSync(file, 'utf8');
|
|
1646
|
+
return {
|
|
1647
|
+
file,
|
|
1648
|
+
mtime,
|
|
1649
|
+
original,
|
|
1650
|
+
lines: original.split('\n')
|
|
1651
|
+
};
|
|
1652
|
+
}
|
|
1653
|
+
function computeUpdate(lines, taskId, action) {
|
|
1654
|
+
const { header, rows } = parseTaskRows(lines);
|
|
1655
|
+
const target = rows.find((row)=>row.taskId === taskId);
|
|
1656
|
+
if (void 0 === target) throw new errors_CliError(`任务清单中未找到 ${taskId}`, errors_EXIT.NOT_FOUND);
|
|
1657
|
+
const statusIndex = columnIndex(header, TASK_HEADERS.status);
|
|
1658
|
+
const acceptanceIndex = columnIndex(header, TASK_HEADERS.acceptance);
|
|
1659
|
+
const currentStatus = target.status;
|
|
1660
|
+
const currentAcceptance = target.acceptance;
|
|
1661
|
+
const meta = ACTION_META[action];
|
|
1662
|
+
if (currentStatus !== meta.from) throw new errors_CliError(`任务 ${taskId} 当前状态为「${currentStatus}」,无法执行「${meta.label}」(要求「${meta.from}」)`, errors_EXIT.USAGE);
|
|
1663
|
+
if ('submit' === action && !canSubmit(target.selfTest)) throw new errors_CliError(`任务 ${taskId} 的 AI 自测状态为「${target.selfTest}」,未通过自测不能提交验收`, errors_EXIT.USAGE);
|
|
1664
|
+
const nextStatus = meta.to;
|
|
1665
|
+
const nextAcceptance = 'accept' === action ? '验收通过' : 'reject' === action ? '验收驳回' : currentAcceptance;
|
|
1666
|
+
const changes = [];
|
|
1667
|
+
if (nextStatus !== currentStatus) changes.push(`${taskId} 任务状态:${currentStatus} → ${nextStatus}`);
|
|
1668
|
+
if (nextAcceptance !== currentAcceptance) changes.push(`${taskId} 开发人工验收:${currentAcceptance} → ${nextAcceptance}`);
|
|
1669
|
+
const updated = [
|
|
1670
|
+
...lines
|
|
1671
|
+
];
|
|
1672
|
+
const taskCells = [
|
|
1673
|
+
...target.cells
|
|
1674
|
+
];
|
|
1675
|
+
taskCells[statusIndex] = nextStatus;
|
|
1676
|
+
taskCells[acceptanceIndex] = nextAcceptance;
|
|
1677
|
+
updated[target.index] = joinRow(taskCells);
|
|
1678
|
+
const withDetail = updateDetailBlock(updated, taskId, {
|
|
1679
|
+
任务状态: nextStatus,
|
|
1680
|
+
人工验收: nextAcceptance
|
|
1681
|
+
});
|
|
1682
|
+
const requirementStatuses = rows.filter((row)=>row.requirementId === target.requirementId).map((row)=>row.taskId === taskId ? nextStatus : row.status);
|
|
1683
|
+
const requirementStatus = aggregateRequirementStatus(requirementStatuses);
|
|
1684
|
+
const completed = requirementStatuses.filter((status)=>'已完成' === status).length;
|
|
1685
|
+
const progress = 0 === requirementStatuses.length ? 0 : Math.round(completed / requirementStatuses.length * 100);
|
|
1686
|
+
const requirementParse = parseRequirementRows(withDetail);
|
|
1687
|
+
const requirementTarget = requirementParse.rows.find((row)=>row.id === target.requirementId);
|
|
1688
|
+
if (void 0 === requirementTarget) throw new errors_CliError(`需求清单中未找到 ${target.requirementId}`, errors_EXIT.NOT_FOUND);
|
|
1689
|
+
const requirementCells = [
|
|
1690
|
+
...requirementTarget.cells
|
|
1691
|
+
];
|
|
1692
|
+
const previousStatus = requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.status)] ?? '';
|
|
1693
|
+
const previousProgress = requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.progress)] ?? '';
|
|
1694
|
+
requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.status)] = requirementStatus;
|
|
1695
|
+
requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.progress)] = String(progress);
|
|
1696
|
+
withDetail[requirementTarget.index] = joinRow(requirementCells);
|
|
1697
|
+
if (previousStatus !== requirementStatus) changes.push(`需求 ${target.requirementId} 开发状态:${previousStatus} → ${requirementStatus}`);
|
|
1698
|
+
if (previousProgress !== String(progress)) changes.push(`需求 ${target.requirementId} 开发进度:${previousProgress}% → ${progress}%`);
|
|
1699
|
+
return {
|
|
1700
|
+
lines: withDetail,
|
|
1701
|
+
changes
|
|
1702
|
+
};
|
|
1703
|
+
}
|
|
1704
|
+
function commit(context, lines, changes, message, iteration, developer, action, taskIds) {
|
|
1705
|
+
if (statSync(context.file).mtimeMs !== context.mtime) throw new errors_CliError('文件已被外部修改,请刷新后重试', errors_EXIT.INVALID);
|
|
1706
|
+
const output = lines.join('\n');
|
|
1707
|
+
if (output === context.original) return {
|
|
1708
|
+
ok: true,
|
|
1709
|
+
message: '状态未发生变化',
|
|
1710
|
+
changes: [],
|
|
1711
|
+
file: context.file
|
|
1712
|
+
};
|
|
1713
|
+
writeFileSync(context.file, output, 'utf8');
|
|
1714
|
+
const violation = validateAfterWrite(dirname(context.file), iteration, developer);
|
|
1715
|
+
if (null !== violation) {
|
|
1716
|
+
writeFileSync(context.file, context.original, 'utf8');
|
|
1717
|
+
throw new errors_CliError(`写入被校验器拒绝,已回滚:${violation}`, errors_EXIT.INVALID);
|
|
1718
|
+
}
|
|
1719
|
+
appendHistory({
|
|
1720
|
+
iteration,
|
|
1721
|
+
developer,
|
|
1722
|
+
taskId: taskIds.join(','),
|
|
1723
|
+
action,
|
|
1724
|
+
changes
|
|
1725
|
+
});
|
|
1726
|
+
return {
|
|
1727
|
+
ok: true,
|
|
1728
|
+
message,
|
|
1729
|
+
changes,
|
|
1730
|
+
file: context.file
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
function applyBatchAction(options) {
|
|
1734
|
+
if (0 === options.taskIds.length) throw new errors_CliError('未选择任务', errors_EXIT.USAGE);
|
|
1735
|
+
const context = loadDoc(options.docsRoot, options.iteration, options.developer);
|
|
1736
|
+
let lines = context.lines;
|
|
1737
|
+
const changes = [];
|
|
1738
|
+
for (const taskId of options.taskIds){
|
|
1739
|
+
const result = computeUpdate(lines, taskId, options.action);
|
|
1740
|
+
lines = result.lines;
|
|
1741
|
+
changes.push(...result.changes);
|
|
1742
|
+
}
|
|
1743
|
+
return commit(context, lines, changes, `已对 ${options.taskIds.length} 个任务执行「${ACTION_META[options.action].label}」`, safeSegment(options.iteration, '迭代目录'), safeSegment(options.developer, '开发者标识'), options.action, options.taskIds);
|
|
1744
|
+
}
|
|
1745
|
+
function applyTaskAction(options) {
|
|
1746
|
+
const context = loadDoc(options.docsRoot, options.iteration, options.developer);
|
|
1747
|
+
const result = computeUpdate(context.lines, options.taskId, options.action);
|
|
1748
|
+
return commit(context, result.lines, result.changes, `已执行「${ACTION_META[options.action].label}」`, safeSegment(options.iteration, '迭代目录'), safeSegment(options.developer, '开发者标识'), options.action, [
|
|
1749
|
+
options.taskId
|
|
1750
|
+
]);
|
|
1751
|
+
}
|
|
1752
|
+
function validateAfterWrite(docsRoot, iteration, developer) {
|
|
1753
|
+
const script = external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py');
|
|
1754
|
+
if (!external_node_fs_existsSync(script)) return null;
|
|
1755
|
+
const bin = external_node_fs_existsSync('/usr/bin/python3') ? '/usr/bin/python3' : 'python3';
|
|
1756
|
+
try {
|
|
1757
|
+
const stdout = execFileSync(bin, [
|
|
1758
|
+
script,
|
|
1759
|
+
'--docs-root',
|
|
1760
|
+
docsRoot,
|
|
1761
|
+
'--iteration',
|
|
1762
|
+
iteration,
|
|
1763
|
+
'--developer',
|
|
1764
|
+
developer,
|
|
1765
|
+
'--format',
|
|
1766
|
+
'json'
|
|
1767
|
+
], {
|
|
1768
|
+
encoding: 'utf8',
|
|
1769
|
+
timeout: 15000,
|
|
1770
|
+
maxBuffer: 16777216
|
|
1771
|
+
});
|
|
1772
|
+
const payload = JSON.parse(stdout);
|
|
1773
|
+
const first = payload.errors?.[0];
|
|
1774
|
+
return first?.message ?? null;
|
|
1775
|
+
} catch (error) {
|
|
1776
|
+
const stdout = error.stdout ?? '';
|
|
1777
|
+
try {
|
|
1778
|
+
const payload = JSON.parse(stdout);
|
|
1779
|
+
return payload.errors?.[0]?.message ?? '校验器未通过';
|
|
1780
|
+
} catch {
|
|
1781
|
+
return null;
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
function recalcRequirements(options) {
|
|
1786
|
+
const context = loadDoc(options.docsRoot, options.iteration, options.developer);
|
|
1787
|
+
const { rows: taskRows } = parseTaskRows(context.lines);
|
|
1788
|
+
const requirementParse = parseRequirementRows(context.lines);
|
|
1789
|
+
const lines = [
|
|
1790
|
+
...context.lines
|
|
1791
|
+
];
|
|
1792
|
+
const changes = [];
|
|
1793
|
+
for (const requirement of requirementParse.rows){
|
|
1794
|
+
const own = taskRows.filter((row)=>row.requirementId === requirement.id);
|
|
1795
|
+
const status = aggregateRequirementStatus(own.map((row)=>row.status));
|
|
1796
|
+
const completed = own.filter((row)=>'已完成' === row.status).length;
|
|
1797
|
+
const progress = 0 === own.length ? 0 : Math.round(completed / own.length * 100);
|
|
1798
|
+
const cells = [
|
|
1799
|
+
...requirement.cells
|
|
1800
|
+
];
|
|
1801
|
+
const previousStatus = cells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.status)] ?? '';
|
|
1802
|
+
const previousProgress = cells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.progress)] ?? '';
|
|
1803
|
+
if (previousStatus !== status || previousProgress !== String(progress)) {
|
|
1804
|
+
cells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.status)] = status;
|
|
1805
|
+
cells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.progress)] = String(progress);
|
|
1806
|
+
lines[requirement.index] = joinRow(cells);
|
|
1807
|
+
if (previousStatus !== status) changes.push(`${requirement.id} 开发状态:${previousStatus} → ${status}`);
|
|
1808
|
+
if (previousProgress !== String(progress)) changes.push(`${requirement.id} 开发进度:${previousProgress}% → ${progress}%`);
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
if (true === options.dryRun || 0 === changes.length) return {
|
|
1812
|
+
changes,
|
|
1813
|
+
file: context.file
|
|
1814
|
+
};
|
|
1815
|
+
return {
|
|
1816
|
+
changes,
|
|
1817
|
+
file: commit(context, lines, changes, `已重算 ${requirementParse.rows.length} 个需求的状态与进度`, safeSegment(options.iteration, '迭代目录'), safeSegment(options.developer, '开发者标识'), 'start', []).file
|
|
1818
|
+
};
|
|
1819
|
+
}
|
|
1820
|
+
function availableActions(options) {
|
|
1821
|
+
const iteration = safeSegment(options.iteration, '迭代目录');
|
|
1822
|
+
const developer = safeSegment(options.developer, '开发者标识');
|
|
1823
|
+
const file = external_node_path_join(options.docsRoot, iteration, `${developer}.md`);
|
|
1824
|
+
if (!external_node_fs_existsSync(file)) return {};
|
|
1825
|
+
const lines = readFileSync(file, 'utf8').split('\n');
|
|
1826
|
+
const { rows } = parseTaskRows(lines);
|
|
1827
|
+
const result = {};
|
|
1828
|
+
for (const row of rows){
|
|
1829
|
+
const list = [];
|
|
1830
|
+
if ('未开始' === row.status) list.push({
|
|
1831
|
+
action: 'start',
|
|
1832
|
+
enabled: true,
|
|
1833
|
+
reason: ''
|
|
1834
|
+
});
|
|
1835
|
+
if ('进行中' === row.status) {
|
|
1836
|
+
const ok = canSubmit(row.selfTest);
|
|
1837
|
+
list.push({
|
|
1838
|
+
action: 'submit',
|
|
1839
|
+
enabled: ok,
|
|
1840
|
+
reason: ok ? '' : `AI 自测为「${row.selfTest}」,需先通过自测`
|
|
1841
|
+
});
|
|
1842
|
+
}
|
|
1843
|
+
if ('待验收' === row.status) {
|
|
1844
|
+
list.push({
|
|
1845
|
+
action: 'accept',
|
|
1846
|
+
enabled: true,
|
|
1847
|
+
reason: ''
|
|
1848
|
+
});
|
|
1849
|
+
list.push({
|
|
1850
|
+
action: 'reject',
|
|
1851
|
+
enabled: true,
|
|
1852
|
+
reason: ''
|
|
1853
|
+
});
|
|
1854
|
+
}
|
|
1855
|
+
result[row.taskId] = list;
|
|
1856
|
+
}
|
|
1857
|
+
return result;
|
|
1858
|
+
}
|
|
1859
|
+
function resolveIteration(options, docsRoot) {
|
|
1860
|
+
const explicit = options.iteration?.trim();
|
|
1861
|
+
if (void 0 !== explicit && explicit.length > 0) return explicit;
|
|
1862
|
+
const cwd = process.cwd();
|
|
1863
|
+
if (cwd.startsWith(docsRoot)) {
|
|
1864
|
+
const relative = cwd.slice(docsRoot.length).split('/').filter((item)=>item.length > 0);
|
|
1865
|
+
const first = relative[0];
|
|
1866
|
+
if (void 0 !== first) return first;
|
|
1867
|
+
}
|
|
1868
|
+
throw new errors_CliError('缺少 --iteration(迭代目录名),或在文档仓库的迭代目录内执行', errors_EXIT.USAGE);
|
|
1869
|
+
}
|
|
1870
|
+
function resolveDeveloper(options, configured) {
|
|
1871
|
+
const explicit = options.developer?.trim();
|
|
1872
|
+
const target = void 0 !== explicit && explicit.length > 0 ? explicit : configured;
|
|
1873
|
+
if (target !== configured) throw new errors_CliError(`只能修改自己的任务文档(当前身份:${configured})`, errors_EXIT.USAGE);
|
|
1874
|
+
return target;
|
|
1875
|
+
}
|
|
1876
|
+
function requireWriteContext(options) {
|
|
1877
|
+
const ready = requireConfig(options.config);
|
|
1878
|
+
const config = ready.config;
|
|
1879
|
+
if ('developer' !== config.profile.mode) throw new errors_CliError('干系人模式不支持修改任务状态', errors_EXIT.USAGE);
|
|
1880
|
+
if (0 === config.docs.root.trim().length) throw new errors_CliError('未配置文档仓库:请先设置 docs.root', errors_EXIT.NOT_FOUND);
|
|
1881
|
+
return {
|
|
1882
|
+
docsRoot: config.docs.root,
|
|
1883
|
+
developer: resolveDeveloper(options, config.profile.developer)
|
|
1884
|
+
};
|
|
1885
|
+
}
|
|
1886
|
+
function runAction(action, taskId, options) {
|
|
1887
|
+
const { docsRoot, developer } = requireWriteContext(options);
|
|
1888
|
+
const iteration = resolveIteration(options, docsRoot);
|
|
1889
|
+
const format = parseFormat(options.format);
|
|
1890
|
+
if (true === options.dryRun) {
|
|
1891
|
+
const actions = availableActions({
|
|
1892
|
+
docsRoot,
|
|
1893
|
+
iteration,
|
|
1894
|
+
developer
|
|
1895
|
+
});
|
|
1896
|
+
const available = actions[taskId] ?? [];
|
|
1897
|
+
const option = available.find((item)=>item.action === action);
|
|
1898
|
+
if (void 0 === option) throw new errors_CliError(`任务 ${taskId} 当前不可执行「${ACTION_META[action].label}」`, errors_EXIT.USAGE);
|
|
1899
|
+
if (!option.enabled) throw new errors_CliError(option.reason, errors_EXIT.USAGE);
|
|
1900
|
+
if ('json' === format) return void printJson({
|
|
1901
|
+
dryRun: true,
|
|
1902
|
+
taskId,
|
|
1903
|
+
action,
|
|
1904
|
+
allowed: true
|
|
1905
|
+
});
|
|
1906
|
+
printLine(`将执行:${taskId} ${ACTION_META[action].label}(未写入,--dry-run)`);
|
|
1907
|
+
return;
|
|
1908
|
+
}
|
|
1909
|
+
const result = applyTaskAction({
|
|
1910
|
+
docsRoot,
|
|
1911
|
+
iteration,
|
|
1912
|
+
developer,
|
|
1913
|
+
taskId,
|
|
1914
|
+
action
|
|
1915
|
+
});
|
|
1916
|
+
if ('json' === format) return void printJson(result);
|
|
1917
|
+
printLine(result.message);
|
|
1918
|
+
for (const change of result.changes)printLine(` · ${change}`);
|
|
1919
|
+
printLine(`文档:${result.file}`);
|
|
1920
|
+
}
|
|
1921
|
+
function runActions(options) {
|
|
1922
|
+
const { docsRoot, developer } = requireWriteContext(options);
|
|
1923
|
+
const iteration = resolveIteration(options, docsRoot);
|
|
1924
|
+
const actions = availableActions({
|
|
1925
|
+
docsRoot,
|
|
1926
|
+
iteration,
|
|
1927
|
+
developer
|
|
1928
|
+
});
|
|
1929
|
+
const format = parseFormat(options.format);
|
|
1930
|
+
if ('json' === format) return void printJson({
|
|
1931
|
+
iteration,
|
|
1932
|
+
developer,
|
|
1933
|
+
actions
|
|
1934
|
+
});
|
|
1935
|
+
const entries = Object.entries(actions);
|
|
1936
|
+
if (0 === entries.length) return void printLine('没有可操作的任务');
|
|
1937
|
+
for (const [taskId, list] of entries){
|
|
1938
|
+
const labels = 0 === list.length ? '—' : list.map((item)=>`${ACTION_META[item.action].label}${item.enabled ? '' : `(不可用:${item.reason})`}`).join('、');
|
|
1939
|
+
printLine(`${taskId} ${labels}`);
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1942
|
+
function runBatch(action, taskIds, options) {
|
|
1943
|
+
const { docsRoot, developer } = requireWriteContext(options);
|
|
1944
|
+
const iteration = resolveIteration(options, docsRoot);
|
|
1945
|
+
const format = parseFormat(options.format);
|
|
1946
|
+
const result = applyBatchAction({
|
|
1947
|
+
docsRoot,
|
|
1948
|
+
iteration,
|
|
1949
|
+
developer,
|
|
1950
|
+
taskIds,
|
|
1951
|
+
action
|
|
1952
|
+
});
|
|
1953
|
+
if ('json' === format) return void printJson(result);
|
|
1954
|
+
printLine(result.message);
|
|
1955
|
+
for (const change of result.changes)printLine(` · ${change}`);
|
|
1956
|
+
}
|
|
1957
|
+
function runHistory(taskId, options) {
|
|
1958
|
+
const { docsRoot, developer } = requireWriteContext(options);
|
|
1959
|
+
const iteration = resolveIteration(options, docsRoot);
|
|
1960
|
+
const entries = readTaskHistory({
|
|
1961
|
+
iteration,
|
|
1962
|
+
developer,
|
|
1963
|
+
taskId,
|
|
1964
|
+
limit: 10
|
|
1965
|
+
});
|
|
1966
|
+
if ('json' === parseFormat(options.format)) return void printJson(entries);
|
|
1967
|
+
if (0 === entries.length) return void printLine('暂无变更记录');
|
|
1968
|
+
for (const entry of entries){
|
|
1969
|
+
printLine(`${new Date(entry.at).toLocaleString('zh-CN')} ${ACTION_META[entry.action].label}`);
|
|
1970
|
+
for (const change of entry.changes)printLine(` · ${change}`);
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
function runRecalc(options) {
|
|
1974
|
+
const { docsRoot, developer } = requireWriteContext(options);
|
|
1975
|
+
const iteration = resolveIteration(options, docsRoot);
|
|
1976
|
+
const format = parseFormat(options.format);
|
|
1977
|
+
const result = recalcRequirements({
|
|
1978
|
+
docsRoot,
|
|
1979
|
+
iteration,
|
|
1980
|
+
developer,
|
|
1981
|
+
dryRun: true === options.dryRun
|
|
1982
|
+
});
|
|
1983
|
+
if ('json' === format) return void printJson({
|
|
1984
|
+
dryRun: true === options.dryRun,
|
|
1985
|
+
...result
|
|
1986
|
+
});
|
|
1987
|
+
if (0 === result.changes.length) return void printLine('需求状态已与任务一致,无需重算');
|
|
1988
|
+
printLine(true === options.dryRun ? '将更新(未写入,--dry-run):' : '已重算需求状态:');
|
|
1989
|
+
for (const change of result.changes)printLine(` · ${change}`);
|
|
1990
|
+
if (true !== options.dryRun) printLine(`文档:${result.file}`);
|
|
1991
|
+
}
|
|
1992
|
+
function registerTask(program) {
|
|
1993
|
+
const task = program.command('task').description('修改本人任务状态(供界面与 Agent 共用)');
|
|
1994
|
+
const commonOptions = (command)=>command.option('-c, --config <path>', '指定配置文件路径').option('-i, --iteration <name>', '迭代目录名(在迭代目录内执行时可省略)').option('-d, --developer <name>', '开发者标识(默认取配置身份)').option('--format <format>', '输出格式:human | json', 'human');
|
|
1995
|
+
commonOptions(task.command('actions')).description('列出每个任务当前可执行的动作').action((options)=>runActions(options));
|
|
1996
|
+
for (const action of [
|
|
1997
|
+
'start',
|
|
1998
|
+
'submit',
|
|
1999
|
+
'accept',
|
|
2000
|
+
'reject'
|
|
2001
|
+
])commonOptions(task.command(`${action} <taskId>`)).description(`执行「${ACTION_META[action].label}」:${ACTION_META[action].from} → ${ACTION_META[action].to}`).option('--dry-run', '只校验是否允许,不写入').action((taskId, options)=>runAction(action, taskId, options));
|
|
2002
|
+
commonOptions(task.command('batch <action> <taskIds...>')).description('批量执行同一动作,例如: ylcwf task batch accept "#2755-T1" "#2755-T2"').action((action, taskIds, options)=>{
|
|
2003
|
+
if (!(action in ACTION_META)) throw new errors_CliError(`未知动作:${action}(可选 ${Object.keys(ACTION_META).join(' / ')})`, errors_EXIT.USAGE);
|
|
2004
|
+
runBatch(action, taskIds, options);
|
|
2005
|
+
});
|
|
2006
|
+
commonOptions(task.command('history <taskId>')).description('查看任务的最近变更记录').action((taskId, options)=>runHistory(taskId, options));
|
|
2007
|
+
const requirement = program.command('requirement').description('需求维度的只读查询与状态重算');
|
|
2008
|
+
commonOptions(requirement.command('recalc')).description('按任务状态重算需求开发状态与进度').option('--dry-run', '只输出差异,不写入').action((options)=>runRecalc(options));
|
|
2009
|
+
}
|
|
2010
|
+
const FIELDS = [
|
|
2011
|
+
'path',
|
|
2012
|
+
'exists',
|
|
2013
|
+
'terminal',
|
|
2014
|
+
'repos'
|
|
2015
|
+
];
|
|
2016
|
+
function isSide(value) {
|
|
2017
|
+
return SIDES.some((side)=>side === value);
|
|
2018
|
+
}
|
|
2019
|
+
function isField(value) {
|
|
2020
|
+
return FIELDS.some((field)=>field === value);
|
|
2021
|
+
}
|
|
2022
|
+
function buildRepoView(terminal) {
|
|
2023
|
+
const view = {
|
|
2024
|
+
frontend: [],
|
|
2025
|
+
backend: []
|
|
2026
|
+
};
|
|
2027
|
+
for (const side of SIDES)view[side] = terminal.repos[side].map((path)=>({
|
|
2028
|
+
path,
|
|
2029
|
+
exists: external_node_fs_existsSync(path)
|
|
2030
|
+
}));
|
|
2031
|
+
return view;
|
|
2032
|
+
}
|
|
2033
|
+
function formatCandidates(items) {
|
|
2034
|
+
return items.map((item, index)=>` ${index + 1}) ${item.path}${item.exists ? '' : '(路径不存在)'}`).join('\n');
|
|
2035
|
+
}
|
|
2036
|
+
function pickRepo(items, pick) {
|
|
2037
|
+
const wanted = pick.trim();
|
|
2038
|
+
const index = Number.parseInt(wanted, 10);
|
|
2039
|
+
if (String(index) === wanted && index >= 1 && index <= items.length) {
|
|
2040
|
+
const hit = items[index - 1];
|
|
2041
|
+
if (void 0 !== hit) return hit;
|
|
2042
|
+
}
|
|
2043
|
+
const byPath = items.find((item)=>item.path === wanted);
|
|
2044
|
+
if (void 0 !== byPath) return byPath;
|
|
2045
|
+
const byName = items.find((item)=>basename(item.path) === wanted || basename(item.path).toLowerCase() === wanted.toLowerCase());
|
|
2046
|
+
if (void 0 !== byName) return byName;
|
|
2047
|
+
throw new errors_CliError(`--pick 未匹配到仓库:${pick}\n候选:\n${formatCandidates(items)}`, errors_EXIT.NOT_FOUND);
|
|
2048
|
+
}
|
|
2049
|
+
function selectRepos(items, terminal, side, pick, all) {
|
|
2050
|
+
if (0 === items.length) throw new errors_CliError(`终端「${terminal}」未配置 ${side} 仓库`, errors_EXIT.NOT_FOUND);
|
|
2051
|
+
if (all) return [
|
|
2052
|
+
...items
|
|
2053
|
+
];
|
|
2054
|
+
if (void 0 !== pick) return [
|
|
2055
|
+
pickRepo(items, pick)
|
|
2056
|
+
];
|
|
2057
|
+
if (1 === items.length) return [
|
|
2058
|
+
items[0]
|
|
2059
|
+
].filter((item)=>void 0 !== item);
|
|
2060
|
+
throw new errors_CliError(`终端「${terminal}」的 ${side} 端存在多个仓库,必须显式指定(--pick)或询问开发者:\n${formatCandidates(items)}`, errors_EXIT.NOT_FOUND);
|
|
2061
|
+
}
|
|
2062
|
+
function runResolve(name, options) {
|
|
2063
|
+
const format = parseFormat(options.format);
|
|
2064
|
+
const ready = requireConfig(options.config);
|
|
2065
|
+
const result = resolveTerminal(ready.config, name);
|
|
2066
|
+
if (!result.matched || null === result.terminal || null === result.entry) {
|
|
2067
|
+
const hint = 0 === result.candidates.length ? '\n请确认终端名,或先运行:ylcwf terminal add' : `\n候选(需人工确认,禁止自动采用):${result.candidates.join('、')}`;
|
|
2068
|
+
throw new errors_CliError(`未找到终端:${name}${hint}`, errors_EXIT.NOT_FOUND);
|
|
2069
|
+
}
|
|
2070
|
+
const rawSide = options.side?.trim();
|
|
2071
|
+
if (void 0 !== rawSide && rawSide.length > 0 && !isSide(rawSide)) throw new errors_CliError(`--side 必须是 frontend / backend:${rawSide}`, errors_EXIT.USAGE);
|
|
2072
|
+
const side = void 0 !== rawSide && rawSide.length > 0 && isSide(rawSide) ? rawSide : void 0;
|
|
2073
|
+
const rawField = options.field?.trim() ?? 'repos';
|
|
2074
|
+
if (!isField(rawField)) throw new errors_CliError(`--field 必须是 ${FIELDS.join(' / ')} 之一:${rawField}`, errors_EXIT.USAGE);
|
|
2075
|
+
const field = rawField;
|
|
2076
|
+
const terminal = result.terminal;
|
|
2077
|
+
const repos = buildRepoView(result.entry);
|
|
2078
|
+
if ('terminal' === field) {
|
|
2079
|
+
if ('json' === format) printJson({
|
|
2080
|
+
terminal,
|
|
2081
|
+
matchedBy: result.matchedBy
|
|
2082
|
+
});
|
|
2083
|
+
else printLine(terminal);
|
|
2084
|
+
return;
|
|
2085
|
+
}
|
|
2086
|
+
if ('path' === field || 'exists' === field) {
|
|
2087
|
+
if (void 0 === side) throw new errors_CliError(`--field ${field} 需要同时指定 --side frontend|backend`, errors_EXIT.USAGE);
|
|
2088
|
+
const selected = selectRepos(repos[side], terminal, side, options.pick, true === options.all);
|
|
2089
|
+
if ('path' === field) {
|
|
2090
|
+
if ('json' === format) printJson({
|
|
2091
|
+
terminal,
|
|
2092
|
+
side,
|
|
2093
|
+
paths: selected.map((item)=>item.path)
|
|
2094
|
+
});
|
|
2095
|
+
else for (const item of selected)printLine(item.path);
|
|
2096
|
+
return;
|
|
2097
|
+
}
|
|
2098
|
+
if ('json' === format) return void printJson({
|
|
2099
|
+
terminal,
|
|
2100
|
+
side,
|
|
2101
|
+
items: selected
|
|
2102
|
+
});
|
|
2103
|
+
for (const item of selected)printLine(1 === selected.length ? String(item.exists) : `${item.path} ${item.exists}`);
|
|
2104
|
+
return;
|
|
2105
|
+
}
|
|
2106
|
+
if (void 0 !== side) {
|
|
2107
|
+
const selected = selectRepos(repos[side], terminal, side, options.pick, true);
|
|
2108
|
+
if ('json' === format) return void printJson({
|
|
2109
|
+
terminal,
|
|
2110
|
+
side,
|
|
2111
|
+
items: selected
|
|
2112
|
+
});
|
|
2113
|
+
for (const item of selected)printLine(`${item.path} ${item.exists ? '✓' : '✗'}`);
|
|
2114
|
+
return;
|
|
2115
|
+
}
|
|
2116
|
+
if ('json' === format) return void printJson({
|
|
2117
|
+
input: name,
|
|
2118
|
+
matched: true,
|
|
2119
|
+
matchedBy: result.matchedBy,
|
|
2120
|
+
terminal,
|
|
2121
|
+
repos
|
|
2122
|
+
});
|
|
2123
|
+
printLine(`终端:${terminal}(匹配方式:${result.matchedBy ?? 'exact'})`);
|
|
2124
|
+
for (const item of SIDES){
|
|
2125
|
+
const list = repos[item];
|
|
2126
|
+
if (0 === list.length) {
|
|
2127
|
+
printLine(` ${item} (未配置)`);
|
|
2128
|
+
continue;
|
|
2129
|
+
}
|
|
2130
|
+
list.forEach((repo, index)=>{
|
|
2131
|
+
const prefix = 1 === list.length ? ` ${item} ` : ` ${item} ${index + 1}) `;
|
|
2132
|
+
printLine(`${prefix}${repo.path} ${repo.exists ? '✓' : '✗'}`);
|
|
2133
|
+
});
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
function registerResolve(program) {
|
|
2137
|
+
program.command('resolve <name>').description('把终端名(支持中文与别名)解析为本地仓库路径').option('-c, --config <path>', '指定配置文件路径').option('--side <side>', '限定端口:frontend | backend').option('--field <field>', '输出字段:path | exists | terminal | repos', 'repos').option('--pick <repo>', '该端存在多个仓库时显式指定:序号(1 起)、完整路径或目录名').option('--all', '输出该端全部仓库').option('--format <format>', '输出格式:human | json', 'human').action((name, options)=>{
|
|
2138
|
+
runResolve(name, options);
|
|
2139
|
+
});
|
|
2140
|
+
}
|
|
2141
|
+
function runDoctor(options) {
|
|
2142
|
+
const format = parseFormat(options.format);
|
|
2143
|
+
const loaded = loadConfig(options.config);
|
|
2144
|
+
if (!loaded.exists) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
|
|
2145
|
+
const checked = checkConfig(loaded.raw, {
|
|
2146
|
+
checkFs: true
|
|
2147
|
+
});
|
|
2148
|
+
const errors = countIssues(checked.issues).errors;
|
|
2149
|
+
const ok = !hasError(checked.issues);
|
|
2150
|
+
if ('json' === format) printJson({
|
|
2151
|
+
ok,
|
|
2152
|
+
configPath: loaded.path,
|
|
2153
|
+
...countIssues(checked.issues),
|
|
2154
|
+
issues: checked.issues
|
|
2155
|
+
});
|
|
2156
|
+
else {
|
|
2157
|
+
printLine(`配置文件 ${loaded.path}`);
|
|
2158
|
+
printLine(formatIssues(checked.issues, '校验通过,未发现问题'));
|
|
2159
|
+
if (!ok) printLine(`\n校验失败:${errors} 项 error`);
|
|
2160
|
+
}
|
|
2161
|
+
if (!ok) process.exitCode = errors_EXIT.INVALID;
|
|
2162
|
+
}
|
|
2163
|
+
function registerDoctor(program) {
|
|
2164
|
+
program.command('doctor').description('严格校验配置(schema、路径存在性、终端唯一性)').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
|
|
2165
|
+
runDoctor(options);
|
|
2166
|
+
});
|
|
2167
|
+
}
|
|
2168
|
+
function runPath(options) {
|
|
2169
|
+
const target = paths_resolveConfigPath(options.config);
|
|
2170
|
+
const format = parseFormat(options.format);
|
|
2171
|
+
if (true === options.exists) {
|
|
2172
|
+
const present = external_node_fs_existsSync(target);
|
|
2173
|
+
if ('json' === format) printJson({
|
|
2174
|
+
configPath: target,
|
|
2175
|
+
exists: present
|
|
2176
|
+
});
|
|
2177
|
+
else printLine(present ? 'true' : 'false');
|
|
2178
|
+
if (!present) process.exitCode = errors_EXIT.NOT_FOUND;
|
|
2179
|
+
return;
|
|
2180
|
+
}
|
|
2181
|
+
printLine(target);
|
|
2182
|
+
}
|
|
2183
|
+
function registerPath(program) {
|
|
2184
|
+
program.command('path').description('输出配置文件绝对路径').option('-c, --config <path>', '指定配置文件路径').option('--exists', '改为输出配置文件是否存在(true/false)').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
|
|
2185
|
+
runPath(options);
|
|
2186
|
+
});
|
|
2187
|
+
}
|
|
2188
|
+
function syncDocument(doc, next) {
|
|
2189
|
+
doc.deleteIn([
|
|
2190
|
+
'schemaVersion'
|
|
2191
|
+
]);
|
|
2192
|
+
doc.setIn([
|
|
2193
|
+
'profile',
|
|
2194
|
+
'developer'
|
|
2195
|
+
], next.profile.developer);
|
|
2196
|
+
doc.setIn([
|
|
2197
|
+
'profile',
|
|
2198
|
+
'role'
|
|
2199
|
+
], next.profile.role);
|
|
2200
|
+
doc.setIn([
|
|
2201
|
+
'profile',
|
|
2202
|
+
'mode'
|
|
2203
|
+
], next.profile.mode);
|
|
2204
|
+
doc.setIn([
|
|
2205
|
+
'docs',
|
|
2206
|
+
'root'
|
|
2207
|
+
], next.docs.root);
|
|
2208
|
+
if (null === next.docs.remote) doc.deleteIn([
|
|
2209
|
+
'docs',
|
|
2210
|
+
'remote'
|
|
2211
|
+
]);
|
|
2212
|
+
else doc.setIn([
|
|
2213
|
+
'docs',
|
|
2214
|
+
'remote'
|
|
2215
|
+
], next.docs.remote);
|
|
2216
|
+
const current = doc.toJS();
|
|
2217
|
+
const currentTerminals = utils_isRecord(current) && utils_isRecord(current['terminals']) ? Object.keys(current['terminals']) : [];
|
|
2218
|
+
for (const key of currentTerminals)if (!Object.hasOwn(next.terminals, key)) doc.deleteIn([
|
|
2219
|
+
'terminals',
|
|
2220
|
+
key
|
|
2221
|
+
]);
|
|
2222
|
+
for (const [key, terminal] of Object.entries(next.terminals)){
|
|
2223
|
+
doc.setIn([
|
|
2224
|
+
'terminals',
|
|
2225
|
+
key,
|
|
2226
|
+
'aliases'
|
|
2227
|
+
], terminal.aliases);
|
|
2228
|
+
doc.setIn([
|
|
2229
|
+
'terminals',
|
|
2230
|
+
key,
|
|
2231
|
+
'repos',
|
|
2232
|
+
'frontend'
|
|
2233
|
+
], terminal.repos.frontend);
|
|
2234
|
+
doc.setIn([
|
|
2235
|
+
'terminals',
|
|
2236
|
+
key,
|
|
2237
|
+
'repos',
|
|
2238
|
+
'backend'
|
|
2239
|
+
], terminal.repos.backend);
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
function collectResetTargets(configPath, includeRepos) {
|
|
2243
|
+
const targets = [
|
|
2244
|
+
{
|
|
2245
|
+
path: configPath,
|
|
2246
|
+
label: '配置文件',
|
|
2247
|
+
kind: 'file'
|
|
2248
|
+
},
|
|
2249
|
+
{
|
|
2250
|
+
path: `${configPath}.lock`,
|
|
2251
|
+
label: '锁文件',
|
|
2252
|
+
kind: 'file'
|
|
2253
|
+
},
|
|
2254
|
+
{
|
|
2255
|
+
path: backupsDir(configPath),
|
|
2256
|
+
label: '配置备份',
|
|
2257
|
+
kind: 'dir'
|
|
2258
|
+
}
|
|
2259
|
+
];
|
|
2260
|
+
if (includeRepos) targets.push({
|
|
2261
|
+
path: managedReposDir(),
|
|
2262
|
+
label: '托管文档仓库副本',
|
|
2263
|
+
kind: 'dir'
|
|
2264
|
+
});
|
|
2265
|
+
return targets.filter((target)=>external_node_fs_existsSync(target.path));
|
|
2266
|
+
}
|
|
2267
|
+
function describeTarget(target) {
|
|
2268
|
+
if ('file' === target.kind) {
|
|
2269
|
+
const size = statSync(target.path).size;
|
|
2270
|
+
return `${target.label}:${target.path}(${size} B)`;
|
|
2271
|
+
}
|
|
2272
|
+
const count = readdirSync(target.path).length;
|
|
2273
|
+
return `${target.label}:${target.path}(${count} 项)`;
|
|
2274
|
+
}
|
|
2275
|
+
function performReset(configPath, targets) {
|
|
2276
|
+
for (const target of targets)rmSync(target.path, {
|
|
2277
|
+
recursive: true,
|
|
2278
|
+
force: true
|
|
2279
|
+
});
|
|
2280
|
+
const parent = dirname(configPath);
|
|
2281
|
+
try {
|
|
2282
|
+
if (external_node_fs_existsSync(parent) && 0 === readdirSync(parent).length) rmSync(parent, {
|
|
2283
|
+
recursive: true,
|
|
2284
|
+
force: true
|
|
2285
|
+
});
|
|
2286
|
+
} catch {}
|
|
2287
|
+
return targets.length;
|
|
2288
|
+
}
|
|
2289
|
+
const SERVER_FEATURES = [
|
|
2290
|
+
'status-breakdown',
|
|
2291
|
+
'branch-switch',
|
|
2292
|
+
'fs-browse',
|
|
2293
|
+
'dir-picker'
|
|
2294
|
+
];
|
|
2295
|
+
function repoView(path) {
|
|
2296
|
+
const exists = external_node_fs_existsSync(path);
|
|
2297
|
+
return {
|
|
2298
|
+
path,
|
|
2299
|
+
exists,
|
|
2300
|
+
isGit: exists && external_node_fs_existsSync(external_node_path_join(path, '.git'))
|
|
2301
|
+
};
|
|
2302
|
+
}
|
|
2303
|
+
function readState(explicitPath) {
|
|
2304
|
+
const configPath = paths_resolveConfigPath(explicitPath);
|
|
2305
|
+
const loaded = loadConfig(explicitPath);
|
|
2306
|
+
const checked = loaded.exists ? checkConfig(loaded.raw, {
|
|
2307
|
+
checkFs: true
|
|
2308
|
+
}) : {
|
|
2309
|
+
config: null,
|
|
2310
|
+
issues: []
|
|
2311
|
+
};
|
|
2312
|
+
return {
|
|
2313
|
+
configPath,
|
|
2314
|
+
exists: loaded.exists,
|
|
2315
|
+
config: checked.config,
|
|
2316
|
+
issues: checked.issues,
|
|
2317
|
+
backups: listBackups(explicitPath),
|
|
2318
|
+
meta: {
|
|
2319
|
+
version: "0.2.0",
|
|
2320
|
+
features: SERVER_FEATURES
|
|
2321
|
+
}
|
|
2322
|
+
};
|
|
2323
|
+
}
|
|
2324
|
+
function saveConfig(raw, explicitPath) {
|
|
2325
|
+
const configPath = paths_resolveConfigPath(explicitPath);
|
|
2326
|
+
const structural = checkConfig(raw, {
|
|
2327
|
+
allowIncomplete: false,
|
|
2328
|
+
checkFs: false
|
|
2329
|
+
});
|
|
2330
|
+
if (null === structural.config || structural.issues.some((issue)=>'error' === issue.level)) {
|
|
2331
|
+
const detail = structural.issues.filter((issue)=>'error' === issue.level).map((issue)=>`- ${issue.message}`).join('\n');
|
|
2332
|
+
throw new errors_CliError(`配置校验未通过,已取消保存:\n${detail}`, errors_EXIT.INVALID);
|
|
2333
|
+
}
|
|
2334
|
+
const loaded = loadConfig(explicitPath);
|
|
2335
|
+
const doc = loaded.doc ?? createEmptyDocument();
|
|
2336
|
+
syncDocument(doc, structural.config);
|
|
2337
|
+
assertWritable(doc, configPath);
|
|
2338
|
+
saveDocument(doc, configPath);
|
|
2339
|
+
return readState(explicitPath);
|
|
2340
|
+
}
|
|
2341
|
+
function listBackups(explicitPath) {
|
|
2342
|
+
const configPath = paths_resolveConfigPath(explicitPath);
|
|
2343
|
+
const dir = backupsDir(configPath);
|
|
2344
|
+
if (!external_node_fs_existsSync(dir)) return [];
|
|
2345
|
+
return readdirSync(dir).filter((name)=>name.endsWith('.yaml')).map((name)=>{
|
|
2346
|
+
const full = external_node_path_join(dir, name);
|
|
2347
|
+
const info = statSync(full);
|
|
2348
|
+
return {
|
|
2349
|
+
name,
|
|
2350
|
+
mtime: info.mtime.toISOString(),
|
|
2351
|
+
size: info.size
|
|
2352
|
+
};
|
|
2353
|
+
}).sort((left, right)=>right.mtime.localeCompare(left.mtime));
|
|
2354
|
+
}
|
|
2355
|
+
function restoreBackup(name, explicitPath) {
|
|
2356
|
+
const configPath = paths_resolveConfigPath(explicitPath);
|
|
2357
|
+
const dir = backupsDir(configPath);
|
|
2358
|
+
const source = external_node_path_join(dir, basename(name));
|
|
2359
|
+
if (!external_node_fs_existsSync(source)) throw new errors_CliError(`备份不存在:${name}`, errors_EXIT.NOT_FOUND);
|
|
2360
|
+
mkdirSync(dir, {
|
|
2361
|
+
recursive: true
|
|
2362
|
+
});
|
|
2363
|
+
if (external_node_fs_existsSync(configPath)) {
|
|
2364
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
2365
|
+
copyFileSync(configPath, external_node_path_join(dir, `config-${stamp}-before-restore.yaml`));
|
|
2366
|
+
}
|
|
2367
|
+
copyFileSync(source, configPath);
|
|
2368
|
+
const loaded = loadConfig(explicitPath);
|
|
2369
|
+
if (null === loaded.config) throw new errors_CliError(`备份内容不合法,已写入但需要人工修复:${configPath}`, errors_EXIT.INVALID);
|
|
2370
|
+
return readState(explicitPath);
|
|
2371
|
+
}
|
|
2372
|
+
function resolveRequest(name, side, explicitPath) {
|
|
2373
|
+
const loaded = loadConfig(explicitPath);
|
|
2374
|
+
if (null === loaded.config) throw new errors_CliError(`配置未初始化或不合法:${loaded.path}`, errors_EXIT.NOT_FOUND);
|
|
2375
|
+
const result = resolveTerminal(loaded.config, name);
|
|
2376
|
+
const repos = {
|
|
2377
|
+
frontend: [],
|
|
2378
|
+
backend: []
|
|
2379
|
+
};
|
|
2380
|
+
if (result.matched && null !== result.entry) {
|
|
2381
|
+
for (const item of SIDES)if (void 0 === side || item === side) repos[item] = result.entry.repos[item].map(repoView);
|
|
2382
|
+
}
|
|
2383
|
+
return {
|
|
2384
|
+
input: name,
|
|
2385
|
+
matched: result.matched,
|
|
2386
|
+
matchedBy: result.matchedBy,
|
|
2387
|
+
terminal: result.terminal,
|
|
2388
|
+
candidates: result.candidates,
|
|
2389
|
+
repos
|
|
2390
|
+
};
|
|
2391
|
+
}
|
|
2392
|
+
function resetConfig(includeRepos, explicitPath) {
|
|
2393
|
+
const configPath = paths_resolveConfigPath(explicitPath);
|
|
2394
|
+
const targets = collectResetTargets(configPath, includeRepos);
|
|
2395
|
+
const removed = performReset(configPath, targets);
|
|
2396
|
+
return {
|
|
2397
|
+
removed,
|
|
2398
|
+
configPath
|
|
2399
|
+
};
|
|
2400
|
+
}
|
|
2401
|
+
function inspectPath(target) {
|
|
2402
|
+
const view = repoView(target);
|
|
2403
|
+
return {
|
|
2404
|
+
...view,
|
|
2405
|
+
hasDocsSkill: view.exists && external_node_fs_existsSync(external_node_path_join(target, 'skills', 'iteration-task-docs', 'SKILL.md'))
|
|
2406
|
+
};
|
|
2407
|
+
}
|
|
2408
|
+
const RESERVED_FILES = new Set([
|
|
2409
|
+
'README.md',
|
|
2410
|
+
'AGENTS.md',
|
|
2411
|
+
'CLAUDE.md'
|
|
2412
|
+
]);
|
|
2413
|
+
const RESERVED_PREFIXES = [
|
|
2414
|
+
'skills/',
|
|
2415
|
+
"scripts/",
|
|
2416
|
+
'_prd/'
|
|
2417
|
+
];
|
|
2418
|
+
const git_SAFE_SEGMENT = /^[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
|
|
2419
|
+
function git(docsRoot, args, timeoutMs = 15000) {
|
|
2420
|
+
return execFileSync('git', [
|
|
2421
|
+
'-C',
|
|
2422
|
+
docsRoot,
|
|
2423
|
+
...args
|
|
2424
|
+
], {
|
|
2425
|
+
encoding: 'utf8',
|
|
2426
|
+
timeout: timeoutMs,
|
|
2427
|
+
maxBuffer: 33554432,
|
|
2428
|
+
env: {
|
|
2429
|
+
...process.env,
|
|
2430
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
2431
|
+
GIT_SSH_COMMAND: process.env['GIT_SSH_COMMAND'] ?? 'ssh -o BatchMode=yes -o ConnectTimeout=8'
|
|
2432
|
+
}
|
|
2433
|
+
}).trim();
|
|
2434
|
+
}
|
|
2435
|
+
function tryGit(docsRoot, args, timeoutMs) {
|
|
2436
|
+
try {
|
|
2437
|
+
return git(docsRoot, args, timeoutMs);
|
|
2438
|
+
} catch {
|
|
2439
|
+
return null;
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
function git_safeSegment(value, label) {
|
|
2443
|
+
const trimmed = value.trim();
|
|
2444
|
+
if (!git_SAFE_SEGMENT.test(trimmed) || '.' === trimmed || '..' === trimmed) throw new errors_CliError(`${label} 不合法:${value}`, errors_EXIT.USAGE);
|
|
2445
|
+
return trimmed;
|
|
2446
|
+
}
|
|
2447
|
+
function getGitStatus(docsRoot) {
|
|
2448
|
+
const empty = {
|
|
2449
|
+
available: false,
|
|
2450
|
+
hasRemote: false,
|
|
2451
|
+
remoteUrl: null,
|
|
2452
|
+
branch: null,
|
|
2453
|
+
upstream: null,
|
|
2454
|
+
head: null,
|
|
2455
|
+
ahead: 0,
|
|
2456
|
+
behind: 0,
|
|
2457
|
+
dirty: false,
|
|
2458
|
+
error: null
|
|
2459
|
+
};
|
|
2460
|
+
if (!external_node_fs_existsSync(external_node_path_join(docsRoot, '.git'))) return {
|
|
2461
|
+
...empty,
|
|
2462
|
+
error: '文档仓库不是 git 仓库,仅支持本地模式'
|
|
2463
|
+
};
|
|
2464
|
+
const inside = tryGit(docsRoot, [
|
|
2465
|
+
'rev-parse',
|
|
2466
|
+
'--is-inside-work-tree'
|
|
2467
|
+
]);
|
|
2468
|
+
if ('true' !== inside) return {
|
|
2469
|
+
...empty,
|
|
2470
|
+
error: '无法读取 git 仓库(可能缺少 git 命令)'
|
|
2471
|
+
};
|
|
2472
|
+
const remoteUrl = tryGit(docsRoot, [
|
|
2473
|
+
'remote',
|
|
2474
|
+
'get-url',
|
|
2475
|
+
'origin'
|
|
2476
|
+
]);
|
|
2477
|
+
const branch = tryGit(docsRoot, [
|
|
2478
|
+
'rev-parse',
|
|
2479
|
+
'--abbrev-ref',
|
|
2480
|
+
'HEAD'
|
|
2481
|
+
]);
|
|
2482
|
+
const head = tryGit(docsRoot, [
|
|
2483
|
+
'rev-parse',
|
|
2484
|
+
'--short',
|
|
2485
|
+
'HEAD'
|
|
2486
|
+
]);
|
|
2487
|
+
const upstream = tryGit(docsRoot, [
|
|
2488
|
+
'rev-parse',
|
|
2489
|
+
'--abbrev-ref',
|
|
2490
|
+
'--symbolic-full-name',
|
|
2491
|
+
'@{u}'
|
|
2492
|
+
]);
|
|
2493
|
+
const dirty = (tryGit(docsRoot, [
|
|
2494
|
+
'status',
|
|
2495
|
+
'--porcelain'
|
|
2496
|
+
]) ?? '').length > 0;
|
|
2497
|
+
let ahead = 0;
|
|
2498
|
+
let behind = 0;
|
|
2499
|
+
if (null !== upstream) {
|
|
2500
|
+
const counts = tryGit(docsRoot, [
|
|
2501
|
+
'rev-list',
|
|
2502
|
+
'--left-right',
|
|
2503
|
+
'--count',
|
|
2504
|
+
`HEAD...${upstream}`
|
|
2505
|
+
]);
|
|
2506
|
+
if (null !== counts) {
|
|
2507
|
+
const [left, right] = counts.split(/\s+/);
|
|
2508
|
+
ahead = Number.parseInt(left ?? '0', 10) || 0;
|
|
2509
|
+
behind = Number.parseInt(right ?? '0', 10) || 0;
|
|
2510
|
+
}
|
|
2511
|
+
}
|
|
2512
|
+
return {
|
|
2513
|
+
available: true,
|
|
2514
|
+
hasRemote: null !== remoteUrl,
|
|
2515
|
+
remoteUrl,
|
|
2516
|
+
branch,
|
|
2517
|
+
upstream,
|
|
2518
|
+
head,
|
|
2519
|
+
ahead,
|
|
2520
|
+
behind,
|
|
2521
|
+
dirty,
|
|
2522
|
+
error: null
|
|
2523
|
+
};
|
|
2524
|
+
}
|
|
2525
|
+
function fetchRemote(docsRoot) {
|
|
2526
|
+
try {
|
|
2527
|
+
git(docsRoot, [
|
|
2528
|
+
'fetch',
|
|
2529
|
+
'--prune',
|
|
2530
|
+
'origin'
|
|
2531
|
+
], 30000);
|
|
2532
|
+
return {
|
|
2533
|
+
ok: true,
|
|
2534
|
+
message: '已同步远程引用(未改动工作区)'
|
|
2535
|
+
};
|
|
2536
|
+
} catch (error) {
|
|
2537
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2538
|
+
return {
|
|
2539
|
+
ok: false,
|
|
2540
|
+
message: `同步失败:${message.split('\n')[0] ?? message}`
|
|
2541
|
+
};
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
function resolveRemoteRef(docsRoot, refName) {
|
|
2545
|
+
const explicit = refName?.trim();
|
|
2546
|
+
const upstream = void 0 !== explicit && explicit.length > 0 ? explicit : tryGit(docsRoot, [
|
|
2547
|
+
'rev-parse',
|
|
2548
|
+
'--abbrev-ref',
|
|
2549
|
+
'--symbolic-full-name',
|
|
2550
|
+
'@{u}'
|
|
2551
|
+
]);
|
|
2552
|
+
if (null === upstream) throw new errors_CliError('当前分支没有上游分支,无法读取远程快照', errors_EXIT.NOT_FOUND);
|
|
2553
|
+
const sha = tryGit(docsRoot, [
|
|
2554
|
+
'rev-parse',
|
|
2555
|
+
upstream
|
|
2556
|
+
]);
|
|
2557
|
+
if (null === sha) throw new errors_CliError(`无法解析远程引用:${upstream}`, errors_EXIT.NOT_FOUND);
|
|
2558
|
+
const committedAt = tryGit(docsRoot, [
|
|
2559
|
+
'log',
|
|
2560
|
+
'-1',
|
|
2561
|
+
'--format=%cI',
|
|
2562
|
+
sha
|
|
2563
|
+
]) ?? '';
|
|
2564
|
+
return {
|
|
2565
|
+
ref: upstream,
|
|
2566
|
+
sha,
|
|
2567
|
+
committedAt
|
|
2568
|
+
};
|
|
2569
|
+
}
|
|
2570
|
+
function isDocMarkdown(path) {
|
|
2571
|
+
if (!path.endsWith('.md')) return false;
|
|
2572
|
+
if (RESERVED_FILES.has(basename(path))) return false;
|
|
2573
|
+
if (RESERVED_PREFIXES.some((prefix)=>path.startsWith(prefix) || path.includes(`/${prefix}`))) return false;
|
|
2574
|
+
return true;
|
|
2575
|
+
}
|
|
2576
|
+
function lastCommitIso(docsRoot, sha, path) {
|
|
2577
|
+
return tryGit(docsRoot, [
|
|
2578
|
+
'log',
|
|
2579
|
+
'-1',
|
|
2580
|
+
'--format=%cI',
|
|
2581
|
+
sha,
|
|
2582
|
+
'--',
|
|
2583
|
+
path
|
|
2584
|
+
]) ?? '';
|
|
2585
|
+
}
|
|
2586
|
+
function getBranchInfo(docsRoot) {
|
|
2587
|
+
const current = tryGit(docsRoot, [
|
|
2588
|
+
'rev-parse',
|
|
2589
|
+
'--abbrev-ref',
|
|
2590
|
+
'HEAD'
|
|
2591
|
+
]);
|
|
2592
|
+
const detached = null === current || 'HEAD' === current;
|
|
2593
|
+
const upstream = detached ? null : tryGit(docsRoot, [
|
|
2594
|
+
'rev-parse',
|
|
2595
|
+
'--abbrev-ref',
|
|
2596
|
+
'--symbolic-full-name',
|
|
2597
|
+
'@{u}'
|
|
2598
|
+
]);
|
|
2599
|
+
const status = tryGit(docsRoot, [
|
|
2600
|
+
'status',
|
|
2601
|
+
'--porcelain'
|
|
2602
|
+
]);
|
|
2603
|
+
const branches = tryGit(docsRoot, [
|
|
2604
|
+
'for-each-ref',
|
|
2605
|
+
'--format=%(refname)',
|
|
2606
|
+
'refs/remotes'
|
|
2607
|
+
]) ?? '';
|
|
2608
|
+
return {
|
|
2609
|
+
current: detached ? null : current,
|
|
2610
|
+
detached,
|
|
2611
|
+
upstream,
|
|
2612
|
+
dirty: null !== status && status.length > 0,
|
|
2613
|
+
remote: branches.split('\n').map((line)=>line.trim().replace(/^refs\/remotes\//, '')).filter((line)=>line.length > 0 && line.includes('/') && !line.endsWith('/HEAD')).sort()
|
|
2614
|
+
};
|
|
2615
|
+
}
|
|
2616
|
+
function listRemoteIterations(docsRoot, ref) {
|
|
2617
|
+
const listed = tryGit(docsRoot, [
|
|
2618
|
+
'ls-tree',
|
|
2619
|
+
'-r',
|
|
2620
|
+
'--name-only',
|
|
2621
|
+
ref.sha
|
|
2622
|
+
]);
|
|
2623
|
+
if (null === listed) throw new errors_CliError(`无法读取远程快照:${ref.ref}`, errors_EXIT.NOT_FOUND);
|
|
2624
|
+
const groups = new Map();
|
|
2625
|
+
for (const path of listed.split('\n')){
|
|
2626
|
+
if (!isDocMarkdown(path)) continue;
|
|
2627
|
+
const segments = path.split('/');
|
|
2628
|
+
if (2 !== segments.length) continue;
|
|
2629
|
+
const [iteration, file] = segments;
|
|
2630
|
+
if (void 0 === iteration || void 0 === file) continue;
|
|
2631
|
+
const sizeText = tryGit(docsRoot, [
|
|
2632
|
+
'cat-file',
|
|
2633
|
+
'-s',
|
|
2634
|
+
`${ref.sha}:${path}`
|
|
2635
|
+
]) ?? '0';
|
|
2636
|
+
const entry = {
|
|
2637
|
+
id: file.replace(/\.md$/, ''),
|
|
2638
|
+
file,
|
|
2639
|
+
mtime: lastCommitIso(docsRoot, ref.sha, path),
|
|
2640
|
+
size: Number.parseInt(sizeText, 10) || 0
|
|
2641
|
+
};
|
|
2642
|
+
const bucket = groups.get(iteration) ?? [];
|
|
2643
|
+
bucket.push(entry);
|
|
2644
|
+
groups.set(iteration, bucket);
|
|
2645
|
+
}
|
|
2646
|
+
const iterations = [
|
|
2647
|
+
...groups.entries()
|
|
2648
|
+
].map(([name, developers])=>({
|
|
2649
|
+
name,
|
|
2650
|
+
mtime: lastCommitIso(docsRoot, ref.sha, name),
|
|
2651
|
+
developers: developers.sort((left, right)=>right.mtime.localeCompare(left.mtime)),
|
|
2652
|
+
hasPrd: listed.includes(`${name}/_prd/meta.json`)
|
|
2653
|
+
})).sort((left, right)=>right.mtime.localeCompare(left.mtime));
|
|
2654
|
+
return {
|
|
2655
|
+
docsRoot,
|
|
2656
|
+
source: 'remote',
|
|
2657
|
+
ref,
|
|
2658
|
+
iterations
|
|
2659
|
+
};
|
|
2660
|
+
}
|
|
2661
|
+
function gitShow(docsRoot, sha, path) {
|
|
2662
|
+
return tryGit(docsRoot, [
|
|
2663
|
+
'show',
|
|
2664
|
+
`${sha}:${path}`
|
|
2665
|
+
]);
|
|
2666
|
+
}
|
|
2667
|
+
function materializeRemote(docsRoot, ref) {
|
|
2668
|
+
const dir = external_node_path_join(external_node_os_tmpdir(), `ylcwf-remote-${ref.sha.slice(0, 12)}`);
|
|
2669
|
+
mkdirSync(external_node_path_join(dir, "scripts"), {
|
|
2670
|
+
recursive: true
|
|
2671
|
+
});
|
|
2672
|
+
return dir;
|
|
2673
|
+
}
|
|
2674
|
+
function exportRemoteDoc(docsRoot, ref, iteration, developer) {
|
|
2675
|
+
const safeIteration = git_safeSegment(iteration, '迭代目录');
|
|
2676
|
+
const safeDeveloper = git_safeSegment(developer, '开发者标识');
|
|
2677
|
+
const relative = `${safeIteration}/${safeDeveloper}.md`;
|
|
2678
|
+
const markdown = gitShow(docsRoot, ref.sha, relative);
|
|
2679
|
+
if (null === markdown) throw new errors_CliError(`远程快照中不存在该文档:${relative}`, errors_EXIT.NOT_FOUND);
|
|
2680
|
+
const dir = materializeRemote(docsRoot, ref);
|
|
2681
|
+
const target = external_node_path_join(dir, safeIteration, `${safeDeveloper}.md`);
|
|
2682
|
+
mkdirSync(dirname(target), {
|
|
2683
|
+
recursive: true
|
|
2684
|
+
});
|
|
2685
|
+
writeFileSync(target, markdown, 'utf8');
|
|
2686
|
+
const scriptPath = external_node_path_join(dir, "scripts", 'validate_task_doc.py');
|
|
2687
|
+
if (!external_node_fs_existsSync(scriptPath)) {
|
|
2688
|
+
const script = gitShow(docsRoot, ref.sha, "scripts/validate_task_doc.py");
|
|
2689
|
+
if (null !== script) writeFileSync(scriptPath, script, 'utf8');
|
|
2690
|
+
}
|
|
2691
|
+
return {
|
|
2692
|
+
dir,
|
|
2693
|
+
markdown,
|
|
2694
|
+
scriptPath: external_node_fs_existsSync(scriptPath) ? scriptPath : null,
|
|
2695
|
+
mtime: lastCommitIso(docsRoot, ref.sha, relative) || ref.committedAt
|
|
2696
|
+
};
|
|
2697
|
+
}
|
|
2698
|
+
function isGitAvailable() {
|
|
2699
|
+
try {
|
|
2700
|
+
execFileSync('git', [
|
|
2701
|
+
'--version'
|
|
2702
|
+
], {
|
|
2703
|
+
timeout: 5000,
|
|
2704
|
+
encoding: 'utf8'
|
|
2705
|
+
});
|
|
2706
|
+
return true;
|
|
2707
|
+
} catch {
|
|
2708
|
+
return false;
|
|
2709
|
+
}
|
|
2710
|
+
}
|
|
2711
|
+
function probeRemote(remote) {
|
|
2712
|
+
if (!isGitAvailable()) return {
|
|
2713
|
+
gitAvailable: false,
|
|
2714
|
+
reachable: false,
|
|
2715
|
+
authorized: false,
|
|
2716
|
+
reason: '未检测到 git 命令,请先安装 Git'
|
|
2717
|
+
};
|
|
2718
|
+
try {
|
|
2719
|
+
execFileSync('git', [
|
|
2720
|
+
'ls-remote',
|
|
2721
|
+
'--heads',
|
|
2722
|
+
remote
|
|
2723
|
+
], {
|
|
2724
|
+
timeout: 20000,
|
|
2725
|
+
encoding: 'utf8',
|
|
2726
|
+
maxBuffer: 8388608,
|
|
2727
|
+
env: {
|
|
2728
|
+
...process.env,
|
|
2729
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
2730
|
+
GIT_SSH_COMMAND: process.env['GIT_SSH_COMMAND'] ?? 'ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new'
|
|
2731
|
+
}
|
|
2732
|
+
});
|
|
2733
|
+
return {
|
|
2734
|
+
gitAvailable: true,
|
|
2735
|
+
reachable: true,
|
|
2736
|
+
authorized: true,
|
|
2737
|
+
reason: null
|
|
2738
|
+
};
|
|
2739
|
+
} catch (error) {
|
|
2740
|
+
const stderr = String(error.stderr ?? '');
|
|
2741
|
+
const lower = stderr.toLowerCase();
|
|
2742
|
+
if (lower.includes('authentication failed') || lower.includes('permission denied') || lower.includes('could not read username') || lower.includes('terminal prompts disabled') || lower.includes('access denied') || lower.includes('401') || lower.includes('403') || lower.includes('not found') || lower.includes('repository not found')) return {
|
|
2743
|
+
gitAvailable: true,
|
|
2744
|
+
reachable: true,
|
|
2745
|
+
authorized: false,
|
|
2746
|
+
reason: '没有访问权限或未配置 Git 凭据,请联系管理员开通文档仓库访问权限'
|
|
2747
|
+
};
|
|
2748
|
+
if (lower.includes('could not resolve host') || lower.includes('connection timed out') || lower.includes('connection refused') || lower.includes("couldn't connect") || lower.includes('network is unreachable')) return {
|
|
2749
|
+
gitAvailable: true,
|
|
2750
|
+
reachable: false,
|
|
2751
|
+
authorized: false,
|
|
2752
|
+
reason: '无法连接远程仓库,请检查网络或代理'
|
|
2753
|
+
};
|
|
2754
|
+
return {
|
|
2755
|
+
gitAvailable: true,
|
|
2756
|
+
reachable: false,
|
|
2757
|
+
authorized: false,
|
|
2758
|
+
reason: stderr.split('\n')[0]?.trim() || '无法访问远程仓库'
|
|
2759
|
+
};
|
|
2760
|
+
}
|
|
2761
|
+
}
|
|
2762
|
+
function repoNameFromRemote(remote) {
|
|
2763
|
+
const cleaned = remote.replace(/\/+$/, '').replace(/\.git$/, '');
|
|
2764
|
+
const last = cleaned.split(/[/:]/).pop() ?? 'docs';
|
|
2765
|
+
return last.replace(/[^\w.\-\u4e00-\u9fa5]/g, '-') || 'docs';
|
|
2766
|
+
}
|
|
2767
|
+
function mostRecentRemoteBranch(docsRoot) {
|
|
2768
|
+
const listed = tryGit(docsRoot, [
|
|
2769
|
+
'for-each-ref',
|
|
2770
|
+
'--sort=-committerdate',
|
|
2771
|
+
'--count=5',
|
|
2772
|
+
'--format=%(refname:short)',
|
|
2773
|
+
'refs/remotes/origin/'
|
|
2774
|
+
]);
|
|
2775
|
+
if (null === listed) return null;
|
|
2776
|
+
const candidate = listed.split('\n').map((line)=>line.trim()).find((name)=>name.length > 0 && !name.endsWith('/HEAD'));
|
|
2777
|
+
return candidate ?? null;
|
|
2778
|
+
}
|
|
2779
|
+
function ensureManagedClone(remote) {
|
|
2780
|
+
const dir = external_node_path_join(managedReposDir(), repoNameFromRemote(remote));
|
|
2781
|
+
const gitDir = external_node_path_join(dir, '.git');
|
|
2782
|
+
if (external_node_fs_existsSync(gitDir)) {
|
|
2783
|
+
const fetched = tryGit(dir, [
|
|
2784
|
+
'fetch',
|
|
2785
|
+
'--prune',
|
|
2786
|
+
'--all'
|
|
2787
|
+
], 60000);
|
|
2788
|
+
if (null === fetched) throw new errors_CliError('同步远程仓库失败,请检查网络或权限', errors_EXIT.INVALID);
|
|
2789
|
+
const branch = mostRecentRemoteBranch(dir);
|
|
2790
|
+
if (null !== branch) {
|
|
2791
|
+
const local = branch.replace(/^origin\//, '');
|
|
2792
|
+
const checked = tryGit(dir, [
|
|
2793
|
+
'checkout',
|
|
2794
|
+
'-B',
|
|
2795
|
+
local,
|
|
2796
|
+
branch
|
|
2797
|
+
]);
|
|
2798
|
+
if (null === checked) throw new errors_CliError(`无法检出分支:${branch}`, errors_EXIT.INVALID);
|
|
2799
|
+
}
|
|
2800
|
+
return {
|
|
2801
|
+
dir,
|
|
2802
|
+
created: false,
|
|
2803
|
+
branch: branch ?? ''
|
|
2804
|
+
};
|
|
2805
|
+
}
|
|
2806
|
+
mkdirSync(dirname(dir), {
|
|
2807
|
+
recursive: true
|
|
2808
|
+
});
|
|
2809
|
+
try {
|
|
2810
|
+
execFileSync('git', [
|
|
2811
|
+
'clone',
|
|
2812
|
+
remote,
|
|
2813
|
+
dir
|
|
2814
|
+
], {
|
|
2815
|
+
timeout: 180000,
|
|
2816
|
+
encoding: 'utf8',
|
|
2817
|
+
maxBuffer: 16777216,
|
|
2818
|
+
env: {
|
|
2819
|
+
...process.env,
|
|
2820
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
2821
|
+
GIT_SSH_COMMAND: process.env['GIT_SSH_COMMAND'] ?? 'ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new'
|
|
2822
|
+
}
|
|
2823
|
+
});
|
|
2824
|
+
} catch (error) {
|
|
2825
|
+
const stderr = String(error.stderr ?? '');
|
|
2826
|
+
throw new errors_CliError(`克隆文档仓库失败:${stderr.split('\n')[0]?.trim() ?? '未知错误'}`, errors_EXIT.INVALID);
|
|
2827
|
+
}
|
|
2828
|
+
const branch = mostRecentRemoteBranch(dir);
|
|
2829
|
+
if (null !== branch) tryGit(dir, [
|
|
2830
|
+
'checkout',
|
|
2831
|
+
'-B',
|
|
2832
|
+
branch.replace(/^origin\//, ''),
|
|
2833
|
+
branch
|
|
2834
|
+
]);
|
|
2835
|
+
return {
|
|
2836
|
+
dir,
|
|
2837
|
+
created: true,
|
|
2838
|
+
branch: branch ?? ''
|
|
2839
|
+
};
|
|
2840
|
+
}
|
|
2841
|
+
function syncManagedRepo(dir) {
|
|
2842
|
+
try {
|
|
2843
|
+
git(dir, [
|
|
2844
|
+
'fetch',
|
|
2845
|
+
'--prune',
|
|
2846
|
+
'--all'
|
|
2847
|
+
], 60000);
|
|
2848
|
+
const upstream = tryGit(dir, [
|
|
2849
|
+
'rev-parse',
|
|
2850
|
+
'--abbrev-ref',
|
|
2851
|
+
'--symbolic-full-name',
|
|
2852
|
+
'@{u}'
|
|
2853
|
+
]);
|
|
2854
|
+
if (null !== upstream) {
|
|
2855
|
+
git(dir, [
|
|
2856
|
+
'reset',
|
|
2857
|
+
'--hard',
|
|
2858
|
+
upstream
|
|
2859
|
+
]);
|
|
2860
|
+
return {
|
|
2861
|
+
ok: true,
|
|
2862
|
+
message: `已同步到 ${upstream}`,
|
|
2863
|
+
branch: upstream
|
|
2864
|
+
};
|
|
2865
|
+
}
|
|
2866
|
+
return {
|
|
2867
|
+
ok: true,
|
|
2868
|
+
message: '已同步远程引用',
|
|
2869
|
+
branch: ''
|
|
2870
|
+
};
|
|
2871
|
+
} catch (error) {
|
|
2872
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2873
|
+
return {
|
|
2874
|
+
ok: false,
|
|
2875
|
+
message: `同步失败:${message.split('\n')[0] ?? message}`,
|
|
2876
|
+
branch: ''
|
|
2877
|
+
};
|
|
2878
|
+
}
|
|
2879
|
+
}
|
|
2880
|
+
function normalizeSelfTest(value) {
|
|
2881
|
+
const text = value.trim();
|
|
2882
|
+
if (0 === text.length) return '未执行';
|
|
2883
|
+
if (text.startsWith('免测')) return '免测';
|
|
2884
|
+
return text;
|
|
2885
|
+
}
|
|
2886
|
+
function normalizeAcceptance(value) {
|
|
2887
|
+
const text = value.trim();
|
|
2888
|
+
return 0 === text.length ? '待验收' : text;
|
|
2889
|
+
}
|
|
2890
|
+
function bump(target, key) {
|
|
2891
|
+
target[key] = (target[key] ?? 0) + 1;
|
|
2892
|
+
}
|
|
2893
|
+
const RESERVED_DIRS = new Set([
|
|
2894
|
+
'_prd',
|
|
2895
|
+
"scripts",
|
|
2896
|
+
'skills',
|
|
2897
|
+
'node_modules',
|
|
2898
|
+
'.git',
|
|
2899
|
+
'.idea',
|
|
2900
|
+
'.vscode'
|
|
2901
|
+
]);
|
|
2902
|
+
const iterations_RESERVED_FILES = new Set([
|
|
2903
|
+
'README.md',
|
|
2904
|
+
'AGENTS.md',
|
|
2905
|
+
'CLAUDE.md'
|
|
2906
|
+
]);
|
|
2907
|
+
const iterations_SAFE_SEGMENT = /^[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
|
|
2908
|
+
function iterations_safeSegment(value, label) {
|
|
2909
|
+
const trimmed = value.trim();
|
|
2910
|
+
if (!iterations_SAFE_SEGMENT.test(trimmed) || '.' === trimmed || '..' === trimmed) throw new errors_CliError(`${label} 不合法:${value}`, errors_EXIT.USAGE);
|
|
2911
|
+
return trimmed;
|
|
2912
|
+
}
|
|
2913
|
+
function joinWithin(root, ...segments) {
|
|
2914
|
+
const target = resolve(root, ...segments);
|
|
2915
|
+
const base = resolve(root) + sep;
|
|
2916
|
+
if (!target.startsWith(base)) throw new errors_CliError(`路径越界:${target}`, errors_EXIT.USAGE);
|
|
2917
|
+
return target;
|
|
2918
|
+
}
|
|
2919
|
+
function inferRole(markdown) {
|
|
2920
|
+
const match = /\|\s*负责范围\s*\|\s*([^|]*)\|/.exec(markdown);
|
|
2921
|
+
const scope = match?.[1]?.trim() ?? '';
|
|
2922
|
+
const hasFrontend = scope.includes('前端');
|
|
2923
|
+
const hasBackend = scope.includes('后端');
|
|
2924
|
+
if (hasFrontend && hasBackend) return 'fullstack';
|
|
2925
|
+
if (hasBackend) return 'backend';
|
|
2926
|
+
return 'frontend';
|
|
2927
|
+
}
|
|
2928
|
+
function listMarkdownFiles(directory) {
|
|
2929
|
+
let entries;
|
|
2930
|
+
try {
|
|
2931
|
+
entries = readdirSync(directory);
|
|
2932
|
+
} catch {
|
|
2933
|
+
return [];
|
|
2934
|
+
}
|
|
2935
|
+
return entries.filter((name)=>name.endsWith('.md') && !iterations_RESERVED_FILES.has(name)).map((name)=>{
|
|
2936
|
+
const full = external_node_path_join(directory, name);
|
|
2937
|
+
const info = statSync(full);
|
|
2938
|
+
return {
|
|
2939
|
+
id: name.replace(/\.md$/, ''),
|
|
2940
|
+
file: name,
|
|
2941
|
+
mtime: info.mtime.toISOString(),
|
|
2942
|
+
size: info.size
|
|
2943
|
+
};
|
|
2944
|
+
}).sort((left, right)=>right.mtime.localeCompare(left.mtime));
|
|
2945
|
+
}
|
|
2946
|
+
function accessReason(error) {
|
|
2947
|
+
const code = error.code;
|
|
2948
|
+
if ('EACCES' === code || 'EPERM' === code) return '没有访问权限,请联系管理员开通文档仓库访问权限';
|
|
2949
|
+
if ('ENOENT' === code) return '文档仓库路径不存在';
|
|
2950
|
+
if (error instanceof Error) return error.message;
|
|
2951
|
+
return String(error);
|
|
2952
|
+
}
|
|
2953
|
+
function listIterations(docsRoot, source = 'local', refName) {
|
|
2954
|
+
const base = {
|
|
2955
|
+
docsRoot,
|
|
2956
|
+
configured: docsRoot.trim().length > 0,
|
|
2957
|
+
accessible: false,
|
|
2958
|
+
reason: null,
|
|
2959
|
+
source,
|
|
2960
|
+
ref: null,
|
|
2961
|
+
iterations: []
|
|
2962
|
+
};
|
|
2963
|
+
if (!base.configured) return {
|
|
2964
|
+
...base,
|
|
2965
|
+
reason: '尚未配置文档仓库'
|
|
2966
|
+
};
|
|
2967
|
+
if (!external_node_fs_existsSync(docsRoot)) return {
|
|
2968
|
+
...base,
|
|
2969
|
+
reason: `文档仓库路径不存在:${docsRoot}`
|
|
2970
|
+
};
|
|
2971
|
+
try {
|
|
2972
|
+
readdirSync(docsRoot);
|
|
2973
|
+
} catch (error) {
|
|
2974
|
+
return {
|
|
2975
|
+
...base,
|
|
2976
|
+
reason: accessReason(error)
|
|
2977
|
+
};
|
|
2978
|
+
}
|
|
2979
|
+
try {
|
|
2980
|
+
return buildIterationList(docsRoot, source, base, refName);
|
|
2981
|
+
} catch (error) {
|
|
2982
|
+
return {
|
|
2983
|
+
...base,
|
|
2984
|
+
reason: accessReason(error)
|
|
2985
|
+
};
|
|
2986
|
+
}
|
|
2987
|
+
}
|
|
2988
|
+
function buildIterationList(docsRoot, source, base, refName) {
|
|
2989
|
+
if ('remote' === source) {
|
|
2990
|
+
const ref = resolveRemoteRef(docsRoot, refName);
|
|
2991
|
+
const snapshot = listRemoteIterations(docsRoot, ref);
|
|
2992
|
+
return {
|
|
2993
|
+
...base,
|
|
2994
|
+
accessible: true,
|
|
2995
|
+
ref: {
|
|
2996
|
+
name: ref.ref,
|
|
2997
|
+
sha: ref.sha,
|
|
2998
|
+
committedAt: ref.committedAt
|
|
2999
|
+
},
|
|
3000
|
+
iterations: snapshot.iterations
|
|
3001
|
+
};
|
|
3002
|
+
}
|
|
3003
|
+
const entries = readdirSync(docsRoot, {
|
|
3004
|
+
withFileTypes: true
|
|
3005
|
+
}).filter((entry)=>entry.isDirectory() && !RESERVED_DIRS.has(entry.name) && !entry.name.startsWith('.')).map((entry)=>{
|
|
3006
|
+
const directory = external_node_path_join(docsRoot, entry.name);
|
|
3007
|
+
const developers = listMarkdownFiles(directory);
|
|
3008
|
+
const info = statSync(directory);
|
|
3009
|
+
return {
|
|
3010
|
+
name: entry.name,
|
|
3011
|
+
mtime: info.mtime.toISOString(),
|
|
3012
|
+
developers,
|
|
3013
|
+
hasPrd: external_node_fs_existsSync(external_node_path_join(directory, '_prd', 'meta.json'))
|
|
3014
|
+
};
|
|
3015
|
+
}).filter((entry)=>entry.developers.length > 0).sort((left, right)=>right.mtime.localeCompare(left.mtime));
|
|
3016
|
+
return {
|
|
3017
|
+
...base,
|
|
3018
|
+
accessible: true,
|
|
3019
|
+
ref: null,
|
|
3020
|
+
iterations: entries
|
|
3021
|
+
};
|
|
3022
|
+
}
|
|
3023
|
+
function coerceIssue(value) {
|
|
3024
|
+
if (!utils_isRecord(value)) return null;
|
|
3025
|
+
const level = 'warning' === value['level'] ? 'warning' : 'error';
|
|
3026
|
+
const code = 'string' == typeof value['code'] ? value['code'] : 'UNKNOWN';
|
|
3027
|
+
const message = 'string' == typeof value['message'] ? value['message'] : '';
|
|
3028
|
+
const ref = 'string' == typeof value['ref'] ? value['ref'] : void 0;
|
|
3029
|
+
return void 0 === ref ? {
|
|
3030
|
+
level,
|
|
3031
|
+
code,
|
|
3032
|
+
message
|
|
3033
|
+
} : {
|
|
3034
|
+
level,
|
|
3035
|
+
code,
|
|
3036
|
+
message,
|
|
3037
|
+
ref
|
|
3038
|
+
};
|
|
3039
|
+
}
|
|
3040
|
+
function coerceRequirement(value) {
|
|
3041
|
+
if (!utils_isRecord(value)) return null;
|
|
3042
|
+
const id = 'string' == typeof value['id'] ? value['id'] : '';
|
|
3043
|
+
if (0 === id.length) return null;
|
|
3044
|
+
return {
|
|
3045
|
+
id,
|
|
3046
|
+
title: 'string' == typeof value['title'] ? value['title'] : '',
|
|
3047
|
+
terminal: 'string' == typeof value['terminal'] ? value['terminal'] : '',
|
|
3048
|
+
status: 'string' == typeof value['status'] ? value['status'] : '',
|
|
3049
|
+
progress: String(value['progress'] ?? ''),
|
|
3050
|
+
note: 'string' == typeof value['note'] ? value['note'] : '',
|
|
3051
|
+
taskIds: isStringArray(value['taskIds']) ? value['taskIds'] : []
|
|
3052
|
+
};
|
|
3053
|
+
}
|
|
3054
|
+
function coerceTask(value) {
|
|
3055
|
+
if (!utils_isRecord(value)) return null;
|
|
3056
|
+
const id = 'string' == typeof value['id'] ? value['id'] : '';
|
|
3057
|
+
if (0 === id.length) return null;
|
|
3058
|
+
return {
|
|
3059
|
+
id,
|
|
3060
|
+
requirementId: 'string' == typeof value['requirementId'] ? value['requirementId'] : '',
|
|
3061
|
+
name: 'string' == typeof value['name'] ? value['name'] : '',
|
|
3062
|
+
type: 'string' == typeof value['type'] ? value['type'] : '',
|
|
3063
|
+
terminal: 'string' == typeof value['terminal'] ? value['terminal'] : '',
|
|
3064
|
+
dependencies: isStringArray(value['dependencies']) ? value['dependencies'] : [],
|
|
3065
|
+
selfTest: 'string' == typeof value['selfTest'] ? value['selfTest'] : '',
|
|
3066
|
+
acceptance: 'string' == typeof value['acceptance'] ? value['acceptance'] : '',
|
|
3067
|
+
status: 'string' == typeof value['status'] ? value['status'] : ''
|
|
3068
|
+
};
|
|
3069
|
+
}
|
|
3070
|
+
function coerceInfo(value) {
|
|
3071
|
+
if (!utils_isRecord(value)) return {};
|
|
3072
|
+
const info = {};
|
|
3073
|
+
for (const [key, item] of Object.entries(value))if ('string' == typeof item) info[key] = item;
|
|
3074
|
+
return info;
|
|
3075
|
+
}
|
|
3076
|
+
function coercePayload(raw) {
|
|
3077
|
+
if (!utils_isRecord(raw)) return null;
|
|
3078
|
+
const stats = utils_isRecord(raw['stats']) ? raw['stats'] : {};
|
|
3079
|
+
const requirements = Array.isArray(raw['requirements']) ? raw['requirements'].map(coerceRequirement).filter((item)=>null !== item) : [];
|
|
3080
|
+
const tasks = Array.isArray(raw['tasks']) ? raw['tasks'].map(coerceTask).filter((item)=>null !== item) : [];
|
|
3081
|
+
const errors = Array.isArray(raw['errors']) ? raw['errors'].map(coerceIssue).filter((item)=>null !== item) : [];
|
|
3082
|
+
const warnings = Array.isArray(raw['warnings']) ? raw['warnings'].map(coerceIssue).filter((item)=>null !== item) : [];
|
|
3083
|
+
const asNumber = (value, fallback)=>'number' == typeof value ? value : fallback;
|
|
3084
|
+
return {
|
|
3085
|
+
valid: true === raw['valid'],
|
|
3086
|
+
iterationInfo: coerceInfo(raw['iterationInfo']),
|
|
3087
|
+
stats: {
|
|
3088
|
+
requirements: asNumber(stats['requirements'], requirements.length),
|
|
3089
|
+
tasks: asNumber(stats['tasks'], tasks.length),
|
|
3090
|
+
completedTasks: asNumber(stats['completedTasks'], tasks.filter((task)=>'已完成' === task.status).length),
|
|
3091
|
+
details: asNumber(stats['details'], 0)
|
|
3092
|
+
},
|
|
3093
|
+
requirements,
|
|
3094
|
+
tasks,
|
|
3095
|
+
errors,
|
|
3096
|
+
warnings
|
|
3097
|
+
};
|
|
3098
|
+
}
|
|
3099
|
+
function runValidator(input) {
|
|
3100
|
+
const script = input.scriptPath;
|
|
3101
|
+
if (null === script || !external_node_fs_existsSync(script)) return null;
|
|
3102
|
+
const args = [
|
|
3103
|
+
script,
|
|
3104
|
+
'--docs-root',
|
|
3105
|
+
input.docsRoot,
|
|
3106
|
+
'--iteration',
|
|
3107
|
+
input.iteration,
|
|
3108
|
+
'--developer',
|
|
3109
|
+
input.developer,
|
|
3110
|
+
'--role',
|
|
3111
|
+
input.role,
|
|
3112
|
+
'--format',
|
|
3113
|
+
'json'
|
|
3114
|
+
];
|
|
3115
|
+
for (const bin of [
|
|
3116
|
+
'python3',
|
|
3117
|
+
'python'
|
|
3118
|
+
])try {
|
|
3119
|
+
const stdout = execFileSync(bin, args, {
|
|
3120
|
+
encoding: 'utf8',
|
|
3121
|
+
timeout: 10000,
|
|
3122
|
+
maxBuffer: 16777216
|
|
3123
|
+
});
|
|
3124
|
+
const parsed = coercePayload(JSON.parse(stdout));
|
|
3125
|
+
if (null !== parsed) return parsed;
|
|
3126
|
+
} catch (error) {
|
|
3127
|
+
const stdout = error.stdout;
|
|
3128
|
+
if ('string' == typeof stdout && stdout.trim().length > 0) try {
|
|
3129
|
+
const parsed = coercePayload(JSON.parse(stdout));
|
|
3130
|
+
if (null !== parsed) return parsed;
|
|
3131
|
+
} catch {}
|
|
3132
|
+
}
|
|
3133
|
+
return null;
|
|
3134
|
+
}
|
|
3135
|
+
function extractSection(markdown, heading) {
|
|
3136
|
+
const lines = markdown.split(/\r?\n/);
|
|
3137
|
+
let start = -1;
|
|
3138
|
+
for(let index = 0; index < lines.length; index += 1)if ((lines[index] ?? '').trim() === heading) {
|
|
3139
|
+
start = index + 1;
|
|
3140
|
+
break;
|
|
3141
|
+
}
|
|
3142
|
+
if (start < 0) return '';
|
|
3143
|
+
const collected = [];
|
|
3144
|
+
for(let index = start; index < lines.length; index += 1){
|
|
3145
|
+
const line = lines[index] ?? '';
|
|
3146
|
+
if (/^##\s+/.test(line)) break;
|
|
3147
|
+
collected.push(line);
|
|
3148
|
+
}
|
|
3149
|
+
return collected.join('\n').trim();
|
|
3150
|
+
}
|
|
3151
|
+
function splitDetails(markdown) {
|
|
3152
|
+
const section = extractSection(markdown, '## 四、任务详情');
|
|
3153
|
+
if (0 === section.length) return [];
|
|
3154
|
+
const blocks = [];
|
|
3155
|
+
const parts = section.split(/^###\s+/m).slice(1);
|
|
3156
|
+
for (const part of parts){
|
|
3157
|
+
const [firstLine, ...rest] = part.split(/\r?\n/);
|
|
3158
|
+
const heading = (firstLine ?? '').trim();
|
|
3159
|
+
const match = /^\[?([#\w\-\u4e00-\u9fa5]+)\]?\s*(.*)$/.exec(heading);
|
|
3160
|
+
const id = match?.[1] ?? heading;
|
|
3161
|
+
const name = match?.[2]?.trim() ?? '';
|
|
3162
|
+
blocks.push({
|
|
3163
|
+
id,
|
|
3164
|
+
name,
|
|
3165
|
+
markdown: rest.join('\n').trim()
|
|
3166
|
+
});
|
|
3167
|
+
}
|
|
3168
|
+
return blocks;
|
|
3169
|
+
}
|
|
3170
|
+
function parseMarkdownDoc(markdown) {
|
|
3171
|
+
const readTable = (sectionHeading, headers)=>{
|
|
3172
|
+
const section = extractSection(markdown, sectionHeading);
|
|
3173
|
+
const rows = section.split(/\r?\n/).map((line)=>line.trim()).filter((line)=>line.startsWith('|')).map((line)=>line.replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell)=>cell.trim())).filter((cells)=>!cells.every((cell)=>/^:?-{2,}:?$/.test(cell) || 0 === cell.length));
|
|
3174
|
+
const [header, ...body] = rows;
|
|
3175
|
+
if (void 0 === header) return [];
|
|
3176
|
+
const matched = headers.every((name, index)=>(header[index] ?? '') === name);
|
|
3177
|
+
return matched ? body : [];
|
|
3178
|
+
};
|
|
3179
|
+
const requirementRows = readTable('## 二、需求清单', [
|
|
3180
|
+
'需求编号',
|
|
3181
|
+
'需求名称',
|
|
3182
|
+
'终端',
|
|
3183
|
+
'开发状态',
|
|
3184
|
+
'开发进度(%)',
|
|
3185
|
+
'备注'
|
|
3186
|
+
]);
|
|
3187
|
+
const taskRows = readTable('## 三、任务清单', [
|
|
3188
|
+
'任务编号',
|
|
3189
|
+
'关联需求编号',
|
|
3190
|
+
'任务名称',
|
|
3191
|
+
'任务类型',
|
|
3192
|
+
'终端',
|
|
3193
|
+
'前置依赖任务编号',
|
|
3194
|
+
'AI自测状态',
|
|
3195
|
+
'开发人工验收',
|
|
3196
|
+
'任务状态'
|
|
3197
|
+
]);
|
|
3198
|
+
const requirements = requirementRows.map((row)=>({
|
|
3199
|
+
id: row[0] ?? '',
|
|
3200
|
+
title: row[1] ?? '',
|
|
3201
|
+
terminal: row[2] ?? '',
|
|
3202
|
+
status: row[3] ?? '',
|
|
3203
|
+
progress: row[4] ?? '',
|
|
3204
|
+
note: row[5] ?? '',
|
|
3205
|
+
taskIds: []
|
|
3206
|
+
}));
|
|
3207
|
+
const tasks = taskRows.map((row)=>({
|
|
3208
|
+
id: row[0] ?? '',
|
|
3209
|
+
requirementId: row[1] ?? '',
|
|
3210
|
+
name: row[2] ?? '',
|
|
3211
|
+
type: row[3] ?? '',
|
|
3212
|
+
terminal: row[4] ?? '',
|
|
3213
|
+
dependencies: (row[5] ?? '').split(/[,,]/).map((item)=>item.trim()).filter((item)=>item.length > 0),
|
|
3214
|
+
selfTest: row[6] ?? '',
|
|
3215
|
+
acceptance: row[7] ?? '',
|
|
3216
|
+
status: row[8] ?? ''
|
|
3217
|
+
}));
|
|
3218
|
+
for (const requirement of requirements)requirement.taskIds = tasks.filter((task)=>task.requirementId === requirement.id).map((task)=>task.id);
|
|
3219
|
+
const details = splitDetails(markdown);
|
|
3220
|
+
const infoMatch = /\|\s*迭代版本\s*\|\s*([^|]*)\|/.exec(markdown);
|
|
3221
|
+
const prdMatch = /\|\s*PRD 来源\s*\|\s*([^|]*)\|/.exec(markdown);
|
|
3222
|
+
const planMatch = /\|\s*排期计划\s*\|\s*([^|]*)\|/.exec(markdown);
|
|
3223
|
+
const ownerMatch = /\|\s*负责人\s*\|\s*([^|]*)\|/.exec(markdown);
|
|
3224
|
+
const scopeMatch = /\|\s*负责范围\s*\|\s*([^|]*)\|/.exec(markdown);
|
|
3225
|
+
const iterationInfo = {};
|
|
3226
|
+
const put = (key, match)=>{
|
|
3227
|
+
const value = match?.[1]?.trim();
|
|
3228
|
+
if (void 0 !== value && value.length > 0) iterationInfo[key] = value;
|
|
3229
|
+
};
|
|
3230
|
+
put('迭代版本', infoMatch);
|
|
3231
|
+
put('PRD 来源', prdMatch);
|
|
3232
|
+
put('排期计划', planMatch);
|
|
3233
|
+
put('负责人', ownerMatch);
|
|
3234
|
+
put('负责范围', scopeMatch);
|
|
3235
|
+
return {
|
|
3236
|
+
valid: false,
|
|
3237
|
+
iterationInfo,
|
|
3238
|
+
stats: {
|
|
3239
|
+
requirements: requirements.length,
|
|
3240
|
+
tasks: tasks.length,
|
|
3241
|
+
completedTasks: tasks.filter((task)=>'已完成' === task.status).length,
|
|
3242
|
+
details: details.length
|
|
3243
|
+
},
|
|
3244
|
+
requirements,
|
|
3245
|
+
tasks,
|
|
3246
|
+
errors: [],
|
|
3247
|
+
warnings: []
|
|
3248
|
+
};
|
|
3249
|
+
}
|
|
3250
|
+
function readMarkdown(target) {
|
|
3251
|
+
return readFileSync(target, 'utf8');
|
|
3252
|
+
}
|
|
3253
|
+
function readIterationDoc(docsRoot, iteration, developer, source = 'local', presetRef, refName) {
|
|
3254
|
+
const safeIteration = iterations_safeSegment(iteration, '迭代目录');
|
|
3255
|
+
const safeDeveloper = iterations_safeSegment(developer, '开发者标识');
|
|
3256
|
+
if ('remote' === source) {
|
|
3257
|
+
const ref = presetRef ?? resolveRemoteRef(docsRoot, refName);
|
|
3258
|
+
const exported = exportRemoteDoc(docsRoot, ref, safeIteration, safeDeveloper);
|
|
3259
|
+
const roleInferred = inferRole(exported.markdown);
|
|
3260
|
+
const scripted = runValidator({
|
|
3261
|
+
docsRoot: exported.dir,
|
|
3262
|
+
scriptPath: exported.scriptPath,
|
|
3263
|
+
iteration: safeIteration,
|
|
3264
|
+
developer: safeDeveloper,
|
|
3265
|
+
role: roleInferred
|
|
3266
|
+
});
|
|
3267
|
+
return {
|
|
3268
|
+
iteration: safeIteration,
|
|
3269
|
+
developer: safeDeveloper,
|
|
3270
|
+
file: `${safeIteration}/${safeDeveloper}.md`,
|
|
3271
|
+
mtime: exported.mtime,
|
|
3272
|
+
roleInferred,
|
|
3273
|
+
parser: null === scripted ? 'fallback' : "script",
|
|
3274
|
+
source: 'remote',
|
|
3275
|
+
ref: {
|
|
3276
|
+
name: ref.ref,
|
|
3277
|
+
sha: ref.sha
|
|
3278
|
+
},
|
|
3279
|
+
validation: scripted ?? parseMarkdownDoc(exported.markdown),
|
|
3280
|
+
details: splitDetails(exported.markdown)
|
|
3281
|
+
};
|
|
3282
|
+
}
|
|
3283
|
+
const directory = joinWithin(docsRoot, safeIteration);
|
|
3284
|
+
if (!external_node_fs_existsSync(directory)) throw new errors_CliError(`迭代目录不存在:${safeIteration}`, errors_EXIT.NOT_FOUND);
|
|
3285
|
+
const file = joinWithin(directory, `${safeDeveloper}.md`);
|
|
3286
|
+
if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${safeIteration}/${safeDeveloper}.md`, errors_EXIT.NOT_FOUND);
|
|
3287
|
+
const markdown = readMarkdown(file);
|
|
3288
|
+
const roleInferred = inferRole(markdown);
|
|
3289
|
+
const scripted = runValidator({
|
|
3290
|
+
docsRoot,
|
|
3291
|
+
scriptPath: external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py'),
|
|
3292
|
+
iteration: safeIteration,
|
|
3293
|
+
developer: safeDeveloper,
|
|
3294
|
+
role: roleInferred
|
|
3295
|
+
});
|
|
3296
|
+
const validation = scripted ?? parseMarkdownDoc(markdown);
|
|
3297
|
+
const parser = null === scripted ? 'fallback' : "script";
|
|
3298
|
+
return {
|
|
3299
|
+
iteration: safeIteration,
|
|
3300
|
+
developer: safeDeveloper,
|
|
3301
|
+
file,
|
|
3302
|
+
mtime: statSync(file).mtime.toISOString(),
|
|
3303
|
+
roleInferred,
|
|
3304
|
+
parser,
|
|
3305
|
+
source: 'local',
|
|
3306
|
+
ref: null,
|
|
3307
|
+
validation,
|
|
3308
|
+
details: splitDetails(markdown)
|
|
3309
|
+
};
|
|
3310
|
+
}
|
|
3311
|
+
function readIterationSummary(docsRoot, iteration, source = 'local', refName) {
|
|
3312
|
+
const safeIteration = iterations_safeSegment(iteration, '迭代目录');
|
|
3313
|
+
const remoteRef = 'remote' === source ? resolveRemoteRef(docsRoot, refName) : null;
|
|
3314
|
+
let developers;
|
|
3315
|
+
if (null === remoteRef) {
|
|
3316
|
+
const directory = joinWithin(docsRoot, safeIteration);
|
|
3317
|
+
if (!external_node_fs_existsSync(directory)) throw new errors_CliError(`迭代目录不存在:${safeIteration}`, errors_EXIT.NOT_FOUND);
|
|
3318
|
+
developers = listMarkdownFiles(directory);
|
|
3319
|
+
} else {
|
|
3320
|
+
const snapshot = listRemoteIterations(docsRoot, remoteRef);
|
|
3321
|
+
const found = snapshot.iterations.find((item)=>item.name === safeIteration);
|
|
3322
|
+
if (void 0 === found) throw new errors_CliError(`远程快照中不存在迭代:${safeIteration}`, errors_EXIT.NOT_FOUND);
|
|
3323
|
+
developers = found.developers;
|
|
3324
|
+
}
|
|
3325
|
+
const summaries = [];
|
|
3326
|
+
const blocked = [];
|
|
3327
|
+
for (const entry of developers){
|
|
3328
|
+
const doc = readIterationDoc(docsRoot, safeIteration, entry.id, source, remoteRef ?? void 0);
|
|
3329
|
+
const statusCounts = {};
|
|
3330
|
+
const selfTestCounts = {};
|
|
3331
|
+
const acceptanceCounts = {};
|
|
3332
|
+
for (const task of doc.validation.tasks){
|
|
3333
|
+
bump(statusCounts, 0 === task.status.length ? '未知' : task.status);
|
|
3334
|
+
bump(selfTestCounts, normalizeSelfTest(task.selfTest));
|
|
3335
|
+
bump(acceptanceCounts, normalizeAcceptance(task.acceptance));
|
|
3336
|
+
}
|
|
3337
|
+
const byId = new Map(doc.validation.tasks.map((task)=>[
|
|
3338
|
+
task.id,
|
|
3339
|
+
task
|
|
3340
|
+
]));
|
|
3341
|
+
for (const task of doc.validation.tasks){
|
|
3342
|
+
if ('已完成' === task.status) continue;
|
|
3343
|
+
const blocking = task.dependencies.map((dep)=>{
|
|
3344
|
+
const target = byId.get(dep);
|
|
3345
|
+
return void 0 === target ? null : {
|
|
3346
|
+
id: dep,
|
|
3347
|
+
status: target.status
|
|
3348
|
+
};
|
|
3349
|
+
}).filter((item)=>null !== item && '已完成' !== item.status);
|
|
3350
|
+
if (blocking.length > 0) blocked.push({
|
|
3351
|
+
developer: entry.id,
|
|
3352
|
+
taskId: task.id,
|
|
3353
|
+
name: task.name,
|
|
3354
|
+
dependencies: task.dependencies,
|
|
3355
|
+
blocking
|
|
3356
|
+
});
|
|
3357
|
+
}
|
|
3358
|
+
const requirementStatusCounts = {};
|
|
3359
|
+
for (const requirement of doc.validation.requirements)bump(requirementStatusCounts, 0 === requirement.status.length ? '未知' : requirement.status);
|
|
3360
|
+
summaries.push({
|
|
3361
|
+
id: entry.id,
|
|
3362
|
+
roleInferred: doc.roleInferred,
|
|
3363
|
+
parser: doc.parser,
|
|
3364
|
+
stats: doc.validation.stats,
|
|
3365
|
+
statusCounts,
|
|
3366
|
+
requirementStatusCounts,
|
|
3367
|
+
selfTestCounts,
|
|
3368
|
+
acceptanceCounts,
|
|
3369
|
+
errors: doc.validation.errors.length,
|
|
3370
|
+
warnings: doc.validation.warnings.length,
|
|
3371
|
+
mtime: doc.mtime
|
|
3372
|
+
});
|
|
3373
|
+
}
|
|
3374
|
+
const mergeCounts = (pick)=>{
|
|
3375
|
+
const merged = {};
|
|
3376
|
+
for (const item of summaries)for (const [status, count] of Object.entries(pick(item)))merged[status] = (merged[status] ?? 0) + count;
|
|
3377
|
+
return merged;
|
|
3378
|
+
};
|
|
3379
|
+
const totals = summaries.reduce((acc, item)=>({
|
|
3380
|
+
developers: acc.developers + 1,
|
|
3381
|
+
requirements: acc.requirements + item.stats.requirements,
|
|
3382
|
+
tasks: acc.tasks + item.stats.tasks,
|
|
3383
|
+
completedTasks: acc.completedTasks + item.stats.completedTasks,
|
|
3384
|
+
errors: acc.errors + item.errors,
|
|
3385
|
+
warnings: acc.warnings + item.warnings
|
|
3386
|
+
}), {
|
|
3387
|
+
developers: 0,
|
|
3388
|
+
requirements: 0,
|
|
3389
|
+
tasks: 0,
|
|
3390
|
+
completedTasks: 0,
|
|
3391
|
+
errors: 0,
|
|
3392
|
+
warnings: 0
|
|
3393
|
+
});
|
|
3394
|
+
return {
|
|
3395
|
+
iteration: safeIteration,
|
|
3396
|
+
docsRoot,
|
|
3397
|
+
source,
|
|
3398
|
+
ref: null === remoteRef ? null : {
|
|
3399
|
+
name: remoteRef.ref,
|
|
3400
|
+
sha: remoteRef.sha,
|
|
3401
|
+
committedAt: remoteRef.committedAt
|
|
3402
|
+
},
|
|
3403
|
+
totals: {
|
|
3404
|
+
...totals,
|
|
3405
|
+
progress: 0 === totals.tasks ? 0 : Math.round(totals.completedTasks / totals.tasks * 100),
|
|
3406
|
+
taskStatusCounts: mergeCounts((item)=>item.statusCounts),
|
|
3407
|
+
requirementStatusCounts: mergeCounts((item)=>item.requirementStatusCounts),
|
|
3408
|
+
selfTestCounts: mergeCounts((item)=>item.selfTestCounts),
|
|
3409
|
+
acceptanceCounts: mergeCounts((item)=>item.acceptanceCounts)
|
|
3410
|
+
},
|
|
3411
|
+
developers: summaries,
|
|
3412
|
+
blocked
|
|
3413
|
+
};
|
|
3414
|
+
}
|
|
3415
|
+
const probeCache = new Map();
|
|
3416
|
+
const PROBE_TTL_MS = 60000;
|
|
3417
|
+
function cachedProbe(remote) {
|
|
3418
|
+
const hit = probeCache.get(remote);
|
|
3419
|
+
if (void 0 !== hit && Date.now() - hit.at < PROBE_TTL_MS) return hit.result;
|
|
3420
|
+
const result = probeRemote(remote);
|
|
3421
|
+
probeCache.set(remote, {
|
|
3422
|
+
at: Date.now(),
|
|
3423
|
+
result
|
|
3424
|
+
});
|
|
3425
|
+
return result;
|
|
3426
|
+
}
|
|
3427
|
+
function isManagedPath(root) {
|
|
3428
|
+
return root.includes('/.ylcwf/repos/');
|
|
3429
|
+
}
|
|
3430
|
+
function inspectOnboarding(configPath) {
|
|
3431
|
+
const loaded = loadConfig(configPath);
|
|
3432
|
+
const config = loaded.config;
|
|
3433
|
+
const mode = config?.profile.mode ?? 'developer';
|
|
3434
|
+
const role = config?.profile.role ?? 'frontend';
|
|
3435
|
+
const root = config?.docs.root ?? '';
|
|
3436
|
+
const remote = config?.docs.remote ?? DEFAULT_DOCS_REMOTE;
|
|
3437
|
+
const remoteIsDefault = config?.docs.remote === null || config?.docs.remote === void 0;
|
|
3438
|
+
const base = {
|
|
3439
|
+
hasConfig: loaded.exists,
|
|
3440
|
+
configValid: null !== config,
|
|
3441
|
+
mode,
|
|
3442
|
+
developer: config?.profile.developer ?? '',
|
|
3443
|
+
role,
|
|
3444
|
+
docsRoot: root,
|
|
3445
|
+
docsRemote: remote,
|
|
3446
|
+
remoteIsDefault,
|
|
3447
|
+
gitAvailable: isGitAvailable(),
|
|
3448
|
+
docsConfigured: root.trim().length > 0,
|
|
3449
|
+
docsAccessible: false,
|
|
3450
|
+
docsManaged: root.trim().length > 0 && isManagedPath(root),
|
|
3451
|
+
iterationCount: 0,
|
|
3452
|
+
reason: null,
|
|
3453
|
+
nextStep: 'ready'
|
|
3454
|
+
};
|
|
3455
|
+
if (!base.hasConfig) return {
|
|
3456
|
+
...base,
|
|
3457
|
+
nextStep: 'create-config'
|
|
3458
|
+
};
|
|
3459
|
+
if (!base.configValid) return {
|
|
3460
|
+
...base,
|
|
3461
|
+
nextStep: 'fix-config',
|
|
3462
|
+
reason: '配置文件结构不合法,请用 ylcwf doctor 查看详情'
|
|
3463
|
+
};
|
|
3464
|
+
if ('stakeholder' === mode) {
|
|
3465
|
+
if (!base.gitAvailable) return {
|
|
3466
|
+
...base,
|
|
3467
|
+
nextStep: 'install-git',
|
|
3468
|
+
reason: '未检测到 git 命令,请先安装 Git'
|
|
3469
|
+
};
|
|
3470
|
+
const probe = cachedProbe(remote);
|
|
3471
|
+
if (!probe.authorized) return {
|
|
3472
|
+
...base,
|
|
3473
|
+
nextStep: 'auth-remote',
|
|
3474
|
+
reason: probe.reason ?? '没有文档仓库访问权限,请联系管理员开通'
|
|
3475
|
+
};
|
|
3476
|
+
if (base.docsConfigured) {
|
|
3477
|
+
const listed = listIterations(root, 'local');
|
|
3478
|
+
if (listed.accessible) return {
|
|
3479
|
+
...base,
|
|
3480
|
+
docsAccessible: true,
|
|
3481
|
+
iterationCount: listed.iterations.length,
|
|
3482
|
+
nextStep: 'ready'
|
|
3483
|
+
};
|
|
3484
|
+
return {
|
|
3485
|
+
...base,
|
|
3486
|
+
reason: listed.reason,
|
|
3487
|
+
nextStep: 'prepare-cache'
|
|
3488
|
+
};
|
|
3489
|
+
}
|
|
3490
|
+
return {
|
|
3491
|
+
...base,
|
|
3492
|
+
nextStep: 'prepare-cache',
|
|
3493
|
+
reason: '需要在本地准备只读副本'
|
|
3494
|
+
};
|
|
3495
|
+
}
|
|
3496
|
+
if (!base.docsConfigured) return {
|
|
3497
|
+
...base,
|
|
3498
|
+
nextStep: 'set-docs-root',
|
|
3499
|
+
reason: '尚未选择本地文档仓库'
|
|
3500
|
+
};
|
|
3501
|
+
const listed = listIterations(root, 'local');
|
|
3502
|
+
if (listed.accessible) return {
|
|
3503
|
+
...base,
|
|
3504
|
+
docsAccessible: true,
|
|
3505
|
+
iterationCount: listed.iterations.length,
|
|
3506
|
+
nextStep: 'ready'
|
|
3507
|
+
};
|
|
3508
|
+
return {
|
|
3509
|
+
...base,
|
|
3510
|
+
reason: listed.reason,
|
|
3511
|
+
nextStep: 'set-docs-root'
|
|
3512
|
+
};
|
|
3513
|
+
}
|
|
3514
|
+
function prepareManagedDocs(configPath) {
|
|
3515
|
+
const loaded = loadConfig(configPath);
|
|
3516
|
+
if (null === loaded.config) throw new errors_CliError('配置未初始化或结构不合法,无法准备文档仓库', errors_EXIT.INVALID);
|
|
3517
|
+
if ('stakeholder' !== loaded.config.profile.mode) throw new errors_CliError('只有干系人模式会自动准备文档仓库;开发者请选择本地仓库路径', errors_EXIT.USAGE);
|
|
3518
|
+
const remote = loaded.config.docs.remote ?? DEFAULT_DOCS_REMOTE;
|
|
3519
|
+
const clone = ensureManagedClone(remote);
|
|
3520
|
+
const next = {
|
|
3521
|
+
...loaded.config,
|
|
3522
|
+
docs: {
|
|
3523
|
+
root: clone.dir,
|
|
3524
|
+
remote
|
|
3525
|
+
}
|
|
3526
|
+
};
|
|
3527
|
+
saveConfig(next, configPath);
|
|
3528
|
+
return inspectOnboarding(configPath);
|
|
3529
|
+
}
|
|
3530
|
+
function completeOnboarding(draftRaw, configPath) {
|
|
3531
|
+
const structural = checkConfig(draftRaw, {
|
|
3532
|
+
allowIncomplete: true,
|
|
3533
|
+
checkFs: false
|
|
3534
|
+
});
|
|
3535
|
+
if (null === structural.config || structural.issues.some((issue)=>'error' === issue.level)) {
|
|
3536
|
+
const detail = structural.issues.filter((issue)=>'error' === issue.level).map((issue)=>`- ${issue.message}`).join('\n');
|
|
3537
|
+
throw new errors_CliError(`配置校验未通过:\n${detail}`, errors_EXIT.INVALID);
|
|
3538
|
+
}
|
|
3539
|
+
const draft = structural.config;
|
|
3540
|
+
if ('developer' === draft.profile.mode && 0 === draft.profile.developer.trim().length) throw new errors_CliError('开发者标识不能为空', errors_EXIT.USAGE);
|
|
3541
|
+
let root = draft.docs.root;
|
|
3542
|
+
const remote = draft.docs.remote ?? DEFAULT_DOCS_REMOTE;
|
|
3543
|
+
if (0 === root.trim().length) {
|
|
3544
|
+
if ('stakeholder' !== draft.profile.mode) throw new errors_CliError('开发者必须选择本地文档仓库路径', errors_EXIT.USAGE);
|
|
3545
|
+
const clone = ensureManagedClone(remote);
|
|
3546
|
+
root = clone.dir;
|
|
3547
|
+
}
|
|
3548
|
+
saveConfig({
|
|
3549
|
+
...draft,
|
|
3550
|
+
docs: {
|
|
3551
|
+
root,
|
|
3552
|
+
remote
|
|
3553
|
+
}
|
|
3554
|
+
}, configPath);
|
|
3555
|
+
return inspectOnboarding(configPath);
|
|
3556
|
+
}
|
|
3557
|
+
function assertDirectory(target) {
|
|
3558
|
+
const absolute = isAbsolute(target) ? resolve(target) : resolve(homedir(), target);
|
|
3559
|
+
if (!external_node_fs_existsSync(absolute)) throw new errors_CliError(`目录不存在:${absolute}`, errors_EXIT.NOT_FOUND);
|
|
3560
|
+
if (!statSync(absolute).isDirectory()) throw new errors_CliError(`不是目录:${absolute}`, errors_EXIT.USAGE);
|
|
3561
|
+
return absolute;
|
|
3562
|
+
}
|
|
3563
|
+
function listDirectories(target) {
|
|
3564
|
+
const start = void 0 === target || 0 === target.trim().length ? homedir() : target;
|
|
3565
|
+
const absolute = assertDirectory(start);
|
|
3566
|
+
const parentCandidate = dirname(absolute);
|
|
3567
|
+
const entries = [];
|
|
3568
|
+
for (const name of readdirSync(absolute)){
|
|
3569
|
+
const full = external_node_path_join(absolute, name);
|
|
3570
|
+
try {
|
|
3571
|
+
if (!statSync(full).isDirectory()) continue;
|
|
3572
|
+
} catch {
|
|
3573
|
+
continue;
|
|
3574
|
+
}
|
|
3575
|
+
entries.push({
|
|
3576
|
+
name,
|
|
3577
|
+
path: full,
|
|
3578
|
+
hidden: name.startsWith('.')
|
|
3579
|
+
});
|
|
3580
|
+
}
|
|
3581
|
+
entries.sort((left, right)=>{
|
|
3582
|
+
if (left.hidden !== right.hidden) return left.hidden ? 1 : -1;
|
|
3583
|
+
return left.name.localeCompare(right.name, 'zh-CN');
|
|
3584
|
+
});
|
|
3585
|
+
return {
|
|
3586
|
+
path: absolute,
|
|
3587
|
+
parent: parentCandidate === absolute ? null : parentCandidate,
|
|
3588
|
+
entries
|
|
3589
|
+
};
|
|
3590
|
+
}
|
|
3591
|
+
function openInFileManager(target) {
|
|
3592
|
+
try {
|
|
3593
|
+
const absolute = assertDirectory(target);
|
|
3594
|
+
const command = 'darwin' === process.platform ? 'open' : 'win32' === process.platform ? 'explorer' : 'xdg-open';
|
|
3595
|
+
spawn(command, [
|
|
3596
|
+
absolute
|
|
3597
|
+
], {
|
|
3598
|
+
detached: true,
|
|
3599
|
+
stdio: 'ignore'
|
|
3600
|
+
}).unref();
|
|
3601
|
+
return {
|
|
3602
|
+
ok: true,
|
|
3603
|
+
message: `已打开 ${absolute}`
|
|
3604
|
+
};
|
|
3605
|
+
} catch (error) {
|
|
3606
|
+
const message = error instanceof errors_CliError ? error.message : String(error);
|
|
3607
|
+
return {
|
|
3608
|
+
ok: false,
|
|
3609
|
+
message
|
|
3610
|
+
};
|
|
3611
|
+
}
|
|
3612
|
+
}
|
|
3613
|
+
let cache = null;
|
|
3614
|
+
const CACHE_TTL_MS = 600000;
|
|
3615
|
+
function isNewer(a, b) {
|
|
3616
|
+
const parse = (text)=>text.replace(/^v/, '').split('-')[0]?.split('.').map((part)=>Number.parseInt(part, 10) || 0) ?? [];
|
|
3617
|
+
const left = parse(a);
|
|
3618
|
+
const right = parse(b);
|
|
3619
|
+
for(let index = 0; index < Math.max(left.length, right.length); index += 1){
|
|
3620
|
+
const diff = (left[index] ?? 0) - (right[index] ?? 0);
|
|
3621
|
+
if (0 !== diff) return diff > 0;
|
|
3622
|
+
}
|
|
3623
|
+
return false;
|
|
3624
|
+
}
|
|
3625
|
+
async function fetchManifest(url) {
|
|
3626
|
+
try {
|
|
3627
|
+
const response = await fetch(url, {
|
|
3628
|
+
signal: AbortSignal.timeout(5000)
|
|
3629
|
+
});
|
|
3630
|
+
if (!response.ok) return null;
|
|
3631
|
+
const payload = await response.json();
|
|
3632
|
+
if ('string' != typeof payload.version || 0 === payload.version.length) return null;
|
|
3633
|
+
return {
|
|
3634
|
+
current: "0.2.0",
|
|
3635
|
+
latest: payload.version,
|
|
3636
|
+
hasUpdate: isNewer(payload.version, "0.2.0"),
|
|
3637
|
+
downloadUrl: 'string' == typeof payload.downloadUrl ? payload.downloadUrl : null,
|
|
3638
|
+
source: 'manifest',
|
|
3639
|
+
checkedAt: new Date().toISOString(),
|
|
3640
|
+
error: null
|
|
3641
|
+
};
|
|
3642
|
+
} catch {
|
|
3643
|
+
return null;
|
|
3644
|
+
}
|
|
3645
|
+
}
|
|
3646
|
+
async function fetchNpm() {
|
|
3647
|
+
const base = {
|
|
3648
|
+
current: "0.2.0",
|
|
3649
|
+
latest: null,
|
|
3650
|
+
hasUpdate: false,
|
|
3651
|
+
downloadUrl: null,
|
|
3652
|
+
source: 'npm',
|
|
3653
|
+
checkedAt: new Date().toISOString(),
|
|
3654
|
+
error: null
|
|
3655
|
+
};
|
|
3656
|
+
try {
|
|
3657
|
+
const response = await fetch('https://registry.npmjs.org/ylcwf/latest', {
|
|
3658
|
+
signal: AbortSignal.timeout(5000)
|
|
3659
|
+
});
|
|
3660
|
+
if (!response.ok) return {
|
|
3661
|
+
...base,
|
|
3662
|
+
source: 'none',
|
|
3663
|
+
error: `版本服务不可用(HTTP ${response.status})`
|
|
3664
|
+
};
|
|
3665
|
+
const payload = await response.json();
|
|
3666
|
+
const latest = 'string' == typeof payload.version ? payload.version : null;
|
|
3667
|
+
if (null === latest) return {
|
|
3668
|
+
...base,
|
|
3669
|
+
source: 'none',
|
|
3670
|
+
error: '版本服务返回内容异常'
|
|
3671
|
+
};
|
|
3672
|
+
return {
|
|
3673
|
+
...base,
|
|
3674
|
+
latest,
|
|
3675
|
+
hasUpdate: isNewer(latest, "0.2.0"),
|
|
3676
|
+
downloadUrl: 'https://www.npmjs.com/package/ylcwf'
|
|
3677
|
+
};
|
|
3678
|
+
} catch (error) {
|
|
3679
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
3680
|
+
return {
|
|
3681
|
+
...base,
|
|
3682
|
+
source: 'none',
|
|
3683
|
+
error: `无法连接版本服务:${message.split('\n')[0]}`
|
|
3684
|
+
};
|
|
3685
|
+
}
|
|
3686
|
+
}
|
|
3687
|
+
async function checkUpdate(force = false) {
|
|
3688
|
+
if (!force && null !== cache && Date.now() - cache.at < CACHE_TTL_MS) return cache.result;
|
|
3689
|
+
const manifestUrl = process.env['YLCWF_UPDATE_MANIFEST']?.trim() ?? '';
|
|
3690
|
+
let result = manifestUrl.length > 0 ? await fetchManifest(manifestUrl) : null;
|
|
3691
|
+
result ??= await fetchNpm();
|
|
3692
|
+
cache = {
|
|
3693
|
+
at: Date.now(),
|
|
3694
|
+
result
|
|
3695
|
+
};
|
|
3696
|
+
return result;
|
|
3697
|
+
}
|
|
3698
|
+
function requireDocsRoot(configPath) {
|
|
3699
|
+
const loaded = loadConfig(configPath);
|
|
3700
|
+
const root = loaded.config?.docs.root ?? '';
|
|
3701
|
+
if (0 === root.length) throw new errors_CliError('未配置文档仓库:请先在「文档仓库」页填写 docs.root 并保存', errors_EXIT.NOT_FOUND);
|
|
3702
|
+
return root;
|
|
3703
|
+
}
|
|
3704
|
+
function parseSource(value) {
|
|
3705
|
+
return 'remote' === value ? 'remote' : 'local';
|
|
3706
|
+
}
|
|
3707
|
+
function pickString(body, key) {
|
|
3708
|
+
if ('object' != typeof body || null === body) return '';
|
|
3709
|
+
const value = Reflect.get(body, key);
|
|
3710
|
+
return 'string' == typeof value ? value : '';
|
|
3711
|
+
}
|
|
3712
|
+
function pickOptionalString(body, key) {
|
|
3713
|
+
const value = pickString(body, key).trim();
|
|
3714
|
+
return 0 === value.length ? void 0 : value;
|
|
3715
|
+
}
|
|
3716
|
+
const MIME = {
|
|
3717
|
+
'.html': 'text/html; charset=utf-8',
|
|
3718
|
+
'.js': "text/javascript; charset=utf-8",
|
|
3719
|
+
'.mjs': "text/javascript; charset=utf-8",
|
|
3720
|
+
'.css': 'text/css; charset=utf-8',
|
|
3721
|
+
'.json': 'application/json; charset=utf-8',
|
|
3722
|
+
'.svg': 'image/svg+xml',
|
|
3723
|
+
'.png': 'image/png',
|
|
3724
|
+
'.jpg': 'image/jpeg',
|
|
3725
|
+
'.webp': 'image/webp',
|
|
3726
|
+
'.woff2': 'font/woff2',
|
|
3727
|
+
'.ico': 'image/x-icon'
|
|
3728
|
+
};
|
|
3729
|
+
const MAX_BODY = 2097152;
|
|
3730
|
+
function sendJson(response, status, payload) {
|
|
3731
|
+
const body = JSON.stringify(payload);
|
|
3732
|
+
response.writeHead(status, {
|
|
3733
|
+
'content-type': 'application/json; charset=utf-8',
|
|
3734
|
+
'content-length': Buffer.byteLength(body),
|
|
3735
|
+
'cache-control': 'no-store'
|
|
3736
|
+
});
|
|
3737
|
+
response.end(body);
|
|
3738
|
+
}
|
|
3739
|
+
function sendError(response, error) {
|
|
3740
|
+
if (error instanceof errors_CliError) return void sendJson(response, error.exitCode === errors_EXIT.NOT_FOUND ? 404 : 400, {
|
|
3741
|
+
error: {
|
|
3742
|
+
code: error.exitCode,
|
|
3743
|
+
message: error.message
|
|
3744
|
+
}
|
|
3745
|
+
});
|
|
3746
|
+
sendJson(response, 500, {
|
|
3747
|
+
error: {
|
|
3748
|
+
code: 500,
|
|
3749
|
+
message: error instanceof Error ? error.message : String(error)
|
|
3750
|
+
}
|
|
3751
|
+
});
|
|
3752
|
+
}
|
|
3753
|
+
async function readJsonBody(request) {
|
|
3754
|
+
const chunks = [];
|
|
3755
|
+
let size = 0;
|
|
3756
|
+
for await (const chunk of request){
|
|
3757
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
3758
|
+
size += buffer.length;
|
|
3759
|
+
if (size > MAX_BODY) throw new errors_CliError('请求体过大', errors_EXIT.USAGE);
|
|
3760
|
+
chunks.push(buffer);
|
|
3761
|
+
}
|
|
3762
|
+
if (0 === size) return;
|
|
3763
|
+
try {
|
|
3764
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
3765
|
+
} catch {
|
|
3766
|
+
throw new errors_CliError('请求体不是合法 JSON', errors_EXIT.USAGE);
|
|
3767
|
+
}
|
|
3768
|
+
}
|
|
3769
|
+
function resolveStaticPath(uiDir, pathname) {
|
|
3770
|
+
const decoded = decodeURIComponent(pathname);
|
|
3771
|
+
const target = resolve(uiDir, `.${'/' === decoded ? '/index.html' : decoded}`);
|
|
3772
|
+
const root = resolve(uiDir) + sep;
|
|
3773
|
+
return target.startsWith(root) ? target : null;
|
|
3774
|
+
}
|
|
3775
|
+
function serveStatic(response, uiDir, pathname) {
|
|
3776
|
+
const target = resolveStaticPath(uiDir, pathname);
|
|
3777
|
+
if (null === target || !external_node_fs_existsSync(target) || !statSync(target).isFile()) return void sendJson(response, 404, {
|
|
3778
|
+
error: {
|
|
3779
|
+
code: 404,
|
|
3780
|
+
message: `未找到静态资源:${pathname}`
|
|
3781
|
+
}
|
|
3782
|
+
});
|
|
3783
|
+
const body = readFileSync(target);
|
|
3784
|
+
const cacheControl = pathname.startsWith('/assets/') ? 'public, max-age=31536000, immutable' : 'no-cache, must-revalidate';
|
|
3785
|
+
response.writeHead(200, {
|
|
3786
|
+
'content-type': MIME[extname(target)] ?? 'application/octet-stream',
|
|
3787
|
+
'content-length': body.length,
|
|
3788
|
+
'cache-control': cacheControl
|
|
3789
|
+
});
|
|
3790
|
+
response.end(body);
|
|
3791
|
+
}
|
|
3792
|
+
async function startServer(options) {
|
|
3793
|
+
const host = options.host ?? '127.0.0.1';
|
|
3794
|
+
const token = options.token;
|
|
3795
|
+
const server = external_node_http_createServer((request, response)=>{
|
|
3796
|
+
(async ()=>{
|
|
3797
|
+
try {
|
|
3798
|
+
const url = new URL(request.url ?? '/', `http://${host}`);
|
|
3799
|
+
const hostHeader = (request.headers.host ?? '').split(':')[0] ?? '';
|
|
3800
|
+
if ('127.0.0.1' !== hostHeader && 'localhost' !== hostHeader) return void sendJson(response, 403, {
|
|
3801
|
+
error: {
|
|
3802
|
+
code: 403,
|
|
3803
|
+
message: '仅允许本地访问'
|
|
3804
|
+
}
|
|
3805
|
+
});
|
|
3806
|
+
if (!url.pathname.startsWith('/api/')) return void serveStatic(response, options.uiDir, url.pathname);
|
|
3807
|
+
const provided = request.headers['x-ylcwf-token'] ?? url.searchParams.get('token');
|
|
3808
|
+
if (provided !== token) return void sendJson(response, 401, {
|
|
3809
|
+
error: {
|
|
3810
|
+
code: 401,
|
|
3811
|
+
message: '令牌无效,请从启动时打开的地址访问'
|
|
3812
|
+
}
|
|
3813
|
+
});
|
|
3814
|
+
if ('GET' === request.method && '/api/state' === url.pathname) return void sendJson(response, 200, readState(options.configPath));
|
|
3815
|
+
if ('PUT' === request.method && '/api/config' === url.pathname) {
|
|
3816
|
+
const body = await readJsonBody(request);
|
|
3817
|
+
const raw = null !== body && 'object' == typeof body && 'config' in body ? body.config : body;
|
|
3818
|
+
sendJson(response, 200, saveConfig(raw, options.configPath));
|
|
3819
|
+
return;
|
|
3820
|
+
}
|
|
3821
|
+
if ('POST' === request.method && '/api/resolve' === url.pathname) {
|
|
3822
|
+
const body = await readJsonBody(request);
|
|
3823
|
+
const payload = body ?? {};
|
|
3824
|
+
const name = 'string' == typeof payload.name ? payload.name : '';
|
|
3825
|
+
const side = 'frontend' === payload.side || 'backend' === payload.side ? payload.side : void 0;
|
|
3826
|
+
sendJson(response, 200, resolveRequest(name, side, options.configPath));
|
|
3827
|
+
return;
|
|
3828
|
+
}
|
|
3829
|
+
if ('GET' === request.method && '/api/inspect' === url.pathname) {
|
|
3830
|
+
const target = url.searchParams.get('path') ?? '';
|
|
3831
|
+
sendJson(response, 200, inspectPath(target));
|
|
3832
|
+
return;
|
|
3833
|
+
}
|
|
3834
|
+
if ('GET' === request.method && '/api/onboarding' === url.pathname) return void sendJson(response, 200, inspectOnboarding(options.configPath));
|
|
3835
|
+
if ('POST' === request.method && '/api/reset' === url.pathname) {
|
|
3836
|
+
const body = await readJsonBody(request);
|
|
3837
|
+
const all = 'object' == typeof body && null !== body && true === Reflect.get(body, 'all');
|
|
3838
|
+
sendJson(response, 200, resetConfig(all, options.configPath));
|
|
3839
|
+
return;
|
|
3840
|
+
}
|
|
3841
|
+
if ('POST' === request.method && '/api/onboarding/prepare' === url.pathname) return void sendJson(response, 200, prepareManagedDocs(options.configPath));
|
|
3842
|
+
if ('POST' === request.method && '/api/onboarding/complete' === url.pathname) {
|
|
3843
|
+
const body = await readJsonBody(request);
|
|
3844
|
+
const payload = body ?? {};
|
|
3845
|
+
sendJson(response, 200, completeOnboarding(payload.config, options.configPath));
|
|
3846
|
+
return;
|
|
3847
|
+
}
|
|
3848
|
+
if ('POST' === request.method && '/api/git/probe' === url.pathname) {
|
|
3849
|
+
const body = await readJsonBody(request);
|
|
3850
|
+
sendJson(response, 200, probeRemote(pickString(body, 'remote')));
|
|
3851
|
+
return;
|
|
3852
|
+
}
|
|
3853
|
+
if ('POST' === request.method && '/api/docs/sync' === url.pathname) {
|
|
3854
|
+
const body = await readJsonBody(request);
|
|
3855
|
+
sendJson(response, 200, syncManagedRepo(pickString(body, 'dir')));
|
|
3856
|
+
return;
|
|
3857
|
+
}
|
|
3858
|
+
if ('GET' === request.method && '/api/fs/list' === url.pathname) return void sendJson(response, 200, listDirectories(url.searchParams.get('path') ?? void 0));
|
|
3859
|
+
if ('POST' === request.method && '/api/fs/open' === url.pathname) {
|
|
3860
|
+
const body = await readJsonBody(request);
|
|
3861
|
+
sendJson(response, 200, openInFileManager(pickString(body, 'path')));
|
|
3862
|
+
return;
|
|
3863
|
+
}
|
|
3864
|
+
if ('POST' === request.method && '/api/reveal' === url.pathname) return void sendJson(response, 200, openInFileManager(dirname(paths_resolveConfigPath(options.configPath))));
|
|
3865
|
+
if ('GET' === request.method && '/api/task-actions' === url.pathname) {
|
|
3866
|
+
const loaded = loadConfig(options.configPath);
|
|
3867
|
+
const developer = url.searchParams.get('developer') ?? '';
|
|
3868
|
+
if (null === loaded.config || developer !== loaded.config.profile.developer) return void sendJson(response, 200, {
|
|
3869
|
+
actions: {},
|
|
3870
|
+
editable: false
|
|
3871
|
+
});
|
|
3872
|
+
const root = requireDocsRoot(options.configPath);
|
|
3873
|
+
sendJson(response, 200, {
|
|
3874
|
+
editable: 'developer' === loaded.config.profile.mode,
|
|
3875
|
+
actions: availableActions({
|
|
3876
|
+
docsRoot: root,
|
|
3877
|
+
iteration: url.searchParams.get('iteration') ?? '',
|
|
3878
|
+
developer
|
|
3879
|
+
})
|
|
3880
|
+
});
|
|
3881
|
+
return;
|
|
3882
|
+
}
|
|
3883
|
+
if ('POST' === request.method && '/api/task-action' === url.pathname) {
|
|
3884
|
+
const body = await readJsonBody(request);
|
|
3885
|
+
const loaded = loadConfig(options.configPath);
|
|
3886
|
+
if (null === loaded.config) return void sendJson(response, 400, {
|
|
3887
|
+
error: {
|
|
3888
|
+
code: 400,
|
|
3889
|
+
message: '配置未初始化'
|
|
3890
|
+
}
|
|
3891
|
+
});
|
|
3892
|
+
const developer = pickString(body, 'developer');
|
|
3893
|
+
if ('developer' !== loaded.config.profile.mode) return void sendJson(response, 403, {
|
|
3894
|
+
error: {
|
|
3895
|
+
code: 403,
|
|
3896
|
+
message: '干系人模式不支持修改状态'
|
|
3897
|
+
}
|
|
3898
|
+
});
|
|
3899
|
+
if (developer !== loaded.config.profile.developer) return void sendJson(response, 403, {
|
|
3900
|
+
error: {
|
|
3901
|
+
code: 403,
|
|
3902
|
+
message: '只能修改自己的任务文档'
|
|
3903
|
+
}
|
|
3904
|
+
});
|
|
3905
|
+
const action = pickString(body, 'action');
|
|
3906
|
+
if (!(action in ACTION_META)) return void sendJson(response, 400, {
|
|
3907
|
+
error: {
|
|
3908
|
+
code: 400,
|
|
3909
|
+
message: `未知动作:${action}`
|
|
3910
|
+
}
|
|
3911
|
+
});
|
|
3912
|
+
const root = requireDocsRoot(options.configPath);
|
|
3913
|
+
sendJson(response, 200, applyTaskAction({
|
|
3914
|
+
docsRoot: root,
|
|
3915
|
+
iteration: pickString(body, 'iteration'),
|
|
3916
|
+
developer,
|
|
3917
|
+
taskId: pickString(body, 'taskId'),
|
|
3918
|
+
action: action
|
|
3919
|
+
}));
|
|
3920
|
+
return;
|
|
3921
|
+
}
|
|
3922
|
+
if ('POST' === request.method && '/api/task-batch' === url.pathname) {
|
|
3923
|
+
const body = await readJsonBody(request);
|
|
3924
|
+
const loaded = loadConfig(options.configPath);
|
|
3925
|
+
if (null === loaded.config) return void sendJson(response, 400, {
|
|
3926
|
+
error: {
|
|
3927
|
+
code: 400,
|
|
3928
|
+
message: '配置未初始化'
|
|
3929
|
+
}
|
|
3930
|
+
});
|
|
3931
|
+
const developer = pickString(body, 'developer');
|
|
3932
|
+
if ('developer' !== loaded.config.profile.mode) return void sendJson(response, 403, {
|
|
3933
|
+
error: {
|
|
3934
|
+
code: 403,
|
|
3935
|
+
message: '干系人模式不支持修改状态'
|
|
3936
|
+
}
|
|
3937
|
+
});
|
|
3938
|
+
if (developer !== loaded.config.profile.developer) return void sendJson(response, 403, {
|
|
3939
|
+
error: {
|
|
3940
|
+
code: 403,
|
|
3941
|
+
message: '只能修改自己的任务文档'
|
|
3942
|
+
}
|
|
3943
|
+
});
|
|
3944
|
+
const action = pickString(body, 'action');
|
|
3945
|
+
if (!(action in ACTION_META)) return void sendJson(response, 400, {
|
|
3946
|
+
error: {
|
|
3947
|
+
code: 400,
|
|
3948
|
+
message: `未知动作:${action}`
|
|
3949
|
+
}
|
|
3950
|
+
});
|
|
3951
|
+
const payload = body ?? {};
|
|
3952
|
+
const taskIds = Array.isArray(payload.taskIds) ? payload.taskIds.filter((item)=>'string' == typeof item) : [];
|
|
3953
|
+
sendJson(response, 200, applyBatchAction({
|
|
3954
|
+
docsRoot: requireDocsRoot(options.configPath),
|
|
3955
|
+
iteration: pickString(body, 'iteration'),
|
|
3956
|
+
developer,
|
|
3957
|
+
taskIds,
|
|
3958
|
+
action: action
|
|
3959
|
+
}));
|
|
3960
|
+
return;
|
|
3961
|
+
}
|
|
3962
|
+
if ('GET' === request.method && '/api/task-history' === url.pathname) return void sendJson(response, 200, readTaskHistory({
|
|
3963
|
+
iteration: url.searchParams.get('iteration') ?? '',
|
|
3964
|
+
developer: url.searchParams.get('developer') ?? '',
|
|
3965
|
+
taskId: url.searchParams.get('taskId') ?? void 0,
|
|
3966
|
+
limit: 5
|
|
3967
|
+
}));
|
|
3968
|
+
if ('GET' === request.method && '/api/update/check' === url.pathname) return void sendJson(response, 200, await checkUpdate('1' === url.searchParams.get('force')));
|
|
3969
|
+
if ('GET' === request.method && '/api/git/branches' === url.pathname) return void sendJson(response, 200, getBranchInfo(requireDocsRoot(options.configPath)));
|
|
3970
|
+
if ('GET' === request.method && '/api/git/status' === url.pathname) return void sendJson(response, 200, getGitStatus(requireDocsRoot(options.configPath)));
|
|
3971
|
+
if ('POST' === request.method && '/api/git/fetch' === url.pathname) return void sendJson(response, 200, fetchRemote(requireDocsRoot(options.configPath)));
|
|
3972
|
+
if ('GET' === request.method && '/api/iterations' === url.pathname) {
|
|
3973
|
+
const source = parseSource(url.searchParams.get('source'));
|
|
3974
|
+
const loaded = loadConfig(options.configPath);
|
|
3975
|
+
const ref = url.searchParams.get('ref') ?? void 0;
|
|
3976
|
+
sendJson(response, 200, listIterations(loaded.config?.docs.root ?? '', source, ref));
|
|
3977
|
+
return;
|
|
3978
|
+
}
|
|
3979
|
+
if ('POST' === request.method && '/api/iteration-summary' === url.pathname) {
|
|
3980
|
+
const body = await readJsonBody(request);
|
|
3981
|
+
const root = requireDocsRoot(options.configPath);
|
|
3982
|
+
sendJson(response, 200, readIterationSummary(root, pickString(body, 'iteration'), parseSource(pickString(body, 'source')), pickOptionalString(body, 'ref')));
|
|
3983
|
+
return;
|
|
3984
|
+
}
|
|
3985
|
+
if ('POST' === request.method && '/api/iteration-doc' === url.pathname) {
|
|
3986
|
+
const body = await readJsonBody(request);
|
|
3987
|
+
const root = requireDocsRoot(options.configPath);
|
|
3988
|
+
sendJson(response, 200, readIterationDoc(root, pickString(body, 'iteration'), pickString(body, 'developer'), parseSource(pickString(body, 'source')), void 0, pickOptionalString(body, 'ref')));
|
|
3989
|
+
return;
|
|
3990
|
+
}
|
|
3991
|
+
if ('POST' === request.method && '/api/backups/restore' === url.pathname) {
|
|
3992
|
+
const body = await readJsonBody(request);
|
|
3993
|
+
const payload = body ?? {};
|
|
3994
|
+
sendJson(response, 200, restoreBackup(String(payload.name ?? ''), options.configPath));
|
|
3995
|
+
return;
|
|
3996
|
+
}
|
|
3997
|
+
sendJson(response, 404, {
|
|
3998
|
+
error: {
|
|
3999
|
+
code: 404,
|
|
4000
|
+
message: `未知接口:${url.pathname}`
|
|
4001
|
+
}
|
|
4002
|
+
});
|
|
4003
|
+
} catch (error) {
|
|
4004
|
+
sendError(response, error);
|
|
4005
|
+
}
|
|
4006
|
+
})();
|
|
4007
|
+
});
|
|
4008
|
+
await new Promise((resolveListen, rejectListen)=>{
|
|
4009
|
+
server.once('error', rejectListen);
|
|
4010
|
+
server.listen(options.port ?? 4317, host, ()=>resolveListen());
|
|
4011
|
+
});
|
|
4012
|
+
const address = server.address();
|
|
4013
|
+
const port = 'object' == typeof address && null !== address ? address.port : options.port ?? 4317;
|
|
4014
|
+
const url = `http://${host}:${port}/?token=${token}`;
|
|
4015
|
+
return {
|
|
4016
|
+
server,
|
|
4017
|
+
url,
|
|
4018
|
+
port,
|
|
4019
|
+
close: ()=>new Promise((resolveClose, rejectClose)=>{
|
|
4020
|
+
server.close((error)=>error ? rejectClose(error) : resolveClose());
|
|
4021
|
+
})
|
|
4022
|
+
};
|
|
4023
|
+
}
|
|
4024
|
+
function assertUiBuilt(uiDir) {
|
|
4025
|
+
if (!external_node_fs_existsSync(external_node_path_join(uiDir, 'index.html'))) throw new errors_CliError(`前端资源未构建:${uiDir}\n请先运行:pnpm build:ui(开发时用 pnpm dev:ui)`, errors_EXIT.INVALID);
|
|
4026
|
+
}
|
|
4027
|
+
function defaultUiDir() {
|
|
4028
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
4029
|
+
const candidates = [
|
|
4030
|
+
resolve(here, '..', 'ui-dist'),
|
|
4031
|
+
resolve(here, '..', '..', 'ui-dist'),
|
|
4032
|
+
resolve(process.cwd(), 'ui-dist')
|
|
4033
|
+
];
|
|
4034
|
+
return candidates.find((dir)=>external_node_fs_existsSync(external_node_path_join(dir, 'index.html'))) ?? candidates[0] ?? 'ui-dist';
|
|
4035
|
+
}
|
|
4036
|
+
function openBrowser(url) {
|
|
4037
|
+
const command = 'darwin' === process.platform ? 'open' : 'win32' === process.platform ? 'cmd' : 'xdg-open';
|
|
4038
|
+
const args = 'win32' === process.platform ? [
|
|
4039
|
+
'/c',
|
|
4040
|
+
'start',
|
|
4041
|
+
'',
|
|
4042
|
+
url
|
|
4043
|
+
] : [
|
|
4044
|
+
url
|
|
4045
|
+
];
|
|
4046
|
+
try {
|
|
4047
|
+
spawn(command, args, {
|
|
4048
|
+
detached: true,
|
|
4049
|
+
stdio: 'ignore'
|
|
4050
|
+
}).unref();
|
|
4051
|
+
} catch {}
|
|
4052
|
+
}
|
|
4053
|
+
function loadOrCreateToken() {
|
|
4054
|
+
const path = serveTokenPath();
|
|
4055
|
+
try {
|
|
4056
|
+
const existing = readFileSync(path, 'utf8').trim();
|
|
4057
|
+
if (/^[a-f0-9]{32}$/.test(existing)) return existing;
|
|
4058
|
+
} catch {}
|
|
4059
|
+
const token = randomBytes(16).toString('hex');
|
|
4060
|
+
try {
|
|
4061
|
+
mkdirSync(CONFIG_DIR, {
|
|
4062
|
+
recursive: true
|
|
4063
|
+
});
|
|
4064
|
+
writeFileSync(path, `${token}\n`, {
|
|
4065
|
+
mode: 384
|
|
4066
|
+
});
|
|
4067
|
+
chmodSync(path, 384);
|
|
4068
|
+
} catch {}
|
|
4069
|
+
return token;
|
|
4070
|
+
}
|
|
4071
|
+
function isPortFree(port) {
|
|
4072
|
+
return new Promise((resolveFree)=>{
|
|
4073
|
+
const probe = createServer();
|
|
4074
|
+
probe.once('error', ()=>resolveFree(false));
|
|
4075
|
+
probe.once('listening', ()=>probe.close(()=>resolveFree(true)));
|
|
4076
|
+
probe.listen(port, '127.0.0.1');
|
|
4077
|
+
});
|
|
4078
|
+
}
|
|
4079
|
+
async function findAvailablePort(desired, attempts = 20) {
|
|
4080
|
+
for(let offset = 0; offset < attempts; offset += 1){
|
|
4081
|
+
const candidate = desired + offset;
|
|
4082
|
+
if (candidate > 65535) break;
|
|
4083
|
+
if (await isPortFree(candidate)) return candidate;
|
|
4084
|
+
}
|
|
4085
|
+
throw new errors_CliError(`端口 ${desired}–${desired + attempts - 1} 均被占用,请用 --port 指定其他端口`, errors_EXIT.USAGE);
|
|
4086
|
+
}
|
|
4087
|
+
async function runServe(options) {
|
|
4088
|
+
const uiDir = void 0 !== options.uiDir ? resolve(options.uiDir) : defaultUiDir();
|
|
4089
|
+
assertUiBuilt(uiDir);
|
|
4090
|
+
const port = void 0 === options.port ? 4317 : Number.parseInt(options.port, 10);
|
|
4091
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new errors_CliError(`--port 不是合法端口:${options.port ?? ''}`, errors_EXIT.USAGE);
|
|
4092
|
+
const token = loadOrCreateToken();
|
|
4093
|
+
const actualPort = await findAvailablePort(port);
|
|
4094
|
+
const running = await startServer({
|
|
4095
|
+
configPath: options.config,
|
|
4096
|
+
uiDir,
|
|
4097
|
+
token,
|
|
4098
|
+
port: actualPort
|
|
4099
|
+
});
|
|
4100
|
+
if (actualPort !== port) printLine(`端口 ${port} 已被占用,已自动改用 ${actualPort}`);
|
|
4101
|
+
printLine(`ylcwf 工作台已启动:${running.url}`);
|
|
4102
|
+
printLine(`配置文件:${paths_resolveConfigPath(options.config)}`);
|
|
4103
|
+
printLine('按 Ctrl+C 停止服务');
|
|
4104
|
+
if (false !== options.open) openBrowser(running.url);
|
|
4105
|
+
await new Promise((resolveStop)=>{
|
|
4106
|
+
const stop = ()=>{
|
|
4107
|
+
running.close().finally(()=>resolveStop());
|
|
4108
|
+
};
|
|
4109
|
+
process.once('SIGINT', stop);
|
|
4110
|
+
process.once('SIGTERM', stop);
|
|
4111
|
+
});
|
|
4112
|
+
}
|
|
4113
|
+
function registerServe(program) {
|
|
4114
|
+
program.command('serve').description('启动本地可视化配置控制台(仅监听 127.0.0.1)').option('-c, --config <path>', '指定配置文件路径').option('--port <port>', '监听端口,默认 4317').option('--ui-dir <dir>', '前端静态资源目录(默认随包发布)').option('--no-open', '不自动打开浏览器').action(async (options)=>{
|
|
4115
|
+
await runServe(options);
|
|
4116
|
+
});
|
|
4117
|
+
}
|
|
4118
|
+
async function runReset(options) {
|
|
4119
|
+
const configPath = paths_resolveConfigPath(options.config);
|
|
4120
|
+
const targets = collectResetTargets(configPath, true === options.all);
|
|
4121
|
+
if (0 === targets.length) return void printLine('没有需要清除的配置,当前已经是干净状态。');
|
|
4122
|
+
printLine('将要清除:');
|
|
4123
|
+
for (const target of targets)printLine(` - ${describeTarget(target)}`);
|
|
4124
|
+
if (true === options.dryRun) return void printLine('\n(--dry-run:未执行任何删除)');
|
|
4125
|
+
if (true !== options.yes) {
|
|
4126
|
+
if (true !== process.stdin.isTTY) throw new errors_CliError('非交互环境需要显式加 --yes 才会执行删除', errors_EXIT.USAGE);
|
|
4127
|
+
const confirmed = await __rspack_external__clack_prompts_d2d5c36d.confirm({
|
|
4128
|
+
message: '确认清除以上内容?此操作不可撤销',
|
|
4129
|
+
initialValue: false
|
|
4130
|
+
});
|
|
4131
|
+
if (__rspack_external__clack_prompts_d2d5c36d.isCancel(confirmed) || true !== confirmed) return void __rspack_external__clack_prompts_d2d5c36d.cancel('已取消');
|
|
4132
|
+
}
|
|
4133
|
+
const removed = performReset(configPath, targets);
|
|
4134
|
+
printLine(`\n已清除 ${removed} 项。下次打开工作台会重新进入首次引导。`);
|
|
4135
|
+
}
|
|
4136
|
+
function registerReset(program) {
|
|
4137
|
+
program.command('reset').description('清除本机配置(配置、备份、可选托管副本),用于从零重新引导').option('-c, --config <path>', '指定配置文件路径').option('--all', '同时清除 ~/.ylcwf/repos 下的托管文档仓库副本').option('--yes', '跳过确认').option('--dry-run', '只列出将要删除的内容').action(async (options)=>{
|
|
4138
|
+
await runReset(options);
|
|
4139
|
+
});
|
|
4140
|
+
}
|
|
4141
|
+
function buildProgram() {
|
|
4142
|
+
const program = new Command();
|
|
4143
|
+
program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与终端仓库映射').version("0.2.0", '-v, --version', '显示版本号').showHelpAfterError();
|
|
4144
|
+
registerInit(program);
|
|
4145
|
+
registerShow(program);
|
|
4146
|
+
registerGet(program);
|
|
4147
|
+
registerSet(program);
|
|
4148
|
+
registerTerminal(program);
|
|
4149
|
+
registerTask(program);
|
|
4150
|
+
registerResolve(program);
|
|
4151
|
+
registerDoctor(program);
|
|
4152
|
+
registerPath(program);
|
|
4153
|
+
registerServe(program);
|
|
4154
|
+
registerReset(program);
|
|
4155
|
+
return program;
|
|
4156
|
+
}
|
|
4157
|
+
function runBare(configPath) {
|
|
4158
|
+
showConfig(configPath, process.stdout.isTTY ? 'human' : 'json');
|
|
4159
|
+
}
|
|
4160
|
+
function splitGlobalArgs(argv) {
|
|
4161
|
+
const rest = [];
|
|
4162
|
+
let config;
|
|
4163
|
+
for(let index = 0; index < argv.length; index += 1){
|
|
4164
|
+
const arg = argv[index] ?? '';
|
|
4165
|
+
if ('-c' === arg || '--config' === arg) {
|
|
4166
|
+
const value = argv[index + 1];
|
|
4167
|
+
if (void 0 !== value) config = value;
|
|
4168
|
+
index += 1;
|
|
4169
|
+
continue;
|
|
4170
|
+
}
|
|
4171
|
+
if (arg.startsWith('--config=')) {
|
|
4172
|
+
config = arg.slice(9);
|
|
4173
|
+
continue;
|
|
4174
|
+
}
|
|
4175
|
+
rest.push(arg);
|
|
4176
|
+
}
|
|
4177
|
+
return void 0 === config ? {
|
|
4178
|
+
rest
|
|
4179
|
+
} : {
|
|
4180
|
+
config,
|
|
4181
|
+
rest
|
|
4182
|
+
};
|
|
4183
|
+
}
|
|
4184
|
+
async function main() {
|
|
4185
|
+
const { config, rest } = splitGlobalArgs(process.argv.slice(2));
|
|
4186
|
+
const wantsMeta = rest.some((arg)=>[
|
|
4187
|
+
'-h',
|
|
4188
|
+
'--help',
|
|
4189
|
+
'-v',
|
|
4190
|
+
'--version'
|
|
4191
|
+
].includes(arg));
|
|
4192
|
+
const hasSubcommand = rest.some((arg)=>!arg.startsWith('-'));
|
|
4193
|
+
if (!hasSubcommand && !wantsMeta) {
|
|
4194
|
+
const unknown = rest.find((arg)=>arg.startsWith('-'));
|
|
4195
|
+
if (void 0 !== unknown) {
|
|
4196
|
+
printError(`error: unknown option '${unknown}'`);
|
|
4197
|
+
process.exit(1);
|
|
4198
|
+
}
|
|
4199
|
+
runBare(config);
|
|
4200
|
+
return;
|
|
4201
|
+
}
|
|
4202
|
+
await buildProgram().parseAsync(process.argv);
|
|
4203
|
+
}
|
|
4204
|
+
main().catch((error)=>{
|
|
4205
|
+
if (error instanceof errors_CliError) {
|
|
4206
|
+
printError(error.message);
|
|
4207
|
+
process.exit(error.exitCode);
|
|
4208
|
+
}
|
|
4209
|
+
printError(error instanceof Error ? error.stack ?? error.message : String(error));
|
|
4210
|
+
process.exit(errors_EXIT.INVALID);
|
|
4211
|
+
});
|