/
index.ts
360 lines (321 loc) 路 9.89 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
import {
ReleasePlan,
Config,
ChangelogFunctions,
NewChangeset,
ModCompWithPackage,
} from "@changesets/types";
import { defaultConfig } from "@changesets/config";
import * as git from "@changesets/git";
import resolveFrom from "resolve-from";
import { Packages } from "@manypkg/get-packages";
import detectIndent from "detect-indent";
import fs from "fs-extra";
import path from "path";
import prettier from "prettier";
import versionPackage from "./version-package";
import getChangelogEntry from "./get-changelog-entry";
function getPrettierInstance(cwd: string): typeof prettier {
try {
return require(require.resolve("prettier", { paths: [cwd] }));
} catch (err) {
if (!err || (err as any).code !== "MODULE_NOT_FOUND") {
throw err;
}
return prettier;
}
}
function stringDefined(s: string | undefined): s is string {
return !!s;
}
async function getCommitsThatAddChangesets(
changesetIds: string[],
cwd: string
) {
const paths = changesetIds.map((id) => `.changeset/${id}.md`);
const commits = await git.getCommitsThatAddFiles(paths, { cwd, short: true });
if (commits.every(stringDefined)) {
// We have commits for all files
return commits;
}
// Some files didn't exist. Try legacy filenames instead
const missingIds = changesetIds
.map((id, i) => (commits[i] ? undefined : id))
.filter(stringDefined);
const legacyPaths = missingIds.map((id) => `.changeset/${id}/changes.json`);
const commitsForLegacyPaths = await git.getCommitsThatAddFiles(legacyPaths, {
cwd,
short: true,
});
// Fill in the blanks in the array of commits
changesetIds.forEach((id, i) => {
if (!commits[i]) {
const missingIndex = missingIds.indexOf(id);
commits[i] = commitsForLegacyPaths[missingIndex];
}
});
return commits;
}
export default async function applyReleasePlan(
releasePlan: ReleasePlan,
packages: Packages,
config: Config = defaultConfig,
snapshot?: string | boolean
) {
let cwd = packages.root.dir;
let touchedFiles = [];
const packagesByName = new Map(
packages.packages.map((x) => [x.packageJson.name, x])
);
let { releases, changesets } = releasePlan;
let releasesWithPackage = releases.map((release) => {
let pkg = packagesByName.get(release.name);
if (!pkg)
throw new Error(
`Could not find matching package for release of: ${release.name}`
);
return {
...release,
...pkg,
};
});
// I think this might be the wrong place to do this, but gotta do it somewhere - add changelog entries to releases
let releaseWithChangelogs = await getNewChangelogEntry(
releasesWithPackage,
changesets,
config,
cwd
);
if (releasePlan.preState !== undefined && snapshot === undefined) {
if (releasePlan.preState.mode === "exit") {
await fs.remove(path.join(cwd, ".changeset", "pre.json"));
} else {
await fs.writeFile(
path.join(cwd, ".changeset", "pre.json"),
JSON.stringify(releasePlan.preState, null, 2) + "\n"
);
}
}
let versionsToUpdate = releases.map(({ name, newVersion, type }) => ({
name,
version: newVersion,
type,
}));
// iterate over releases updating packages
let finalisedRelease = releaseWithChangelogs.map((release) => {
return versionPackage(release, versionsToUpdate, {
updateInternalDependencies: config.updateInternalDependencies,
onlyUpdatePeerDependentsWhenOutOfRange:
config.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH
.onlyUpdatePeerDependentsWhenOutOfRange,
bumpVersionsWithWorkspaceProtocolOnly:
config.bumpVersionsWithWorkspaceProtocolOnly,
snapshot,
});
});
let prettierInstance = getPrettierInstance(cwd);
let prettierConfig = await prettierInstance.resolveConfig(cwd);
for (let release of finalisedRelease) {
let { changelog, packageJson, dir, name } = release;
const pkgJSONPath = path.resolve(dir, "package.json");
await updatePackageJson(pkgJSONPath, packageJson);
touchedFiles.push(pkgJSONPath);
if (changelog && changelog.length > 0) {
const changelogPath = path.resolve(dir, "CHANGELOG.md");
await updateChangelog(
changelogPath,
changelog,
name,
prettierInstance,
prettierConfig
);
touchedFiles.push(changelogPath);
}
}
if (
releasePlan.preState === undefined ||
releasePlan.preState.mode === "exit"
) {
let changesetFolder = path.resolve(cwd, ".changeset");
await Promise.all(
changesets.map(async (changeset) => {
let changesetPath = path.resolve(changesetFolder, `${changeset.id}.md`);
let changesetFolderPath = path.resolve(changesetFolder, changeset.id);
if (await fs.pathExists(changesetPath)) {
// DO NOT remove changeset for ignored packages
// Mixed changeset that contains both ignored packages and not ignored packages are disallowed
// At this point, we know there is no such changeset, because otherwise the program would've already failed,
// so we just check if any ignored package exists in this changeset, and only remove it if none exists
// Ignored list is added in v2, so we don't need to do it for v1 changesets
if (
!changeset.releases.find((release) =>
config.ignore.includes(release.name)
)
) {
touchedFiles.push(changesetPath);
await fs.remove(changesetPath);
}
// TO REMOVE LOGIC - this works to remove v1 changesets. We should be removed in the future
} else if (await fs.pathExists(changesetFolderPath)) {
touchedFiles.push(changesetFolderPath);
await fs.remove(changesetFolderPath);
}
})
);
}
// We return the touched files to be committed in the cli
return touchedFiles;
}
async function getNewChangelogEntry(
releasesWithPackage: ModCompWithPackage[],
changesets: NewChangeset[],
config: Config,
cwd: string
) {
if (!config.changelog) {
return Promise.resolve(
releasesWithPackage.map((release) => ({
...release,
changelog: null,
}))
);
}
let getChangelogFuncs: ChangelogFunctions = {
getReleaseLine: () => Promise.resolve(""),
getDependencyReleaseLine: () => Promise.resolve(""),
};
const changelogOpts = config.changelog[1];
let changesetPath = path.join(cwd, ".changeset");
let changelogPath = resolveFrom(changesetPath, config.changelog[0]);
let possibleChangelogFunc = require(changelogPath);
if (possibleChangelogFunc.default) {
possibleChangelogFunc = possibleChangelogFunc.default;
}
if (
typeof possibleChangelogFunc.getReleaseLine === "function" &&
typeof possibleChangelogFunc.getDependencyReleaseLine === "function"
) {
getChangelogFuncs = possibleChangelogFunc;
} else {
throw new Error("Could not resolve changelog generation functions");
}
let commits = await getCommitsThatAddChangesets(
changesets.map((cs) => cs.id),
cwd
);
let moddedChangesets = changesets.map((cs, i) => ({
...cs,
commit: commits[i],
}));
return Promise.all(
releasesWithPackage.map(async (release) => {
let changelog = await getChangelogEntry(
release,
releasesWithPackage,
moddedChangesets,
getChangelogFuncs,
changelogOpts,
{
updateInternalDependencies: config.updateInternalDependencies,
onlyUpdatePeerDependentsWhenOutOfRange:
config.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH
.onlyUpdatePeerDependentsWhenOutOfRange,
}
);
return {
...release,
changelog,
};
})
).catch((e) => {
console.error(
"The following error was encountered while generating changelog entries"
);
console.error(
"We have escaped applying the changesets, and no files should have been affected"
);
throw e;
});
}
async function updateChangelog(
changelogPath: string,
changelog: string,
name: string,
prettierInstance: typeof prettier,
prettierConfig: prettier.Options | null
) {
let templateString = `\n\n${changelog.trim()}\n`;
try {
if (fs.existsSync(changelogPath)) {
await prependFile(
changelogPath,
templateString,
name,
prettierInstance,
prettierConfig
);
} else {
await writeFormattedMarkdownFile(
changelogPath,
`# ${name}${templateString}`,
prettierInstance,
prettierConfig
);
}
} catch (e) {
console.warn(e);
}
}
async function updatePackageJson(
pkgJsonPath: string,
pkgJson: any
): Promise<void> {
const pkgRaw = await fs.readFile(pkgJsonPath, "utf-8");
const indent = detectIndent(pkgRaw).indent || " ";
const stringified =
JSON.stringify(pkgJson, null, indent) + (pkgRaw.endsWith("\n") ? "\n" : "");
return fs.writeFile(pkgJsonPath, stringified);
}
async function prependFile(
filePath: string,
data: string,
name: string,
prettierInstance: typeof prettier,
prettierConfig: prettier.Options | null
) {
const fileData = fs.readFileSync(filePath).toString();
// if the file exists but doesn't have the header, we'll add it in
if (!fileData) {
const completelyNewChangelog = `# ${name}${data}`;
await writeFormattedMarkdownFile(
filePath,
completelyNewChangelog,
prettierInstance,
prettierConfig
);
return;
}
const newChangelog = fileData.replace("\n", data);
await writeFormattedMarkdownFile(
filePath,
newChangelog,
prettierInstance,
prettierConfig
);
}
async function writeFormattedMarkdownFile(
filePath: string,
content: string,
prettierInstance: typeof prettier,
prettierConfig: prettier.Options | null
) {
await fs.writeFile(
filePath,
// Prettier v3 returns a promise
await prettierInstance.format(content, {
...prettierConfig,
filepath: filePath,
parser: "markdown",
})
);
}