Processing math: 100%

3.08.2015

Working with Multiple GitHub Accounts

複数のGitHubアカウントを使い分ける

 

モチベーション

  • クローン元のリポジトリによって、接続する GitHub アカウントを使い分ける
  • GitHub アカウントが異なれば、SSH 鍵も異なる
  • Git にコミットする user.name, user.email もアカウントによって切り替えたい

セットアップ

ディレクトリを作成

mkdir -p ~/.git-wrapper/shims
mkdir -p ~/.git-wrapper/ssh

ssh ディレクトリに実行ファイルを作り、SSH鍵との紐付けを定義

~/.git-wrapper/ssh/ssh-yourname-1
#! /bin/sh
exec ssh -oIdentitiesOnly=yes -oIdentityFile=~/.ssh/yourname1.github "$@"
~/.git-wrapper/ssh/ssh-yourname-2
#! /bin/sh
exec ssh -oIdentitiesOnly=yes -oIdentityFile=~/.ssh/yourname2.github "$@"

shims ディレクトリにラッパーシェルを作る。18-26行目は適宜書き換える。

  • ~/.git-wrapper/shims/git
#!/bin/bash
GIT=/usr/local/bin/git
SCRIPT_DIR=(cd"( dirname "$0" )" && pwd -P )
if [ "$1" = "clone" ]; then
origin_url="$2"
else
# check if current directory is under git repository
origin_url=("GIT" config --get remote.origin.url) || {
"GIT""@"
exit $?
}
fi
# definitions
case ${origin_url} in
git@github.com:your-company/*)
readonly user_name='Your name 1'
readonly user_email='youremail1@example.com'
readonly git_ssh='ssh-yourname-1'
;;
*)
readonly user_name='Your name 2'
readonly user_email='youremail2@example.com'
readonly git_ssh='ssh-yourname-2'
;;
esac
# check name and email
if [ "$1" != "clone" ]; then
current_name=("GIT" config --get user.name) || {
echo "Failed to get user name. Aborted."
exit 1
}
current_email=("GIT" config --get user.email) || {
echo "Failed to get user email. Aborted."
exit 1
}
if [ "currentname"!="{user_name}" ]; then
echo "Setting user name: \"GIT\"configuser.name\"{user_name}\""
"GIT"configuser.name"{user_name}"
fi
if [ "currentemail"!="{user_email}" ]; then
echo "Setting user email: \"GIT\"configuser.email\"{user_email}\""
"GIT"configuser.email"{user_email}"
fi
fi
# launch git command
GIT_SSH="SCRIPTDIR/../ssh/{git_ssh}" "GIT""@"
view raw git-wrapper hosted with ❤ by GitHub

.bashrc または .zshrc で以下のようにパスを追加

export PATH="${HOME}/.git-wrapper/shims:${PATH}"

注意

A-7 無料アカウントを複数作るのは規約違反。

GitHub Terms of Service - User Documentation

 

References

0 件のコメント:

コメントを投稿