Skip to content

Instantly share code, notes, and snippets.

@deskid
Created September 2, 2017 19:05
Show Gist options
  • Save deskid/d025f48d4cc7e25b51e3c999c00c2a19 to your computer and use it in GitHub Desktop.
Save deskid/d025f48d4cc7e25b51e3c999c00c2a19 to your computer and use it in GitHub Desktop.
auto change git user
#!/usr/bin/env bash
# 用 repo 的 "remote.origin.url" 来匹配user配置
git_remotes[0]="github"
git_remotes[1]="gitlab"
# user info配置
local_id_0[0]="github user"
local_id_0[1]="github email"
local_id_1[0]="gitlab user"
local_id_1[1]="gitlab email"
# 默认 User info
local_fallback_id[0]="${local_id_0[0]}"
local_fallback_id[1]="${local_id_0[1]}"
# 设置 Use info
setIdentity()
{
local current_id local_id
current_id[0]="$(git config --get --local user.name)"
current_id[1]="$(git config --get --local user.email)"
local_id=("$@")
if [[ "${current_id[0]}" == "${local_id[0]}" &&
"${current_id[1]}" == "${local_id[1]}" ]]; then
printf " Local identity is:\n"
printf "» User: %s\n» Mail: %s\n\n" "${current_id[@]}"
else
printf "» User: %s\n» Mail: %s\n\n" "${local_id[@]}"
git config --local user.name "${local_id[0]}"
git config --local user.email "${local_id[1]}"
fi
return 0
}
current_remote_url="$(git config --get --local remote.origin.url)"
if [[ "$current_remote_url" ]]; then
for service in "${git_remotes[@]}"; do
# 关闭正则匹配的大小写
shopt -s nocasematch
if [[ "$current_remote_url" =~ $service ]]; then
case "$service" in
"${git_remotes[0]}" )
printf "\n»» An Intermission\n» %s repository found." "${git_remotes[0]}"
setIdentity "${local_id_0[@]}"
exit 0
;;
"${git_remotes[1]}" )
printf "\n»» An Intermission\n» %s repository found." "${git_remotes[1]}"
setIdentity "${local_id_1[@]}"
exit 0
;;
* )
printf "\n» pre-commit hook: unknown error\n» Quitting.\n"
exit 1
;;
esac
fi
done
else
printf "\n»» An Intermission\n» No remote repository set. Using local fallback identity:\n"
printf "» User: %s\n» Mail: %s\n\n" "${local_fallback_id[@]}"
git config --local user.name "${local_fallback_id[0]}"
git config --local user.email "${local_fallback_id[1]}"
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment