commit-pack 1.1.4 → 1.1.7

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/lib/index.mjs CHANGED
@@ -11,10 +11,37 @@ var _url = require("url");
11
11
  var _chalkColor = require("./chalkColor.js");
12
12
  var _installWithProgress = require("./installWithProgress.js");
13
13
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
14
+ const printBanner = () => {
15
+ const top = '╭' + '─'.repeat(40) + '╮';
16
+ const bottom = '╰' + '─'.repeat(40) + '╯';
17
+ const middle = `│ ${_chalk.default.bold.cyan('🚀 Commit Pack 初始化中...')} │`;
18
+ console.log('\n' + top);
19
+ console.log(middle);
20
+ console.log(bottom + '\n');
21
+ };
22
+
14
23
  // 模拟 CommonJS 的 __dirname
15
24
  const _filename = (0, _url.fileURLToPath)(import.meta.url);
16
25
  const _dirname = _path.default.dirname(_filename);
17
26
 
27
+ // 解析命令行参数
28
+ const args = process.argv.slice(2);
29
+ const workspaceArgIndex = args.findIndex(arg => arg.startsWith('--workspace=') || arg.startsWith('-w='));
30
+ let workspaceName = '';
31
+ if (workspaceArgIndex !== -1) {
32
+ const arg = args[workspaceArgIndex];
33
+ workspaceName = arg.split('=')[1];
34
+ } else {
35
+ // 查找是否有单独的 -w 或 --workspace 参数
36
+ const wIndex = args.findIndex(arg => arg === '-w');
37
+ const workspaceIndex = args.findIndex(arg => arg === '--workspace');
38
+ if (wIndex !== -1 && wIndex + 1 < args.length) {
39
+ workspaceName = args[wIndex + 1];
40
+ } else if (workspaceIndex !== -1 && workspaceIndex + 1 < args.length) {
41
+ workspaceName = args[workspaceIndex + 1];
42
+ }
43
+ }
44
+
18
45
  // 向上查找带锁文件的根目录
19
46
  function findProjectRootWithLockFile() {
20
47
  let dir = _dirname;
@@ -42,18 +69,92 @@ function detectPackageManager() {
42
69
  }
43
70
  }
44
71
  const packageManager = detectPackageManager();
72
+
73
+ // 计算实际的工作目录
74
+ let actualProjectRoot = projectRoot;
75
+ if (workspaceName) {
76
+ const packageJsonContent = JSON.parse(_fs.default.readFileSync(_path.default.join(projectRoot, 'package.json'), 'utf8'));
77
+
78
+ // 根据包管理器确定工作spaces路径
79
+ let workspaces = [];
80
+ if (packageJsonContent.workspaces) {
81
+ if (Array.isArray(packageJsonContent.workspaces)) {
82
+ workspaces = packageJsonContent.workspaces;
83
+ } else if (packageJsonContent.workspaces.packages) {
84
+ workspaces = packageJsonContent.workspaces.packages;
85
+ }
86
+ }
87
+
88
+ // 查找workspace包的路径
89
+ if (workspaces.length > 0) {
90
+ for (const workspacePattern of workspaces) {
91
+ // 处理通配符模式,例如 'packages/*'
92
+ if (workspacePattern.includes('*')) {
93
+ const basePath = workspacePattern.replace('/*', '');
94
+ const packagesDir = _path.default.join(projectRoot, basePath);
95
+ if (_fs.default.existsSync(packagesDir)) {
96
+ const packageDirs = _fs.default.readdirSync(packagesDir);
97
+ for (const dir of packageDirs) {
98
+ const dirPath = _path.default.join(packagesDir, dir);
99
+ if (_fs.default.statSync(dirPath).isDirectory()) {
100
+ try {
101
+ const pkgPath = _path.default.join(dirPath, 'package.json');
102
+ if (_fs.default.existsSync(pkgPath)) {
103
+ const pkg = JSON.parse(_fs.default.readFileSync(pkgPath, 'utf8'));
104
+ if (pkg.name === workspaceName || dir === workspaceName) {
105
+ actualProjectRoot = dirPath;
106
+ break;
107
+ }
108
+ }
109
+ } catch (e) {
110
+ console.log(e);
111
+ }
112
+ }
113
+ }
114
+ }
115
+ } else {
116
+ // 直接路径匹配
117
+ const dirPath = _path.default.join(projectRoot, workspacePattern);
118
+ if (_fs.default.existsSync(dirPath) && _fs.default.statSync(dirPath).isDirectory()) {
119
+ try {
120
+ const pkgPath = _path.default.join(dirPath, 'package.json');
121
+ if (_fs.default.existsSync(pkgPath)) {
122
+ const pkg = JSON.parse(_fs.default.readFileSync(pkgPath, 'utf8'));
123
+ if (pkg.name === workspaceName || _path.default.basename(dirPath) === workspaceName) {
124
+ actualProjectRoot = dirPath;
125
+ break;
126
+ }
127
+ }
128
+ } catch (e) {
129
+ console.log(e);
130
+ }
131
+ }
132
+ }
133
+ }
134
+ }
135
+ }
136
+ console.log('');
137
+ printBanner();
138
+ console.log('');
45
139
  console.log('');
