自动区分工作仓库和个人仓库的 Git 提交

通常,公司会自建 GitHubGitLab 服务,而个人可能在 GitHub 官网上有自己的个人项目。然而,公司内部项目和个人项目的邮箱配置可能不同。当项目数量较多时,使用 git config --local--global 进行设置就会变得相当麻烦。在这里,我将记录下我个人的解决方案,以便后续参考。

区分不同的 SSH Key

生成 SSH Key 文件

~/.ssh/ 目录下生成 SSH Key 文件:

  • 对于公司内部使用的邮箱,生成一个 SSH Key 文件命名为 ssh-company
  • 对于个人 GitHub 使用的邮箱,生成一个 SSH Key 文件命名为 ssh-github

添加 config 文件

~/.ssh/ 目录下创建一个 config 文件,并添加以下内容:

1
2
3
4
5
6
7
8
9
10
11
Host github.com
HostName github.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/ssh-github

Host gitlab.com
HostName gitlab.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/ssh-company

这样设置后,使用 git 命令和远程 Git 仓库进行交互时,将根据 Git 远程地址前缀使用不同的 SSH Key。

使用不同的姓名和邮箱

在进行 Git 提交时,可以区分个人项目和公司项目,使用不同的姓名和邮箱。

添加 .gitconfig 文件

生成 ~/.gitconfig 文件,相当于使用 git config --global 进行全局配置。在该文件中,可以设置个人的 Git 相关配置,例如:

1
2
3
4
5
6
7
[alias]
st = status
co = checkout
[includeIf "hasconfig:remote.*.url:git@gitlab.com:*/**"]
path = ~/.gitconfig-company
[includeIf "hasconfig:remote.*.url:git@github.com:*/**"]
path = ~/.gitconfig-github

includeIf 是 Git 的条件引入配置语法,它允许根据特定条件从其他文件中读取并合并配置。通过使用 includeIf,可以根据当前仓库的位置或其他条件有选择地包含额外的配置文件,从而实现为不同的仓库或目录设置不同配置而无需手动切换。

生成 .gitconfig-xxx 文件

为了区分姓名和邮箱,可以创建 .gitconfig-xxx 文件,并根据个人喜好添加配置。如果只想区分姓名和邮箱,可以按照以下方式设置:

1
2
3
4
5
6
7
8
9
### .gitconfig-company
[user]
name = 公司姓名
email = 公司邮箱

### .gitconfig-github
[user]
name = 个人姓名
email = 个人邮箱

这样,当进行提交时,根据远程主机地址前缀判断使用哪个姓名和邮箱。

处理 Hexo 部署异常问题

在使用 .gitconfig 文件自动区分提交后,执行 hexo d 命令时可能会出现以下提示:

1
2
3
4
5
6
7
8
9
10
11
12
Initialized empty Git repository in F:/Blog/.deploy_git/.g
Author identity unknown

*** 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.

这是因为在执行 hexo d 命令时,默认使用了全局的 Git user.nameuser.email

解决方案

在 Hexo 的 _config.yml 配置文件中进行设置:

1
2
3
4
5
6
7
8
9
# You can use this:
deploy:
type: git
repo: <repository url>
branch: [branch]
message: [message]
name: [git user]
email: [git email]
extend_dirs: [extend directory]

然而,即使使用了上述解决方案,再次执行 hexo d 命令时,仍然会使用全局的 Git 用户信息,导致报错。

解决方案的解决方案

如果 .deploy_git 目录已经生成并存在,会导致错误发生。此时,需要删除整个 .deploy_git 目录,然后再次执行 hexo d 命令。

希望这些解决方案能解决你的问题!如果还有其他疑问,请随时提问。

Done!