基于当前路径的不同 .gitconfig

noi*_*ixy 5 zsh git

在我的.zshrc文件中,我有一个基于当前路径设置环境变量的chpwd函数GIT_CONFIG

像这样的东西:

update_gitconfig() {
  if [[ "$(pwd | grep -Poe '^/home/user/repositories/user-A(/|$)')" != "" ]]
  then
    export GIT_CONFIG="$HOME/.gitconfig-A"
    return
  fi

  if [[ "$(pwd | grep -Poe '^/home/user/repositories/user-B(/|$)')" != "" ]]
  then
    export GIT_CONFIG="$HOME/.gitconfig-B"
    return
  fi

  export GIT_CONFIG="$HOME/.gitconfig-default"
}

update_gitconfig
chpwd_functions+=(update_gitconfig)
Run Code Online (Sandbox Code Playgroud)

如果我运行git config --list,它会在每个目录下显示预期的配置:

  • $HOME/repositories/user-A它下面显示来自 的设置$HOME/.gitconfig-A
  • $HOME/repositories/user-B它下面显示来自 的设置$HOME/.gitconfig-B
  • 在其他任何地方,它都会显示$HOME/.gitconfig-default.

当我运行时,问题就开始了git commit;它似乎没有得到设置:

*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: unable to auto-detect email address (got 'user@host.(none)')
Run Code Online (Sandbox Code Playgroud)

所以,问题是:

有没有办法强制git commit$GIT_CONFIG文件中获取信息?

注意:我知道我可以git configchpwd钩子中运行命令来自动将本地设置应用于每个存储库,但我正在寻找一种更“优雅”的方式。

小智 2

Git v1.6.0 发行说明包含一条线索:

GIT_CONFIG, which was only documented as affecting "git config", but
actually affected all git commands, now only affects "git config".
Run Code Online (Sandbox Code Playgroud)

git v1.8.2 修复了git clone仍然受到影响的命令的新行为。

我感兴趣的解决方法是:

  • 根据需要与尽可能多的用户一起使用 git su命令行工具可以提供帮助)
  • 写出像alias gitcommit='git commit --author=$(git config user.email)' (ugly)这样的别名。
  • 将配置文件复制到存储库本地配置中(任何配置修改都必须手动传播)
  • ~/.gitconfig通过环境变量覆盖进行虚假查找HOME。例如:HOME=~/.gitconfig/user-a/ git commit应该阅读~/.gitconfig/user-a/.gitconfig (可能有一些其他副作用)

另外,如果您使用chpwdzsh hook,请注意支持在多个存储库中运行的多个 zsh。