自动配置Git仓库提交作者
Contents
1. 背景
公司使用的代码仓库是Gitlab
,个人代码仓库又是Github
。每次提交代码的时候,需要切换不同的提交作者和提交邮箱,非常容易出错。
这个脚本是根据repo url自动设置提交作者,避免每次手动配置。
2. 方法
2.1 安装Git
Linux
上安装Git
直接使用sudo yum install git
或者sudo apt-get install git
命令即可。Windows
上安装到官网下载安装软件安装即可。安装地址
2.2 添加脚本
在/root/下添加.git-templates/hooks
目录,添加脚本post-checkout
,脚本内容如下:
#!/bin/bash
#checkout hook to locally set user name and email based on user defined patterns
#The patterns are matched against the clone url.
#
#Based on http://www.dvratil.cz/2015/12/git-trick-628-automatically-set-commit-author-based-on-repo-url/
function warn {
echo -e "\n$1 Email and author not initialized in local config!"
}
email="$(git config --local user.email)"
name="$(git config --local user.name)"
if [[ $1 != "0000000000000000000000000000000000000000" || -n $email || -n $name ]]; then
exit 0
fi
#get remote name:
# only one: take it
# more: take "origin", or fail
remote="$([[ $(git remote | wc -l) -eq 1 ]] && git remote || git remote | grep "^origin$")"
if [[ -z $remote ]]; then
warn "Failed to detect remote."
exit 0
fi
url="$(git config --local remote.${remote}.url)"
if [[ ! -f ~/.git-clone-init ]]; then
cat << INPUT > ~/.git-clone-init
#!/bin/bash
case "\$url" in
*@github.com:* ) email=""; name="";;
*//github.com/* ) email=""; name="";;
esac
INPUT
warn "\nMissing file ~/.git-clone-init. Template created..."
exit 0
fi
. ~/.git-clone-init
if [[ -z $name || -z $email ]]; then
warn "Failed to detect identity using ~/.git-clone-init."
exit 0
fi
git config --local user.email "$email"
git config --local user.name "$name"
echo -e "\nIdentity set to $name <$email>"
2.3 添加配置文件
在/root/.gitconfig
文件中(没有的话自行创建)添加如下内容,指定使用的模板:
[user]
[init]
templatedir = /root/.git-templates
[push]
default = simple
在/root/.git-clone-init
中针对不同的git仓库添加提交作者和邮箱:
#!/bin/bash
case "$url" in
*@github.com:* ) email="test@qq.com"; name="xq";;
*//github.com/* ) email="test@qq.com"; name="xq";;
*@gitlab.com:* ) email="test@google.com"; name="xq";;
*//gitlab.com/* ) email="test@google.com"; name="xq";;
esac
2.4 验证
- 更改脚本
post-checkout
的权限并执行。sudo chmod 777 post-checkout
sh post-checkout
- 尝试从github 克隆一个仓库:可以看到最后一行的打印出来的信息,自动针对该仓库设置了提交作者和邮箱,下一次提交就会使用这个提交作者和邮箱。
[root@yxj-test git_storage]# git clone git@github.com:XueqiangChen/scripts.git Cloning into 'scripts'... Warning: Permanently added the RSA host key for IP address '52.74.223.119' to the list of known hosts. remote: Enumerating objects: 8, done. remote: Counting objects: 100% (8/8), done. remote: Compressing objects: 100% (6/6), done. remote: Total 8 (delta 0), reused 5 (delta 0), pack-reused 0 Receiving objects: 100% (8/8), done. Identity set to XueqiangChen <569503960@qq.com>
欢迎访问GITHUB查看具体代码!!!
参考文章