aboutsummaryrefslogtreecommitdiff
path: root/scripts/shared/commits.mjs
blob: aaccb4d0a0fac989359b7207b210551d0c5c31e5 (plain) (blame)
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
import _ from 'lodash';

export { rawCommitsToMarkdown };

const commitScopesToHumanReadable = {
  build: 'Build system',
  chore: 'Chores',
  ci: 'Continuous integration',
  docs: 'Documentation',
  feat: 'Features',
  fix: 'Bug fixes',
  infra: 'Infrastucture',
  perf: 'Performance',
  refactor: 'Refactoring',
  test: 'Tests',
};

const commitTypesOrder = ['feat', 'fix', 'perf', 'refactor', 'test', 'build', 'ci', 'chore', 'other'];

const getCommitTypeSortIndex = (type) =>
  commitTypesOrder.includes(type) ? commitTypesOrder.indexOf(type) : commitTypesOrder.length;

function parseCommitLine(commit) {
  const [sha, ...splittedRawMessage] = commit.trim().split(' ');
  const rawMessage = splittedRawMessage.join(' ');
  const { type, scope, subject } = /^(?<type>.*?)(\((?<scope>.*)\))?: ?(?<subject>.+)$/.exec(rawMessage)?.groups ?? {};

  return {
    sha: sha.slice(0, 7),
    type: type ?? 'other',
    scope,
    subject: subject ?? rawMessage,
  };
}

function commitSectionsToMarkdown({ type, commits }) {
  return [
    `### ${commitScopesToHumanReadable[type] ?? _.capitalize(type)}`,
    ...commits.map(({ sha, scope, subject }) => ['-', scope ? `**${scope}**:` : '', subject, `(${sha})`].join(' ')),
  ].join('\n');
}

function rawCommitsToMarkdown({ rawCommits }) {
  return _.chain(rawCommits)
    .trim()
    .split('\n')
    .map(parseCommitLine)
    .groupBy('type')
    .map((commits, type) => ({ type, commits }))
    .sortBy(({ type }) => getCommitTypeSortIndex(type))
    .map(commitSectionsToMarkdown)
    .join('\n\n')
    .value();
}