summaryrefslogtreecommitdiff
path: root/ci/github-script/lint-commits.js
blob: 6f2dc540a2c64a75c24c777ea676d8349f71cb99 (plain)
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
// @ts-check
const { classify } = require('../supportedBranches.js')
const { getCommitDetailsForPR } = require('./get-pr-commit-details.js')

// Supported Conventional Commit types for Project Tick
const CONVENTIONAL_TYPES = [
  'build',
  'chore',
  'ci',
  'docs',
  'feat',
  'fix',
  'perf',
  'refactor',
  'revert',
  'style',
  'test',
]

// Known project scopes in the monorepo
const KNOWN_SCOPES = [
  'archived',
  'cgit',
  'ci',
  'cmark',
  'corebinutils',
  'forgewrapper',
  'genqrcode',
  'hooks',
  'images4docker',
  'json4cpp',
  'libnbtplusplus',
  'meshmc',
  'meta',
  'mnv',
  'neozip',
  'tomlplusplus',
  'repo',
  'deps',
]

/**
 * Validates commit messages against Project Tick Conventional Commits conventions.
 *
 * Format: type(scope): subject
 *   type  — one of: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
 *   scope — optional, should match a project directory or be a known scope
 *   subject — imperative, no trailing period, no uppercase first letter
 *
 * @param {{
 *  github: InstanceType<import('@actions/github/lib/utils').GitHub>,
 *  context: import('@actions/github/lib/context').Context,
 *  core: import('@actions/core'),
 *  repoPath?: string,
 * }} CheckCommitMessagesProps
 */
async function checkCommitMessages({ github, context, core, repoPath }) {
  const pull_number = context.payload.pull_request?.number
  if (!pull_number) {
    core.info('This is not a pull request. Skipping checks.')
    return
  }

  const pr = (
    await github.rest.pulls.get({
      ...context.repo,
      pull_number,
    })
  ).data

  const baseBranchType = classify(
    pr.base.ref.replace(/^refs\/heads\//, ''),
  ).type
  const headBranchType = classify(
    pr.head.ref.replace(/^refs\/heads\//, ''),
  ).type

  if (
    baseBranchType.includes('development') &&
    headBranchType.includes('development') &&
    pr.base.repo.id === pr.head.repo?.id
  ) {
    core.info(
      'This PR is from one development branch to another. Skipping checks.',
    )
    return
  }

  // Skip commit lint for automated bot PRs (e.g. Dependabot)
  const prAuthor = pr.user?.login || ''
  if (prAuthor === 'dependabot[bot]') {
    core.info(
      `PR author is "${prAuthor}". Skipping commit message checks for bot PRs.`,
    )
    return
  }

  const commits = await getCommitDetailsForPR({ core, pr, repoPath })

  const failures = new Set()
  const warnings = new Set()

  const conventionalRegex = new RegExp(
    `^(${CONVENTIONAL_TYPES.join('|')})(\\(([^)]+)\\))?(!)?: .+$`,
  )

  for (const commit of commits) {
    const msg = commit.subject
    const logPrefix = `Commit ${commit.sha.slice(0, 12)}`

    // Check: fixup/squash commits
    const fixups = ['amend!', 'fixup!', 'squash!']
    if (fixups.some((s) => msg.startsWith(s))) {
      core.error(
        `${logPrefix}: starts with "${fixups.find((s) => msg.startsWith(s))}". ` +
          'Did you forget to run `git rebase -i --autosquash`?',
      )
      failures.add(commit.sha)
      continue
    }

    // Check: Conventional Commit format
    if (!conventionalRegex.test(msg)) {
      core.error(
        `${logPrefix}: "${msg}" does not follow Conventional Commits format. ` +
          'Expected: type(scope): subject  (e.g. "feat(mnv): add keybinding")',
      )
      failures.add(commit.sha)
      continue
    }

    // Extract parts
    const match = msg.match(conventionalRegex)
    const type = match[1]
    const scope = match[3] || null

    // Check: trailing period
    if (msg.endsWith('.')) {
      core.error(
        `${logPrefix}: subject should not end with a period.`,
      )
      failures.add(commit.sha)
    }

    // Warning: unknown scope
    if (scope && !KNOWN_SCOPES.includes(scope)) {
      core.warning(
        `${logPrefix}: scope "${scope}" is not a known project. ` +
          `Known scopes: ${KNOWN_SCOPES.join(', ')}`,
      )
      warnings.add(commit.sha)
    }

    // Check: subject should not start with uppercase (after type(scope): )
    const subjectStart = msg.indexOf(': ') + 2
    if (subjectStart < msg.length) {
      const firstChar = msg[subjectStart]
      if (firstChar === firstChar.toUpperCase() && firstChar !== firstChar.toLowerCase()) {
        core.warning(
          `${logPrefix}: subject should start with lowercase letter.`,
        )
        warnings.add(commit.sha)
      }
    }

    if (!failures.has(commit.sha)) {
      core.info(`${logPrefix}: "${msg}" — passed.`)
    }
  }

  if (failures.size !== 0) {
    core.error(
      'Please review the Conventional Commits guidelines at ' +
        '<https://www.conventionalcommits.org/> and the project CONTRIBUTING.md.',
    )
    core.setFailed(
      `${failures.size} commit(s) do not follow commit conventions.`,
    )
  } else if (warnings.size !== 0) {
    core.warning(
      `${warnings.size} commit(s) have minor issues (see warnings above).`,
    )
  }
}

module.exports = checkCommitMessages