icon
git-tricks-learn-during-internship

2023年10月3日星期二 下午1:35

實習時學到的 Git 用法

When I was having my internship, I found that the git account is basically shared among all the directory. It’s kinda awkward when you doing both the development of personal and company on your own laptop. The commit email might happen to be your personal account if you not aware of it.

Therefore, I need a way to kind of separate the accounts and use the right one corresponding to the project.

That’s what I found:

3 Levels of git configuration

  1. local
  2. global
  3. system
# local
git config --local  --get-all user.email #local repo git config file)

# global
git config --global --get-all user.email #user config file)

# system
git config --system --get-all user.email #system git config file)

Duplicated values

You might find that your configurations will be combined all together in a directory when you type git config --list inside a project directory. So it might be confusing at the glimpse and not knowing which one is being used.

Basically, the last one wins.

# to confirm which one git is using
git config --get user.email

Customized git for single repo

For every local repo, there's a folder name .git that is comprised of all the information required for version control. There's one file named config which lays all the local configurations.

We can then set the user info for this single repo:

[user]
	name = your_name
	email = your_email@gmail.com

Customized git for directories

Even though we can configure the git account for a specific project, however, it could be cumbersome every time you are working on a new project. To make your life easier, we can nominate a file .gitconfig for a specific directory at the root of it. Then all the projects inside the directory will be automatically preset.

Let's say we are working for two companies:

# ~/company-A/.gitconfig
[user]
	name = your_name
	email = your_email@companyA.com
# ~/company-B/.gitconfig
[user]
	name = your_name
	email = your_email@companyB.com

Then we need to update the global .gitconfig.

# ~/.gitconfig, add the following

[includeIf "gitdir:~/company-A/"]
		path = ~/company-A/.gitconfig

[includeIf "gitdir:~/company-B/"]
		path = ~/company-B/.gitconfig

Reference

  1. Customize git for all projects in a directory: https://alysivji.github.io/multiple-gitconfig-files.html
  2. Stack Overflow, More than one value for the key user.name Git: https://stackoverflow.com/questions/4310974/more-than-one-value-for-the-key-user-name-git