ai-git-tools 2.0.61 → 2.0.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -142,7 +142,7 @@ program
142
142
  .command('write-and-test')
143
143
  .description('AI 為指定檔案生成 Jest 測試,並自動執行與修復(最多 2 次)')
144
144
  .requiredOption('--file <path>', '原始碼路徑')
145
- .option('--test-type <type>', '測試類型:auto、unit 或 component(預設 auto)', 'auto')
145
+ .option('--test-type <type>', '測試類型:auto、unit、componentboth(可用逗號指定多個)', 'auto')
146
146
  .option('--max-fixes <number>', '最大自動修復次數(預設 2)', '2')
147
147
  .option('--no-confirm', '跳過確認直接生成並執行測試')
148
148
  .option('--model <model>', '指定 AI 模型')
@@ -158,11 +158,11 @@ program
158
158
  // Auto Dev 整合命令
159
159
  program
160
160
  .command('auto-dev')
161
- .description('一鍵自動化:從 GitHub Issue 到代碼生成、測試與提交')
161
+ .description('一鍵自動化:從 GitHub Issue 到代碼生成與測試修正')
162
162
  .requiredOption('--issue <number>', 'GitHub Issue 編號')
163
163
  .option('--file <path>', '目標檔案路徑(若無則自動推斷)')
164
164
  .option('--context <description>', '額外說明或補充需求')
165
- .option('--test-type <type>', '測試類型:auto、unit 或 component(預設 auto)', 'auto')
165
+ .option('--test-type <type>', '測試類型:auto、unit、componentboth(預設 auto)', 'auto')
166
166
  .option('--max-lines <number>', '最大行數限制(預設 500)', '500')
167
167
  .option('--max-fixes <number>', '最大自動修復次數(預設 2)', '2')
168
168
  .option('--no-confirm', '全自動模式,跳過所有確認')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-git-tools",
3
- "version": "2.0.61",
3
+ "version": "2.0.62",
4
4
  "description": "AI-powered Git automation tools for commit messages and PR generation",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -11,9 +11,7 @@ import inquirer from 'inquirer';
11
11
  import { IssueReader } from '../core/issue-reader.js';
12
12
  import { CodeGenerator } from '../core/code-generator.js';
13
13
  import { AIClient } from '../core/ai-client.js';
14
- import { GitOperations } from '../core/git-operations.js';
15
- import { TestGenerator } from '../core/test-generator.js';
16
- import { writeAndTestCommand, TEST_TYPE_CHOICES, normalizeTestType } from './write-and-test.js';
14
+ import { writeAndTestCommand, TEST_TYPE_CHOICES, normalizeTestTypeSelection, resolveRequestedTestTypes } from './write-and-test.js';
17
15
  import { Logger } from '../utils/logger.js';
18
16
 
19
17
  export async function autoDevCommand(options = {}) {
@@ -125,10 +123,10 @@ export async function autoDevCommand(options = {}) {
125
123
  requestedTestType: options.testType,
126
124
  });
127
125
 
128
- const resolvedRuntimeTestType = resolveRuntimeTestType(absoluteFilePath, selectedTestType);
126
+ const resolvedRuntimeTestTypes = resolveRequestedTestTypes(absoluteFilePath, selectedTestType);
129
127
 
130
128
  logger.step('正在驗證專案可用的測試腳本...');
131
- ensureJestAvailable(resolvedRuntimeTestType);
129
+ ensureJestAvailable(resolvedRuntimeTestTypes);
132
130
  logger.success('已確認可執行 Jest 測試。');
133
131
  console.log('');
134
132
 
@@ -149,25 +147,15 @@ export async function autoDevCommand(options = {}) {
149
147
  return;
150
148
  }
151
149
 
152
- // ============================================================
153
- // 第七步:自動 Commit
154
- // ============================================================
155
- logger.step('正在自動提交...');
156
- try {
157
- GitOperations.exec(`git add "${absoluteFilePath}" "${testResult.testFilePath}"`, { silent: true });
158
- const commitMsg = `feat(auto-dev): Issue #${issue.number} - ${issue.title}\n\n生成檔案:\n- ${filePath}\n- ${testResult.testFilePath.replace(process.cwd(), '.')}`;
159
- GitOperations.exec(`git commit -m "${commitMsg.split('\n')[0]}"`, { silent: true });
160
- logger.success('已自動提交');
161
- } catch {
162
- logger.warning('自動 commit 失敗(可能已有相同 commit 或尚未 staged)');
163
- }
164
-
165
150
  console.log('');