46
140
  console.log(`🍀 包管理器:${packageManager}`);
47
- console.log(`📁 根目录:${projectRoot}`);
48
- const packageJsonPath = _path.default.join(projectRoot, 'package.json');
141
+ console.log(`📁 根目录:${actualProjectRoot}`);
142
+ if (workspaceName) {
143
+ console.log(`📦 工作空间: ${workspaceName}`);
144
+ }
145
+ const packageJsonPath = _path.default.join(actualProjectRoot, 'package.json');
49
146
  const packageJson = JSON.parse(_fs.default.readFileSync(packageJsonPath, 'utf8'));
50
147
 
51
148
  // 检查是否已经初始化过
52
- const initFlagPath = _path.default.join(projectRoot, '.commit-pack-init');
149
+ const initFlagPath = _path.default.join(actualProjectRoot, '.commit-pack-init');
53
150
  if (_fs.default.existsSync(initFlagPath)) {
151
+ console.log(_chalkColor.log.warn('⚠️ 该工作空间/项目已被初始化,跳过初始化'));
54
152
  process.exit(0);
55
153
  }
56
154
 
155
+ // 回滚机制:记录初始状态
156
+ const initialPackageJson = JSON.stringify(packageJson, null, 2);
157
+
57
158
  // 确保 devDependencies 存在
58
159
  if (!packageJson.devDependencies) {
59
160
  packageJson.devDependencies = {};
@@ -76,114 +177,193 @@ for (const [dep, version] of Object.entries(devDependenciesWithVersion)) {
76
177
  dependenciesToInstall.push(`${dep}@${version}`);
77
178
  }
78
179
  }
