gitgithubgithub-for-mac

Set git credentials based on folder


Is it possible to have a folder that contains multiple repos use one set of credentials and have another folder user a different account? For example I would like to have one folder on my mac for work repos and one folder for personal and have the git username and password automatically switch based on which folder I am in.


Solution

  • After a lot of searching I found what I was looking for (but maybe not exactly what I initially asked). The solution I went with was to use ssh. Github has some good help docs to follow here (under authenticating) but basically you have to 1. Generate a ssh key for each account and add it to the ssh agent* 2. Add the ssh key to your github accounts 3. On a mac Update the config file in ~/.ssh/config (scroll down to "choosing between multiple accounts on GitHub or Heroku")

    To fix this, I created a bash function, added it to the bash rc files for all shells so I can just call it as a terminal command. The code is here:

    #!/bin/bash
    
    function addSshKeysToAgent() {
      echo "starting ssh agent:"
      echo ""
    
      eval 'ssh-agent -s'
      echo ""
    
      echo "adding identities: "
      ssh-add -K ~/.ssh/personal_rsa
      ssh-add -K ~/.ssh/work_rsa
      echo ""
    
      echo "Private keys loaded into SSH: "
      ssh-add -l -E md5
      echo ""
    
      echo "ssh keys added to ssh agent."
    }
    
    function clone() {
      addSshKeysToAgent
      git clone gh-work:Company/$1
    }
    

    Replace personal_rsa and work_rsa with the name of your ssh key file and Company with your organization name (if that's what you want to do), which comes from the config file you updated. Here is how my config file looks:

    Host *
     Port 22
     ServerAliveInterval 60
     ForwardAgent yes
     UseKeychain yes
     AddKeysToAgent yes
     IdentityFile ~/.ssh/personal_rsa
     IdentityFile ~/.ssh/work_rsa
    
    Host gh-personal
      Hostname github.com
      User git
      IdentityFile ~/.ssh/personal_rsa
      AddKeysToAgent yes
      UseKeychain yes
    
    Host gh-work
      Hostname github.com
      User git
      IdentityFile ~/.ssh/work_rsa
      AddKeysToAgent yes    
      UseKeychain yes
    

    with all this, you should be able to clone a repo from the terminal with the following command:

    clone reponame.git
    

    I sincerely hope this helps someone out. It took me almost a full day of searching and hacking things together to get this working and as I was writing this response I came across a really great gist to do exactly what I wanted here