This repository has been archived by the owner on Aug 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefaults.js
453 lines (389 loc) · 16.3 KB
/
defaults.js
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
'use strict';
// TODO: when using webpack to bundle the TypeScript version of this, ensure to
// TODO: bundle the handlebars assets as inline resources
const { basename } = require('path');
const { readFileSync, existsSync } = require('fs');
const { toss } = require('toss-expression');
const debug = require('debug')(`${require('./package.json').name}:defaults`);
const semver = require('semver');
// ? The preamble prefixed to any generated changelog
const CHANGELOG_TITLE =
`# Changelog\n\n` +
`All notable changes to this project will be documented in this auto-generated\n` +
`file. The format is based on [Conventional Commits](https://conventionalcommits.org);\n` +
`this project adheres to [Semantic Versioning](https://semver.org).`;
// ? Strings in commit messages that, when found, are skipped
const SKIP_COMMANDS = ['[skip ci]', '[ci skip]', '[skip cd]', '[cd skip]'];
// ? Commits, having been grouped by type, will appear in the CHANGELOG in the
// ? order they appear in COMMIT_TYPE_CHANGELOG_ORDER. Types that are not listed
// ? in COMMIT_TYPE_CHANGELOG_ORDER will appear in input order _after_ listed
// ? types.
const COMMIT_TYPE_CHANGELOG_ORDER = ['feat', 'fix', 'perf', 'build', 'revert'];
// ? Matches a valid GitHub username with respect to the following:
// ? - Avoids matching scoped package names (e.g. @xunnamius/package)
// ? - Will match multiple usernames separated by slash (e.g. @user1/@user2)
const USERNAME_REGEX = /\B@([a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38})\b(?!\/(?!@))/gi;
// ? Used to normalize the aesthetic of revert CHANGELOG entries
const DELETE_REVERT_PREFIX_REGEX = /^Revert\s+/;
// ? The character(s) used to reference issues by number on GitHub
const ISSUE_PREFIXES = ['#'];
// ? Handlebars template data
const templates = {
commit: readFileSync(require.resolve('./templates/commit.hbs'), 'utf-8'),
footer: readFileSync(require.resolve('./templates/footer.hbs'), 'utf-8'),
header: readFileSync(require.resolve('./templates/header.hbs'), 'utf-8'),
template: readFileSync(require.resolve('./templates/template.hbs'), 'utf-8'),
// ? Handlebars partials for property substitutions using commit context
partials: {
owner: '{{#if this.owner}}{{~this.owner}}{{else}}{{[email protected]}}{{/if}}',
host: '{{[email protected]}}',
repository:
'{{#if this.repository}}{{~this.repository}}{{else}}{{[email protected]}}{{/if}}'
}
};
/**
* Transform a string into sentence case capitalization.
*
* @param {string} s The string to transform
*/
const sentenceCase = (s) => s.toString().charAt(0).toUpperCase() + s.toString().slice(1);
/**
* Expand simple handlebars templates without actually using handlebars.
*
* @param {string} template
* @param {Record<string, string>} context
*/
const expandTemplate = (template, context) => {
Object.keys(context).forEach((key) => {
template = template.replace(new RegExp(`{{${key}}}`, 'g'), context[key]);
});
return template;
};
/**
* Returns true if the current working directory (cwd) contains a package.json
* file, the grandparent directory is `packages/`, and _its_ parent contains
* a package.json file
*/
// TODO: break off into separate monorepo tools package
const isInMonoPkgContext = (dbg) => {
const cwd = process.cwd();
if (!existsSync(`${cwd}/package.json`)) {
dbg('monorepo: no (missing package.json in cwd)');
return false;
}
if (!existsSync(`${cwd}/../../packages`)) {
dbg('monorepo: no (missing packages dir in grandparent)');
return false;
}
if (!existsSync(`${cwd}/../../package.json`)) {
dbg('monorepo: no (missing package.json in grandparent)');
return false;
}
dbg('monorepo: yes');
return true;
};
// TODO: break off this code into separate monorepo tooling (along with other)
const getMonoPkgName = () => {
const cwd = process.cwd();
if (!existsSync(`${cwd}/../../packages`)) {
throw new Error(`assert failed: illegal cwd: ${cwd}`);
}
return basename(cwd);
};
/**
* Returns a partially initialized configuration object as well as a `finish`
* function. Call `finish()` to complete initialization or behavior is
* undefined.
*/
module.exports = () => {
/**
* Adds additional breaking change notes for the special case
* `test(system)!: hello world` but with no `BREAKING CHANGE` in body.
*
* @param {Record<string, unknown>} commit
*/
const addBangNotes = ({ header, notes }) => {
const match = header.match(config.parserOpts.breakingHeaderPattern);
if (match && notes.length == 0) {
const noteText = match[3]; // ? Commit subject becomes BC note text
notes.push({
text: noteText
});
}
};
// ? Single source of truth for shared values
const memory = {
issuePrefixes: ISSUE_PREFIXES
};
/**
* The default partially-initialized conventional-changelog config object.
*/
// TODO: add this comment to type description instead
const config = {
// * Custom configuration keys * \\
changelogTitle: CHANGELOG_TITLE,
skipCommands: SKIP_COMMANDS.map((cmd) => cmd.toLowerCase()),
// * Core configuration keys * \\
// ? conventionalChangelog and recommendedBumpOpts keys are defined below
gitRawCommitsOpts: {},
// ? See: https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-commits-parser#options
parserOpts: {
headerPattern: /^(\w*)(?:\(([^\)]*)\))?!?: (.*)$/,
breakingHeaderPattern: /^(\w*)(?:\(([^\)]*)\))?!: (.*)$/,
headerCorrespondence: ['type', 'scope', 'subject'],
mergePattern: /^Merge pull request #(\d+) from (.*)$/,
mergeCorrespondence: ['id', 'source'],
revertPattern: /^(?:Revert|revert:)\s"?([\s\S]+?)"?\s*This reverts commit (\w*)\./i,
revertCorrespondence: ['header', 'hash'],
noteKeywords: ['BREAKING CHANGE', 'BREAKING CHANGES', 'BREAKING'],
// ? See: https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-commits-parser#warn
warn: console.warn.bind(console),
get issuePrefixes() {
return memory.issuePrefixes;
},
set issuePrefixes(v) {
memory.issuePrefixes = v;
}
},
// ? See: https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-writer#options
writerOpts: {
generateOn: (commit) => {
const debug1 = debug.extend('writerOpts:generateOn');
let version = commit.version;
let decision = false;
debug1(`saw version: ${version}`);
if (version) {
if (isInMonoPkgContext(debug1)) {
const pkgName = getMonoPkgName();
debug1(`package: ${pkgName}`);
if (RegExp(`^${pkgName}@.{5,}$`).test(version)) {
// ? Remove the package name from the version string
commit.version = version = version.split('@').slice(-1)[0];
debug1(`using version: ${version}`);
}
}
decision = !!semver.valid(version) && !semver.prerelease(version);
}
debug1(`decision: ${decision ? 'NEW block' : 'same block'}`);
return decision;
},
// transform sub-key is defined below
mainTemplate: templates.template,
// headerPartial and commitPartial sub-keys are defined below
footerPartial: templates.footer,
groupBy: 'type',
// ? Commit message groupings (e.g. Features) are sorted by their
// ? importance. Unlike the original version, this is a stable sort algo!
// ? See: https://v8.dev/features/stable-sort
commitGroupsSort: (a, b) => {
a = commitGroupOrder.indexOf(a.title);
b = commitGroupOrder.indexOf(b.title);
return a == -1 || b == -1 ? b - a : a - b;
},
commitsSort: ['scope', 'subject'],
noteGroupsSort: 'title'
},
// * Spec-compliant configuration keys * \\
// ? See: https://github.com/conventional-changelog/conventional-changelog-config-spec/blob/master/versions/2.1.0/README.md
// ? Commits are grouped by section; new types can alias existing types by
// ? matching sections:
// prettier-ignore
types: [
{ type: 'feat', section: '✨ Features', hidden: false },
{ type: 'feature', section: '✨ Features', hidden: false },
{ type: 'fix', section: '🪄 Fixes', hidden: false },
{ type: 'perf', section: '⚡️ Optimizations', hidden: false },
{ type: 'revert', section: '🔥 Reverted', hidden: false },
{ type: 'build', section: '⚙️ Build system', hidden: false },
{ type: 'docs', section: '📚 Documentation', hidden: true },
{ type: 'style', section: '💎 Aesthetics', hidden: true },
{ type: 'refactor', section: '🧙🏿 Refactored', hidden: true },
{ type: 'test', section: '⚗️ Test system', hidden: true },
{ type: 'ci', section: '🏭 CI/CD', hidden: true },
{ type: 'cd', section: '🏭 CI/CD', hidden: true },
{ type: 'chore', section: '🗄️ Miscellaneous', hidden: true }
],
commitUrlFormat: '{{host}}/{{owner}}/{{repository}}/commit/{{hash}}',
compareUrlFormat:
'{{host}}/{{owner}}/{{repository}}/compare/{{previousTag}}...{{currentTag}}',
issueUrlFormat: '{{host}}/{{owner}}/{{repository}}/issues/{{id}}',
userUrlFormat: '{{host}}/{{user}}',
get issuePrefixes() {
return memory.issuePrefixes;
},
set issuePrefixes(v) {
memory.issuePrefixes = v;
}
};
config.writerOpts.transform = (commit, context) => {
const debug1 = debug.extend('writerOpts:transform');
// ? Scope should always be lowercase (or undefined)
commit.scope = commit.scope?.toLowerCase();
let discard = true;
const issues = [];
const typeKey = (commit.revert ? 'revert' : commit.type || '').toLowerCase();
const typeEntry = config.types.find(
(entry) => entry.type == typeKey && (!entry.scope || entry.scope == commit.scope)
);
const skipCmdEvalTarget = `${commit.subject || ''}${
commit.header || ''
}`.toLowerCase();
// ? Ignore any commits with skip commands in them (including BCs)
if (config.skipCommands.some((cmd) => skipCmdEvalTarget.includes(cmd))) {
debug1('saw skip command in commit message; discarding immediately');
debug1('decision: commit discarded');
return;
}
addBangNotes(commit);
// ? Otherwise, never ignore breaking changes. Additionally, make all scopes
// ? bold. For multi-line notes, make the first line bold and each
// ? successive line indented with two spaces. Scope-less subjects are made
// ? sentence case.
commit.notes.forEach((note) => {
if (note.text) {
debug1('saw BC notes for this commit; NOT discarding...');
const [firstLine, ...remainder] = note.text.trim().split('\n');
const isMultiline = !!(note.text.trim().split('\n\n').length > 1);
const firstLineSentenceCase =
/* !commit.scope ? */ sentenceCase(firstLine); /* : firstLine */
// ? Never discard breaking changes
discard = false;
note.title = 'BREAKING CHANGES';
note.text =
(isMultiline ? `**${firstLineSentenceCase}**` : firstLineSentenceCase) +
remainder.reduce((result, line) => `${result}\n ${line}`, '') +
'\n';
}
});
// ? Discard entries of unknown or hidden types if discard == true
if (discard && (typeEntry === undefined || typeEntry.hidden)) {
debug1('decision: commit discarded');
return;
} else debug1('decision: commit NOT discarded');
if (typeEntry) commit.type = typeEntry.section;
if (commit.scope == '*') commit.scope = '';
if (typeof commit.hash == 'string') commit.shortHash = commit.hash.substring(0, 7);
// ? Badly crafted reverts are all header and no subject
if (typeKey == 'revert' && !commit.subject) {
commit.subject = commit.header.replace(DELETE_REVERT_PREFIX_REGEX, '');
}
if (typeof commit.subject == 'string') {
// ? Replace issue refs with URIs
const issueRegex = new RegExp(`(${config.issuePrefixes.join('|')})([0-9]+)`, 'g');
commit.subject = commit.subject.replace(issueRegex, (_, prefix, issue) => {
const issueStr = `${prefix}${issue}`;
const url = expandTemplate(config.issueUrlFormat, {
host: context.host,
owner: context.owner,
repository: context.repository,
id: issue,
prefix: prefix
});
issues.push(issueStr);
return `[${issueStr}](${url})`;
});
// ? Replace user refs with URIs
commit.subject = commit.subject.replace(
// * https://github.com/shinnn/github-username-regex
USERNAME_REGEX,
(_, user) => {
const usernameUrl = expandTemplate(config.userUrlFormat, {
host: context.host,
owner: context.owner,
repository: context.repository,
user
});
return `[@${user}](${usernameUrl})`;
}
);
// ? Make scope-less commit subjects sentence case
if (!commit.scope) commit.subject = sentenceCase(commit.subject);
// ? Italicize reverts
if (typeKey == 'revert') commit.subject = `*${commit.subject}*`;
}
// ? Remove references that already appear in the subject
commit.references = commit.references.filter(
({ prefix, issue }) => !issues.includes(`${prefix}${issue}`)
);
debug1('transformed commit: %O', commit);
return commit;
};
// ? The order commit type groups will appear in (ordered by section title)
const commitGroupOrder = COMMIT_TYPE_CHANGELOG_ORDER.map(
(type) =>
config.types.find((entry) => entry.type == type).section ||
toss(new Error(`unmatched commit type "${type}" in COMMIT_TYPE_CHANGELOG_ORDER`))
);
// ! Must be called after tweaking the default config object !
/**
* Finish initializing the default config object.
*/
// TODO: add this comment to type description instead
const finish = () => {
if (!config.writerOpts.headerPartial) {
config.writerOpts.headerPartial = expandTemplate(templates.header, {
compareUrlFormat: expandTemplate(config.compareUrlFormat, {
host: templates.partials.host,
owner: templates.partials.owner,
repository: templates.partials.repository
})
});
}
if (!config.writerOpts.commitPartial) {
config.writerOpts.commitPartial = expandTemplate(templates.commit, {
commitUrlFormat: expandTemplate(config.commitUrlFormat, {
host: templates.partials.host,
owner: templates.partials.owner,
repository: templates.partials.repository
}),
issueUrlFormat: expandTemplate(config.issueUrlFormat, {
host: templates.partials.host,
owner: templates.partials.owner,
repository: templates.partials.repository,
id: '{{this.issue}}',
prefix: '{{this.prefix}}'
})
});
}
};
config.conventionalChangelog = {
parserOpts: config.parserOpts,
writerOpts: config.writerOpts
};
config.recommendedBumpOpts = {
parserOpts: config.parserOpts,
whatBump: (commits) => {
const debug1 = debug.extend('writerOpts:whatBump');
let level = 2; // ? 0 = major, 1 = minor, 2 = patch (default)
let breakings = 0;
let features = 0;
commits.forEach((commit) => {
addBangNotes(commit);
if (commit.notes.length > 0) {
breakings += commit.notes.length;
level = 0; // ? -> major
} else if (commit.type == 'feat' || commit.type == 'feature') {
features += 1;
level == 2 && (level = 1); // ? patch -> minor
}
});
// ? If release <1.0.0 and we were gonna do a major/minor bump, do a
// ? minor/patch (respectively) bump instead
if (config.preMajor && level < 2) {
debug1('preMajor release detected; restricted to minor and patch bumps');
level++;
}
const recommendation = {
level,
reason: `There ${breakings == 1 ? 'is' : 'are'} ${breakings} breaking change${
breakings == 1 ? '' : 's'
} and ${features} feature${features == 1 ? '' : 's'}`
};
debug1('recommendation: %O');
return recommendation;
}
};
debug('types: %O', config.types);
return { config, finish };
};
debug.extend('exports')('exports: %O', module.exports);