-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.ts
More file actions
350 lines (304 loc) · 7.77 KB
/
utils.ts
File metadata and controls
350 lines (304 loc) · 7.77 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
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import assert from "node:assert";
import { parse as parseToml } from "jsr:@std/toml@1.0.2";
import {
format as formatSemVer,
increment as incrementSemVer,
parse as parseSemVer,
} from "jsr:@std/semver@1.0.4";
import { DOMParser } from "jsr:@b-fuze/deno-dom@0.1.49";
import { existsSync } from "node:fs";
export async function getReposWithIssueN(issueN: number) {
const issue = await fetch(
`https://github.com/zed-industries/extensions/issues/${issueN}`,
).then((response) => response.text()).then((text) =>
new DOMParser().parseFromString(text, "text/html")
);
const links = issue
.querySelector(".contains-task-list")
?.querySelectorAll("a");
assert(links);
const repos = [...links]
.map((element) => element.getAttribute("href"))
.filter((href) => !href?.includes("issues"))
.map((repo) => {
assert(repo);
const [user, name] = repo.split("/").slice(-2);
return { repo, user, name };
});
return repos;
}
export async function fetchRepo(repo: string) {
await run(["gh", "repo", "clone", repo]);
}
export async function getCurrentRepoInfo(user: string, name: string) {
const { stdout, success } = await run([
"gh",
"repo",
"view",
`${user}/${name}`,
"--json",
"name,owner",
]);
if (!success) {
throw new Error(`Failed to get repo info for ${user}/${name}`);
}
const repoData = JSON.parse(stdout);
return { owner: repoData.owner.login, name: repoData.name };
}
export async function run(cmd: string[], options = {}) {
console.log(`Running: ${cmd.join(" ")}`);
const process = new Deno.Command(cmd[0], {
args: cmd.slice(1),
...options,
});
const { stdout, stderr, success } = await process.output();
if (!success) {
console.error("Command failed:");
console.error(new TextDecoder().decode(stderr));
}
return {
success,
stdout: new TextDecoder().decode(stdout),
stderr: new TextDecoder().decode(stderr),
};
}
export async function getGitHubUsername() {
// Get current user from gh cli
const { stdout, success } = await run([
"gh",
"api",
"user",
"--jq",
".login",
]);
if (!success) {
throw new Error("Failed to get GitHub username");
}
return stdout.trim();
}
export function bumpVersion(name: string) {
const tomlConfigPath = `${name}/extension.toml`;
const jsonConfigPath = `${name}/extension.json`;
if (existsSync(tomlConfigPath)) {
let tomlFile = Deno.readTextFileSync(tomlConfigPath);
const tomlConfig = parseToml(tomlFile);
const newVersion = formatSemVer(incrementSemVer(
parseSemVer(tomlConfig.version as string),
"patch",
));
tomlFile = tomlFile.replace(
/version = "[^"]+"/,
`version = "${newVersion}"`,
);
Deno.writeTextFileSync(tomlConfigPath, tomlFile);
return;
}
if (existsSync(jsonConfigPath)) {
let jsonFile = Deno.readTextFileSync(jsonConfigPath);
const jsonConfig = JSON.parse(jsonFile);
const newVersion = formatSemVer(incrementSemVer(
parseSemVer(jsonConfig.version),
"patch",
));
jsonFile = jsonFile.replace(
/"version": "[^"]+"/,
`"version": "${newVersion}"`,
);
Deno.writeTextFileSync(jsonConfigPath, jsonFile);
return;
}
}
export async function retry(fn: () => Promise<void>) {
while (true) {
try {
await fn();
return;
} catch (e) {
console.log("error", e);
if (!confirm("Do you want to retry ? ")) {
return;
}
}
}
}
export async function correctRepoInfo(
repo: { repo: string; user: string; name: string },
) {
// Get the *current* repository name using gh repo view
const repoInfo = await getCurrentRepoInfo(
repo.user,
repo.name.replace(/\.git$/, ""), /* github strips .git */
);
return {
repo: repo.repo,
user: repoInfo.owner,
// Update the repo object with the CORRECTED name
name: repoInfo.name,
};
}
export async function getExistingPR(
user: string,
repo: string,
username: string,
): Promise<string | null> {
const { stdout, success } = await run([
"gh",
"pr",
"list",
"--repo",
`${user}/${repo}`,
"--author",
username,
"--json",
"number,headRefName",
]);
if (!success) {
console.error(`Failed to check for open PRs for ${user}/${repo}`);
return null;
}
const prs = JSON.parse(stdout);
if (prs.length === 0) return null;
// Return the branch name for the existing PR
return prs[0].headRefName;
}
export function createWorkDir() {
const path = `${Deno.cwd()}/work`;
try {
Deno.removeSync(path, { recursive: true });
} catch { /* ignore */ }
Deno.mkdirSync(path);
return path;
}
export function switchDirTemp(dir: string) {
const originalDir = Deno.cwd();
Deno.chdir(dir);
return {
[Symbol.dispose]() {
Deno.chdir(originalDir);
},
};
}
export async function openPR(
{
repoUser: user,
repoName: name,
botUsername: username,
commitMsg,
prTitle,
prBody,
}: {
repoUser: string;
repoName: string;
botUsername: string;
commitMsg: string;
prTitle: string;
prBody: string;
},
) {
console.log(`Opening PR for ${name}`);
// Create a branch name
const branchName = `update-attr-${Date.now()}`;
// Change directory to the cloned repo
using _ = switchDirTemp(name);
// git diff
{
const { stdout, stderr } = await run(["git", "diff"]);
console.log(stdout, stderr);
}
// Fork the repository *before* any git operations
await run(["gh", "repo", "fork", `${user}/${name}`, "--remote=false"]); // --remote=false is important here!
// Add a remote for *your* fork
await run([
"git",
"remote",
"add",
"fork",
`https://github.com/${username}/${name}.git`,
]);
// Create a new branch
await run(["git", "checkout", "-b", branchName]);
// Add the changed files
await run(["git", "add", "."]);
// Commit the changes
const commitResult = await run([
"git",
"commit",
"-m",
commitMsg,
]);
if (!commitResult.success) {
console.log("Nothing to commit, skipping PR creation");
return;
}
// Push to the *fork* remote
await run(["git", "push", "-u", "fork", branchName]);
// Create a PR using gh cli
const prResult = await run([
"gh",
"pr",
"create",
"--title",
prTitle,
"--body",
prBody,
"--repo",
`${user}/${name}`,
]);
if (prResult.success) {
const prUrl = prResult.stdout.trim().split("\n")[0];
console.log(`Pull request created: ${prUrl}`);
}
}
export async function fetchPrAndSetupBranch(
{ repoName: name, branchName, botUsername }: {
repoName: string;
branchName: string;
botUsername: string;
},
) {
console.log(`Updating PR for ${name}`);
using _ = switchDirTemp(name);
// Add a remote for *your* fork
await run([
"git",
"remote",
"add",
"fork",
`https://github.com/${botUsername}/${name}.git`,
]);
// Fetch from the fork to get the branch
await run(["git", "fetch", "fork"]);
// Checkout the existing branch
await run(["git", "checkout", `fork/${branchName}`]);
}
export async function updatePr(
{ repoUser, repoName, branchName, commitMsg }: {
repoUser: string;
repoName: string;
branchName: string;
commitMsg: string;
},
) {
using _ = switchDirTemp(repoName);
// git diff
{
const { stdout, stderr } = await run(["git", "diff"]);
console.log(stdout, stderr);
}
// Add the changed files
await run(["git", "add", "."]);
// Commit the changes
const commitResult = await run([
"git",
"commit",
"-m",
commitMsg,
]);
if (!commitResult.success) {
console.log("Nothing to commit, skipping PR creation");
return;
}
// Push to the *fork* remote
await run(["git", "push", "-u", "fork", branchName]);
console.log(`Updated PR branch for ${repoUser}/${repoName}`);
}