我提出的解决方案灵感来自Scott Weldon's answer。由于它不直接适用于我的情况,我修改了钩子的 bash 脚本并改进了几个部分*。
假设主目录的目录结构如下:
~
.gitconfig // [init] templatedir
.git-template
hooks
post-checkout // our bash script
MyDomain
.gitconfig // [user] name, email
最初我让 Git 知道我的模板目录在哪里。在 Windows 上,您可能需要指定绝对路径 (C:/Users/MyUser/.git-template)。
git config --global init.templatedir '~/.git-template'
在~/MyDomain/.gitconfig 中,我存储了该目录(域)的配置,该配置应应用于其中的所有存储库及其子目录。
cd ~/MyDomain
git config --file .gitconfig user.name "My Name"
git config --file .gitconfig user.email "my@email.com"
有趣的部分是post-checkout bash 脚本,它定义了结帐后挂钩。我使用自定义user.inferredConfig 标志只执行一次(在git clone),而不是重复执行(在git checkout)。当然也可以创建一个单独的文件来表示该状态。
#!/bin/bash
# Git post-checkout hook for automated use of directory-local git config
# https://stackoverflow.com/a/40450106
# Check for custom git-config flag, to execute hook only once on clone, not repeatedly on every checkout
if grep -q "inferredConfig" .git/config
then
exit
fi
# Automatically set Git config values from parent folders.
echo "Infer Git configuration from directory..."
# Go upwards in directory hierarchy, examine all .gitconfig files we find
# Allows to have multiple nested .gitconfig files with different scopes
dir=$(pwd)
configFiles=()
while [ "$dir" != "/" ]
do
# Skip first directory (the newly created Git repo)
dir=$(dirname "$dir")
if [ -f "$dir/.gitconfig" ]
then
configFiles+=("$dir/.gitconfig")
fi
done
# Iterate through configFiles array in reverse order, so that more local configurations override parent ones
for (( index=${#configFiles[@]}-1 ; index>=0 ; index-- )) ; do
gitconfig="${configFiles[index]}"
echo "* From $gitconfig:"
# Iterate over each line in found .gitconfig file
output=$(git config --file "$gitconfig" --list)
while IFS= read -r line
do
# Split line into two parts, separated by '='
IFS='=' read key localValue <<< "$line"
# For values that differ from the parent Git configuration, adjust the local one
parentValue=$(git config $key)
if [ "$parentValue" != "$localValue" ]
then
echo " * $key: $localValue"
git config "$key" "$localValue"
fi
done <<< "$output"
# Set custom flag that we have inferred the configuration, so that future checkouts don't need to do it
git config user.inferredConfig 1
done
*:对原代码的改动包括:
- 适用于路径中的空格(在 Windows 上尤其有趣)
- 正确解析来自
.gitconfig 的键值对(don't read lines with for、iterate with while read instead)
- 检查
.gitconfig 文件从根目录到本地目录,反之亦然
- 仅在初始克隆时调用挂钩,而不是在每次结帐时调用
- 输出应用于
git clone 的配置设置