git相关技巧

配置

配置用户名称和邮件地址

如果未配置用户名称,git 提交时会报错:

~$ git commit -a
fatal: name consists only of disallowed characters: ""

需要配置用户名称和邮件地址:

~$ git config user.name XXX
~$ git config user.email XXX@test.com

代理

例如指定 HTTPS 协议使用 socks5 代理:

~# git config --global https.proxy socks5://127.0.0.1:8050

删除代理配置:

~# git config --global --unset https.proxy

忽略文件模式修改

如果文件的模式被修改,git 默认视为存在修改,可以配置忽略文件模式:

~# git config core.fileMode false

修改最近一次的提交

~# git commit --amend

复位

例如回滚最近一次提交:

~# git reset HEAD~1

获取短的提交 hash 值

单行显示短的提交日志:

~# git log --abbrev-commit --pretty=oneline

直接获取最新短的提交 hash:

~# git rev-parse --short HEAD
~# git describe --always

带有短 hash 和最新日志的分支:

~# git branch -v

显示指定数量的提交

例如仅显示最近两次的提交:

~# git show -n 2

或者显示从某个提交之后开始到最近的所有提交 hash 值:

~# git rev-list <since_hash>..HEAD

如果需要包含指定的提交:

~# git rev-list <since_hash>^..HEAD

仅显示修改的文件名

git show 指定 --name-only 参数将仅显示提交日志和修改的文件名:

~# git show --name-only XXX

我们还可以显示从某个提交之后到最近的提交,以单行显示日志,并仅显示文件状态:

~# git show --oneline --name-status 6a89d6b..HEAD

仅显示指定文件的提交

~# git log -p -- child/file

检出子目录(Sparse checkout)

首先初始化代码仓库:

~# git init linux && cd linux

然后启用 Sparse checkout 功能:

~# git config core.sparseCheckout true

将子目录路径写入 sparse-checkout 文件:

~# echo "/drivers/net/ethernet/phytium/*" >> .git/info/sparse-checkout

设置远程仓库:

~# git remote add origin https://gitee.com/phytium_embedded/phytium-linux-kernel.git

最后拉取代码:

~# git pull origin linux-4.19 --depth=1

使用 git 命令修改 ini 配置文件

对于 ini 类型的配置文件,可以使用 git 命令直接进行修改:

~# git config --file=/etc/default/nginx somegroup.ULIMIT '-n 4096'

同步合并远程分支

例如从 GitHub 项目 fork 出的项目,修改之后需要与原项目的最新版本进行同步合并。

首先显示远程分支:

~# git remote -v

添加远程上游仓库:

~# git remote add upstream https://github.com/miniflux/v2.git

检出最新修改:

~# git fetch upstream
~# git checkout main

尝试进行合并,冲突的会列出来并报错:

~# git merge upstream/main
Auto-merging internal/reader/fetcher/request_builder.go
CONFLICT (content): Merge conflict in internal/reader/fetcher/request_builder.go
Automatic merge failed; fix conflicts and then commit the result.

添加本地修改的文件:

~# git add internal/reader/fetcher/request_builder.go

提交并推送:

~# git commit
~# git push origin main