-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathcheck-diff-async.mjs
More file actions
133 lines (111 loc) · 4.07 KB
/
check-diff-async.mjs
File metadata and controls
133 lines (111 loc) · 4.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/**
* Check that all new/modified functions in the current git diff use async/await.
* Fails with exit code 1 if any additions introduce callback-style functions.
*
* Usage: node scripts/check-diff-async.mjs
* In CI: runs against the current PR diff (files changed vs base branch)
*/
import { execFileSync } from 'node:child_process';
import { Project, SyntaxKind } from 'ts-morph';
const CALLBACK_PARAM_PATTERN = /^(cb|callback|next|done)$/i;
function getChangedJsFiles() {
const base = process.env.GITHUB_BASE_REF
? `origin/${process.env.GITHUB_BASE_REF}`
: 'HEAD';
const output = execFileSync('git', [
'diff',
'--name-only',
'--diff-filter=ACMR',
base,
'--',
'**/*.js',
], { encoding: 'utf8' }).trim();
return output ? output.split('\n').filter(f => f.endsWith('.js')) : [];
}
/**
* Get added line numbers for a file in the current diff.
*/
function getAddedLineNumbers(filePath) {
const base = process.env.GITHUB_BASE_REF
? `origin/${process.env.GITHUB_BASE_REF}`
: 'HEAD';
const diff = execFileSync('git', ['diff', base, '--', filePath], { encoding: 'utf8' });
const addedLines = new Set();
let currentLine = 0;
for (const line of diff.split('\n')) {
const hunkMatch = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
if (hunkMatch) {
currentLine = parseInt(hunkMatch[1], 10) - 1;
continue;
}
if (line.startsWith('+') && !line.startsWith('+++')) {
currentLine++;
addedLines.add(currentLine);
} else if (!line.startsWith('-')) {
currentLine++;
}
}
return addedLines;
}
const changedFiles = getChangedJsFiles();
if (changedFiles.length === 0) {
console.log('No changed JS files to check.');
process.exit(0);
}
console.log(`Checking ${changedFiles.length} changed JS file(s) for async/await compliance...\n`);
const project = new Project({
compilerOptions: { allowJs: true, noEmit: true },
skipAddingFilesFromTsConfig: true,
});
const filesToCheck = changedFiles.filter(f =>
!f.startsWith('tests/') &&
!f.startsWith('node_modules/') &&
(
f.startsWith('lib/') ||
f.startsWith('bin/') ||
!f.includes('/')
)
);
if (filesToCheck.length === 0) {
console.log('No source JS files in diff (tests and node_modules excluded).');
process.exit(0);
}
project.addSourceFilesAtPaths(filesToCheck);
const violations = [];
for (const sourceFile of project.getSourceFiles()) {
const filePath = sourceFile.getFilePath().replace(process.cwd() + '/', '');
const addedLines = getAddedLineNumbers(filePath);
if (addedLines.size === 0) continue;
const functions = [
...sourceFile.getDescendantsOfKind(SyntaxKind.FunctionDeclaration),
...sourceFile.getDescendantsOfKind(SyntaxKind.FunctionExpression),
...sourceFile.getDescendantsOfKind(SyntaxKind.ArrowFunction),
...sourceFile.getDescendantsOfKind(SyntaxKind.MethodDeclaration),
];
for (const fn of functions) {
if (fn.isAsync()) continue;
const startLine = fn.getStartLineNumber();
if (!addedLines.has(startLine)) continue;
const params = fn.getParameters();
const lastParam = params[params.length - 1];
if (lastParam && CALLBACK_PARAM_PATTERN.test(lastParam.getName())) {
violations.push({
file: filePath,
line: startLine,
type: 'callback',
detail: `function has callback parameter '${lastParam.getName()}'`,
});
}
}
}
if (violations.length === 0) {
console.log('✓ All new code in the diff uses async/await.');
process.exit(0);
}
console.error(`✗ Found ${violations.length} async/await violation(s) in the diff:\n`);
for (const v of violations) {
console.error(` ${v.file}:${v.line} [${v.type}] ${v.detail}`);
}
console.error('\nNew code must use async/await instead of callbacks.');
console.error('See the async/await migration guide in CONTRIBUTING.md for help.');
process.exit(1);