前言
在团队合作中,code review 不仅能更好的发现代码中可能存在的隐患,也能让大家有一个平台能互相交流学习,那么选用合适的工具来做 code review 就很关键了,本文介绍使用 phabricator 来做 code review。
在做 code review 时,提交的代码只有在 review 通过后,才能入库,所以我们需要通过拦截用户的提交,来强制做 code review。强制拦截的方式有两种:
大家都习惯在 gitlab 上进行代码托管,故本文结合 gitlab 喝 phabricator 来实现 code review。
gitlab server 添加 hook
gitlab 服务端 hook 分为两种,一种是针对单个仓库局部生效,一种是针对所有仓库全局生效。
局部 hook
局部 hook 配置的方式如下
1、gitlab server进入到具体的仓库路径下;2、创建自定义hook目录,mkdir custom_hooks;3、创建pre-receive文件;4、修改文件权限为755;
复制代码
备注:可以参考文章 https://xie.infoq.cn/article/b077c8d4b793369de4c4eb347 进行局部 hook 的配置。
全局 hook
1.开启gitlab的自定义hook参数vim /etc/gitlab/gitlab.rb #配置如下 gitlab_shell['custom_hooks_dir'] = "/opt/gitlab/embedded/service/gitlab-shell/hooks/custom_hooks" #取消这行注释,默认是注释2.mkdir -p /opt/gitlab/embedded/service/gitlab-shell/hooks/custom_hooks/pre-receive.d # 创建目录3.touch /opt/gitlab/embedded/service/gitlab-shell/hooks/custom_hooks/pre-receive.d/pre-receive #创建文件pre-receive 4.chmod 755 /opt/gitlab/embedded/service/gitlab-shell/hooks/custom_hooks/pre-receive.d/pre-receive 5.pre-receive #文件内容如上6.gitlab-ctl reconfigure #重新加载gitlab的配置, 使配置生效
复制代码
code review 脚本
code review 的服务端 hook 脚本代码如下,根据 hook 的部署方式进行局部部署或者全部部署即可。
#!/bin/bin/env python
import sysimport reimport requestsimport osimport jsonimport fileinput
PhabricatorUrl = "***/api/differential.query"ApiToken = "api-***"
def has_been_reviewed(origin_commit, curr_commit): ''' @name: 该commit是否被review通过 @msg: @param {*} @return True/False ''' cmd = 'git rev-list %s...%s' % (origin_commit, curr_commit,) Flag = False commits = os.popen(cmd).readlines() pattern = re.compile(r'Differential Revision: (.*)') for commit in commits: cmd = 'git rev-list --format=' + '%s%b ' + '--max-count=1 %s' % commit res = os.popen(cmd).readlines()[-2] match_str = pattern.match(res) if not match_str: print("Please use 'arc diff' to commit") continue http_url = match_str.group(1) phcid = int(http_url.split("/")[-1][1:]) url = "{}?api.token={}&ids[0]={}".format( PhabricatorUrl, ApiToken, phcid) info = json.loads(requests.get(url).text) for i in info['result']: if i['uri'] != http_url: continue if int(i['status']) == 2: Flag = True else: print("Current Status: %s, Need Review and Accepted" % i['statusName']) break
if Flag: sys.exit(0) else: sys.exit(1)
if __name__ == "__main__": origin_commit, curr_commit, branch = None, None, None # 读取用户试图更新的所有引用 for line in fileinput.input(): line_list = line.strip().split() if len(line_list) >= 3: origin_commit, curr_commit, branch = line_list[:3] break
has_been_reviewed(origin_commit, curr_commit)
复制代码
代码详解:
1、12-13 行是 pharicator 的部署域名及 API token;
2、56-62 行从 gitlab 标准输入中获取本次提交的 commit id;
3、28 行从 git log 中获取使用 arc diff 命令提交到 phabricator 系统中 review 的 url;
4、36-47 行从 phabricator 获取到本次 review 的状态,来决定是否将本次提交入库;
参考链接
1、phabricator 官网:https://www.phacility.com/phabricator/
2、phabricator 安装教程
评论