利用Git-hook自動配置不同倉庫的使用者資訊

蘇茂林發表於2018-03-14

微博上看到的 利用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 "
$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 "
Missing 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 "
Identity 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地址匹配不同的賬號,新增規則的時候注意正則的匹配規則!

相關文章