gitの認証切り替えるfor mac


| 3 min read | engineering github git

gitで個人のprivateリポジトリのpullなどもできるようにしたかった

httpsでの認証方法について調べたのでメモ

環境

  • git: 2.34.1

1. リポジトリごとに設定(local config)

localのconfigに設定することでリポジトリ単位(.git単位)で認証設定できるようになる

  • localでのconfig設定
git config --local credential.helper osxkeychain

これで個別なキーチェーンを参照するようになる

認証情報の保存先としてmacのキーチェーンアクセスを使うため、一度認証すればOK

  • 確認

globalの設定が上に、localの設定が下に表示される。おそらく後勝ちで適用される

user.nameとuser.emailも変えておく

git config --list
credential.helper=osxkeychain
init.defaultbranch=main
user.name=yuni
user.email=xxxx
...
core.precomposeunicode=true
user.name=uni
user.email=xxxx
remote.origin.url=https://github.com/uni-3/repository.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
credential.helper=osxkeychain

2. 特定フォルダ以下について切り替える(includeIf)

chatGPTに教えてもらった。特定のフォルダ以下で適用されるため複数の(個人の)リポジトリの設定を管理したい場合に便利

  • globalのconfig設定

includeIf以下のときに、特定の.gitconfigを反映させる

# ~/.gitconfigに追記
[includeIf "gitdir:~/my_repos/"]
path = ~/my_repos/.gitconfig
 

~/my_repos/.gitconfig に適用したい場合の設定作成

[user]
    name = uni
    email = xxxx
 
[credential "https://github.com"]
    username = uni-3
    helper = osxkeychain

以下のコマンドで設定が有効になっているか確認。~/my_repos以下で実行してみる。指定したpathのものを読み込んでいれば成功

git config --list --show-origin
...
file:~/my_repos/.gitconfig        user.name=uni
file:~/my_repos/.gitconfig        user.email=xxx
 

確認

pullしてみる

  • git remoteの設定

リモートリポジトリのURLにユーザー名をつけて設定する

 
# 変更の場合はgit remote set-url origin {URL}
git remote add origin https://{username}@github.com/{owner}/repository.git 
 

この状態でgit pull origin mainなどを実行すると認証情報の入力モーダルが表示されるので

ユーザー名=ユーザー名

パスワード=パーソナルアクセストークン

を入力。パーソナルアクセストークンは以下のページから作成する

https://github.com/settings/personal-access-tokens

注意点

  • ghコマンドはまた別に認証しているため、git cloneなどで操作する必要がある
  • local configの場合はgit initしてconfigを追加しなければならない

参考