How to use VScode with multiple GitHub accounts

How to use VScode with multiple GitHub accounts

First of all, you need 2 GitHub account and you have to generate two pairs of ssh-keys

ssh-keygen -t rsa -b 4096 -C "personal_email@gmail.com"
ssh-keygen -t rsa -b 4096 -C "company_email@gmail.com"

It is important during the creation of the second key to use a different file to store the key otherwise the first key will be overwritten.

Now that you have 2 pairs of keys you need to go on our GitHub accounts and insert the public key one for each account, in Settings>>SSH and GPG keys, just copy-paste the key in the text box and assign it a title.

Now in the in C\Users\'username'\.ssh directory you have to create a file named config (without extension, with vscode just a right-click and create a new file). Inside config you have to insert this code

Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa

Host github.com-COMPANY
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_company

Where id_rsa and id_rsa_company are the files that you created during the first step with ssh-keygen

Now to clone a repository it's simply necessary to change the URL in the clone command

git clone git@github.com:(Repo path).git

git clone git@github.com-COMPANY:(Repo path).git

Where Repo path is the name of the directory on GitHub, so if you need to clone a directory on your personal GitHub account nothing change but to clone a directory on the company GitHub account it's necessary to add the -COMPANY string in the command.

Now on VScode, it's necessary to download an extension:

Senza nome.png

With this extension every time you open a new directory connected to git, it forces you to set the username and email of the GitHub account associated with that directory. After you have entered the data of both accounts once, it is possible to quickly choose which account to use without having to enter username and password each time. This data are store in the JSON configuration file of vscode (ctrl + shift + p and type open settings JSON)