-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathget-changed-packages.ts
More file actions
320 lines (285 loc) · 9 KB
/
Copy pathget-changed-packages.ts
File metadata and controls
320 lines (285 loc) · 9 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
import nodePath from "path";
import { assembleReleasePlan } from "@changesets/assemble-release-plan";
import { validateConfig } from "@changesets/config";
import { parseChangesetFile } from "@changesets/parse";
import type {
NewChangeset,
Package,
Packages,
PreState,
WrittenConfig,
PackageJSON as ChangesetPackageJSON,
} from "@changesets/types";
import micromatch from "micromatch";
import type { ProbotOctokit } from "probot";
import subset from "semver/ranges/subset.js";
import * as yaml from "yaml";
import { isChangeset } from "./is-changeset.ts";
interface PackageJSON extends ChangesetPackageJSON {
workspaces?: ReadonlyArray<string> | { packages: ReadonlyArray<string> };
bolt?: { workspaces: ReadonlyArray<string> };
}
interface PnpmWorkspace {
packages: ReadonlyArray<string>;
}
type ToolType = Packages["tool"]["type"];
/** Expected validation failures that should be surfaced in the PR comment. */
export class UserValidationError extends Error {}
const changesetsV2Range = ">=2.0.0 <3.0.0";
function isChangesetsV2Range(declaredVersion: string | undefined) {
if (declaredVersion === undefined) {
return false;
}
try {
return subset(declaredVersion, changesetsV2Range);
} catch {
return false;
}
}
function getReleasePlanConfig(
rawConfig: WrittenConfig & { prettier?: unknown },
rootPackageJsonContent: PackageJSON,
): WrittenConfig {
// The bot only calculates a release plan, so options used exclusively for formatting,
// writing files, Git comparisons, publishing, and snapshots are intentionally ignored.
const {
access: _access,
baseBranch: _baseBranch,
changedFilePatterns: _changedFilePatterns,
changelog: _changelog,
commit: _commit,
format: _format,
prettier: _prettier,
snapshot: _snapshot,
...releasePlanConfig
} = rawConfig;
const declaredChangesetsVersion =
rootPackageJsonContent.devDependencies?.["@changesets/cli"] ??
rootPackageJsonContent.dependencies?.["@changesets/cli"];
if (!isChangesetsV2Range(declaredChangesetsVersion)) {
return releasePlanConfig;
}
const privatePackages = rawConfig.privatePackages;
if (!("privatePackages" in rawConfig)) {
return { ...releasePlanConfig, privatePackages: { version: true } };
}
if (privatePackages === true) {
throw new UserValidationError(
"The `privatePackages` option can only be `false` or an object when using Changesets v2.",
);
}
// Changesets v2 defaulted an omitted `version` to `true` even inside the object form.
// Only adapt that valid shape; invalid values must pass through to `validateConfig`.
if (
typeof privatePackages === "object" &&
privatePackages !== null &&
!Array.isArray(privatePackages) &&
!("version" in privatePackages)
) {
return {
...releasePlanConfig,
privatePackages: { version: true, ...privatePackages },
};
}
return releasePlanConfig;
}
// TODO: it might be possible to remove this if improvements to `Array.isArray` ever land
// related thread: github.com/microsoft/TypeScript/issues/36554
function isArray<T>(
arg: T | {},
): arg is T extends ReadonlyArray<any>
? unknown extends T
? never
: ReadonlyArray<any>
: Array<any> {
return Array.isArray(arg);
}
export const getChangedPackages = async ({
owner,
repo,
ref,
changedFiles: changedFilesPromise,
octokit,
installationToken,
}: {
owner: string;
repo: string;
ref: string;
changedFiles: ReadonlyArray<string> | Promise<ReadonlyArray<string>>;
octokit: InstanceType<typeof ProbotOctokit>;
installationToken: string;
}) => {
let hasErrored = false;
const encodedCredentials = Buffer.from(`x-access-token:${installationToken}`).toString("base64");
function fetchFile(path: string) {
return fetch(`https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${path}`, {
headers: {
Authorization: `Basic ${encodedCredentials}`,
},
});
}
async function fetchJsonFile<T>(path: string): Promise<T> {
try {
const x = await fetchFile(path);
return x.json() as Promise<T>;
} catch (error) {
hasErrored = true;
console.error(error);
return {} as Promise<T>;
}
}
async function fetchTextFile(path: string): Promise<string> {
try {
const x = await fetchFile(path);
return x.text();
} catch (err) {
hasErrored = true;
console.error(err);
return "";
}
}
async function getPackage(pkgPath: string): Promise<{ dir: string; packageJson: PackageJSON }> {
const jsonContent = await fetchJsonFile(pkgPath + "/package.json");
return {
dir: pkgPath,
packageJson: jsonContent as PackageJSON,
};
}
const rootPackageJsonContentsPromise: Promise<PackageJSON> = fetchJsonFile("package.json");
const rawConfigPromise: Promise<WrittenConfig> = fetchJsonFile(".changeset/config.json");
const tree = await octokit.git.getTree({
owner,
repo,
recursive: "1",
tree_sha: ref,
});
let preStatePromise: Promise<PreState> | undefined;
const changesetPromises: Array<Promise<NewChangeset>> = [];
const potentialWorkspaceDirectories: Array<string> = [];
let isPnpm = false;
const changedFiles = await changedFilesPromise;
for (const item of tree.data.tree) {
if (!item.path) {
continue;
}
if (nodePath.basename(item.path) === "package.json") {
const dirPath = nodePath.dirname(item.path);
potentialWorkspaceDirectories.push(dirPath);
} else if (item.path === "pnpm-workspace.yaml") {
isPnpm = true;
} else if (item.path === ".changeset/pre.json") {
preStatePromise = fetchJsonFile(".changeset/pre.json");
} else if (changedFiles.includes(item.path) && isChangeset(item.path)) {
const res = /\.changeset\/([^.]+)\.md/.exec(item.path);
if (!res) {
throw new Error("could not get name from changeset filename");
}
const id = res[1];
changesetPromises.push(
fetchTextFile(item.path).then((text) => {
try {
return {
...parseChangesetFile(text),
id,
};
} catch (error) {
throw new UserValidationError(Error.isError(error) ? error.message : String(error), {
cause: error,
});
}
}),
);
}
}
let tool:
| {
type: ToolType;
globs: ReadonlyArray<string>;
}
| undefined;
if (isPnpm) {
const pnpmWorkspaceContent = await fetchTextFile("pnpm-workspace.yaml");
const pnpmWorkspace = yaml.parse(pnpmWorkspaceContent) as PnpmWorkspace;
if (pnpmWorkspace.packages) {
tool = {
type: "pnpm",
globs: pnpmWorkspace.packages,
};
}
} else {
const rootPackageJsonContent = await rootPackageJsonContentsPromise;
if (rootPackageJsonContent.workspaces) {
if (isArray(rootPackageJsonContent.workspaces)) {
tool = {
type: "yarn",
globs: rootPackageJsonContent.workspaces,
};
} else {
tool = {
type: "yarn",
globs: rootPackageJsonContent.workspaces.packages,
};
}
} else if (rootPackageJsonContent.bolt && rootPackageJsonContent.bolt.workspaces) {
tool = {
type: "bolt",
globs: rootPackageJsonContent.bolt.workspaces,
};
}
}
const rootPackageJsonContent = await rootPackageJsonContentsPromise;
const rootPackage: Package = {
dir: "/",
packageJson: rootPackageJsonContent,
};
const packages: Packages = {
rootDir: "/",
rootPackage,
tool: { type: tool ? tool.type : "root" },
packages: [],
};
if (tool) {
if (
!Array.isArray(tool.globs) ||
!tool.globs.every((glob: unknown) => typeof glob === "string")
) {
throw new Error("globs are not valid: " + JSON.stringify(tool.globs));
}
const matches = micromatch(potentialWorkspaceDirectories, tool.globs);
packages.packages = await Promise.all(matches.map((dir) => getPackage(dir)));
} else {
packages.packages.push(rootPackage);
}
if (hasErrored) {
throw new Error("an error occurred when fetching files");
}
const rawConfig = await rawConfigPromise;
const configResult = validateConfig(
getReleasePlanConfig(rawConfig, rootPackageJsonContent),
packages,
);
if (configResult.errors) {
throw new UserValidationError(
"Some errors occurred when validating the changesets config:\n" +
configResult.errors.join("\n"),
);
}
const releasePlan = assembleReleasePlan(
await Promise.all(changesetPromises),
packages,
configResult.config,
await preStatePromise,
);
// A root-only project has a single package covering the whole repository,
// so there is no directory to narrow the changed files down to.
const changedPackages =
packages.tool.type === "root"
? packages.packages
: packages.packages.filter((pkg) =>
changedFiles.some((changedFile) => changedFile.startsWith(`${pkg.dir}/`)),
);
return {
changedPackages: changedPackages.map((pkg) => pkg.packageJson.name),
releasePlan,
};
};