利用Git-hook自动配置不同仓库的用户信息

苏茂林

微博上看到的 利用Git-hook自动配置不同仓库的用户信息,看了下平时也有这样的情况,不过没有在意过,现在看到了就要改啦!

看了下里面的参考链接:

  1. 让你的git拥有不同身份
  2. Automatic setup of user identity (user.email / user.name) on git clone

遇到的问题是我 我在windows 7 系统下paht路径识别的问题:
~/.git-templates 改成了 E:/Program Files/.git-templates

post-checkout的内容中涉及的 ~/.git-clone-init 改成了 "E:/Program Files/.git-templates/hooks/.git-clone-init" 记得加 " windows下没引号会引起转义错误,上全部代码!

post-checkout

#!/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 "E:/Program Files/.git-templates/hooks/.git-clone-init" ]]; then
cat << INPUT > "E:/Program Files/.git-templates/hooks/.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
. "E:/Program Files/.git-templates/hooks/.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>"

.git-clone-init

case "$url" in
  *@github.com:* ) email="sumaolin@gmail.com";    name="sumaolin";;
  *//github.com/* ) email="sumaolin@gmail.com";    name="sumaolin";;
  *@git.kmtongji.com:* ) email="sumaolin@kongming-inc.com"; name="sumaolin";;
  *//git.kmtongji.com/* ) email="sumaolin@kongming-inc.com"; name="sumaolin";;
  *@git.coding.net:* ) email="sumaolin@qq.com"; name="sumaolin";;
  *//git.coding.net/* ) email="sumaolin@qq.com"; name="sumaolin";;
esac

不同的git地址匹配不同的账号,添加规则的时候注意正则的匹配规则!

设置完成后还要设置git hook生效:

git config --global init.templatedir ~/.git-templates
阅读 1.6k

努力做个全栈吧!

109 声望
3 粉丝
0 条评论
你知道吗?

努力做个全栈吧!

109 声望
3 粉丝
宣传栏