Git 技巧

不同域名使用不同秘钥

修改~/.ssh/config

1
2
3
4
5
Host example.com
IdentityFile ~/.ssh/id_rsa_example

Host github.com
IdentityFile ~/.ssh/id_rsa_github

git 多commit 支持

区分公司commit信息和个人commit信息
单独每次用git config 改很麻烦
可以用git Include 条件引入小技巧达到
比如公司git有强制commit信息要求

修改
~/.gitconfig

1
2
3
4
5
[include]
path = /home/your_name/.gitconfig-default

[includeIf "gitdir:/home/your_name/workspaces/**"]
path = /home/your_name/.gitconfig-corp

~/.gitconfig-default 保留默认commit配置
~/.gitconfig-corp workspaces 目录下面使用公司commit配置

1
2
3
4
5
6
7
8
9
10
11
cat ~/.gitconfig-default

[user]
email = custom-email@xxxxx.com
name = xxxx

cat ~/.gitconfig-corp

[user]
email = xxxx@corp-xxx.com
name = xxxx

给github单独设置代理

  1. http/https 代理 (自己有单独代理或公司代理)
    比如我自己已经有了科学上网代理 本地监听1080 socks5 代理
    修改~/.gitconfig
    1
    2
    3
    4
    5
    [github "com.http"]
    proxy = socks5://127.0.0.1:1080
    [github "com.https"]
    proxy = socks5://127.0.0.1:1080
    [

如果是http代理 换成
proxy = http://host:port 即可

命令行git神器 lazygit

使用 stash

如果您需要在切换分支之前保存未提交的更改,可以使用 git stash 命令。这将把未提交的更改保存在一个堆栈中,以便稍后恢复。

示例:

1
2
3
4
5
6
7
8
# 保存未提交的更改
git stash

# 恢复未提交的更改
git stash apply

# 从stash堆栈弹出(remove from stash list)
git stash pop

使用 rebase

使用 git rebase 命令可以将当前分支的更改应用到另一个分支上。这可以帮助您保持分支历史记录的整洁和有序。

示例:

1
2
3
# 将当前分支的更改应用到另一个分支上
git checkout another-branch
git rebase current-branch

使用 amend

如果您需要修改最近一次提交的提交信息或者添加一些遗漏的文件,可以使用 git commit --amend 命令。

示例:

1
2
3
4
5
6
# 修改最近一次提交的提交信息
git commit --amend -m "New commit message"

# 添加遗漏的文件
git add missed-file
git commit --amend

使用 reflog

如果您不小心删除了一个分支或者提交,可以使用 git reflog 命令来查找并恢复它们。

示例:

1
2
3
4
5
# 查找删除的分支
git reflog | grep deleted-branch

# 恢复删除的分支
git checkout -b recovered-branch HEAD@{1}

使用 tag

使用 git tag 命令可以给特定的提交打上标签,以便稍后更容易地找到。

示例:

1
2
# 给特定的提交打上标签
git tag v1.0.0

使用 submodule

如果您需要将一个 Git 仓库作为另一个 Git 仓库的一部分使用,可以使用 git submodule 命令。

示例:

1
2
3
4
5
# 添加一个子模块
git submodule add https://github.com/user/repo.git

# 更新子模块
git submodule update --remote

使用 bisect

如果您需要找到导致代码出现问题的提交,可以使用 git bisect 命令。这将帮助您快速缩小问题所在的提交范围。

示例:

1
2
3
4
5
6
7
8
9
10
11
# 开始二分查找
git bisect start

# 标记当前提交为有问题的提交
git bisect bad

# 标记一个已知没有问题的提交
git bisect good v1.0.0

# 继续二分查找
git bisect run test.sh

使用 cherry-pick

如果您需要将一个提交应用到一个不同的分支上,可以使用 git cherry-pick 命令。

示例:

1
2
# 将一个提交应用到当前分支上
git cherry-pick abc123

使用 gitignore

创建一个 .gitignore 文件,可以在提交时忽略特定的文件或目录,以保持代码库的整洁。
gitignore.io 是一个在线生成ignore模板网站

示例:

1
2
# 忽略所有 .log 文件
*.log

neovim git plugins

  1. gitsigns
    1. show file git status (in nvim-tree)
    2. toggle line blame