lintcommit.lua 8.5 KB

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