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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
|
import { getRepoPath, getDefaultBranch } from "../git/repository";
export interface RepairResult {
repaired: boolean;
repairs: Repair[];
commitSha: string | null;
}
export interface Repair {
file: string;
type: string;
description: string;
linesChanged: number;
}
async function exec(
cmd: string[],
cwd: string,
stdin?: string
): Promise<{ stdout: string; exitCode: number }> {
const proc = Bun.spawn(cmd, {
cwd,
stdout: "pipe",
stderr: "pipe",
stdin: stdin !== undefined ? "pipe" : undefined,
env: {
...process.env,
GIT_AUTHOR_NAME: "gluecron[bot]",
GIT_AUTHOR_EMAIL: "bot@gluecron.com",
GIT_COMMITTER_NAME: "gluecron[bot]",
GIT_COMMITTER_EMAIL: "bot@gluecron.com",
},
});
if (stdin !== undefined && proc.stdin) {
proc.stdin.write(new TextEncoder().encode(stdin));
proc.stdin.end();
}
const stdout = await new Response(proc.stdout).text();
const exitCode = await proc.exited;
return { stdout: stdout.trim(), exitCode };
}
export async function autoRepair(
owner: string,
repo: string,
ref: string
): Promise<RepairResult> {
const repoDir = getRepoPath(owner, repo);
const repairs: Repair[] = [];
const { stdout: fileList } = await exec(
["git", "ls-tree", "-r", "--name-only", ref],
repoDir
);
const files = fileList.split("\n").filter(Boolean);
const modifications: Map<string, string> = new Map();
const gitignoreFile = files.find((f) => f === ".gitignore");
if (gitignoreFile) {
const { stdout: content } = await exec(
["git", "show", `${ref}:.gitignore`],
repoDir
);
const essentialEntries = [
"node_modules/",
".env",
".env.local",
".DS_Store",
"dist/",
];
const lines = content.split("\n");
const missing = essentialEntries.filter(
(entry) => !lines.some((l) => l.trim() === entry)
);
if (missing.length > 0) {
const newContent = content.trimEnd() + "\n\n# Auto-added by gluecron\n" + missing.join("\n") + "\n";
modifications.set(".gitignore", newContent);
repairs.push({
file: ".gitignore",
type: "gitignore",
description: `Added missing entries: ${missing.join(", ")}`,
linesChanged: missing.length,
});
}
} else if (files.includes("package.json")) {
const newContent = `# Auto-generated by gluecron
node_modules/
dist/
.env
.env.local
.env.*.local
*.log
.DS_Store
coverage/
.cache/
`;
modifications.set(".gitignore", newContent);
repairs.push({
file: ".gitignore",
type: "gitignore",
description: "Created .gitignore with standard entries",
linesChanged: 10,
});
}
const textExtensions = /\.(ts|tsx|js|jsx|json|md|txt|yaml|yml|toml|css|html|py|rb|go|rs|java|sh|sql)$/;
const textFiles = files.filter((f) => textExtensions.test(f)).slice(0, 50);
for (const filePath of textFiles) {
const { stdout: content, exitCode } = await exec(
["git", "show", `${ref}:${filePath}`],
repoDir
);
if (exitCode !== 0) continue;
let modified = content;
let changes = 0;
const lines = modified.split("\n");
const trimmed = lines.map((line) => {
const trimmedLine = line.replace(/[\t ]+$/, "");
if (trimmedLine !== line) changes++;
return trimmedLine;
});
modified = trimmed.join("\n");
if (modified.length > 0 && !modified.endsWith("\n")) {
modified += "\n";
changes++;
}
if (modified !== content) {
modifications.set(filePath, modified);
repairs.push({
file: filePath,
type: "whitespace",
description: `Fixed ${changes} whitespace issue${changes > 1 ? "s" : ""}`,
linesChanged: changes,
});
}
}
for (const filePath of textFiles) {
if (filePath.includes("test") || filePath.includes("spec")) continue;
if (filePath.endsWith(".md") || filePath.endsWith(".txt")) continue;
const existing = modifications.get(filePath);
const { stdout: rawContent } = await exec(
["git", "show", `${ref}:${filePath}`],
repoDir
);
const content = existing || rawContent;
let modified = content;
let secretsFound = 0;
modified = modified.replace(
/((?:AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16})/g,
(match) => {
secretsFound++;
return "process.env.AWS_ACCESS_KEY_ID";
}
);
if (secretsFound > 0 && modified !== content) {
modifications.set(filePath, modified);
repairs.push({
file: filePath,
type: "secret-masking",
description: `Masked ${secretsFound} hardcoded secret${secretsFound > 1 ? "s" : ""}`,
linesChanged: secretsFound,
});
}
}
const jsonFiles = files.filter((f) => f.endsWith(".json")).slice(0, 20);
for (const filePath of jsonFiles) {
const existing = modifications.get(filePath);
const { stdout: rawContent } = await exec(
["git", "show", `${ref}:${filePath}`],
repoDir
);
const content = existing || rawContent;
try {
JSON.parse(content);
} catch {
let fixed = content;
fixed = fixed.replace(/,(\s*[}\]])/g, "$1");
try {
const parsed = JSON.parse(fixed);
const reformatted = JSON.stringify(parsed, null, 2) + "\n";
modifications.set(filePath, reformatted);
repairs.push({
file: filePath,
type: "json-fix",
description: "Fixed JSON syntax (trailing commas, formatting)",
linesChanged: 1,
});
} catch {
}
}
}
if (modifications.size === 0) {
return { repaired: false, repairs: [], commitSha: null };
}
const { stdout: currentTree } = await exec(
["git", "ls-tree", "-r", ref],
repoDir
);
const treeEntries = currentTree.split("\n").filter(Boolean);
const modifiedPaths = new Set(modifications.keys());
const newEntries: string[] = [];
for (const entry of treeEntries) {
const match = entry.match(/^(\d+) (\w+) ([0-9a-f]+)\t(.+)$/);
if (!match) continue;
const [, mode, type, sha, path] = match;
if (modifiedPaths.has(path)) {
const newContent = modifications.get(path)!;
const { stdout: newBlobSha } = await exec(
["git", "hash-object", "-w", "--stdin"],
repoDir,
newContent
);
newEntries.push(`${mode} blob ${newBlobSha}\t${path}`);
modifiedPaths.delete(path);
} else {
newEntries.push(entry);
}
}
for (const path of modifiedPaths) {
const content = modifications.get(path)!;
const { stdout: blobSha } = await exec(
["git", "hash-object", "-w", "--stdin"],
repoDir,
content
);
newEntries.push(`100644 blob ${blobSha}\t${path}`);
}
const treeInput = newEntries.join("\n") + "\n";
const { stdout: newTreeSha } = await exec(
["git", "mktree"],
repoDir,
treeInput
);
const { stdout: parentSha } = await exec(
["git", "rev-parse", ref],
repoDir
);
const repairSummary = repairs
.map((r) => `- ${r.file}: ${r.description}`)
.join("\n");
const commitMsg = `fix: auto-repair by gluecron\n\n${repairs.length} automatic repair${repairs.length > 1 ? "s" : ""}:\n${repairSummary}\n\nThis commit was created automatically by gluecron's repair engine.`;
const { stdout: commitSha } = await exec(
["git", "commit-tree", newTreeSha, "-p", parentSha, "-m", commitMsg],
repoDir
);
await exec(
["git", "update-ref", `refs/heads/${ref}`, commitSha],
repoDir
);
console.log(
`[autorepair] ${owner}/${repo}@${ref}: ${repairs.length} repairs committed as ${commitSha.slice(0, 7)}`
);
return { repaired: true, repairs, commitSha };
}
|