今天的文章比较简单,1. 就是为 Git 单个项目做身份配置,就是配置单独的邮箱和用户名。因为我们平时可能会在不同的几个项目中工作,各个项目的用户名可能不同,最基本的就是公司的项目和我们自己在 GitHub 上玩,所以为了保证日志的准确性和提交时无误,最好对各个项目设置。以前没有研究过,所以就一只默认用公司的用户名玩,但一直感觉不太好,2. 在提交时,user.name, user.email会进入日志。这些信息,是追踪代码变更的关键,所以必须配置,偶然看见秋大有篇文章写这个,试了一些不错,记录一下。

全局配置和项目配置

全局配置信息在: ~/.gitconfig
项目配置在项目目录下的: ./.git/config

  1. 配置多个用户身份

git config –global 操作全局配置, 不带 –global 选项的话,会尝试相对于当前目录下找:./git/config, 找不到的话,报错,所以如此一来,我们就可以:


\# for global setting  
git config –global user.name xxx  
git config –global user.email xxx@xxx.com

\# for repository  
git config user.name xxxx  
git config user.email xxxx@xxx.com

另,我们都知道 Linux 下,我们可以通过 alias 命令设置别名(之前一直就不住这个命令,每次都是查一下,后来一朋友说多好记啊 ali as,阿里 as,就再也忘不了了),我们可以通过一个短命令把 git 日志重新格式化一下,至于其他的像:git status,git commit 是否重命名就看习惯了(看过有人把常错的单词都重命名为正确的,省时间,机智)


git config &#8211;global alias.lg "log &#8211;color &#8211;graph &#8211;pretty=format:&#8217;%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset&#8217; &#8211;abbrev-commit &#8211;"
  1. 强制检查各个项目用户名邮箱设置

使用 pre-commit 钩子进行检查,所以在 .git/hooks 中添加一个 pre-commit 文件(注意权限),内容如下:


#!/bin/sh  
#  
\# A git hook to make sure user.email and user.mail in repository exists before committing

global_email=$(git config &#8211;global user.email)  
global_name=$(git config &#8211;global user.name)

repository_email=$(git config user.email)  
repository_name=$(git config user.name)

if [ -z "$repository_email" ] || [ -z "$repository_name" ] || [ -n "$global_email" ] || [ -n "$global_name" ]; then  
\# user.email is empty  
echo "ERROR: [pre-commit hook] Aborting commit because user.email or user.name is missing. Configure them for this repository. Make sure not to configure globally."  
exit 1  
else  
\# user.email is not empty  
exit 0  
fi

参考文章:
https://www.liaohuqiu.net/cn/posts/git-setup-and-setting/
https://www.liaohuqiu.net/cn/posts/using-diffrent-user-config-for-different-repository/