Gerrit Code Review

在公司平常使用 Gerrit 代码审核方式,平常提交代码需要分为两步

1
2
git commit -m "msg"
git push origin HEAD:refs/for/${branch}

每次都要打一串代码比较麻烦,比 git push 长了很多,有没有办法简化呢?答案是有的,通过 shell 的 alias 将一个复杂的 shell 函数对应到一个简单的命令上,比如 gcmit "这是我的提交信息",一次就解决了 git commit 和 push 两条命令

同样的方式也可以单独搞一个 git push 的简化版,不过我比较懒就这样吧

函数说明

这个函数分了以下几步

  • 首先检查是否提供了提交信息。
  • 使用提供的消息执行 git commit 命令。
  • 是否提供了分支名,如果没有就获取当前分支名称。
  • 使用分支名称执行 git push,将提交推送到 Gerrit 代码审查系统的 refs/for/branch_name 引用。

简化提交代码

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
gcmit() {
# 检查是否有提交信息作为第一个参数传递
if [ -z "$1" ]; then
echo "Error: Commit message is required."
return 1
fi

# 第二个参数,如果提供,则使用该分支名称
local target_branch="$2"

# 如果没有提供第二个参数,则获取当前分支名称
if [ -z "$target_branch" ]; then
target_branch=$(git rev-parse --abbrev-ref HEAD)

# 检查是否成功获取分支名称
if [ -z "$target_branch" ]; then
echo "Error: Failed to get current branch name."
return 1
fi
fi

# 执行 git commit
git commit -m "$1"

# 检查 git commit 是否成功
if [ $? -ne 0 ]; then
echo "Error: Git commit failed."
return 1
fi

# 执行 git push
git push origin HEAD:refs/for/$target_branch
}

alias gcmit=gcmit

使用

将下面的函数保存在 shell 配置文件末尾,然后重新加载配置文件,例如运行 source ~/.bashrc 或者 source ~/.zshrc,或者简单地关闭并重新打开终端,就可以了