-
Notifications
You must be signed in to change notification settings - Fork 291
/
Copy pathrun.ts
440 lines (387 loc) · 12.4 KB
/
run.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
import { exec, getExecOutput } from "@actions/exec";
import { GitHub, getOctokitOptions } from "@actions/github/lib/utils";
import * as github from "@actions/github";
import * as core from "@actions/core";
import fs from "fs-extra";
import { getPackages, Package } from "@manypkg/get-packages";
import path from "path";
import * as semver from "semver";
import { PreState } from "@changesets/types";
import {
getChangelogEntry,
getChangedPackages,
sortTheThings,
getVersionsByDirectory,
} from "./utils";
import * as gitUtils from "./gitUtils";
import readChangesetState from "./readChangesetState";
import resolveFrom from "resolve-from";
import { throttling } from "@octokit/plugin-throttling";
type ReleasedPackage = Package & { uploadUrl: string };
// GitHub Issues/PRs messages have a max size limit on the
// message body payload.
// `body is too long (maximum is 65536 characters)`.
// To avoid that, we ensure to cap the message to 60k chars.
const MAX_CHARACTERS_PER_MESSAGE = 60000;
const setupOctokit = (githubToken: string) => {
return new (GitHub.plugin(throttling))(
getOctokitOptions(githubToken, {
throttle: {
onRateLimit: (retryAfter, options: any, octokit, retryCount) => {
core.warning(
`Request quota exhausted for request ${options.method} ${options.url}`
);
if (retryCount <= 2) {
core.info(`Retrying after ${retryAfter} seconds!`);
return true;
}
},
onSecondaryRateLimit: (
retryAfter,
options: any,
octokit,
retryCount
) => {
core.warning(
`SecondaryRateLimit detected for request ${options.method} ${options.url}`
);
if (retryCount <= 2) {
core.info(`Retrying after ${retryAfter} seconds!`);
return true;
}
},
},
})
);
};
const createRelease = async (
octokit: ReturnType<typeof setupOctokit>,
{ pkg, tagName }: { pkg: Package; tagName: string }
) => {
try {
let changelogFileName = path.join(pkg.dir, "CHANGELOG.md");
let changelog = await fs.readFile(changelogFileName, "utf8");
let changelogEntry = getChangelogEntry(changelog, pkg.packageJson.version);
if (!changelogEntry) {
// we can find a changelog but not the entry for this version
// if this is true, something has probably gone wrong
throw new Error(
`Could not find changelog entry for ${pkg.packageJson.name}@${pkg.packageJson.version}`
);
}
return await octokit.rest.repos.createRelease({
name: tagName,
tag_name: tagName,
body: changelogEntry.content,
prerelease: pkg.packageJson.version.includes("-"),
...github.context.repo,
});
} catch (err) {
// if we can't find a changelog, the user has probably disabled changelogs
if (
err &&
typeof err === "object" &&
"code" in err &&
err.code !== "ENOENT"
) {
throw err;
}
}
};
type PublishOptions = {
script: string;
githubToken: string;
createGithubReleases: boolean;
cwd?: string;
};
type PublishedPackage = { name: string; version: string };
type PublishResult =
| {
published: true;
publishedPackages: PublishedPackage[];
}
| {
published: false;
};
export async function runPublish({
script,
githubToken,
createGithubReleases,
cwd = process.cwd(),
}: PublishOptions): Promise<PublishResult> {
const octokit = setupOctokit(githubToken);
let [publishCommand, ...publishArgs] = script.split(/\s+/);
let changesetPublishOutput = await getExecOutput(
publishCommand,
publishArgs,
{ cwd }
);
await gitUtils.pushTags();
let { packages, tool } = await getPackages(cwd);
let packagesToRelease: Package[] = [];
let releasedPackages: ReleasedPackage[] = [];
if (tool !== "root") {
let newTagRegex = /New tag:\s+(@[^/]+\/[^@]+|[^/]+)@([^\s]+)/;
let packagesByName = new Map(packages.map((x) => [x.packageJson.name, x]));
for (let line of changesetPublishOutput.stdout.split("\n")) {
let match = line.match(newTagRegex);
if (match === null) {
continue;
}
let pkgName = match[1];
let pkg = packagesByName.get(pkgName);
if (pkg === undefined) {
throw new Error(
`Package "${pkgName}" not found.` +
"This is probably a bug in the action, please open an issue"
);
}
packagesToRelease.push(pkg);
}
if (createGithubReleases) {
releasedPackages = (
await Promise.all(
packagesToRelease.map(async (pkg) => {
const release = await createRelease(octokit, {
pkg,
tagName: `${pkg.packageJson.name}@${pkg.packageJson.version}`,
});
if (release) {
return { ...pkg, uploadUrl: release.data.upload_url };
}
})
)
).filter((pkg) => pkg !== undefined);
}
} else {
if (packages.length === 0) {
throw new Error(
`No package found.` +
"This is probably a bug in the action, please open an issue"
);
}
let pkg = packages[0];
let newTagRegex = /New tag:/;
for (let line of changesetPublishOutput.stdout.split("\n")) {
let match = line.match(newTagRegex);
if (match) {
packagesToRelease.push(pkg);
if (createGithubReleases) {
const release = await createRelease(octokit, {
pkg,
tagName: `v${pkg.packageJson.version}`,
});
if (release) {
releasedPackages.push({
...pkg,
uploadUrl: release.data.upload_url,
});
}
}
break;
}
}
}
if (releasedPackages.length) {
return {
published: true,
publishedPackages: releasedPackages.map((pkg) => ({
name: pkg.packageJson.name,
version: pkg.packageJson.version,
uploadUrl: pkg.uploadUrl,
})),
};
}
return { published: false };
}
const requireChangesetsCliPkgJson = (cwd: string) => {
try {
return require(resolveFrom(cwd, "@changesets/cli/package.json"));
} catch (err) {
if (
err &&
typeof err === "object" &&
"code" in err &&
err.code === "MODULE_NOT_FOUND"
) {
throw new Error(
`Have you forgotten to install \`@changesets/cli\` in "${cwd}"?`
);
}
throw err;
}
};
type GetMessageOptions = {
hasPublishScript: boolean;
branch: string;
changedPackagesInfo: {
highestLevel: number;
private: boolean;
content: string;
header: string;
}[];
prBodyMaxCharacters: number;
preState?: PreState;
};
export async function getVersionPrBody({
hasPublishScript,
preState,
changedPackagesInfo,
prBodyMaxCharacters,
branch,
}: GetMessageOptions) {
let messageHeader = `This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and ${
hasPublishScript
? `the packages will be published to npm automatically`
: `publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing)`
}. If you're not ready to do a release yet, that's fine, whenever you add more changesets to ${branch}, this PR will be updated.
`;
let messagePrestate = !!preState
? `⚠️⚠️⚠️⚠️⚠️⚠️
\`${branch}\` is currently in **pre mode** so this branch has prereleases rather than normal releases. If you want to exit prereleases, run \`changeset pre exit\` on \`${branch}\`.
⚠️⚠️⚠️⚠️⚠️⚠️
`
: "";
let messageReleasesHeading = `# Releases`;
let fullMessage = [
messageHeader,
messagePrestate,
messageReleasesHeading,
...changedPackagesInfo.map((info) => `${info.header}\n\n${info.content}`),
].join("\n");
// Check that the message does not exceed the size limit.
// If not, omit the changelog entries of each package.
if (fullMessage.length > prBodyMaxCharacters) {
fullMessage = [
messageHeader,
messagePrestate,
messageReleasesHeading,
`\n> The changelog information of each package has been omitted from this message, as the content exceeds the size limit.\n`,
...changedPackagesInfo.map((info) => `${info.header}\n\n`),
].join("\n");
}
// Check (again) that the message is within the size limit.
// If not, omit all release content this time.
if (fullMessage.length > prBodyMaxCharacters) {
fullMessage = [
messageHeader,
messagePrestate,
messageReleasesHeading,
`\n> All release information have been omitted from this message, as the content exceeds the size limit.`,
].join("\n");
}
return fullMessage;
}
type VersionOptions = {
script?: string;
githubToken: string;
cwd?: string;
prTitle?: string;
commitMessage?: string;
hasPublishScript?: boolean;
prBodyMaxCharacters?: number;
branch?: string;
};
type RunVersionResult = {
pullRequestNumber: number;
};
export async function runVersion({
script,
githubToken,
cwd = process.cwd(),
prTitle = "Version Packages",
commitMessage = "Version Packages",
hasPublishScript = false,
prBodyMaxCharacters = MAX_CHARACTERS_PER_MESSAGE,
branch,
}: VersionOptions): Promise<RunVersionResult> {
const octokit = setupOctokit(githubToken);
let repo = `${github.context.repo.owner}/${github.context.repo.repo}`;
branch = branch ?? github.context.ref.replace("refs/heads/", "");
let versionBranch = `changeset-release/${branch}`;
let { preState } = await readChangesetState(cwd);
await gitUtils.switchToMaybeExistingBranch(versionBranch);
await gitUtils.reset(github.context.sha);
let versionsByDirectory = await getVersionsByDirectory(cwd);
if (script) {
let [versionCommand, ...versionArgs] = script.split(/\s+/);
await exec(versionCommand, versionArgs, { cwd });
} else {
let changesetsCliPkgJson = requireChangesetsCliPkgJson(cwd);
let cmd = semver.lt(changesetsCliPkgJson.version, "2.0.0")
? "bump"
: "version";
await exec("node", [resolveFrom(cwd, "@changesets/cli/bin.js"), cmd], {
cwd,
});
}
const existingPullRequestsPromise = octokit.rest.pulls.list({
...github.context.repo,
state: "open",
head: `${github.context.repo.owner}:${versionBranch}`,
base: branch,
});
let changedPackages = await getChangedPackages(cwd, versionsByDirectory);
let changedPackagesInfoPromises = Promise.all(
changedPackages.map(async (pkg) => {
let changelogContents = await fs.readFile(
path.join(pkg.dir, "CHANGELOG.md"),
"utf8"
);
let entry = getChangelogEntry(changelogContents, pkg.packageJson.version);
return {
highestLevel: entry.highestLevel,
private: !!pkg.packageJson.private,
content: entry.content,
header: `## ${pkg.packageJson.name}@${pkg.packageJson.version}`,
};
})
);
const finalPrTitle = `${prTitle}${!!preState ? ` (${preState.tag})` : ""}`;
// project with `commit: true` setting could have already committed files
if (!(await gitUtils.checkIfClean())) {
const finalCommitMessage = `${commitMessage}${
!!preState ? ` (${preState.tag})` : ""
}`;
await gitUtils.commitAll(finalCommitMessage);
}
await gitUtils.push(versionBranch, { force: true });
let existingPullRequests = await existingPullRequestsPromise;
core.info(JSON.stringify(existingPullRequests.data, null, 2));
const changedPackagesInfo = (await changedPackagesInfoPromises)
.filter((x) => x)
.sort(sortTheThings);
let prBody = await getVersionPrBody({
hasPublishScript,
preState,
branch,
changedPackagesInfo,
prBodyMaxCharacters,
});
if (existingPullRequests.data.length === 0) {
core.info("creating pull request");
const { data: newPullRequest } = await octokit.rest.pulls.create({
base: branch,
head: versionBranch,
title: finalPrTitle,
body: prBody,
...github.context.repo,
});
return {
pullRequestNumber: newPullRequest.number,
};
} else {
const [pullRequest] = existingPullRequests.data;
core.info(`updating found pull request #${pullRequest.number}`);
await octokit.rest.pulls.update({
pull_number: pullRequest.number,
title: finalPrTitle,
body: prBody,
...github.context.repo,
state: "open",
});
return {
pullRequestNumber: pullRequest.number,
};
}
}