-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
645 lines (596 loc) · 20.1 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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
import { Context, Probot } from "probot";
import { parse, query } from "kdljs";
import micromatch from "micromatch";
import path from "path";
import semver from "semver";
interface PackageVersions {
[path: string]: {
version: string;
changesets: Changesets;
};
}
interface Changesets {
added?: string[];
changed?: string[];
deprecated?: string[];
removed?: string[];
fixed?: string[];
security?: string[];
}
interface ChangesetNode {
name: "major" | "minor" | "patch";
values: string[];
properties: {
type: "added" | "changed" | "deprecated" | "removed" | "fixed" | "security";
package?: string;
};
}
export default (app: Probot) => {
// create issue if nanpa changesets exist
app.on("push", async (context) => {
const repo = context.repo();
const botLogin = (
await context.octokit.apps.getInstallation({
installation_id: context.payload.installation!.id,
})
).data.app_slug;
const baseBranch = (
await context.octokit.repos.get({
owner: repo.owner,
repo: repo.repo,
})
).data.default_branch;
if (context.payload.ref === "refs/heads/" + baseBranch) {
await setBody(context, repo, botLogin, undefined);
}
});
app.on("issue_comment.created", async (context) => {
const repo = context.repo();
const botLogin = (
await context.octokit.apps.getInstallation({
installation_id: context.payload.installation!.id,
})
).data.app_slug;
if (
context.payload.issue.user.login == botLogin + "[bot]" &&
context.payload.comment.user.login !== botLogin + "[bot]"
) {
try {
// Get existing defined prereleases
const prereleases = JSON.parse(
context.payload.issue.body!.match(
/<!-- ilo-prereleases: (.*) -->/,
)![1],
);
const messages: string[] = [];
// Get all lines from comment
const lines = context.payload.comment.body.split("\n");
lines.forEach((line) => {
const preHeader = /^ilo prerelease ([\d\w/_-]+)( [\d\w_-]+)?$/.exec(
line,
);
if (preHeader) {
if (preHeader[2]) {
preHeader[2] = preHeader[2].trim();
prereleases[preHeader[1]] = preHeader[2];
messages.push(
`Prerelease mode set to \`${preHeader[2]}\` for package ${preHeader[1]}.`,
);
} else {
delete prereleases[preHeader[1]];
messages.push(
`Prerelease mode disabled for package ${preHeader[1]}.`,
);
}
}
});
await setBody(context, repo, botLogin, prereleases);
// Comment changes
await context.octokit.issues.createComment({
owner: repo.owner,
repo: repo.repo,
issue_number: context.payload.issue.number,
body: messages.join("\n"),
});
} catch (error) {
console.error(error);
}
}
});
app.on("issues.closed", async (context) => {
const botLogin = (
await context.octokit.apps.getInstallation({
installation_id: context.payload.installation!.id,
})
).data.app_slug;
if (context.payload.issue.user.login == botLogin + "[bot]") {
try {
// Fetch the workflow id from the repository secrets
const repo = context.repo();
const workflow_id = await context.octokit.actions
.getRepoVariable({
owner: repo.owner,
repo: repo.repo,
name: "NANPA_WORKFLOW",
})
.then((value) => value.data.value);
if (workflow_id == "") {
context.log.error("NANPA_WORKFLOW secret is not set");
return;
}
// get packages to update
const packages = [
...context.payload.issue.body!.matchAll(/- \[x\] ([^\n ]+)\n?/g),
]
.map((x) => x.slice(1))
.flat();
if (packages.length == 0) return;
const inputs = {
packages: JSON.stringify(packages),
};
await context.octokit.actions.createWorkflowDispatch({
owner: context.payload.repository.owner.login,
repo: context.payload.repository.name,
workflow_id,
ref: context.payload.repository.default_branch,
inputs,
});
} catch (error) {
console.error(error);
}
}
});
app.on("pull_request.opened", async (context) => {
try {
const repo = context.repo();
const diff = await context.octokit.repos
.compareCommitsWithBasehead({
owner: repo.owner,
repo: repo.repo,
basehead: `${(context.payload.pull_request as any).base.sha}...${(context.payload.pull_request as any).head.sha}`,
})
.then((payload) => payload.data);
if (
diff.files &&
diff.files.some(
(file) => file.filename.endsWith(".kdl") && file.status === "added",
)
) {
return;
}
const body = `it seems like you haven't added any nanpa changeset files to this PR.
if this pull request includes changes to code, make sure to add a changeset, by writing a file to \`.nanpa/<unique-name>.kdl\`:
\`\`\`
minor type="added" "Introduce frobnication algorithm"
\`\`\`
refer to [the manpage](https://github.com/nbsp/nanpa/blob/master/doc/nanpa-changeset.5.scd) for more information.`;
await context.octokit.issues.createComment({
owner: repo.owner,
repo: repo.repo,
issue_number: (context.payload.pull_request as any).number,
body,
});
} catch (error) {
console.error(error)
}
});
};
async function setBody(
context: Context,
repo: { repo: never; owner: never },
botLogin: string,
prereleases?: { [id: string]: string },
) {
try {
const glob = "**/.nanparc";
const baseBranch = (
await context.octokit.repos.get({
owner: repo.owner,
repo: repo.repo,
})
).data.default_branch;
// show open issues by bot
const openIssues = await context.octokit.issues.listForRepo({
owner: repo.owner,
repo: repo.repo,
state: "open",
creator: botLogin + "[bot]",
});
if (prereleases === undefined) {
if (openIssues.data.length > 0) {
// get existing defined prereleases
prereleases = JSON.parse(
await context.octokit.issues
.get({
owner: repo.owner,
repo: repo.repo,
issue_number: openIssues.data[0].number,
})
.then(
(issue) =>
issue.data.body!.match(/<!-- ilo-prereleases: (.*) -->/)![1],
),
);
} else {
prereleases = {};
}
}
// list files
const tree = await context.octokit.git.getTree({
owner: repo.owner,
repo: repo.repo,
tree_sha: baseBranch,
recursive: "true",
});
// get all nanpa-defined projects
const filePaths = tree.data.tree
.map((file) => file.path)
.filter((x) => typeof x == "string");
const packages = [
...new Set(
micromatch(filePaths, glob).map((filePath) => {
if (filePath.startsWith(".nanparc")) return "";
return filePath.slice(0, filePath.length - "/.nanparc".length);
}),
),
];
let srcPackages: string[];
let superPackages: string[];
if (packages.length === 1) {
srcPackages = packages;
superPackages = [];
} else {
// only get packages that aren't superpackages
srcPackages = await Promise.all(
packages.map(async (pkg) => {
const packagePath = path.join(pkg, ".nanpa");
const matchedFiles = tree.data.tree.filter(
(x) =>
x.path &&
x.path.startsWith(packagePath) &&
x.path.endsWith(".kdl"),
);
// no local changesets
if (matchedFiles.length === 0) return pkg;
return (await matchedFiles.reduce(async (acc, file) => {
if (await acc) return true;
const content = await context.octokit.repos
.getContent({
owner: repo.owner,
repo: repo.repo,
tree_sha: baseBranch,
path: file.path!,
})
.then((result) => {
if (!("content" in result.data)) throw new Error();
return result.data.content;
})
.then((result) => Buffer.from(result, "base64").toString())
.then((content) => parse(content).output!);
return query(content, "[prop(package)]").length > 0;
}, Promise.resolve(false)))
? null
: pkg;
}),
).then((pkgs) => pkgs.filter((x): x is string => !!x));
superPackages = packages.filter((pkg) => !(pkg in srcPackages));
}
const updates = await srcPackages.reduce(
async (accPromise: Promise<PackageVersions>, pkg) => {
const acc = await accPromise;
let bump = 0;
const changesets: Changesets = {};
let version = /(?<=version +)[^\n ]+(?= *\n?)/.exec(
await context.octokit.repos
.getContent({
owner: repo.owner,
repo: repo.repo,
tree_sha: baseBranch,
path: path.join(pkg, ".nanparc"),
})
.then((result) => {
if (!("content" in result.data)) throw new Error();
return result.data.content;
})
.then((result) => Buffer.from(result, "base64").toString()),
)![0];
// get changesets from inside package
const packagePath = path.join(pkg, ".nanpa");
const matchedFiles = tree.data.tree.filter(
(x) =>
x.path && x.path.startsWith(packagePath) && x.path.endsWith(".kdl"),
);
for (const file of matchedFiles) {
const content = await context.octokit.repos
.getContent({
owner: repo.owner,
repo: repo.repo,
tree_sha: baseBranch,
path: file.path!,
})
.then((result) => {
if (!("content" in result.data)) throw new Error();
return result.data.content;
})
.then((result) => Buffer.from(result, "base64").toString())
.then((content) => parse(content).output!);
for (const node of query(content, "top()")[0]
.children as ChangesetNode[]) {
switch (node.name) {
case "major":
bump = 3;
break;
case "minor":
if (bump < 2) bump = 2;
break;
case "patch":
if (bump < 1) bump = 1;
break;
}
switch (node.properties.type) {
case "added":
if (!changesets.added) changesets.added = [];
changesets.added.push(node.values[0]);
break;
case "changed":
if (!changesets.changed) changesets.changed = [];
changesets.changed.push(node.values[0]);
break;
case "deprecated":
if (!changesets.deprecated) changesets.deprecated = [];
changesets.deprecated.push(node.values[0]);
break;
case "removed":
if (!changesets.removed) changesets.removed = [];
changesets.removed.push(node.values[0]);
break;
case "fixed":
if (!changesets.fixed) changesets.fixed = [];
changesets.fixed.push(node.values[0]);
break;
case "security":
if (!changesets.security) changesets.security = [];
changesets.security.push(node.values[0]);
break;
}
}
}
// get changesets from superpackages
for (const spkg of superPackages) {
const packagePath = path.join(spkg, ".nanpa");
const matchedFiles = tree.data.tree.filter(
(x) =>
x.path &&
x.path.startsWith(packagePath) &&
x.path.endsWith(".kdl"),
);
for (const file of matchedFiles) {
const content = await context.octokit.repos
.getContent({
owner: repo.owner,
repo: repo.repo,
tree_sha: baseBranch,
path: file.path!,
})
.then((result) => {
if (!("content" in result.data)) throw new Error();
return result.data.content;
})
.then((result) => Buffer.from(result, "base64").toString())
.then((content) => parse(content).output!);
for await (const node of query(content, "top()")[0]
.children as ChangesetNode[]) {
if (
!node.properties.package ||
path.join(spkg, node.properties.package) !== pkg
) {
continue;
}
switch (node.name) {
case "major":
bump = 3;
break;
case "minor":
if (bump < 2) bump = 2;
break;
case "patch":
if (bump < 1) bump = 1;
break;
}
switch (node.properties.type) {
case "added":
if (!changesets.added) changesets.added = [];
changesets.added.push(node.values[0]);
break;
case "changed":
if (!changesets.changed) changesets.changed = [];
changesets.changed.push(node.values[0]);
break;
case "deprecated":
if (!changesets.deprecated) changesets.deprecated = [];
changesets.deprecated.push(node.values[0]);
break;
case "removed":
if (!changesets.removed) changesets.removed = [];
changesets.removed.push(node.values[0]);
break;
case "fixed":
if (!changesets.fixed) changesets.fixed = [];
changesets.fixed.push(node.values[0]);
break;
case "security":
if (!changesets.security) changesets.security = [];
changesets.security.push(node.values[0]);
break;
}
}
}
}
const pkgName = `${repo.repo}${pkg === "" ? "" : `/${pkg}`}`;
// special flag that allows bumping prereleases even without changesets.
// 0.2.0-alpha.2 can be bumped to 0.2.0, or 0.2.0-beta.0, but *not* 0.2.0-alpha.3.
let bumpPre = false;
// bump version
switch (bump) {
case 0:
if (semver.prerelease(version)) {
if (prereleases && prereleases[pkgName]) {
if (semver.prerelease(version)![0] !== prereleases[pkgName]) {
bumpPre = true;
version = semver.inc(
version,
"prerelease",
prereleases[pkgName],
)!;
}
} else {
bumpPre = true;
version = semver.inc(version, "patch")!;
}
}
break;
case 1:
if (prereleases && prereleases[pkgName]) {
version = semver.inc(
version,
"prerelease",
prereleases[pkgName],
)!;
} else {
version = semver.inc(version, "patch")!;
}
break;
case 2:
if (prereleases && prereleases[pkgName]) {
if (semver.prerelease(version) && semver.patch(version) === 0) {
version = semver.inc(
version,
"prerelease",
prereleases[pkgName],
)!;
} else {
version = semver.inc(
version,
"preminor",
prereleases[pkgName],
)!;
}
} else {
version = semver.inc(version, "minor")!;
}
break;
case 3:
if (prereleases && prereleases[pkgName]) {
if (
semver.prerelease(version) &&
semver.minor(version) === 0 &&
semver.patch(version) === 0
) {
version = semver.inc(
version,
"prerelease",
prereleases[pkgName],
)!;
} else {
version = semver.inc(
version,
"premajor",
prereleases[pkgName],
)!;
}
} else {
version = semver.inc(version, "major")!;
}
break;
}
if (
!changesets.added &&
!changesets.changed &&
!changesets.deprecated &&
!changesets.fixed &&
!changesets.removed &&
!changesets.security &&
!bumpPre
) {
return acc;
}
acc[pkgName] = {
version,
changesets,
};
return acc;
},
Promise.resolve({}),
);
let title = `bump: ${Object.keys(updates).join(", ")}`;
let body =
`<!-- ilo-prereleases: ${JSON.stringify(prereleases)} -->\n` +
"ilo has detected nanpa changesets files and/or prereleased packages in this repository.\n" +
`choose which packages you wish to update from the checkboxes below, and close this issue to start a CI build on \`${baseBranch}\`.\n` +
"for more information, refer to the [nanpa](https://github.com/nbsp/nanpa) and [ilo](https://github.com/nbsp/ilo) repositories.\n\n";
Object.entries(updates).forEach((update) => {
const [name, { version, changesets }] = update;
body += `## ${name}@${version}\n\n`;
if (changesets.added) {
body += "### Added\n\n";
changesets.added.forEach((changeset) => (body += `- ${changeset}\n`));
}
if (changesets.changed) {
body += "### Changed\n\n";
changesets.changed.forEach((changeset) => (body += `- ${changeset}\n`));
}
if (changesets.deprecated) {
body += "### Deprecated\n\n";
changesets.deprecated.forEach(
(changeset) => (body += `- ${changeset}\n`),
);
}
if (changesets.fixed) {
body += "### Fixed\n\n";
changesets.fixed.forEach((changeset) => (body += `- ${changeset}\n`));
}
if (changesets.removed) {
body += "### Removed\n\n";
changesets.removed.forEach((changeset) => (body += `- ${changeset}\n`));
}
if (changesets.security) {
body += "### Security\n\n";
changesets.security.forEach(
(changeset) => (body += `- ${changeset}\n`),
);
}
});
body += "# Packages to update\n";
Object.entries(updates).forEach((update) => {
const [name, { version }] = update;
body += `- [x] ${name}@${version}\n`;
});
if (Object.entries(updates).length == 0) {
title = "bump: nothing staged";
body =
"<!-- ilo-prereleases: {} -->\n" +
"ilo could not detect nanpa changesets files in this repository. when you add some, you'll see them here.\n" +
"for more information, refer to the [nanpa](https://github.com/nbsp/nanpa) and [ilo](https://github.com/nbsp/ilo) repositories.";
}
if (openIssues.data.length > 0) {
await context.octokit.issues.update({
owner: repo.owner,
repo: repo.repo,
issue_number: openIssues.data[0].number,
title,
body,
});
} else {
if (Object.entries(updates).length > 0) {
await context.octokit.issues.create({
owner: repo.owner,
repo: repo.repo,
title,
body,
});
}
}
} catch (error) {
console.error(error);
}
}