/
index.ts
60 lines (49 loc) 路 1.64 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
import fs from "fs-extra";
import path from "path";
import prettier from "prettier";
import humanId from "human-id";
import { Changeset } from "@changesets/types";
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;
}
}
async function writeChangeset(
changeset: Changeset,
cwd: string
): Promise<string> {
const { summary, releases } = changeset;
const changesetBase = path.resolve(cwd, ".changeset");
// Worth understanding that the ID merely needs to be a unique hash to avoid git conflicts
// experimenting with human readable ids to make finding changesets easier
const changesetID = humanId({
separator: "-",
capitalize: false,
});
const prettierInstance = getPrettierInstance(cwd);
const prettierConfig = await prettierInstance.resolveConfig(cwd);
const newChangesetPath = path.resolve(changesetBase, `${changesetID}.md`);
// NOTE: The quotation marks in here are really important even though they are
// not spec for yaml. This is because package names can contain special
// characters that will otherwise break the parsing step
const changesetContents = `---
${releases.map((release) => `"${release.name}": ${release.type}`).join("\n")}
---
${summary}
`;
await fs.writeFile(
newChangesetPath,
// Prettier v3 returns a promise
await prettierInstance.format(changesetContents, {
...prettierConfig,
parser: "markdown",
})
);
return changesetID;
}
export default writeChangeset;