166
151
  logger.section('✅ 自動化工作流完成');
167
152
  console.log(`Issue #${issue.number}:${issue.title}`);
168
153
  console.log(`生成檔案:${filePath}`);
169
- console.log(`測試檔案:${testResult.testFilePath.replace(process.cwd(), '.')}`);
170
- console.log(`測試類型:${testResult.testType}`);
154
+ testResult.testFilePaths.forEach((testFilePath) => {
155
+ console.log(`測試檔案:${testFilePath.replace(process.cwd(), '.')}`);
156
+ });
157
+ console.log(`測試類型:${testResult.testTypes.join('、')}`);
158
+ console.log('狀態:已完成代碼與測試流程,未自動 commit');
171
159
  console.log(`合計行數:${codeResult.linesCount + ' (程式碼)'}`);
172
160
  }
173
161
 
@@ -257,8 +245,10 @@ function getLanguageFromFilePath(filePath) {
257
245
  }
258
246
 
259
247
  async function resolveTestTypeForAutoDev({ noConfirm, requestedTestType }) {
248
+ const defaultTestType = normalizeTestTypeSelection(requestedTestType || 'auto')[0] || 'auto';
249
+
260
250
  if (noConfirm) {
261
- return normalizeTestType(requestedTestType || 'auto');
251
+ return requestedTestType || 'auto';
262
252
  }
263
253
 
264
254
  const { testType } = await inquirer.prompt([{
@@ -266,22 +256,13 @@ async function resolveTestTypeForAutoDev({ noConfirm, requestedTestType }) {
266
256
  name: 'testType',
267
257
  message: '請選擇這次要執行的測試方式:',
268
258
  choices: TEST_TYPE_CHOICES,
269
- default: normalizeTestType(requestedTestType || 'auto'),
259
+ default: defaultTestType === 'auto' ? 'both' : defaultTestType,
270
260
  }]);
271
261
 
272
- return normalizeTestType(testType);
273
- }
274
-
275
- function resolveRuntimeTestType(sourceFilePath, requestedTestType) {
276
- if (requestedTestType !== 'auto') {
277
- return requestedTestType;
278
- }
279
-
280
- const sourceCode = readFileSync(sourceFilePath, 'utf-8');
281
- return TestGenerator.resolveTestType(sourceFilePath, sourceCode, 'auto');
262
+ return testType;
282
263
  }
283
264
 
284
- function ensureJestAvailable(runtimeTestType = 'unit') {
265
+ function ensureJestAvailable(runtimeTestType = ['unit']) {
285
266
  const packageJson = readProjectPackageJson();
286
267
 
287
268
  try {
@@ -321,7 +302,7 @@ function readProjectPackageJson() {
321
302
  }
322
303
 
323
304
  function ensureComponentTestDependencies(packageJson, runtimeTestType) {
324
- if (runtimeTestType !== 'component') {
305
+ if (!runtimeTestType.includes('component')) {
325
306
  return;
326
307
  }
327
308
 
@@ -8,7 +8,7 @@ import { resolve } from 'path';
8
8
  import inquirer from 'inquirer';
9
9
  import { IssueReader } from '../core/issue-reader.js';
10
10
  import { CodeGenerator } from '../core/code-generator.js';
11
- import { writeAndTestCommand, TEST_TYPE_CHOICES } from './write-and-test.js';
11
+ import { writeAndTestCommand, TEST_TYPE_CHOICES, normalizeTestTypeSelection } from './write-and-test.js';
12
12
  import { Logger } from '../utils/logger.js';
13
13
 
14
14
  export async function generateCodeCommand(options = {}) {
@@ -97,13 +97,13 @@ export async function generateCodeCommand(options = {}) {
97
97
  value: 'skip',
98
98
  },
99
99
  ],
100
- default: 'auto',
100
+ default: 'both',
101
101
  }]);
102
102
 
103
103
  if (nextAction !== 'skip') {
104
104
  await writeAndTestCommand({
105
105
  file: filePath,
106
- testType: nextAction,
106
+ testType: normalizeTestTypeSelection(nextAction).join(','),
107
107
  maxFixes: options.maxFixes || '2',
108
108
  model: options.model,
109
109
  noConfirm: true,
@@ -4,8 +4,7 @@
4
4
  */
5
5
 
6
6
  import { resolve, basename, dirname, join } from 'path';
7
- import { existsSync } from 'fs';
8
- import { execSync } from 'child_process';
7
+ import { existsSync, readFileSync } from 'fs';
9
8
  import inquirer from 'inquirer';
10
9
  import { TestGenerator } from '../core/test-generator.js';
11
10
  import { TestRunner } from '../core/test-runner.js';
@@ -24,31 +23,75 @@ export const TEST_TYPE_CHOICES = [
24
23
  name: '寫元件測試',
25
24
  value: 'component',
26
25
  },
26
+ {
27
+ name: '同時寫 Jest 單元測試 + 元件測試',
28
+ value: 'both',
29
+ },
27
30
  ];
28
31
 
29
- export function normalizeTestType(testType = 'auto') {
30
- const normalized = String(testType).trim().toLowerCase();
32
+ export function normalizeTestTypeSelection(testType = 'auto') {
33
+ const rawValues = Array.isArray(testType)
34
+ ? testType
35
+ : String(testType)
36
+ .split(',')
37
+ .map((value) => value.trim())
38
+ .filter(Boolean);
31
39
 
32
- if (normalized === 'auto' || normalized === 'unit' || normalized === 'component') {
33
- return normalized;
34
- }
40
+ const normalizedValues = rawValues.length > 0 ? rawValues : ['auto'];
41
+ const resolvedValues = normalizedValues.flatMap((value) => {
42
+ const normalized = value.toLowerCase();
35
43
 
36
- if (normalized === 'jest' || normalized === 'jest-unit' || normalized === 'unit-test') {
37
- return 'unit';
38
- }
44
+ if (normalized === 'auto' || normalized === 'unit' || normalized === 'component') {
45
+ return normalized;
46
+ }
47
+
48
+ if (normalized === 'both' || normalized === 'all') {
49
+ return ['unit', 'component'];
50
+ }
51
+
52
+ if (normalized === 'jest' || normalized === 'jest-unit' || normalized === 'unit-test') {
53
+ return 'unit';
54
+ }
55
+
56
+ if (normalized === 'component-test' || normalized === 'react-component') {
57
+ return 'component';
58
+ }
59
+
60
+ throw new Error(`不支援的測試類型:${value}`);
61
+ });
62
+
63
+ return [...new Set(resolvedValues)];
64
+ }
65
+
66
+ export function resolveRequestedTestTypes(sourceFilePath, requestedTestType = 'auto') {
67
+ const normalizedTestTypes = normalizeTestTypeSelection(requestedTestType);
39
68
 
40
- if (normalized === 'component-test' || normalized === 'react-component') {
41
- return 'component';
69
+ if (!normalizedTestTypes.includes('auto')) {
70
+ return normalizedTestTypes;
42
71
  }
43
72
 
44
- throw new Error(`不支援的測試類型:${testType}`);
73
+ const sourceCode = readFileSync(sourceFilePath, 'utf-8');
74
+ const inferredTestType = TestGenerator.resolveTestType(sourceFilePath, sourceCode, 'auto');
75
+
76
+ return [...new Set(
77
+ normalizedTestTypes.flatMap((testType) => (testType === 'auto' ? inferredTestType : testType))
78
+ )];
79
+ }
80
+
81
+ function formatTestTypes(testTypes) {
82
+ const labels = {
83
+ auto: '自動判斷',
84
+ unit: 'Jest 單元測試',
85
+ component: '元件測試',
86
+ };
87
+
88
+ return testTypes.map((testType) => labels[testType] || testType).join('、');
45
89
  }
46
90
 
47
91
  export async function writeAndTestCommand(options = {}) {
48
92
  const logger = new Logger();
49
93
 
50
94
  const filePath = options.file;
51
- const requestedTestType = normalizeTestType(options.testType || 'auto');
52
95
  const maxFixes = parseInt(options.maxFixes || '2', 10);
53
96
 
54
97
  if (!filePath) {
@@ -62,13 +105,18 @@ export async function writeAndTestCommand(options = {}) {
62
105
  throw new Error(`找不到原始碼:${absoluteSourcePath}`);
63
106
  }
64
107
 
65
- // 推導測試檔案路徑
66
- const testFilePath = deriveTestFilePath(absoluteSourcePath);
108
+ const resolvedTestTypes = resolveRequestedTestTypes(absoluteSourcePath, options.testType || 'auto');
109
+ const testTargets = resolvedTestTypes.map((testType) => ({
110
+ testType,
111
+ testFilePath: deriveTestFilePath(absoluteSourcePath, testType),
112
+ }));
67
113
 
68
114
  logger.header('write-and-test');
69
115
  console.log(`原始碼 :${absoluteSourcePath}`);
70
- console.log(`測試檔案:${testFilePath}`);
71
- console.log(`測試類型:${requestedTestType}`);
116
+ console.log(`測試類型:${formatTestTypes(resolvedTestTypes)}`);
117
+ testTargets.forEach(({ testType, testFilePath }) => {
118
+ console.log(`${testType === 'component' ? '元件測試' : '單元測試'}:${testFilePath}`);
119
+ });
72
120
  console.log(`最大修復:${maxFixes} 次`);
73
121
  console.log('');
74
122
 
@@ -77,7 +125,7 @@ export async function writeAndTestCommand(options = {}) {
77
125
  const { confirmed } = await inquirer.prompt([{
78
126
  type: 'confirm',
79
127
  name: 'confirmed',
80
- message: `確認為 ${filePath} 生成 ${requestedTestType} 測試並執行?`,
128
+ message: `確認為 ${filePath} 生成 ${formatTestTypes(resolvedTestTypes)} 並執行?`,
81
129
  default: true,
82
130
  }]);
83
131
 
@@ -89,14 +137,18 @@ export async function writeAndTestCommand(options = {}) {
89
137
 
90
138
  // 2. 生成測試
91
139
  logger.step('正在生成測試代碼...');
92
- const generatedTest = await TestGenerator.generateTests(
93
- absoluteSourcePath,
94
- testFilePath,
95
- requestedTestType,
96
- options.model
97
- );
98
- logger.success(`測試已寫入:${testFilePath}`);
99
- logger.info(`實際測試類型:${generatedTest.testType}`);
140
+ const generatedTests = [];
141
+ for (const { testType, testFilePath } of testTargets) {
142
+ const generatedTest = await TestGenerator.generateTests(
143
+ absoluteSourcePath,
144
+ testFilePath,
145
+ testType,
146
+ options.model
147
+ );
148
+ generatedTests.push(generatedTest);
149
+ logger.success(`測試已寫入:${testFilePath}`);
150
+ }
151
+ logger.info(`實際測試類型:${formatTestTypes(generatedTests.map(({ testType }) => testType))}`);
100
152
 
101
153
  // 3. 執行測試 + 自動修復循環
102
154
  let lastErrors = [];
@@ -108,16 +160,15 @@ export async function writeAndTestCommand(options = {}) {
108
160
  }
109
161
 
110
162
  logger.step(`正在執行測試${attempt > 0 ? `(第 ${attempt} 次修復後)` : ''}...`);
111
- const result = await TestRunner.runTests(testFilePath);
163
+ const result = await TestRunner.runTests(generatedTests.map(({ testFilePath }) => testFilePath));
112
164
 
113
165
  if (result.success) {
114
166
  logger.success('所有測試通過! 🎉');
115
-
116
- // 4. 自動 commit 測試檔案
117
- if (!options.skipCommit) {
118
- await commitGeneratedFiles(testFilePath, absoluteSourcePath, logger);
119
- }
120
- return { success: true, testFilePath, testType: generatedTest.testType };
167
+ return {
168
+ success: true,
169
+ testFilePaths: generatedTests.map(({ testFilePath }) => testFilePath),
170
+ testTypes: generatedTests.map(({ testType }) => testType),
171
+ };
121
172
  }
122
173
 
123
174
  lastErrors = result.errors;
@@ -139,12 +190,14 @@ export async function writeAndTestCommand(options = {}) {
139
190
  });
140
191
  console.log('');
141
192
  console.log(`原始碼路徑:${absoluteSourcePath}`);
142
- console.log(`測試路徑 :${testFilePath}`);
193
+ generatedTests.forEach(({ testFilePath }) => {
194
+ console.log(`測試路徑 :${testFilePath}`);
195
+ });
143
196
  return {
144
197
  success: false,
145
- testFilePath,
198
+ testFilePaths: generatedTests.map(({ testFilePath }) => testFilePath),
146
199
  errors: lastErrors,
147
- testType: generatedTest.testType,
200
+ testTypes: generatedTests.map(({ testType }) => testType),
148
201
  };
149
202
  }
150
203
  }
@@ -152,25 +205,11 @@ export async function writeAndTestCommand(options = {}) {
152
205
 
153
206
  /**
154
207
  * 依據原始檔案路徑推導測試檔案路徑
155
- * e.g. src/core/foo.js → src/core/__tests__/foo.test.js
156
208
  */
157
- export function deriveTestFilePath(sourceFilePath) {
209
+ export function deriveTestFilePath(sourceFilePath, testType = 'unit') {
158
210
  const dir = dirname(sourceFilePath);
159
211
  const name = basename(sourceFilePath).replace(/\.(js|jsx|ts|tsx|mjs|cjs)$/, '');
160
212
  const ext = /\.(ts|tsx)$/.test(sourceFilePath) ? '.ts' : '.js';
161
- return join(dir, '__tests__', `${name}.test${ext}`);
162
- }
163
-
164
- /**
165
- * 將原始碼與測試檔案一併 commit 到 git
166
- */
167
- async function commitGeneratedFiles(testFilePath, sourceFilePath, logger) {
168
- try {
169
- execSync(`git add "${sourceFilePath}" "${testFilePath}"`, { stdio: 'pipe' });
170
- const name = basename(sourceFilePath);
171
- execSync(`git commit -m "test: 為 ${name} 新增自動生成的測試"`, { stdio: 'pipe' });
172
- logger.success('原始碼與測試檔案已自動 commit。');
173
- } catch {
174
- logger.warning('無法自動 commit 產生的檔案(可能沒有 staged 變更或不在 git 倉庫中)。');
175
- }
213
+ const suffix = testType === 'component' ? 'component' : 'unit';
214
+ return join(dir, '__tests__', `${name}.${suffix}.test${ext}`);
176
215
  }
@@ -10,17 +10,23 @@ import { resolve } from 'path';
10
10
  export class TestRunner {
11
11
  /**
12
12
  * 執行指定的測試檔案
13
- * @param {string} testFilePath - 測試檔案路徑(絕對路徑)
13
+ * @param {string|string[]} testFilePath - 測試檔案路徑(絕對路徑)
14
14
  * @returns {Promise<{ success: boolean, errors: string[] }>}
15
15
  */
16
16
  static async runTests(testFilePath) {
17
- if (!existsSync(testFilePath)) {
18
- return { success: false, errors: [`測試檔案不存在:${testFilePath}`] };
17
+ const testFilePaths = Array.isArray(testFilePath) ? testFilePath : [testFilePath];
18
+ const missingTestFilePath = testFilePaths.find((filePath) => !existsSync(filePath));
19
+
20
+ if (missingTestFilePath) {
21
+ return { success: false, errors: [`測試檔案不存在:${missingTestFilePath}`] };
19
22
  }
20
23
 
21
24
  try {
22
- const absoluteTestFilePath = resolve(testFilePath);
23
- execSync(`npx jest --runInBand --runTestsByPath "${absoluteTestFilePath}" --no-coverage`, {
25
+ const absoluteTestFilePaths = testFilePaths
26
+ .map((filePath) => `"${resolve(filePath)}"`)
27
+ .join(' ');
28
+
29
+ execSync(`npx jest --runInBand --runTestsByPath ${absoluteTestFilePaths} --no-coverage`, {
24
30
  encoding: 'utf-8',
25
31
  stdio: 'pipe',
26
32
  timeout: 120000, // 2 分鐘超時