79
- (0, _installWithProgress.installWithProgress)(dependenciesToInstall, packageManager, projectRoot);
80
- let isGitRepo = false;
81
180
  try {
82
- // 获取 Git 仓库的顶级目录
83
- const gitTopLevel = (0, _child_process.execSync)('git rev-parse --show-toplevel', {
84
- cwd: projectRoot
85
- }).toString().trim();
86
- // 比较顶级目录与当前项目目录
87
- if (_path.default.resolve(gitTopLevel) === _path.default.resolve(projectRoot)) {
88
- isGitRepo = true;
89
- } else {
181
+ (0, _installWithProgress.installWithProgress)(dependenciesToInstall, packageManager, actualProjectRoot);
182
+ let isGitRepo = false;
183
+ try {
184
+ // 获取 Git 仓库的顶级目录
185
+ const gitTopLevel = (0, _child_process.execSync)('git rev-parse --show-toplevel', {
186
+ cwd: actualProjectRoot
187
+ }).toString().trim();
188
+ // 比较顶级目录与当前项目目录
189
+ if (_path.default.resolve(gitTopLevel) === _path.default.resolve(actualProjectRoot)) {
190
+ isGitRepo = true;
191
+ } else {
192
+ isGitRepo = false;
193
+ }
194
+ } catch {
90
195
  isGitRepo = false;
91
196
  }
92
- } catch {
93
- isGitRepo = false;
94
- }
95
- if (isGitRepo) {
96
- console.log(_chalkColor.log.success('👍 Git仓库已存在'));
97
- } else {
98
- console.log(_chalkColor.log.warn('👌 Git仓库初始化...'));
99
- (0, _child_process.execSync)('git init', {
197
+ if (isGitRepo) {
198
+ console.log(_chalkColor.log.success('👍 Git仓库已存在'));
199
+ } else {
200
+ console.log(_chalkColor.log.warn('👌 Git仓库初始化...'));
201
+ (0, _child_process.execSync)('git init', {
202
+ stdio: 'inherit',
203
+ cwd: actualProjectRoot
204
+ });
205
+ }
206
+
207
+ // 根据包管理器,执行对应的 Husky 初始化命令
208
+ let huskyInitCommand = '';
209
+ switch (packageManager) {
210
+ case 'pnpm':
211
+ huskyInitCommand = 'pnpm exec husky init';
212
+ break;
213
+ case 'yarn':
214
+ huskyInitCommand = 'yarn dlx husky init';
215
+ break;
216
+ case 'bun':
217
+ huskyInitCommand = 'bunx husky init';
218
+ break;
219
+ default:
220
+ huskyInitCommand = 'npx husky init';
221
+ break;
222
+ }
223
+ console.log(_chalk.default.green(`🐶 Husky初始化...`));
224
+ (0, _child_process.execSync)(huskyInitCommand, {
100
225
  stdio: 'inherit',
101
- cwd: projectRoot
226
+ cwd: actualProjectRoot
102
227
  });
103
- }
104
228
 
105
- // 根据包管理器,执行对应的 Husky 初始化命令
106
- let huskyInitCommand = '';
107
- switch (packageManager) {
108
- case 'pnpm':
109
- huskyInitCommand = 'pnpm exec husky init';
110
- break;
111
- case 'yarn':
112
- huskyInitCommand = 'yarn dlx husky init';
113
- break;
114
- case 'bun':
115
- huskyInitCommand = 'bunx husky init';
116
- break;
117
- default:
118
- huskyInitCommand = 'npx husky init';
119
- break;
120
- }
121
- console.log(_chalk.default.green(`🐶 Husky初始化...`));
122
- (0, _child_process.execSync)(huskyInitCommand, {
123
- stdio: 'inherit',
124
- cwd: projectRoot
125
- });
126
-
127
- // 执行 setup-script 中的所有文件
128
- console.log('🚀 创建配置文件...');
129
- try {
229
+ // 执行 setup-script 中的所有文件
230
+ console.log('🚀 创建配置文件...');
130
231
  const setupScripts = ['prettier.sh', 'lintstagedrc.sh', 'eslint.sh', 'czrc.sh', 'husky.sh', 'cz-config.sh', 'commitlintrc.sh'];
131
232
  for (const script of setupScripts) {
132
233
  const scriptPath = _path.default.join(_dirname, '..', 'setup-script', script);
133
234
  (0, _child_process.execSync)(`sh ${scriptPath}`, {
134
235
  stdio: 'inherit',
135
- cwd: projectRoot
236
+ cwd: actualProjectRoot
136
237
  });
137
238
  }
138
- } catch (error) {
139
- console.error(_chalkColor.log.warn('❌ 文件创建出错'), error);
140
- }
141
239
 
142
- // 创建或更新脚本
143
- if (!packageJson.scripts) {
144
- packageJson.scripts = {};
145
- console.log('🔥 创建或更新脚本...');
146
- }
147
- let modified = false;
148
- if (!packageJson.scripts.lint) {
149
- packageJson.scripts.lint = 'eslint ./ --ext .ts,.tsx,.json --max-warnings=0';
150
- console.log(_chalkColor.log.success('已添加 "lint" 至 package.json'));
151
- modified = true;
152
- } else {
153
- console.log(_chalkColor.log.warn('package.json 中已存在 "lint" 未作修改'));
154
- }
155
- if (!packageJson.scripts.format) {
156
- packageJson.scripts.format = "prettier --config .prettierrc '.' --write";
157
- console.log(_chalkColor.log.success('已添加 "format" 至 package.json'));
240
+ // 创建或更新脚本
241
+ if (!packageJson.scripts) {
242
+ packageJson.scripts = {};
243
+ console.log('🔥 创建或更新脚本...');
244
+ }
245
+ let modified = false;
246
+ if (!packageJson.scripts.lint) {
247
+ if (workspaceName) {
248
+ // 为workspace项目使用工作空间命令
249
+ if (packageManager === 'pnpm') {
250
+ packageJson.scripts.lint = `pnpm -F ${workspaceName} exec eslint ./ --ext .ts,.tsx,.json --max-warnings=0`;
251
+ } else if (packageManager === 'yarn') {
252
+ packageJson.scripts.lint = `yarn workspace ${workspaceName} exec eslint ./ --ext .ts,.tsx,.json --max-warnings=0`;
253
+ } else {
254
+ packageJson.scripts.lint = 'eslint ./ --ext .ts,.tsx,.json --max-warnings=0';
255
+ }
256
+ } else {
257
+ packageJson.scripts.lint = 'eslint ./ --ext .ts,.tsx,.json --max-warnings=0';
258
+ }
259
+ console.log(_chalkColor.log.success('✅ 已添加 "lint" 至 package.json'));
260
+ modified = true;
261
+ } else {
262
+ console.log(_chalkColor.log.warn('⚠️ package.json 中已存在 "lint" 未作修改'));
263
+ }
264
+ if (!packageJson.scripts.format) {
265
+ if (workspaceName) {
266
+ // 为workspace项目使用工作空间命令
267
+ if (packageManager === 'pnpm') {
268
+ packageJson.scripts.format = `pnpm -F ${workspaceName} exec prettier --config .prettierrc '.' --write`;
269
+ } else if (packageManager === 'yarn') {
270
+ packageJson.scripts.format = `yarn workspace ${workspaceName} exec prettier --config .prettierrc '.' --write`;
271
+ } else {
272
+ packageJson.scripts.format = "prettier --config .prettierrc '.' --write";
273
+ }
274
+ } else {
275
+ packageJson.scripts.format = "prettier --config .prettierrc '.' --write";
276
+ }
277
+ console.log(_chalkColor.log.success('✅ 已添加 "format" 至 package.json'));
278
+ modified = true;
279
+ } else {
280
+ console.log(_chalkColor.log.warn('⚠️ package.json 中已存在 "format" 未作修改'));
281
+ }
282
+
283
+ // 添加或更新 "commit" 脚本
284
+ if (workspaceName) {
285
+ // 为workspace项目使用工作空间命令
286
+ if (packageManager === 'pnpm') {
287
+ packageJson.scripts.commit = `pnpm -F ${workspaceName} exec cz`;
288
+ } else if (packageManager === 'yarn') {
289
+ packageJson.scripts.commit = `yarn workspace ${workspaceName} exec cz`;
290
+ } else {
291
+ packageJson.scripts.commit = 'cz';
292
+ }
293
+ } else {
294
+ packageJson.scripts.commit = 'cz';
295
+ }
296
+ console.log(_chalkColor.log.success('✅ 已添加 "commit" 至 package.json'));
158
297
  modified = true;
159
- } else {
160
- console.log(_chalkColor.log.warn('package.json 中已存在 "format" 未作修改'));
161
- }
162
298
 
163
- // 添加或更新 "commit" 脚本
164
- packageJson.scripts.commit = 'cz';
165
- console.log(_chalkColor.log.success('已添加或更新 "commit" 脚本到 package.json'));
166
- modified = true;
299
+ // 添加或更新 "config.commitizen" 配置
300
+ if (!packageJson.config) {
301
+ packageJson.config = {};
302
+ }
303
+ packageJson.config.commitizen = {
304
+ path: 'node_modules/cz-customizable'
305
+ };
306
+ modified = true;
167
307
 
168
- // 添加或更新 "config.commitizen" 配置
169
- if (!packageJson.config) {
170
- packageJson.config = {};
171
- }
172
- packageJson.config.commitizen = {
173
- path: 'node_modules/cz-customizable'
174
- };
175
- modified = true;
308
+ // 写入修改后的 package.json
309
+ if (modified) {
310
+ _fs.default.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf8');
311
+ console.log(_chalk.default.green('✅ 已更新 package.json'));
312
+ console.log('');
313
+ console.log('');
314
+ }
176
315
 
177
- // 写入修改后的 package.json
178
- if (modified) {
179
- _fs.default.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf8');
180
- console.log(_chalk.default.green('已更新 package.json'));
181
- console.log('');
316
+ // 创建初始化标志文件
317
+ _fs.default.writeFileSync(initFlagPath, 'initialized', 'utf8');
318
+ console.log(_chalkColor.log.success(' 🎉🎉🎉 完成啦!'));
182
319
  console.log('');
183
- }
320
+ if (workspaceName) {
321
+ console.log(` 在 ${workspaceName} 工作空间中,运行: git add . && ${packageManager} run commit`);
322
+ } else {
323
+ console.log(` 运行 git add 后 | 运行 ${packageManager} run commit 即可`);
324
+ }
325
+ } catch (error) {
326
+ console.error(_chalkColor.log.error('❌ 初始化过程中发生错误,正在执行回滚...'));
327
+ console.error('错误详情:', error.message);
328
+ console.error('错误堆栈:', error.stack);
329
+ if (error.stdout) console.error('标准输出:', error.stdout.toString());
330
+ if (error.stderr) console.error('错误输出:', error.stderr.toString());
331
+ try {
332
+ // 回滚:恢复原始的package.json
333
+ _fs.default.writeFileSync(packageJsonPath, initialPackageJson, 'utf8');
334
+ console.log(_chalkColor.log.warn('✅ 已恢复原始 package.json'));
184
335
 
185
- // 创建初始化标志文件
186
- // fs.writeFileSync(initFlagPath, 'initialized', 'utf8')
187
- console.log(_chalkColor.log.success(' 🎉🎉🎉 完成啦!'));
188
- console.log('');
189
- console.log(` 运行 git add 后 | 运行 ${packageManager} run commit 即可`);
336
+ // 删除可能创建的配置文件
337
+ const configFiles = ['.prettierrc', '.eslintrc', '.commitlintrc.json', '.cz-config.js', '.czrc', '.lintstagedrc', '.prettierignore', '.eslintignore'];
338
+ for (const configFile of configFiles) {
339
+ const configPath = _path.default.join(actualProjectRoot, configFile);
340
+ if (_fs.default.existsSync(configPath)) {
341
+ _fs.default.unlinkSync(configPath);
342
+ console.log(_chalkColor.log.warn(`✅ 已删除临时配置文件: ${configFile}`));
343
+ }
344
+ }
345
+
346
+ // 删除可能创建的.husky目录
347
+ const huskyDir = _path.default.join(actualProjectRoot, '.husky');
348
+ if (_fs.default.existsSync(huskyDir)) {
349
+ _fs.default.rmSync(huskyDir, {
350
+ recursive: true,
351
+ force: true
352
+ });
353
+ console.log(_chalkColor.log.warn('✅ 已删除临时 .husky 目录'));
354
+ }
355
+
356
+ // 删除初始化标志文件
357
+ if (_fs.default.existsSync(initFlagPath)) {
358
+ _fs.default.unlinkSync(initFlagPath);
359
+ }
360
+ console.log(_chalkColor.log.success(' 🔄 回滚完成'));
361
+ } catch (rollbackError) {
362
+ console.error(_chalkColor.log.error('❌ 回滚过程中也发生了错误,请手动检查项目状态'));
363
+ console.error('回滚错误详情:', rollbackError.message);
364
+ console.error('回滚错误堆栈:', rollbackError.stack);
365
+ if (rollbackError.stdout) console.error('回滚标准输出:', rollbackError.stdout.toString());
366
+ if (rollbackError.stderr) console.error('回滚错误输出:', rollbackError.stderr.toString());
367
+ }
368
+ process.exit(1); // 确保进程以错误码退出
369
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "commit-pack",
3
- "version": "1.1.4",
3
+ "version": "1.1.7",
4
4
  "description": "A setup package to automatly check project's style and commit configuration",
5
5
  "main": "lib/index.js",
6
6
  "bin": {
@@ -77,6 +77,6 @@
77
77
  "format": "prettier --config .prettierrc '.' --write",
78
78
  "commit": "cz",
79
79
  "build": "babel bin/index.mjs --out-file lib/index.mjs",
80
- "release": "standard-version"
80
+ "release": "HUSKY=0 standard-version"
81
81
  }
82
82
  }
@@ -1,7 +1,25 @@
1
- echo '
2
- npx lint-staged
1
+ echo '#!/usr/bin/env sh
2
+ set -e
3
+ if [ -n "$PNPM_PACKAGE_NAME" ]; then
4
+ # 在工作空间环境中运行 pnpm 命令
5
+ pnpm exec lint-staged
6
+ else
7
+ # 在普通环境中运行
8
+ npx lint-staged
9
+ fi
3
10
  ' > .husky/pre-commit
4
11
 
5
- echo '
6
- npx --no -- commitlint --edit "$1"
7
- ' > .husky/commit-msg
12
+ chmod +x .husky/pre-commit
13
+
14
+ echo '#!/usr/bin/env sh
15
+ set -e
16
+ if [ -n "$PNPM_PACKAGE_NAME" ]; then
17
+ # 在工作空间环境中运行 pnpm 命令
18
+ pnpm exec -- commitlint --edit "$1"
19
+ else
20
+ # 在普通环境中运行
21
+ npx --no -- commitlint --edit "$1"
22
+ fi
23
+ ' > .husky/commit-msg
24
+
25
+ chmod +x .husky/commit-msg
@@ -1,5 +1,5 @@
1
1
  echo '
2
2
  {
3
- "*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"]
3
+ "*.{js,jsx,ts,tsx,json,md}": ["eslint --fix", "prettier --write"]
4
4
  }
5
5
  ' > .lintstagedrc