robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. Keyestest: lint naming conventions #3911711a1ec7df3

master
8.7 KiB312 linesraw
1-- Usage:
2--    # verbose
3--    nvim -l scripts/lintcommit.lua main --trace
4--
5--    # silent
6--    nvim -l scripts/lintcommit.lua main
7--
8--    # self-test
9--    nvim -l scripts/lintcommit.lua _test
10
11--- @type table<string,fun(opt: LintcommitOptions)>
12local M = {}
13
14local _trace = false
15
16local allowed_types =
17  { 'build', 'ci', 'docs', 'feat', 'fix', 'perf', 'refactor', 'revert', 'test', 'vim-patch' }
18
19-- Print message
20local function p(s)
21  vim.cmd('set verbose=1')
22  vim.api.nvim_echo({ { s, '' } }, false, {})
23  vim.cmd('set verbose=0')
24end
25
26-- Executes and returns the output of `cmd`, or nil on failure.
27--
28-- Prints `cmd` if `trace` is enabled.
29local function run(cmd, or_die)
30  if _trace then
31    p('run: ' .. vim.inspect(cmd))
32  end
33  local res = vim.system(cmd):wait()
34  local rv = vim.trim(res.stdout)
35  if res.code ~= 0 then
36    if or_die then
37      p(rv)
38      os.exit(1)
39    end
40    return nil
41  end
42  return rv
43end
44
45-- Returns nil if the given commit message is valid, or returns a string
46-- message explaining why it is invalid.
47local function validate_commit(commit_message)
48  local commit_split = vim.split(commit_message, ':', { plain = true })
49  -- Return nil if the type is vim-patch since most of the normal rules don't
50  -- apply.
51  if commit_split[1] == 'vim-patch' then
52    return nil
53  end
54
55  -- Skip release commits.
56  if commit_message:match('^NVIM v%d+%.%d+%.%d+') then
57    return nil
58  end
59
60  -- Check that message isn't too long.
61  if commit_message:len() > 80 then
62    return [[Commit message is too long, a maximum of 80 characters is allowed.]]
63  end
64
65  local before_colon = commit_split[1]
66
67  local after_idx = 2
68  if before_colon:match('^[^%(]*%([^%)]*$') then
69    -- Need to find the end of commit scope when commit scope contains colons.
70    while after_idx <= vim.tbl_count(commit_split) do
71      after_idx = after_idx + 1
72      if commit_split[after_idx - 1]:find(')') then
73        break
74      end
75    end
76  end
77  if after_idx > vim.tbl_count(commit_split) then
78    return [[Commit message does not include colons.]]
79  end
80  local after_colon_split = {}
81  while after_idx <= vim.tbl_count(commit_split) do
82    table.insert(after_colon_split, commit_split[after_idx])
83    after_idx = after_idx + 1
84  end
85  local after_colon = table.concat(after_colon_split, ':')
86
87  -- Check if commit introduces a breaking change.
88  if vim.endswith(before_colon, '!') then
89    before_colon = before_colon:sub(1, -2)
90  end
91
92  -- Check if type is correct
93  local type = vim.split(before_colon, '(', { plain = true })[1]
94  if not vim.tbl_contains(allowed_types, type) then
95    return string.format(
96      [[Invalid commit type "%s". Allowed types are:
97      %s.
98    If none of these seem appropriate then use "fix"]],
99      type,
100      vim.inspect(allowed_types)
101    )
102  end
103
104  -- Check if scope is appropriate
105  if before_colon:match('%(') then
106    local scope = vim.trim(commit_message:match('%((.-)%)'))
107
108    if scope == '' then
109      return [[Scope can't be empty]]
110    end
111
112    if vim.startswith(scope, 'nvim_') then
113      return [[Scope should be "api" instead of "nvim_..."]]
114    end
115
116    local alternative_scope = {
117      ['filetype.vim'] = 'filetype',
118      ['filetype.lua'] = 'filetype',
119      ['tree-sitter'] = 'treesitter',
120      ['ts'] = 'treesitter',
121      ['hl'] = 'highlight',
122    }
123
124    if alternative_scope[scope] then
125      return ('Scope should be "%s" instead of "%s"'):format(alternative_scope[scope], scope)
126    end
127  end
128
129  -- Check that description doesn't end with a period
130  if vim.endswith(after_colon, '.') then
131    return [[Description ends with a period (".").]]
132  end
133
134  -- Check that description starts with a whitespace.
135  if after_colon:sub(1, 1) ~= ' ' then
136    return [[There should be a whitespace after the colon.]]
137  end
138
139  -- Check that description doesn't start with multiple whitespaces.
140  if after_colon:sub(1, 2) == '  ' then
141    return [[There should only be one whitespace after the colon.]]
142  end
143
144  -- Allow lowercase or ALL_UPPER but not Titlecase.
145  if after_colon:match('^ *%u%l') then
146    return [[Description first word should not be Capitalized.]]
147  end
148
149  -- Check that description isn't just whitespaces
150  if vim.trim(after_colon) == '' then
151    return [[Description shouldn't be empty.]]
152  end
153
154  return nil
155end
156
157--- @param opt? LintcommitOptions
158function M.main(opt)
159  _trace = not opt or not not opt.trace
160
161  local branch = run({ 'git', 'rev-parse', '--abbrev-ref', 'HEAD' }, true)
162  -- TODO(justinmk): check $GITHUB_REF
163  local ancestor = run({ 'git', 'merge-base', 'origin/master', branch })
164  if not ancestor then
165    ancestor = run({ 'git', 'merge-base', 'upstream/master', branch })
166  end
167  local commits_str = run({ 'git', 'rev-list', ancestor .. '..' .. branch }, true)
168  assert(commits_str)
169
170  local commits = {} --- @type string[]
171  for substring in commits_str:gmatch('%S+') do
172    table.insert(commits, substring)
173  end
174
175  local failed = 0
176  for _, commit_id in ipairs(commits) do
177    local msg = run({ 'git', 'show', '-s', '--format=%s', commit_id })
178    if vim.v.shell_error ~= 0 then
179      p('Invalid commit-id: ' .. commit_id .. '"')
180    else
181      local invalid_msg = validate_commit(msg)
182      if invalid_msg then
183        failed = failed + 1
184
185        -- Some breathing room
186        if failed == 1 then
187          p('\n')
188        end
189
190        p(string.format(
191          [[
192Invalid commit message: "%s"
193    Commit: %s
194    %s
195]],
196          msg,
197          commit_id,
198          invalid_msg
199        ))
200      end
201    end
202  end
203
204  if failed > 0 then
205    p([[
206See also:
207    https://github.com/neovim/neovim/blob/master/CONTRIBUTING.md#commit-messages
208
209]])
210    os.exit(1)
211  else
212    p('')
213  end
214end
215
216function M._test()
217  -- message:expected_result
218  local test_cases = {
219    ['ci: normal message'] = true,
220    ['build: normal message'] = true,
221    ['build: version bump'] = true,
222    ['docs: normal message'] = true,
223    ['feat: normal message'] = true,
224    ['fix: normal message'] = true,
225    ['perf: normal message'] = true,
226    ['refactor: normal message'] = true,
227    ['revert: normal message'] = true,
228    ['test: normal message'] = true,
229    ['ci(window): message with scope'] = true,
230    ['ci!: message with breaking change'] = true,
231    ['ci(tui)!: message with scope and breaking change'] = true,
232    ['vim-patch:8.2.3374: Pyret files are not recognized (#15642)'] = true,
233    ['vim-patch:8.1.1195,8.2.{3417,3419}'] = true,
234    ['NVIM v0.12.0'] = true,
235    ['revert: "ci: use continue-on-error instead of "|| true""'] = true,
236    ['fixup'] = false,
237    ['fixup: commit message'] = false,
238    ['fixup! commit message'] = false,
239    [':no type before colon 1'] = false,
240    [' :no type before colon 2'] = false,
241    ['  :no type before colon 3'] = false,
242    ['ci(empty description):'] = false,
243    ['ci(only whitespace as description): '] = false,
244    ['docs(multiple whitespaces as description):   '] = false,
245    ['revert(multiple whitespaces and then characters as description):  description'] = false,
246    ['ci no colon after type'] = false,
247    ['test:  extra space after colon'] = false,
248    ['ci:	tab after colon'] = false,
249    ['ci:no space after colon'] = false,
250    ['ci :extra space before colon'] = false,
251    ['refactor(): empty scope'] = false,
252    ['ci( ): whitespace as scope'] = false,
253    ['ci: period at end of sentence.'] = false,
254    ['ci: period: at end of sentence.'] = false,
255    ['ci: Capitalized first word'] = false,
256    ['ci: UPPER_CASE First Word'] = true,
257    ['unknown: using unknown type'] = false,
258    ['feat: foo:bar'] = true,
259    ['feat: :foo:bar'] = true,
260    ['feat: :Foo:Bar'] = true,
261    ['feat(something): foo:bar'] = true,
262    ['feat(something): :foo:bar'] = true,
263    ['feat(something): :Foo:Bar'] = true,
264    ['feat(:grep): read from pipe'] = true,
265    ['feat(:grep/:make): read from pipe'] = true,
266    ['feat(:grep): foo:bar'] = true,
267    ['feat(:grep/:make): foo:bar'] = true,
268    ['feat(:grep)'] = false,
269    ['feat(:grep/:make)'] = false,
270    ['feat(:grep'] = false,
271    ['feat(:grep/:make'] = false,
272    ["ci: you're saying this commit message just goes on and on and on and on and on and on for way too long?"] = false,
273  }
274
275  local failed = 0
276  for message, expected in pairs(test_cases) do
277    local is_valid = (nil == validate_commit(message))
278    if is_valid ~= expected then
279      failed = failed + 1
280      p(
281        string.format('[ FAIL ]: expected=%s, got=%s\n    input: "%s"', expected, is_valid, message)
282      )
283    end
284  end
285
286  if failed > 0 then
287    os.exit(1)
288  end
289end
290
291--- @class LintcommitOptions
292--- @field trace? boolean
293local opt = {}
294
295for _, a in ipairs(arg) do
296  if vim.startswith(a, '--') then
297    local nm, val = a:sub(3), true
298    if vim.startswith(a, '--no') then
299      nm, val = a:sub(5), false
300    end
301
302    if nm == 'trace' then
303      opt.trace = val
304    end
305  end
306end
307
308for _, a in ipairs(arg) do
309  if M[a] then
310    M[a](opt)
311  end
312end