是否可以在.gitconfig中为每个通配符域配置user.name和user.email?

And*_*rew 30 git github

我有一台工作计算机,全局配置为在提交时使用我的工作电子邮件和名称.这很好.但是,我想制定某种规则,"如果回购来源是github,请使用用户X和电子邮件Y"

我意识到你可以为每个存储库创建一个配置条目,但我希望它更自动:如果克隆是github,它应该使用github用户详细信息.如果我从工作中克隆,它应该使用工作细节.

有没有办法根据远程域全局配置?或者另一种方式?

编辑/ UPDATE

我接受了下面的答案,但稍微修改了一下脚本:

#!/usr/bin/env bash

# "Real" git is the second one returned by 'which'
REAL_GIT=$(which -a git | sed -n 2p)

# Does the remote "origin" point to GitHub?
if ("$REAL_GIT" remote -v 2>/dev/null | grep '^origin\b.*github.com.*(push)$' >/dev/null 2>&1); then

    # Yes.  Set username and email that you use on GitHub.
    export GIT_AUTHOR_NAME=$("$REAL_GIT" config --global user.ghname)
    export GIT_AUTHOR_EMAIL=$("$REAL_GIT" config --global user.ghemail)

fi

"$REAL_GIT" "$@"
Run Code Online (Sandbox Code Playgroud)

主要添加是需要两个git config值.

git config --global user.ghname "Your Name"
git config --global user.ghemail "you@yourmail.com"
Run Code Online (Sandbox Code Playgroud)

这避免了对脚本中的值进行硬编码,从而使其更具可移植性.也许?

Jas*_*mbs 19

Git 2.13增加了对条件配置包括的支持.如果将结帐组织到每个工作域的目录中,则可以根据结帐的位置添加自定义设置.在你的全局git配置中:

[includeIf "gitdir:code/work/"]
    path = /Users/self/code/work/.gitconfig
Run Code Online (Sandbox Code Playgroud)

然后在〜/ code/work/.gitconfig中:

[user]
    email = self@work.com
Run Code Online (Sandbox Code Playgroud)

当然,您可以根据自己的喜好为多个工作领域做到这一点.

  • 这对我来说是很好的解决方案。对于 Windows,`[includeIf "gitdir:D:/repositories/"]` 将匹配 `D:\repositories\\` 中的所有存储库。显然需要最终的`\`。 (2认同)
  • 如果您希望将其应用于工作区文件夹内的多个文件夹,则必须包含 /** glob,例如: `[includeIf "gitdir:code/work/**"]` (2认同)

Mik*_*rty 18

Git没有内置这样做(据我所知),但是下面的shell脚本看起来非常可靠.在检查GitHub时将其修改为拥有所需的用户名和电子邮件地址,然后在"真实"git 之前的某个位置将其保存为名为"git"的可执行文件.

#!/usr/bin/env bash

# "Real" git is the second one returned by 'which'
REAL_GIT=$(which -a git | sed -n 2p)

# Does the remote "origin" point to GitHub?
if ("$REAL_GIT" remote -v 2>/dev/null |
    grep '^origin\b.*github.com.*(push)$' >/dev/null 2>&1); then

    # Yes.  Set username and email that you use on GitHub.
    export GIT_AUTHOR_NAME='*** put your name here ***'
    export GIT_AUTHOR_EMAIL='*** put your email address here ***'

fi

"$REAL_GIT" "$@"
Run Code Online (Sandbox Code Playgroud)

ssh在我的机器上使用了类似的技巧- 我希望ssh在运行时更改窗口背景颜色,然后在退出时将其更改回来 - 它对我来说可靠.

另请注意,这是硬编码的,只能查看命名的遥控器origin.


小智 6

我写了post-checkhout钩子,根据存储库的原始URL设置repo的本地作者详细信息.

它不会使用通配符域,但它会使用git config --urlmatch据称会回退到最接近的匹配URL.

请在此处查看:https://github.com/boywhoroared/dotfiles/blob/master/git/template/hooks/post-checkout.d/author


小智 5

~/.gitconfig

[user]
    name = John Doe
    email = jdoe@private.com

[includeIf "hasconfig:remote.*.url:https://git.work.com/**"]
    path = .gitconfig.work
Run Code Online (Sandbox Code Playgroud)

~/.gitconfig.work

[user]
    name = John Doe
    email = jdoe@work.com
Run Code Online (Sandbox Code Playgroud)

这样,如果存储库包含任何远程匹配,~/.gitconfig.work则将包含用户详细信息并覆盖设置~/.gitconfighttps://git.work.com/**