1 つのマシンで2つの git のユーザーを簡単に切り替える方法
使うモノ
ghq ... ローカルのリポジトリが管理が簡単にできる
direnv ... 指定のディレクトリ事に環境変数を設定できる
今回は private(個人開発用) と business(仕事用) を切り替えることを想定します
また、動作検証などは ssh でのみ行っています
1.ghq を用いつつクローン時に設定を良い感じに書き換えるスクリプトの準備
private-ghq
#!/usr/bin/env ruby
github_host = "private.github.com"
username = "private-user" ## 適宜書き換える
email = "[email protected]" ## 適宜書き換える
if ARGV[0] == "get"
args = []
repo = ""
ARGV[1..-1].each do |arg|
repo = arg if arg.match(/^[email protected]/)
args << arg.gsub(/^[email protected]/, "git@#{github_host}")
end
system "ghq", "get", *args
exit_code = $?.to_i
unless repo.empty?
dir = repo.match(/^[email protected]:([^.]*)(\.git)?/)[1]
ghq_root = `ghq root`.chomp
Dir.chdir(File.join(ghq_root, "#{github_host}/#{dir}/")) do
system "git config user.name '#{username}'"
system "git config user.email #{email}"
end
end
exit exit_code
else
exec "ghq", *ARGV
end
work-ghq
#!/usr/bin/env ruby
github_host = "work.github.com"
username = "work-user" ## 適宜書き換える
email = "[email protected]" ## 適宜書き換える
if ARGV[0] == "get"
args = []
repo = ""
ARGV[1..-1].each do |arg|
repo = arg if arg.match(/^[email protected]/)
args << arg.gsub(/^[email protected]/, "git@#{github_host}")
end
system "ghq", "get", *args
exit_code = $?.to_i
unless repo.empty?
dir = repo.match(/^[email protected]:([^.]*)(\.git)?/)[1]
ghq_root = `ghq root`.chomp
Dir.chdir(File.join(ghq_root, "#{github_host}/#{dir}/")) do
system "git config user.name '#{username}'"
system "git config user.email #{email}"
end
end
exit exit_code
else
exec "ghq", *ARGV
end
2. .ssh/config
の設定を追記
Host work.github.com
HostName github.com
IdentityFile ~/.ssh/work
User git
AddKeysToAgent yes
UseKeychain yes
TCPKeepAlive yes
IdentitiesOnly yes
Host private.github.com
HostName github.com
IdentityFile ~/.ssh/private
User git
AddKeysToAgent yes
UseKeychain yes
TCPKeepAlive yes
IdentitiesOnly yes
3. clone をする
趣味アカウントで操作をしたい場合は private-ghq
仕事アカウントで操作をしたい場合はwork-ghq
を、利用して clone します
./private-ghq get [email protected]:konnta0/wabl-cs.git
or
./work-ghq get [email protected]:company/repository.git
4.ディレクトリによって git user を自動的に切り替えるようにする
ghq の設定はデフォルトと想定します。
これの設定を行う事によって指定のディレクトリ内に移動したときに自動でコミッターなどの環境変数が変更されます。
$ cd ~/ghq/private.github.com
$ cat << EOF > .envrc
export GIT_COMMITTER_NAME="private-user"
export GIT_COMMITTER_EMAIL="[email protected]"
export GIT_AUTHOR_NAME="private-user"
export GIT_AUTHOR_EMAIL="[email protected]"
EOF
$ direnv allow
$ cd ~/ghq/work.github.com
$ cat << EOF > .envrc
export GIT_COMMITTER_NAME="work-user"
export GIT_COMMITTER_EMAIL="[email protected]"
export GIT_AUTHOR_NAME="work-user"
export GIT_AUTHOR_EMAIL="[email protected]"
EOF
$ direnv allow