-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathget-changed-packages.ts
More file actions
224 lines (202 loc) · 6.17 KB
/
Copy pathget-changed-packages.ts
File metadata and controls
224 lines (202 loc) · 6.17 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
import nodePath from "path";
import assembleReleasePlan from "@changesets/assemble-release-plan";
import { parse as parseConfig } from "@changesets/config";
import parseChangeset from "@changesets/parse";
import type {
NewChangeset,
PreState,
WrittenConfig,
PackageJSON as ChangesetPackageJSON,
} from "@changesets/types";
import type { Packages, Tool } from "@manypkg/get-packages";
import jsYaml from "js-yaml";
import micromatch from "micromatch";
import type { ProbotOctokit } from "probot";
interface PackageJSON extends ChangesetPackageJSON {
workspaces?: ReadonlyArray<string> | { packages: ReadonlyArray<string> };
bolt?: { workspaces: ReadonlyArray<string> };
}
interface PnpmWorkspace {
packages: ReadonlyArray<string>;
}
// 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 (
item.path !== ".changeset/README.md" &&
item.path.startsWith(".changeset") &&
item.path.endsWith(".md") &&
changedFiles.includes(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) => ({
...parseChangeset(text),
id,
})),
);
}
}
let tool:
| {
tool: Tool;
globs: ReadonlyArray<string>;
}
| undefined;
if (isPnpm) {
const pnpmWorkspaceContent = await fetchTextFile("pnpm-workspace.yaml");
const pnpmWorkspace = jsYaml.safeLoad(pnpmWorkspaceContent) as PnpmWorkspace;
if (pnpmWorkspace.packages) {
tool = {
tool: "pnpm",
globs: pnpmWorkspace.packages,
};
}
} else {
const rootPackageJsonContent = await rootPackageJsonContentsPromise;
if (rootPackageJsonContent.workspaces) {
if (isArray(rootPackageJsonContent.workspaces)) {
tool = {
tool: "yarn",
globs: rootPackageJsonContent.workspaces,
};
} else {
tool = {
tool: "yarn",
globs: rootPackageJsonContent.workspaces.packages,
};
}
} else if (rootPackageJsonContent.bolt && rootPackageJsonContent.bolt.workspaces) {
tool = {
tool: "bolt",
globs: rootPackageJsonContent.bolt.workspaces,
};
}
}
const rootPackageJsonContent = await rootPackageJsonContentsPromise;
const packages: Packages = {
root: {
dir: "/",
packageJson: rootPackageJsonContent,
},
tool: tool ? tool.tool : "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(packages.root);
}
if (hasErrored) {
throw new Error("an error occurred when fetching files");
}
const releasePlan = assembleReleasePlan(
await Promise.all(changesetPromises),
packages,
parseConfig(await rawConfigPromise, packages),
await preStatePromise,
);
return {
changedPackages: (packages.tool === "root"
? packages.packages
: packages.packages.filter((pkg) =>
changedFiles.some((changedFile) => changedFile.startsWith(`${pkg.dir}/`)),
)
).map((pkg) => pkg.packageJson.name),
releasePlan,
};
};