构建高质量软件:持续集成与持续交付系统实践
上QQ阅读APP看书,第一时间看更新

3.5 Git的配置和别名操作

关于Git的配置,3.1节已有所涉及,本节将进一步深入讲解Git配置的更多知识。在Git中,所有的配置均存储于文本文件中,并使用git config命令进行管理。

3.5.1 Git的基本配置

Git的配置包含三个不同的作用域,分别为system、global和local,它们的配置信息分别存储在操作系统的不同位置中,具体说明如下。

  • system:“/etc/gitconfig”文件,作用于当前机器中所有用户的Git仓库。
  • global:“~/.gitconfig”文件,作用于当前用户的所有Git仓库。
  • local:“.git/config”文件,仅作用于某个Git仓库。

虽然可以手动配置这些文件,但是笔者还是建议大家通过git config命令进行配置,以免引起错误。配置命令具体如下。

# 列出Git的所有配置项。
> git config --list
user.email=alex@wangwenjun.com
user.name=Alex Wang
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
remote.origin.url=git@github.com:wangwenjun/git_section.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master
branch.dev.remote=origin
branch.dev.merge=refs/heads/dev
branch.test.remote=origin
branch.test.merge=refs/heads/test
# 仅列出local作用域的配置项。
> git config --list --local
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
remote.origin.url=git@github.com:wangwenjun/git_section.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master
branch.dev.remote=origin
branch.dev.merge=refs/heads/dev
branch.test.remote=origin
branch.test.merge=refs/heads/test
#在global作用域中新增配置。
> git config --global core.editor vim
#在system作用域中新增配置。
> git config --system user.email 'alex@wangwenjun.com'

如果local、global和system中拥有相同的配置项,则local的配置会优先生效,因为Git配置项的生效优先级采用就近原则,顺序依次为:local>global>system。

3.5.2 Git的别名

Git也支持将一些比较复杂或书写较长的命令定义成别名,保存在Git的配置文件中,这有点类似于UNIX/Linux的别名操作,请看下面的示例代码。

# 新增别名配置,请注意配置别名的格式,必须要有“alias.”作为前缀。
> git config --global alias.nice 'log --graph --decorate --pretty=oneline --abbrev-commit'
> git config --global --list
user.email=alex@wangwenjun.com
user.name=Alex Wang
core.editor=vim
alias.nice=log --graph --decorate --pretty=oneline --abbrev-commit
# 使用配置的别名。
> git nice
* 3eb4cc6 (HEAD -> dev, origin/dev) add the new file test.txt
* ed7caa7 (tag: v0.0.1, origin/master, master) initial commit

别名可用于将一些常用的Git命令保存在配置文件中以方便操作。