1
- const { execSync, spawnSync } = require ( "node:child_process" ) ;
1
+ const { execSync, spawn } = require ( "node:child_process" ) ;
2
2
const path = require ( "node:path" ) ;
3
3
const process = require ( "node:process" ) ;
4
+ const { consola } = require ( "consola" ) ;
4
5
5
6
/**
6
7
* 获取 `暂存区` 所有文件(过滤以删除的文件)
@@ -26,8 +27,8 @@ function getStagedFiles() {
26
27
async function processFilesWithESLint ( stagedFiles ) {
27
28
try {
28
29
const results = await Promise . allSettled (
29
- stagedFiles . map ( file =>
30
- eslintFix ( file ) . then ( ( ) => runGitAdd ( file ) ) ,
30
+ stagedFiles . map ( ( file , index ) =>
31
+ eslintFix ( file , stagedFiles . length , index + 1 ) . then ( ( ) => runGitAdd ( file ) ) ,
31
32
) ,
32
33
) ;
33
34
@@ -46,31 +47,40 @@ async function processFilesWithESLint(stagedFiles) {
46
47
/**
47
48
* 执行 ESLint 修复单个文件
48
49
*/
49
- function eslintFix ( filePath ) {
50
+ function eslintFix ( filePath , length , index ) {
50
51
return new Promise ( ( resolve , reject ) => {
51
- const eslint = spawnSync (
52
+ consola . start ( `[${ index } /${ length } ] Eslint Formatting... [filePath: ${ filePath } ] ` ) ;
53
+
54
+ // 使用异步的 spawn
55
+ const eslintProcess = spawn (
52
56
"npx eslint" ,
53
57
[ "--fix" , "--quiet" , filePath ] ,
54
- {
55
- stdio : "inherit" ,
56
- shell : true ,
57
- } ,
58
+ { shell : true , stdio : "inherit" } , // stdio: 'inherit' 直接输出到控制台
58
59
) ;
59
60
60
- if ( eslint . status !== 0 ) {
61
- reject ( new Error ( `ESLint 修复失败: ${ filePath } ` ) ) ;
62
- }
63
- else {
64
- resolve ( ) ;
65
- }
61
+ eslintProcess . on ( "close" , ( code ) => {
62
+ if ( code === 0 ) {
63
+ consola . success ( `[${ index } /${ length } ] Eslint Format successfully! [filePath: ${ filePath } ]` ) ;
64
+ resolve ( ) ;
65
+ }
66
+ else {
67
+ consola . error ( `[${ index } /${ length } ] Eslint Format failed! [filePath: ${ filePath } ]` ) ;
68
+ reject ( new Error ( `ESLint 修复失败: ${ filePath } ` ) ) ;
69
+ }
70
+ } ) ;
71
+
72
+ eslintProcess . on ( "error" , ( error ) => {
73
+ consola . error ( `[${ index } /${ length } ] Eslint Execution Error! [filePath: ${ filePath } ]` ) ;
74
+ reject ( error ) ;
75
+ } ) ;
66
76
} ) ;
67
77
}
68
78
69
79
/**
70
80
* 执行 `git add ` 将 `eslint --fix` 的文件推送至暂存区
71
81
*/
72
82
function runGitAdd ( filePath ) {
73
- spawnSync (
83
+ spawn (
74
84
"git" ,
75
85
[ "add" , "--" , path . normalize ( filePath ) ] ,
76
86
{
0 commit comments