@workskills/getskill 1.2.0 → 2.1.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.
@@ -5,19 +5,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.fetchSkillToCache = fetchSkillToCache;
7
7
  exports.cloneOrUpdateRepo = cloneOrUpdateRepo;
8
- exports.restartOpenClawGateway = restartOpenClawGateway;
8
+ exports.restartAgentGateway = restartAgentGateway;
9
9
  exports.downloadSkill = downloadSkill;
10
10
  exports.updateSkill = updateSkill;
11
11
  exports.updateAllSkills = updateAllSkills;
12
12
  exports.uninstallSkill = uninstallSkill;
13
- exports.publishSkill = publishSkill;
14
13
  const fs_1 = __importDefault(require("fs"));
15
14
  const path_1 = __importDefault(require("path"));
16
15
  const config_1 = require("./config");
17
16
  const logger_1 = __importDefault(require("./logger"));
18
17
  const network_1 = require("./network");
19
18
  const state_1 = require("./state");
20
- const skill_validator_1 = require("./skill-validator");
21
19
  const system_1 = require("./system");
22
20
  const unzip_1 = require("./unzip");
23
21
  function assertVersionAvailable(entry, requestedVersion) {
@@ -59,16 +57,23 @@ async function cloneOrUpdateRepo(skillName, options = {}) {
59
57
  const { repoPath } = await fetchSkillToCache(skillName, options);
60
58
  return repoPath;
61
59
  }
62
- async function restartOpenClawGateway() {
63
- const restartCommand = 'openclaw gateway restart';
60
+ /**
61
+ * 安装/更新后的可选 Agent 重载钩子。
62
+ * 仅当 Agent 预设定义了重启命令,或设置了 `GETSKILL_RESTART_CMD` 时才执行。
63
+ */
64
+ async function restartAgentGateway() {
65
+ const restartCommand = (0, config_1.getAgentRestartCommand)();
66
+ if (!restartCommand) {
67
+ return;
68
+ }
64
69
  logger_1.default.info(`尝试执行: ${restartCommand}`);
65
70
  try {
66
71
  await (0, system_1.executeCommand)(restartCommand);
67
- logger_1.default.info('OpenClaw Gateway 重启成功,新技能应已生效。');
72
+ logger_1.default.info('Agent 服务重启成功,新技能应已生效。');
68
73
  }
69
74
  catch (error) {
70
75
  const message = error instanceof Error ? error.message : String(error);
71
- logger_1.default.warn('自动重启 OpenClaw Gateway 失败,请手动执行: openclaw gateway restart');
76
+ logger_1.default.warn(`自动执行 "${restartCommand}" 失败,请手动重启 Agent 以加载新技能。`);
72
77
  logger_1.default.warn(`失败原因: ${message}`);
73
78
  }
74
79
  }
@@ -134,17 +139,58 @@ async function updateSkill(skillName, options = {}) {
134
139
  version: entry.version
135
140
  };
136
141
  }
137
- async function updateAllSkills() {
142
+ async function updateAllSkills(options = {}) {
138
143
  const installedSkills = (0, state_1.listInstalledSkillNames)();
139
144
  const results = [];
145
+ if (installedSkills.length === 0) {
146
+ return results;
147
+ }
148
+ // 一次性拉取索引,用于识别已下架/改名的历史安装记录
149
+ let indexKeys = null;
150
+ try {
151
+ const entries = await (0, network_1.fetchSkillsIndex)();
152
+ indexKeys = new Set();
153
+ entries.forEach((entry) => {
154
+ indexKeys?.add((0, network_1.normalizeSkillIndexKey)(entry.id));
155
+ if (entry.name) {
156
+ indexKeys?.add((0, network_1.normalizeSkillIndexKey)(entry.name));
157
+ }
158
+ });
159
+ }
160
+ catch (error) {
161
+ const message = error instanceof Error ? error.message : String(error);
162
+ logger_1.default.warn(`技能索引获取失败,将逐个尝试更新: ${message}`);
163
+ }
164
+ const staleSkillNames = [];
140
165
  for (const skillName of installedSkills) {
166
+ const missingInIndex = Boolean(indexKeys && !indexKeys.has((0, network_1.normalizeSkillIndexKey)(skillName)));
167
+ if (missingInIndex) {
168
+ staleSkillNames.push(skillName);
169
+ results.push({
170
+ skillName,
171
+ ok: false,
172
+ skipped: true,
173
+ error: '技能索引中已不存在该技能(历史安装记录失效)'
174
+ });
175
+ continue;
176
+ }
141
177
  try {
142
178
  const result = await updateSkill(skillName);
143
179
  results.push({ skillName, ok: true, result });
144
180
  }
145
181
  catch (error) {
146
182
  const message = error instanceof Error ? error.message : String(error);
147
- results.push({ skillName, ok: false, error: message });
183
+ const skipped = message.includes('技能不存在');
184
+ if (skipped) {
185
+ staleSkillNames.push(skillName);
186
+ }
187
+ results.push({ skillName, ok: false, skipped, error: message });
188
+ }
189
+ }
190
+ if (options.prune && staleSkillNames.length > 0) {
191
+ const pruned = (0, state_1.pruneInstallState)(staleSkillNames);
192
+ if (pruned.length > 0) {
193
+ logger_1.default.info(`已清理失效安装记录: ${pruned.join(', ')}`);
148
194
  }
149
195
  }
150
196
  return results;
@@ -157,112 +203,3 @@ async function uninstallSkill(skillName, options = {}) {
157
203
  }
158
204
  return result;
159
205
  }
160
- function quoteShellArg(value) {
161
- return value.replace(/"/g, '\\"');
162
- }
163
- async function ensureLocalGitIdentity(repoPath, username, email) {
164
- if (username) {
165
- try {
166
- const { stdout } = await (0, system_1.executeCommand)('git config user.name', repoPath);
167
- if (!stdout.trim()) {
168
- throw new Error('missing user.name');
169
- }
170
- }
171
- catch {
172
- await (0, system_1.executeCommand)(`git config user.name "${quoteShellArg(username)}"`, repoPath);
173
- }
174
- }
175
- if (email) {
176
- try {
177
- const { stdout } = await (0, system_1.executeCommand)('git config user.email', repoPath);
178
- if (!stdout.trim()) {
179
- throw new Error('missing user.email');
180
- }
181
- }
182
- catch {
183
- await (0, system_1.executeCommand)(`git config user.email "${quoteShellArg(email)}"`, repoPath);
184
- }
185
- }
186
- }
187
- function resolvePublishRepoName(skillPath, options, skillNameFromManifest) {
188
- const candidate = options.repoName?.trim() ||
189
- skillNameFromManifest ||
190
- path_1.default.basename(skillPath);
191
- const repoName = (0, skill_validator_1.sanitizeRepositoryName)(candidate);
192
- if (!repoName) {
193
- throw new Error('无法确定仓库名称,请通过 --name 指定有效仓库名');
194
- }
195
- return repoName;
196
- }
197
- async function publishSkill(skillPath, options = {}) {
198
- await (0, system_1.ensureGitInstalled)();
199
- const resolvedSkillPath = path_1.default.resolve(skillPath);
200
- if (!fs_1.default.existsSync(resolvedSkillPath)) {
201
- throw new Error(`技能目录不存在: ${resolvedSkillPath}`);
202
- }
203
- const validation = (0, skill_validator_1.validateSkillDirectory)(resolvedSkillPath);
204
- if (!validation.valid) {
205
- throw new Error(`SKILL.md 校验失败:\n- ${validation.errors.join('\n- ')}`);
206
- }
207
- logger_1.default.info('SKILL.md 校验通过,允许继续发布。');
208
- const repoName = resolvePublishRepoName(resolvedSkillPath, options, validation.metadata.name);
209
- const gitDirPath = path_1.default.join(resolvedSkillPath, '.git');
210
- if (!fs_1.default.existsSync(gitDirPath)) {
211
- logger_1.default.info('未检测到 Git 仓库,正在初始化...');
212
- await (0, system_1.executeCommand)('git init', resolvedSkillPath);
213
- }
214
- const branch = options.branch?.trim() || 'main';
215
- const commitMessage = options.message?.trim() || 'chore: publish skill via getskill';
216
- let currentRemoteUrl = '';
217
- if (options.repoUrl?.trim()) {
218
- currentRemoteUrl = options.repoUrl.trim();
219
- }
220
- else {
221
- try {
222
- const { stdout } = await (0, system_1.executeCommand)('git remote get-url origin', resolvedSkillPath);
223
- currentRemoteUrl = stdout.trim();
224
- }
225
- catch {
226
- currentRemoteUrl = '';
227
- }
228
- }
229
- if (!currentRemoteUrl) {
230
- throw new Error('getskill.work 已迁移为 Cloudflare 静态托管,官方技能库不再支持通过 CLI 注册/推送。\n' +
231
- '请使用 --repo <git-url> 发布到你自己的 Git 仓库(如 GitHub),\n' +
232
- '或将技能提交到 https://github.com/work-skills 组织下的技能仓库以收录进官方站点。');
233
- }
234
- try {
235
- await (0, system_1.executeCommand)(`git remote set-url origin "${quoteShellArg(currentRemoteUrl)}"`, resolvedSkillPath);
236
- }
237
- catch {
238
- await (0, system_1.executeCommand)(`git remote add origin "${quoteShellArg(currentRemoteUrl)}"`, resolvedSkillPath);
239
- }
240
- await (0, system_1.executeCommand)(`git checkout -B "${quoteShellArg(branch)}"`, resolvedSkillPath);
241
- await ensureLocalGitIdentity(resolvedSkillPath, options.username, options.email || null);
242
- await (0, system_1.executeCommand)('git add .', resolvedSkillPath);
243
- let committed = false;
244
- try {
245
- await (0, system_1.executeCommand)(`git commit -m "${quoteShellArg(commitMessage)}"`, resolvedSkillPath);
246
- committed = true;
247
- }
248
- catch (error) {
249
- const message = error instanceof Error ? error.message : String(error);
250
- const normalizedMessage = message.toLowerCase();
251
- if (normalizedMessage.includes('nothing to commit') ||
252
- normalizedMessage.includes('nothing added to commit')) {
253
- committed = false;
254
- }
255
- else {
256
- throw error;
257
- }
258
- }
259
- await (0, system_1.executeCommand)(`git push -u origin "${quoteShellArg(branch)}"`, resolvedSkillPath);
260
- logger_1.default.info(`已发布技能目录: ${resolvedSkillPath}`);
261
- return {
262
- skillPath: resolvedSkillPath,
263
- remoteUrl: currentRemoteUrl,
264
- branch,
265
- committed,
266
- repositoryName: repoName
267
- };
268
- }
@@ -3,6 +3,11 @@ export declare function normalizeSkillName(skillName: string): string;
3
3
  export declare function getRemoteSkillPath(skillName: string): string;
4
4
  export declare function normalizeCliSkillArgument(rawSkillName: string): string;
5
5
  export declare function collectSkillMarkdownFiles(dirPath: string, baseDir?: string, result?: string[]): string[];
6
+ /**
7
+ * 兼容 1.x/2.0 版本:状态文件曾存放在 `<agent 根目录>/getskill/state.json`。
8
+ * 首次读取时自动迁移到 `~/.getskill/state.json`。
9
+ */
10
+ export declare function migrateLegacyInstallState(): string | null;
6
11
  export declare function readInstallState(): InstallState;
7
12
  export declare function writeInstallState(state: InstallState): void;
8
13
  export declare function updateInstallState(skillName: string, repoPath: string, installDir: string, action: 'install' | 'update', requestedVersion?: string, version?: string): Promise<void>;
@@ -12,6 +17,12 @@ export declare function replaceDirectoryAtomically(sourceDir: string, targetDir:
12
17
  export declare function copySkillFiles(repoPath: string, skillName: string): string[];
13
18
  export declare function listLocalSkills(): string[];
14
19
  export declare function listInstalledSkillNames(): string[];
20
+ /**
21
+ * 清理状态文件中的失效记录。
22
+ * 不传参数时清理不属于当前技能目录(Agent)的记录,
23
+ * 传入技能名时只清理指定记录。返回被清理的技能名列表。
24
+ */
25
+ export declare function pruneInstallState(skillNames?: string[]): string[];
15
26
  export declare function getInstalledSkillInfo(skillName: string): InstalledSkillInfo;
16
27
  export declare function removeInstalledSkill(skillName: string, options?: {
17
28
  removeCache?: boolean;
package/dist/lib/state.js CHANGED
@@ -7,6 +7,7 @@ exports.normalizeSkillName = normalizeSkillName;
7
7
  exports.getRemoteSkillPath = getRemoteSkillPath;
8
8
  exports.normalizeCliSkillArgument = normalizeCliSkillArgument;
9
9
  exports.collectSkillMarkdownFiles = collectSkillMarkdownFiles;
10
+ exports.migrateLegacyInstallState = migrateLegacyInstallState;
10
11
  exports.readInstallState = readInstallState;
11
12
  exports.writeInstallState = writeInstallState;
12
13
  exports.updateInstallState = updateInstallState;
@@ -16,6 +17,7 @@ exports.replaceDirectoryAtomically = replaceDirectoryAtomically;
16
17
  exports.copySkillFiles = copySkillFiles;
17
18
  exports.listLocalSkills = listLocalSkills;
18
19
  exports.listInstalledSkillNames = listInstalledSkillNames;
20
+ exports.pruneInstallState = pruneInstallState;
19
21
  exports.getInstalledSkillInfo = getInstalledSkillInfo;
20
22
  exports.removeInstalledSkill = removeInstalledSkill;
21
23
  const fs_1 = __importDefault(require("fs"));
@@ -23,6 +25,7 @@ const path_1 = __importDefault(require("path"));
23
25
  const config_1 = require("./config");
24
26
  const logger_1 = __importDefault(require("./logger"));
25
27
  const system_1 = require("./system");
28
+ const unzip_1 = require("./unzip");
26
29
  function normalizeSkillName(skillName) {
27
30
  return skillName.replace(/^skills\//, '').replace(/[\\/]/g, '_');
28
31
  }
@@ -65,13 +68,8 @@ function collectSkillMarkdownFiles(dirPath, baseDir = dirPath, result = []) {
65
68
  });
66
69
  return result;
67
70
  }
68
- function readInstallState() {
69
- const stateFilePath = (0, config_1.getStateFilePath)();
70
- if (!fs_1.default.existsSync(stateFilePath)) {
71
- return { skills: {} };
72
- }
71
+ function parseInstallState(content) {
73
72
  try {
74
- const content = fs_1.default.readFileSync(stateFilePath, 'utf8');
75
73
  const parsed = JSON.parse(content);
76
74
  if (!parsed || typeof parsed !== 'object') {
77
75
  return { skills: {} };
@@ -86,6 +84,47 @@ function readInstallState() {
86
84
  return { skills: {} };
87
85
  }
88
86
  }
87
+ /**
88
+ * 兼容 1.x/2.0 版本:状态文件曾存放在 `<agent 根目录>/getskill/state.json`。
89
+ * 首次读取时自动迁移到 `~/.getskill/state.json`。
90
+ */
91
+ function migrateLegacyInstallState() {
92
+ const stateFilePath = (0, config_1.getStateFilePath)();
93
+ if (fs_1.default.existsSync(stateFilePath)) {
94
+ return null;
95
+ }
96
+ for (const legacyPath of (0, config_1.getLegacyStateFilePaths)()) {
97
+ if (!fs_1.default.existsSync(legacyPath)) {
98
+ continue;
99
+ }
100
+ try {
101
+ const content = fs_1.default.readFileSync(legacyPath, 'utf8');
102
+ (0, system_1.ensureDirectoryExists)(path_1.default.dirname(stateFilePath));
103
+ fs_1.default.writeFileSync(stateFilePath, content, 'utf8');
104
+ logger_1.default.info(`已迁移历史安装记录: ${legacyPath} -> ${stateFilePath}`);
105
+ return legacyPath;
106
+ }
107
+ catch (error) {
108
+ logger_1.default.debug(`迁移历史安装记录失败 (${legacyPath}): ${error instanceof Error ? error.message : String(error)}`);
109
+ }
110
+ }
111
+ return null;
112
+ }
113
+ function readInstallState() {
114
+ const stateFilePath = (0, config_1.getStateFilePath)();
115
+ if (!fs_1.default.existsSync(stateFilePath)) {
116
+ migrateLegacyInstallState();
117
+ }
118
+ if (!fs_1.default.existsSync(stateFilePath)) {
119
+ return { skills: {} };
120
+ }
121
+ try {
122
+ return parseInstallState(fs_1.default.readFileSync(stateFilePath, 'utf8'));
123
+ }
124
+ catch {
125
+ return { skills: {} };
126
+ }
127
+ }
89
128
  function writeInstallState(state) {
90
129
  const stateFilePath = (0, config_1.getStateFilePath)();
91
130
  (0, system_1.ensureDirectoryExists)(path_1.default.dirname(stateFilePath));
@@ -108,7 +147,9 @@ async function updateInstallState(skillName, repoPath, installDir, action, reque
108
147
  updatedAt: now,
109
148
  gitCommitHash: previous?.gitCommitHash || null,
110
149
  requestedVersion: requestedVersion ?? previous?.requestedVersion ?? null,
111
- version: version ?? previous?.version ?? null
150
+ version: version ?? previous?.version ?? null,
151
+ agent: (0, config_1.getAgentName)(),
152
+ skillsDir: (0, config_1.getSkillsDirectory)()
112
153
  };
113
154
  writeInstallState(state);
114
155
  }
@@ -201,9 +242,27 @@ function listLocalSkills() {
201
242
  .filter((entry) => entry.isDirectory())
202
243
  .map((entry) => entry.name);
203
244
  }
245
+ function recordSkillsDir(record) {
246
+ if (record.skillsDir) {
247
+ return record.skillsDir;
248
+ }
249
+ // 2.0 及更早版本的记录未保存技能目录,用安装目录的父目录推断
250
+ if (record.installDir) {
251
+ return path_1.default.dirname(record.installDir);
252
+ }
253
+ return null;
254
+ }
255
+ function recordMatchesCurrentSkillsDir(record) {
256
+ const recordDir = recordSkillsDir(record);
257
+ if (!recordDir) {
258
+ return true;
259
+ }
260
+ return (0, config_1.isSamePath)(recordDir, (0, config_1.getSkillsDirectory)());
261
+ }
204
262
  function listInstalledSkillNames() {
205
263
  const state = readInstallState();
206
264
  const stateNames = Object.values(state.skills)
265
+ .filter(recordMatchesCurrentSkillsDir)
207
266
  .map((item) => item.inputSkillName || item.localSkillName)
208
267
  .filter(Boolean);
209
268
  if (stateNames.length > 0) {
@@ -211,13 +270,52 @@ function listInstalledSkillNames() {
211
270
  }
212
271
  return listLocalSkills();
213
272
  }
273
+ /**
274
+ * 清理状态文件中的失效记录。
275
+ * 不传参数时清理不属于当前技能目录(Agent)的记录,
276
+ * 传入技能名时只清理指定记录。返回被清理的技能名列表。
277
+ */
278
+ function pruneInstallState(skillNames = []) {
279
+ const state = readInstallState();
280
+ const targets = new Set(skillNames.map((name) => normalizeSkillName(name)).filter(Boolean));
281
+ const removed = [];
282
+ Object.keys(state.skills).forEach((localSkillName) => {
283
+ const record = state.skills[localSkillName];
284
+ const shouldRemove = targets.size > 0
285
+ ? targets.has(localSkillName)
286
+ : !recordMatchesCurrentSkillsDir(record);
287
+ if (shouldRemove) {
288
+ delete state.skills[localSkillName];
289
+ removed.push(record.inputSkillName || localSkillName);
290
+ }
291
+ });
292
+ if (removed.length > 0) {
293
+ writeInstallState(state);
294
+ }
295
+ return removed;
296
+ }
297
+ /**
298
+ * 解析技能的实际解压目录:
299
+ * 优先使用安装记录中的 repoPath,其次解析缓存目录中的单层包装目录。
300
+ */
301
+ function resolveCachePaths(localSkillName, record) {
302
+ const cacheDir = path_1.default.join((0, config_1.getSkillsCacheDirectory)(), localSkillName);
303
+ if (record?.repoPath && fs_1.default.existsSync(record.repoPath)) {
304
+ return { cacheDir, repoPath: record.repoPath };
305
+ }
306
+ if (fs_1.default.existsSync(cacheDir)) {
307
+ return { cacheDir, repoPath: (0, unzip_1.resolveSkillRoot)(cacheDir) };
308
+ }
309
+ return { cacheDir, repoPath: cacheDir };
310
+ }
214
311
  function getInstalledSkillInfo(skillName) {
215
312
  const normalizedSkillName = normalizeCliSkillArgument(skillName);
216
313
  const localSkillName = normalizeSkillName(normalizedSkillName);
217
314
  const state = readInstallState();
218
315
  const record = state.skills[localSkillName] || null;
219
- const skillDir = path_1.default.join((0, config_1.getSkillsDirectory)(), localSkillName);
220
- const repoPath = path_1.default.join((0, config_1.getSkillsCacheDirectory)(), localSkillName);
316
+ const skillsDir = (0, config_1.getSkillsDirectory)();
317
+ const skillDir = path_1.default.join(skillsDir, localSkillName);
318
+ const { cacheDir, repoPath } = resolveCachePaths(localSkillName, record);
221
319
  return {
222
320
  skillName: normalizedSkillName,
223
321
  localSkillName,
@@ -225,6 +323,10 @@ function getInstalledSkillInfo(skillName) {
225
323
  cached: fs_1.default.existsSync(repoPath),
226
324
  skillDir,
227
325
  repoPath,
326
+ cacheDir,
327
+ skillsDir,
328
+ agent: (0, config_1.getAgentName)(),
329
+ agentLabel: (0, config_1.getAgentLabel)(),
228
330
  state: record
229
331
  };
230
332
  }
@@ -232,17 +334,27 @@ function removeInstalledSkill(skillName, options = {}) {
232
334
  const normalizedSkillName = normalizeCliSkillArgument(skillName);
233
335
  const localSkillName = normalizeSkillName(normalizedSkillName);
234
336
  const removeCache = options.removeCache !== false;
337
+ const state = readInstallState();
338
+ const record = state.skills[localSkillName] || null;
235
339
  const skillDir = path_1.default.join((0, config_1.getSkillsDirectory)(), localSkillName);
236
- const repoPath = path_1.default.join((0, config_1.getSkillsCacheDirectory)(), localSkillName);
340
+ const { cacheDir, repoPath } = resolveCachePaths(localSkillName, record);
237
341
  let removedInstall = false;
238
342
  let removedCache = false;
239
343
  if (fs_1.default.existsSync(skillDir)) {
240
344
  fs_1.default.rmSync(skillDir, { recursive: true, force: true });
241
345
  removedInstall = true;
242
346
  }
243
- if (removeCache && fs_1.default.existsSync(repoPath)) {
244
- fs_1.default.rmSync(repoPath, { recursive: true, force: true });
245
- removedCache = true;
347
+ if (removeCache) {
348
+ if (fs_1.default.existsSync(cacheDir)) {
349
+ fs_1.default.rmSync(cacheDir, { recursive: true, force: true });
350
+ removedCache = true;
351
+ }
352
+ if (!(0, config_1.isSamePath)(repoPath, cacheDir) &&
353
+ !repoPath.startsWith(`${cacheDir}${path_1.default.sep}`) &&
354
+ fs_1.default.existsSync(repoPath)) {
355
+ fs_1.default.rmSync(repoPath, { recursive: true, force: true });
356
+ removedCache = true;
357
+ }
246
358
  }
247
359
  removeInstallState(normalizedSkillName);
248
360
  return {
@@ -251,6 +363,6 @@ function removeInstalledSkill(skillName, options = {}) {
251
363
  removedInstall,
252
364
  removedCache,
253
365
  skillDir,
254
- repoPath
366
+ repoPath: cacheDir
255
367
  };
256
368
  }
@@ -3,15 +3,9 @@ export declare function ensureDirectoryExists(dirPath: string): void;
3
3
  export declare function executeCommand(command: string, cwd?: string, options?: {
4
4
  env?: NodeJS.ProcessEnv;
5
5
  }): Promise<CommandOutput>;
6
- export declare function checkGitInstalled(): Promise<boolean>;
7
- export declare function getGitDownloadUrl(): string | null;
8
- export declare function downloadFile(url: string, destPath: string): Promise<string>;
9
- export declare function installGit(): Promise<void>;
10
- export declare function ensureGitInstalled(): Promise<true>;
11
6
  export declare function isInteractiveTerminal(): boolean;
12
7
  export declare function promptForInput(question: string, options?: {
13
8
  defaultValue?: string;
14
9
  required?: boolean;
15
10
  secret?: boolean;
16
11
  }): Promise<string>;
17
- export declare function getGitCommitHash(repoPath: string): Promise<string | null>;
@@ -5,21 +5,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ensureDirectoryExists = ensureDirectoryExists;
7
7
  exports.executeCommand = executeCommand;
8
- exports.checkGitInstalled = checkGitInstalled;
9
- exports.getGitDownloadUrl = getGitDownloadUrl;
10
- exports.downloadFile = downloadFile;
11
- exports.installGit = installGit;
12
- exports.ensureGitInstalled = ensureGitInstalled;
13
8
  exports.isInteractiveTerminal = isInteractiveTerminal;
14
9
  exports.promptForInput = promptForInput;
15
- exports.getGitCommitHash = getGitCommitHash;
16
10
  const fs_1 = __importDefault(require("fs"));
17
- const os_1 = __importDefault(require("os"));
18
- const path_1 = __importDefault(require("path"));
19
11
  const readline_1 = __importDefault(require("readline"));
20
12
  const child_process_1 = require("child_process");
21
- const http_1 = __importDefault(require("http"));
22
- const https_1 = __importDefault(require("https"));
23
13
  function ensureDirectoryExists(dirPath) {
24
14
  if (!fs_1.default.existsSync(dirPath)) {
25
15
  fs_1.default.mkdirSync(dirPath, { recursive: true });
@@ -106,146 +96,6 @@ function executeCommand(command, cwd, options = {}) {
106
96
  });
107
97
  });
108
98
  }
109
- async function checkGitInstalled() {
110
- try {
111
- await executeCommand('git --version');
112
- return true;
113
- }
114
- catch {
115
- return false;
116
- }
117
- }
118
- function getGitDownloadUrl() {
119
- const platform = os_1.default.platform();
120
- const arch = os_1.default.arch();
121
- switch (platform) {
122
- case 'win32':
123
- return arch === 'x64'
124
- ? 'https://github.com/git-for-windows/git/releases/download/v2.44.0.windows.1/Git-2.44.0-64-bit.exe'
125
- : 'https://github.com/git-for-windows/git/releases/download/v2.44.0.windows.1/Git-2.44.0-32-bit.exe';
126
- case 'darwin':
127
- return 'homebrew';
128
- case 'linux':
129
- return 'package-manager';
130
- default:
131
- return null;
132
- }
133
- }
134
- function cleanupFile(filePath) {
135
- if (fs_1.default.existsSync(filePath)) {
136
- fs_1.default.unlinkSync(filePath);
137
- }
138
- }
139
- function downloadFile(url, destPath) {
140
- return new Promise((resolve, reject) => {
141
- const urlObj = new URL(url);
142
- const protocol = urlObj.protocol === 'https:' ? https_1.default : http_1.default;
143
- const file = fs_1.default.createWriteStream(destPath);
144
- protocol
145
- .get(url, (response) => {
146
- if (response.statusCode === 301 ||
147
- response.statusCode === 302) {
148
- const locationHeader = response.headers.location;
149
- const redirectLocation = Array.isArray(locationHeader)
150
- ? locationHeader[0]
151
- : locationHeader;
152
- file.close();
153
- cleanupFile(destPath);
154
- if (!redirectLocation) {
155
- reject(new Error('下载重定向缺少 location 头'));
156
- return;
157
- }
158
- downloadFile(redirectLocation, destPath)
159
- .then(resolve)
160
- .catch(reject);
161
- return;
162
- }
163
- if (response.statusCode !== 200) {
164
- file.close();
165
- cleanupFile(destPath);
166
- reject(new Error(`下载失败,状态码: ${response.statusCode}`));
167
- return;
168
- }
169
- const totalSize = Number.parseInt(response.headers['content-length'] || '0', 10);
170
- let downloadedSize = 0;
171
- response.on('data', (chunk) => {
172
- downloadedSize += chunk.length;
173
- if (totalSize > 0) {
174
- const percent = ((downloadedSize / totalSize) *
175
- 100).toFixed(2);
176
- process.stdout.write(`\r下载进度: ${percent}%`);
177
- }
178
- });
179
- response.pipe(file);
180
- file.on('finish', () => {
181
- file.close();
182
- console.log('\n下载完成!');
183
- resolve(destPath);
184
- });
185
- })
186
- .on('error', (error) => {
187
- file.close();
188
- cleanupFile(destPath);
189
- reject(error);
190
- });
191
- });
192
- }
193
- async function installGit() {
194
- const platform = os_1.default.platform();
195
- const downloadUrl = getGitDownloadUrl();
196
- console.log('检测到系统未安装 Git,正在准备安装...\n');
197
- if (downloadUrl === 'homebrew') {
198
- console.log('macOS 系统检测到未安装 Git');
199
- console.log('请使用以下命令安装 Git:\n');
200
- console.log(' brew install git');
201
- console.log('\n如果未安装 Homebrew,请访问: https://brew.sh/');
202
- throw new Error('请先安装 Git 后再运行此命令');
203
- }
204
- if (downloadUrl === 'package-manager') {
205
- console.log('Linux 系统检测到未安装 Git');
206
- console.log('请使用系统包管理器安装 Git:\n');
207
- console.log(' Ubuntu/Debian: sudo apt-get install git');
208
- console.log(' CentOS/RHEL: sudo yum install git');
209
- console.log(' Fedora: sudo dnf install git');
210
- console.log(' Arch: sudo pacman -S git');
211
- throw new Error('请先安装 Git 后再运行此命令');
212
- }
213
- if (platform === 'win32' && downloadUrl) {
214
- console.log('Windows 系统检测到未安装 Git');
215
- console.log('正在下载 Git 安装程序...\n');
216
- const installerPath = path_1.default.join(os_1.default.tmpdir(), 'git-installer.exe');
217
- try {
218
- await downloadFile(downloadUrl, installerPath);
219
- console.log(`\nGit 安装程序已下载到: ${installerPath}`);
220
- console.log('\n正在启动安装程序,请按照提示完成安装...');
221
- console.log('安装完成后,请重新运行此命令。\n');
222
- const child = (0, child_process_1.spawn)(installerPath, [], {
223
- detached: true,
224
- stdio: 'ignore',
225
- windowsHide: false
226
- });
227
- child.on('error', (error) => {
228
- console.error('启动安装程序失败:', error.message);
229
- });
230
- child.unref();
231
- throw new Error('请完成 Git 安装后重新运行此命令');
232
- }
233
- catch (error) {
234
- const message = error instanceof Error ? error.message : String(error);
235
- console.error('\n下载 Git 安装程序失败:', message);
236
- console.log('\n您可以手动访问以下网址下载 Git:');
237
- console.log('https://git-scm.com/download/win');
238
- throw new Error('请先安装 Git 后再运行此命令');
239
- }
240
- }
241
- }
242
- async function ensureGitInstalled() {
243
- const installed = await checkGitInstalled();
244
- if (!installed) {
245
- await installGit();
246
- }
247
- return true;
248
- }
249
99
  function isInteractiveTerminal() {
250
100
  return Boolean(process.stdin.isTTY && process.stdout.isTTY);
251
101
  }
@@ -296,12 +146,3 @@ function promptForInput(question, options = {}) {
296
146
  });
297
147
  });
298
148
  }
299
- async function getGitCommitHash(repoPath) {
300
- try {
301
- const { stdout } = await executeCommand('git rev-parse HEAD', repoPath);
302
- return stdout.trim();
303
- }
304
- catch {
305
- return null;
306
- }
307
- }