File size: 7,431 Bytes
a03b3ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { getPackagesSync } = require("@manypkg/get-packages");
const gh = require("@changesets/get-github-info");
const { existsSync, readFileSync, writeFileSync } = require("fs");
const { join } = require("path");

const { getInfo, getInfoFromPullRequest } = gh;
const { packages, rootDir } = getPackagesSync(process.cwd());

/**
 * @typedef {{packageJson: {name: string, python?: boolean}, dir: string}} Package
 */

/**
 * @typedef {{summary: string, id: string, commit: string, releases: {name: string}}} Changeset
 */

/**
 *
 * @param {string} package_name The name of the package to find the directories for
 * @returns {string[]} The directories for the package
 */
function find_packages_dirs(package_name) {
	/** @type {string[]} */
	let package_dirs = [];

	/** @type {Package | undefined} */
	const _package = packages.find((p) => p.packageJson.name === package_name);
	if (!_package) throw new Error(`Package ${package_name} not found`);

	package_dirs.push(_package.dir);
	if (_package.packageJson.python) {
		package_dirs.push(join(_package.dir, ".."));
	}
	return package_dirs;
}

const changelogFunctions = {
	/**
	 *
	 * @param {Changeset[]} changesets The changesets that have been created
	 * @param {any} dependenciesUpdated The dependencies that have been updated
	 * @param {any} options The options passed to the changelog generator
	 * @returns {Promise<string>} The release line for the dependencies
	 */
	getDependencyReleaseLine: async (
		changesets,
		dependenciesUpdated,
		options
	) => {
		if (!options.repo) {
			throw new Error(
				'Please provide a repo to this changelog generator like this:\n"changelog": ["@changesets/changelog-github", { "repo": "org/repo" }]'
			);
		}
		if (dependenciesUpdated.length === 0) return "";

		const changesetLink = `- Updated dependencies [${(
			await Promise.all(
				changesets.map(async (cs) => {
					if (cs.commit) {
						let { links } = await getInfo({
							repo: options.repo,
							commit: cs.commit
						});
						return links.commit;
					}
				})
			)
		)
			.filter((_) => _)
			.join(", ")}]:`;

		const updatedDepenenciesList = dependenciesUpdated.map(
			/**
			 *
			 * @param {any} dependency The dependency that has been updated
			 * @returns {string} The formatted dependency
			 */
			(dependency) => `  - ${dependency.name}@${dependency.newVersion}`
		);

		return [changesetLink, ...updatedDepenenciesList].join("\n");
	},
	/**
	 *
	 * @param {{summary: string, id: string, commit: string, releases: {name: string}[]}} changeset The changeset that has been created
	 * @param {any} type The type of changeset
	 * @param {any} options The options passed to the changelog generator
	 * @returns {Promise<string>} The release line for the changeset
	 */
	getReleaseLine: async (changeset, type, options) => {
		if (!options || !options.repo) {
			throw new Error(
				'Please provide a repo to this changelog generator like this:\n"changelog": ["@changesets/changelog-github", { "repo": "org/repo" }]'
			);
		}

		let prFromSummary;
		let commitFromSummary;
		/**
		 * @type {string[]}
		 */
		let usersFromSummary = [];

		const replacedChangelog = changeset.summary
			.replace(/^\s*(?:pr|pull|pull\s+request):\s*#?(\d+)/im, (_, pr) => {
				let num = Number(pr);
				if (!isNaN(num)) prFromSummary = num;
				return "";
			})
			.replace(/^\s*commit:\s*([^\s]+)/im, (_, commit) => {
				commitFromSummary = commit;
				return "";
			})
			.replace(/^\s*(?:author|user):\s*@?([^\s]+)/gim, (_, user) => {
				usersFromSummary.push(user);
				return "";
			})
			.trim();

		const [firstLine, ...futureLines] = replacedChangelog
			.split("\n")
			.map((l) => l.trimRight());

		const links = await (async () => {
			if (prFromSummary !== undefined) {
				let { links } = await getInfoFromPullRequest({
					repo: options.repo,
					pull: prFromSummary
				});
				if (commitFromSummary) {
					links = {
						...links,
						commit: `[\`${commitFromSummary}\`](https://github.com/${options.repo}/commit/${commitFromSummary})`
					};
				}
				return links;
			}
			const commitToFetchFrom = commitFromSummary || changeset.commit;
			if (commitToFetchFrom) {
				let { links } = await getInfo({
					repo: options.repo,
					commit: commitToFetchFrom
				});
				return links;
			}
			return {
				commit: null,
				pull: null,
				user: null
			};
		})();

		const users =
			usersFromSummary && usersFromSummary.length
				? usersFromSummary
						.map(
							(userFromSummary) =>
								`[@${userFromSummary}](https://github.com/${userFromSummary})`
						)
						.join(", ")
				: links.user;

		const prefix = [
			links.pull === null ? "" : `${links.pull}`,
			links.commit === null ? "" : `${links.commit}`
		]
			.join(" ")
			.trim();

		const suffix = users === null ? "" : ` Thanks ${users}!`;

		/**
		 * @typedef {{[key: string]: string[] | {dirs: string[], current_changelog: string, feat: {summary: string}[], fix: {summary: string}[], highlight: {summary: string}[]}}} ChangesetMeta
		 */

		/**
		 * @type { ChangesetMeta & { _handled: string[] } }}
		 */
		let lines;
		if (existsSync(join(rootDir, ".changeset", "_changelog.json"))) {
			lines = JSON.parse(
				readFileSync(join(rootDir, ".changeset", "_changelog.json"), "utf-8")
			);
		} else {
			lines = {
				_handled: []
			};
		}

		if (lines._handled.includes(changeset.id)) {
			return "done";
		}
		lines._handled.push(changeset.id);

		changeset.releases.forEach((release) => {
			if (!lines[release.name])
				lines[release.name] = {
					dirs: find_packages_dirs(release.name),
					current_changelog: "",
					feat: [],
					fix: [],
					highlight: []
				};

			const changelog_path = join(
				//@ts-ignore
				lines[release.name].dirs[1] || lines[release.name].dirs[0],
				"CHANGELOG.md"
			);

			if (existsSync(changelog_path)) {
				//@ts-ignore
				lines[release.name].current_changelog = readFileSync(
					changelog_path,
					"utf-8"
				)
					.replace(`# ${release.name}`, "")
					.trim();
			}

			const [, _type, summary] = changeset.summary
				.trim()
				.match(/^(feat|fix|highlight)\s*:\s*([^]*)/im) || [
				,
				"feat",
				changeset.summary
			];

			let formatted_summary = "";

			if (_type === "highlight") {
				const [heading, ...rest] = summary.trim().split("\n");
				const _heading = `${heading} ${prefix ? `(${prefix})` : ""}`;
				const _rest = rest.concat(["", suffix]);

				formatted_summary = `${_heading}\n${_rest.join("\n")}`;
			} else {
				formatted_summary = handle_line(summary, prefix, suffix);
			}

			//@ts-ignore
			lines[release.name][_type].push({
				summary: formatted_summary
			});
		});

		writeFileSync(
			join(rootDir, ".changeset", "_changelog.json"),
			JSON.stringify(lines, null, 2)
		);

		return `\n\n-${prefix ? `${prefix} -` : ""} ${firstLine}\n${futureLines
			.map((l) => `  ${l}`)
			.join("\n")}`;
	}
};

/**
 * @param {string} str The changelog entry
 * @param {string} prefix The prefix to add to the first line
 * @param {string} suffix The suffix to add to the last line
 * @returns {string} The formatted changelog entry
 */
function handle_line(str, prefix, suffix) {
	const [_s, ...lines] = str.split("\n").filter(Boolean);

	const desc = `${prefix ? `${prefix} -` : ""} ${_s.replace(
		/[\s\.]$/,
		""
	)}. ${suffix}`;

	if (_s.length === 1) {
		return desc;
	}

	return [desc, ...lines.map((l) => `  ${l}`)].join("/n");
}

module.exports = changelogFunctions;