LoginSignup
218
212

More than 5 years have passed since last update.

gitのuser.nameとuser.emailを会社/個人で自動的に切り替える方法

Posted at

想定ユーザー

  • 仕事用のコミットとプライベートなコミットはuser.nameとuser.emailを分けたい
  • 個人のgitリポジトリでuser.nameとuser.emailを設定するの忘れて会社の設定でコミットしてしまった

上に当てはまる人は幸せになれるかも?

設定方法

  • よく使う方を--globalで設定しておく(今回は仕事用)
git config --global user.name "Taro Qiita"
git config --global user.email taro@qiita.com
  • プライベートなgitリポジトリの置き場を作る
mkdir ~/private
  • init.templatedirを--globalで設定する(pre-commitフックを全てのリポジトリに適応するため)
git config --global init.templatedir '~/.git_template'
  • ~/.git_template/hooksディレクトリにpre-commitフックを作る
~/.git_template/hooks/pre-commit
#!/bin/sh
# ここにプライベートで利用するnameとemailを設定
PRIVATE_NAME="qii-taro"
PRIVATE_EMAIL="qii-taro@gmail.com"
# 上で作ったプライベートな置き場の絶対パス
PRIVATE_DIR="/Users/taro/private"

if [ $(pwd | fgrep "$PRIVATE_DIR") ]; then
  if [ "$(git config user.name)" != "$PRIVATE_NAME" -o "$(git config user.email)" != "$PRIVATE_EMAIL" ]; then
    echo "Git init in private directory. Change user.name and user.email."
    git config user.name "$PRIVATE_NAME"
    git config user.email "$PRIVATE_EMAIL"
  fi
fi
exit 0
  • 最後にpre-commitファイルに実行権限を付与する
chmod +x ~/.git_template/hooks/pre-commit
  • 完了!

使い方

~/private以下に個人用リポジトリを置く。
このなかでgit initしたりgit cloneしたリポジトリは、コミット前に勝手にuser.nameuser.emailが書き換わるようになっている。

すでにあるリポジトリを~/private以下に移動させた場合、再度git initすればOK。

218
212
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
218
212