现在团队采用 Angular 代码规范,需要对提交到 gitlab 的代码进行验证,由于 gitlab 提供了 hooks 机制,所以做起来还是毕竟方便的,这里写一些我怎么做的
首先 Angular 代码规范参考: http://www.ruanyifeng.com/blog/2016/01/commit_message_change_log.html
gitlab 的 hook 机制参考: https://docs.gitlab.com/ee/administration/server_hooks.html
也就是说我们可以在 pre-receive 、update 和 post-receive 这 3 个阶段来对 commit message 进行验证,我之前写的的在 update 中验证的,你可以选你熟悉的脚本语言来写。在 gitlab 调用 update 脚本的时候会传入更新的 2 个 commit 的 hash ID,然后在这里可以调用 git 来解析出有哪些 commit 需要验证(你最好找个别人写好的解析 git commit message 的库),如果验证通过就返回 0,否则返回非 0,标准输出可以在 git push 的命令行中看到。需要注意的时候当 push 的为 tag 或者新的分支的时候,hash ID 可能为“0000000000000000000000000000000000000000”,还有就是“Merge branch”的需要考虑边界情况,大部分都是内容处理没啥可说的。如果你们还有别的要求,可以自己加。
Angular 规范正则可以写成:
//匹配 Angular 规范关键字
$res = preg_match("#^\s*(feat|fix|docs|style|refactor|test|chore)(\(.+\))?\:.+#", $message, $matches); if(!$res){ $msg = "your commit message format is wrong, see:'http://www.ruanyifeng.com/blog/2016/01/commit_message_change_log.html', message:{$message}"; if($NEED_VERIFY){ log_file($msg, true); exit(1); }else{ log_file($msg); } } 最后就是,在某些情况下我们需要 skip 掉验证,但是 hook 没有提供额外的参数,这里只有手动去改了,搜了一下 gitlab 用了 git push -o 的参数,在 pre-receive 下,加上这行:
refs = $stdin.read require_relative '../lib/hooks_utils' push_optiOns= HooksUtils.get_push_options if push_options[0]=="skip" aFile = File.new("/tmp/gitlab-skip", "w") if aFile cOntent= aFile.syswrite(refs) else puts "Unable to open /tmp/gitlab-skip" end end 然后在 update 脚本里检查的时候去 /tmp/gitlab-skip 读取 commit 的 hash,看相等就跳过验证
