-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathdangerfile.ts
More file actions
188 lines (153 loc) · 5.51 KB
/
dangerfile.ts
File metadata and controls
188 lines (153 loc) · 5.51 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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { execSync } from 'child_process';
import { danger, fail, schedule, warn } from 'danger';
const pr = danger.github.pr;
const modified = danger.git.modified_files;
const created = danger.git.created_files;
const deleted = danger.git.deleted_files;
// Ensure PR has description
if (!pr.body || pr.body.length < 10) {
fail('Please add a meaningful description to the PR.');
}
// PR size check
const bigPRThreshold = 600;
const totalChanges = modified.length + created.length + deleted.length;
if (totalChanges > bigPRThreshold) {
warn(
`This PR has ${totalChanges} changed files. Consider breaking it into smaller PRs for easier review.`,
);
}
interface StrictError {
filename: string;
start: { line: number; character: number };
message: string;
}
interface StrictErrorResult {
success: boolean;
totalErrors: number;
errorsByFile: Record<string, StrictError[]>;
}
async function checkStrictModeErrors() {
const DEBUG = false; // Set to true to enable detailed logging
try {
const tmpFile = `/tmp/strict-errors-${Date.now()}.json`;
execSync(`pnpm dlx esno scripts/count-strict-errors.ts > ${tmpFile}`, {
encoding: 'utf8',
cwd: process.cwd(),
timeout: 5 * 60 * 1000,
shell: '/bin/bash',
});
const fs = await import('fs');
const output = fs.readFileSync(tmpFile, 'utf8');
fs.unlinkSync(tmpFile);
if (!output || output.trim().length === 0) {
console.error('Script produced no output');
return;
}
const lines = output.trim().split('\n');
const jsonLine = lines[lines.length - 1];
let result: StrictErrorResult;
try {
result = JSON.parse(jsonLine);
} catch {
console.error('Failed to parse strict mode check results');
warn(
'⚠️ Failed to parse strict mode check results. Check CI logs for details.',
);
return;
}
if (!result.success) {
console.error('Script reported failure');
return;
}
const changedFiles = new Set([
...danger.git.modified_files,
...danger.git.created_files,
]);
if (DEBUG) {
console.log('Changed files in PR:', Array.from(changedFiles));
}
// Find errors in files that were changed in this PR
const relevantErrors: Record<string, StrictError[]> = {};
let relevantErrorCount = 0;
for (const [filename, errors] of Object.entries(result.errorsByFile)) {
const isChanged = Array.from(changedFiles).some(
(changedFile) =>
changedFile.includes(filename) || filename.includes(changedFile),
);
if (isChanged) {
relevantErrors[filename] = errors;
relevantErrorCount += errors.length;
}
}
if (relevantErrorCount === 0) {
return;
}
const percentageInPR = (
(relevantErrorCount / result.totalErrors) *
100
).toFixed(1);
// Post summary warning with all errors
let warningMessage = `📊 **Strict Mode**: ${relevantErrorCount} error${relevantErrorCount > 1 ? 's' : ''} in ${Object.keys(relevantErrors).length} file${Object.keys(relevantErrors).length > 1 ? 's' : ''} (${percentageInPR}% of ${result.totalErrors} total)\n\n`;
for (const [filename, errors] of Object.entries(relevantErrors)) {
warningMessage += `<details>\n<summary><strong>${filename}</strong> (${errors.length})</summary>\n\n`;
for (const error of errors) {
warningMessage += `- L${error.start.line}:${error.start.character}: ${error.message}\n`;
}
warningMessage += '\n</details>\n\n';
}
warn(warningMessage);
// Post individual warnings for errors on lines in the diff
for (const [filename, errors] of Object.entries(relevantErrors)) {
if (DEBUG) {
console.log(`Processing ${errors.length} errors for file: ${filename}`);
}
const structuredDiff = await danger.git.structuredDiffForFile(filename);
if (!structuredDiff) {
if (DEBUG) {
console.log(`No structured diff found for ${filename}`);
}
continue;
}
// Calculate which line numbers exist in the new version of the file
const linesInDiff = new Set<number>();
for (const chunk of structuredDiff.chunks) {
// Parse chunk header: @@ -old_start,old_count +new_start,new_count @@
const match = chunk.content.match(
/@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,
);
if (!match) continue;
let currentNewLine = parseInt(match[1], 10);
for (const change of chunk.changes) {
if (change.type === 'add' || change.type === 'normal') {
linesInDiff.add(currentNewLine);
currentNewLine++;
}
// Deleted lines don't exist in the new file, so skip them
}
}
if (DEBUG) {
console.log(
`Lines in diff: ${Array.from(linesInDiff)
.sort((a, b) => a - b)
.join(', ')}`,
);
}
// Post warnings for errors on lines that are in the diff
for (const error of errors) {
if (linesInDiff.has(error.start.line)) {
if (DEBUG) {
console.log(`Posting warning for ${filename}:${error.start.line}`);
}
warn(error.message, filename, error.start.line);
}
}
}
} catch (error) {
console.error('Error checking strict mode errors:', error);
const errorMessage = error instanceof Error ? error.message : String(error);
warn(
`⚠️ Strict mode check failed: ${errorMessage.split('\n')[0]}. Check CI logs for details.`,
);
}
}
schedule(checkStrictModeErrors());