Git configuration

There are 3 levels of git config; project, global and system.

  • project: Project configs are only available for the current project and stored in .git/config in the project’s > directory.
  • global: Global configs are available for all projects for the current user and stored in ~/.gitconfig.
  • system: System configs are available for all the users/projects and stored in /etc/gitconfig.

git支持多级配置,如:系统级、用户级、项目级、工作区级;它们的优先级如下:工作区级配置 > 项目级配置 > 用户级配置 > 系统级配置;每级配置记录在对> 应的配置文件中,通过 git config 命令设置的配置项 也都会写在对应的配置文件中,配置文件的具体信息如下:

  • /etc/gitconfig :系统级配置文件;对系统中所有用户都普遍适用的配置。若使用 git config 时用 –system 选项,读写的就是这个文件。
  • ~/.gitconfig :用户级配置文件;用户目录下的配置文件只适用于该用户。若使用 git config 时用 –global 选项,读写的就是这个文件。
  • 当前项目的 git仓库目录中的配置文件(也就是工作目录中的 .git/config 文件):这里的配置仅仅针对当前项目有效。若使用 git config 时用 > –local 选项 或 省略,读写的就是这个文件。
  • 工作区级配置文件 :这里的配置仅仅针对当前工作区有效。若使用 git config 时用 –worktree 选项,读写的就是这个文件。

面对不同类型的代码仓库,有时候我们需要使用不同的用户名,以及一些特殊一些的git参数。如何有效快速的设置,而不是按照一个一个repo去逐一的设置;但全局设置又兼顾不到一些剩余的代码仓库

编辑home目录下的 .gitconfig,按照如下配置的前提是:通常我们把一类代码仓库的放在一个目录下,例如按照公司名称来区分目录,或者是 gitlab_repo, github_repo这样来分。下面的代码片段只是展示最为简单的配置方法,可自行根据需求设置。

1
2
3
4
5
6
vim ~/.gitconfig

[includeIf "gitdir:~/company_a/"]
path = .gitconfig-company_a
[includeIf "gitdir:~/company_b/"]
path = .gitconfig-company_b

注意⚠️:

  • gitdir 后面的目录路径在最后需要包含 一个斜杠 “/”;后面的 Conditional 规则也是支持灵活匹配的
  • path 路径建议使用绝对路径

在对应的 .gitconfig-company_a.gitconfig-company_b 文件中,参数的设置就如何普通的 .gitconfig 一样,例如下面的代码片段。

如果是一些字段(如user.name)的值是一致的,也可以无需在多个gitconfig文件中声明,只在 home目录下的.gitconfig 文件中定义一次,等同于运行命令 git config --global user.name "John Doe"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[user]
name = John Smith
email = john.smith@companya.net

[core]
sshCommand = ssh -i ~/.ssh/id_rsa_companya

#### or
[credential]
helper = osxkeychain
[pull]
rebase = true
[rebase]
autostash = true
[gpg]
program = gpg
[commit]
gpgsign = true

[http "http://git.cn.companyB.net"]
sslVerify = false

如何查看我们设置的参数是否生效了

1
2
3
4
5
$ git config --show-origin --get user.email
file:.git/config tomcat@companyA.net

$ git config user.email #并不能显示是哪个文件
tomcat@companyA.net

另外也可以通过命令的形式将参数写入具体的文件中,例如 git config -f 对应的配置文件/的路径/gitconfig_company_c user.email abcdef@qq.com`

更多详细的gitconfig中的参数可以参考 https://git-scm.com/docs/git-config,或者在本地用man命令查看, 如 $ man git-config


reference links:

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2019-2024 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~