forked from Comfy-Org/Comfy-PR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
314 lines (281 loc) · 8.74 KB
/
index.ts
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
#!/usr/bin/env bun
import { $ as bunSh } from "bun";
import "dotenv/config";
import { readFile, rm } from "fs/promises";
import md5 from "md5";
import { basename, dirname } from "path";
import yaml from "yaml";
import { chalk, os, question, $ as zx } from "zx";
import { DIE } from "./DIE";
import { $ } from "./echoBunShell";
import { gh } from "./scripts/gh";
zx.verbose = true;
// read env/parameters
console.log("Fetch Current Github User...");
const user = (await gh.users.getAuthenticated()).data;
const GIT_USERNAME =
process.env.GIT_USERNAME ||
(user.email && user.name) ||
(await question("Input env.GIT_USERNAME: ")) ||
DIE("Missing env.GIT_USERNAME");
const GIT_USEREMAIL =
process.env.GIT_USEREMAIL ||
(user.email && user.email) ||
(await question("Input env.GIT_USEREMAIL: ")) ||
DIE("Missing env.GIT_USEREMAIL");
const FORK_OWNER =
process.env.FORK_OWNER?.replace(/"/g, "")?.trim() ||
user.name ||
(await question(
"Input env.FORK_OWNER (for example FORK_OWNER=ComfyNodePRs, will fork into https://github.com/ComfyNodePRs): "
)) ||
DIE("Missing env.FORK_OWNER");
const FORK_PREFIX =
(process.env.FORK_PREFIX?.replace(/"/g, "")?.trim() ||
(await question(
"Input env.FORK_PREFIX ('PR-' is Recommened, but also it could be empty): "
))) ??
DIE('Missing env.FORK_PREFIX, if you want empty maybe try FORK_PREFIX=""');
const upstreamUrl =
process.env.REPO ||
(await question("Input the PR target env.REPO: ")) ||
DIE("Missing env.REPO");
const activate =
os.platform() === "win32" ? ".venv\\Scripts\\activate" : ".venv/bin/activate";
if (!(await bunSh`comfy --help`.quiet().catch(() => null))) {
DIE(
`
Cound not found comfy-cli.
Please install comfy-cli before run "bunx comfy-pr" here.
$ >>>>>>>>>>>>>>>>>>>>>>>>>>
python -m venv .venv
${activate}
pip install comfy-cli
comfy-cli --help
`.trim()
);
}
console.log("GIT_USER: ", user.name, user.email);
// main
{
await ComfyRegistryPR();
// todo: build and publish to npm
}
async function ComfyRegistryPR() {
// Repo Define
const upstream = parseOwnerRepo(upstreamUrl);
const salt = process.env.SALT || "m3KMgZ2AeZGWYh7W";
console.log(`* Change env.SALT=${salt} will fork into a different repo`);
const repo_hash = md5(
`${salt}-${user.name}-${upstream.owner}/${upstream.repo}`
).slice(0, 8);
const forkRepoName =
(FORK_PREFIX && `${FORK_PREFIX}${upstream.repo}-${repo_hash}`) ||
upstream.repo;
const forkDst = `${FORK_OWNER}/${forkRepoName}`;
const forkSSHUrl = `[email protected]:${forkDst}`;
const forkHTTPSUrl = `https://github.com/${forkDst}`;
const src = parseOwnerRepo(forkSSHUrl);
// console.log("PR_SRC: ", forkSSHUrl);
// console.log("PR_DST: ", upstreamUrl);
// console.log(forkSSHUrl);
console.log("Cleaning the pr before run");
const dir = `prs/${src.repo}`;
await rm(dir, { recursive: true }).catch(() => null);
// const choose = await question(
// `
// Prepare to fork...
// From: ${upstreamUrl}
// To: ${forkHTTPSUrl}
// Are you ready to fork (y/N)?
// `.trim()
// );
// choose.match(/y/i) || DIE("User Aborted");
// FORK
await fork(upstream, src);
// prInfos
const PR_REQUESTS = (
await Promise.all([
add_publish(dir, upstreamUrl, forkSSHUrl),
add_pyproject(dir, upstreamUrl, forkSSHUrl),
])
).map((content) => ({ ...content, src, dst: upstream }));
console.log("PR Infos");
console.log(chalk.green(yaml.stringify({ PR_REQUESTS })));
// prs
await Promise.all(PR_REQUESTS.map((prInfo) => pr({ ...prInfo })));
console.log("ALL DONE");
}
async function pr({
title,
body,
branch,
src,
dst,
}: {
title: string;
body: string;
branch: string;
src: { owner: string; repo: string };
dst: { owner: string; repo: string };
}) {
const repo = (await gh.repos.get({ ...dst })).data;
// TODO: seems has bugs on head_repo
const existedList = (
await gh.pulls.list({
// source repo
state: "all",
head_repo: src.owner + "/" + src.repo,
head: src.owner + ":" + branch,
// pr will merge into
owner: dst.owner,
repo: dst.repo,
base: repo.default_branch,
})
).data;
if (existedList.length) {
const msg = {
PR_Existed: existedList.map((e) => ({ url: e.html_url, title: e.title })),
};
console.log(chalk.red(yaml.stringify(msg)));
return;
}
const pr_result = await gh.pulls
.create({
// pr info
title,
body,
// source repo
head_repo: src.owner + "/" + src.repo,
head: src.owner + ":" + branch,
// pr will merge into
owner: dst.owner,
repo: dst.repo,
base: repo.default_branch,
maintainer_can_modify: true,
// draft: true,
})
.catch(async (e) => {
if (e.message.match("A pull request already exists for")) {
console.log("PR Existed ", e);
// WARN: will search all prs
const existedList = (
await gh.pulls.list({
// source repo
state: "open",
head_repo: src.owner + "/" + src.repo,
// head: src.owner + ":" + branch,
// pr will merge into
owner: dst.owner,
repo: dst.repo,
base: repo.default_branch,
})
).data;
if (existedList.length) {
const msg = {
PR_Existed: existedList.map((e) => ({
url: e.html_url,
title: e.title,
})),
};
console.log(chalk.red(yaml.stringify(msg)));
return;
}
return null;
}
throw e;
});
console.log("PR OK", pr_result?.data.html_url);
}
async function add_pyproject(
dir: string,
upstreamUrl: string,
forkUrl: string
) {
const branch = "pyproject";
const tmpl = await readFile("./templates/add-toml.md", "utf8");
const { title, body } = parseTitleBodyOfMarkdown(tmpl);
const repo = parseOwnerRepo(forkUrl);
if (await gh.repos.getBranch({ ...repo, branch }).catch(() => null)) {
console.log("Skip changes as branch existed: " + branch);
return { title, body, branch };
}
const src = parseOwnerRepo(upstreamUrl);
const cwd = `${dir}/${branch}/${src.repo}`; // src.repo is for keep correct directory name
// commit changes
await $`
git clone ${upstreamUrl} ${cwd}
cd ${cwd}
echo N | comfy node init
git config user.name ${GIT_USERNAME} && \
git config user.email ${GIT_USEREMAIL} && \
git checkout -b ${branch} && \
git add . && \
git commit -am ${`chore(${branch}): ${title}`} && \
git push "${forkUrl}" ${branch}:${branch}
`;
const branchUrl = `https://github.com/${repo.owner}/${repo.repo}/tree/${branch}`;
console.log(`Branch Push OK: ${branchUrl}`);
return { title, body, branch };
}
async function add_publish(dir: string, upstreamUrl: string, forkUrl: string) {
const branch = "publish";
const tmpl = await readFile("./templates/add-action.md", "utf8");
const { title, body } = parseTitleBodyOfMarkdown(tmpl);
const repo = parseOwnerRepo(forkUrl);
if (await gh.repos.getBranch({ ...repo, branch }).catch(() => null)) {
console.log("Skip changes as branch existed: " + branch);
return { title, body, branch };
}
const src = parseOwnerRepo(upstreamUrl);
const cwd = `${dir}/${branch}/${src.repo}`; // src.repo is for keep correct directory name
const file = `${cwd}/.github/workflows/publish.yml`;
const publishYmlPath = "./templates/publish.yaml";
// commit & push changes
await $`
git clone ${upstreamUrl} ${cwd}
mkdir -p ${dirname(file)}
cat ${publishYmlPath} > ${file}
cd ${cwd}
git config user.name ${GIT_USERNAME} && \
git config user.email ${GIT_USEREMAIL} && \
git checkout -b ${branch} && \
git add . && \
git commit -am "chore(${branch}): ${title}" && \
git push "${forkUrl}" ${branch}:${branch}
`;
const branchUrl = `https://github.com/${repo.owner}/${repo.repo}/tree/${branch}`;
console.log(`Branch Push OK: ${branchUrl}`);
return { title, body, branch };
}
async function fork(
from: { owner: string; repo: string },
to: { owner: string; repo: string }
) {
const forkResult = await gh.repos
.createFork({
...(user.name !== to.owner && { organization: to.owner }),
name: to.repo,
owner: from.owner,
repo: from.repo,
})
.catch((e) => {
if (e.message.match("Name already exists on this account")) return null;
throw e;
});
const forkedUrl =
forkResult?.data.html_url ??
"https://github.com/" + to.owner + "/" + to.repo;
console.log("FORK OK ", forkedUrl);
}
function parseOwnerRepo(name: string) {
return {
owner: basename(dirname(name.replace(/:/, "/"))),
repo: basename(name.replace(/:/, "/")),
};
}
function parseTitleBodyOfMarkdown(tmpl: string) {
const title = tmpl.split("\n")[0].slice(1).trim();
const body = tmpl.split("\n").slice(1).join("\n").trim();
return { title, body };
}