下面是使用 git 过程中遇到的问题

公司的仓库设置 name, email 为 姓名,公司邮箱。github 的仓库设置为 name, email 为 kntt, 个人邮箱。每次拉去新仓库都需要手动设置非常麻烦!

每次 clone 完新仓库,都需要git config --local user.email,git config --local user.name设置,非常麻烦。如果忘记设置了,你会发现你在公司的仓库提交记录是你的 github 昵称和邮箱,或者反过来!

怎样才可以根据拉去的仓库不同自动是这 author,email 呢?

下面分享一下我的配置,自动化根据仓库地址设置不同的 name&email。

以 mac 用户为例:

1. 在用户目录创建文件夹 ~/.git-templates/hooks

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
36
37
38
39
40
41
42
43
44
#!/bin/bash

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

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. 在用户目录创建~/.git-clone-init 文件

1
2
3
4
5
6
7
8
9
case "$url" in
*@github.com:* ) email="youemail@example.com"; name="Nickname";;
*//github.com/* ) email="youemail@example.com"; name="Nickname";;
*@gitee.com:* ) email="youemail@example.com"; name="Nickname";;
*//gitee.com/* ) email="youemail@example.com"; name="Nickname";;
*@gitlab.company.com:* ) email="youemail@company.com"; name="username";;
*//gitlab.company.com/* ) email="youemail@company.com"; name="username";;

esac

在这里可以根据自己的需要,增加需要特殊处理的仓库地址,以及地址对应的 author,email。

两条地址,分别对应的 ssh 方式认证,或者 https 方式认证。

3. 最后一步,配置 git 的 init 钩子, 在全局的~/.gitconfig中增加如下内容

1
2
3
4
[init]
templatedir = /Users/you_user_name/.git-templates
# other config
# ...

4. 最后验证一下

当你看到Identity set to you_name <you_email>时,证明配置成功!
如果其他的提示,请按着提示检查配置是否正确~
对于以前拉取的仓库,需要重新拉取才会执行配置

最后的最后

留下一点悬念,留待下次整理

如果你有两个 github 账号,都需要配置 ssh 认证,如何才能拉取不同账号仓库时,使用不同的私钥认证呢? 如何设置为不同账号的 name&email 呢?

希望能提升你的开发效率,开发幸福感~