星际穿越

Git Tricks

2025-03-20

git alias

基操

1
2
3
4
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status

从hashcode创建新分支, 并switch

1
2
3
4
git ccb test-ct 17c252234

# git branch -f 17c252234 test-ct
# git switch 17c252234
1
2
3
4
5
6
7
8
9
10
11
git config --global alias.ccb '!f() { \
if [ $# -ne 2 ]; then \
echo "Usage: git setct <branch-name> <commit-hash>"; \
return 1; \
fi; \
if ! git rev-parse --verify "$2" >/dev/null 2>&1; then \
echo "Error: Invalid commit hash '$2'"; \
return 1; \
fi; \
git branch -f "$1" "$2" && git switch "$1"; \
}; f'

统一/智能选择 cherry-pick/rebase --continue/abort

1
2
3
4
5
git ct
# git cherry-pick/rebase --continue

git ab
# git cherry-pick/rebase --abort

Since we add "$@" below, maybe different from directly invoke the commands.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
git config --global alias.ct '!f() { \
if git rev-parse --verify CHERRY_PICK_HEAD 2> /dev/null; then \
git cherry-pick --continue "$@"; \
elif git rev-parse --verify REBASE_HEAD 2> /dev/null; then \
git rebase --continue "$@"; \
else \
echo "Error: Not in rebase/cherry-pick state"; \
return 1; \
fi; \
}; f'
git config --global alias.ab '!f() { \
if git rev-parse --verify CHERRY_PICK_HEAD 2> /dev/null; then \
git cherry-pick --abort "$@"; \
elif git rev-parse --verify REBASE_HEAD 2> /dev/null; then \
git rebase --abort "$@"; \
else \
echo "Error: Not in rebase/cherry-pick state"; \
return 1; \
fi; \
}; f'

git 全局设置 用户名和邮箱

要将 Git 配置改为全局配置,请在命令中添加 –global 参数。修改后的命令如下:

1
2
git config --global user.name "liyongkang"
git config --global user.email "liyongkang@licoded.site"

​验证配置

运行以下命令检查是否生效:

1
git config --list | grep user

输出应显示:

1
2
user.name=liyongkang
user.email=liyongkang@licoded.site

git log

按作者过滤

1
git log --oneline --author="gao*"

打印日期

方案一

1
git log --oneline --pretty=format:"%h - %ad : %s" --date=iso

2025-03-11 17:13:12 +0800
日期最后多了个 +0800,比较难受

方案二(推荐

1
2
3
git log --oneline --pretty=format:"%h - %ad : %s"

git config --global log.date format:"%Y-%m-%d %H:%M:%S"

lazygit 支持非主流git网站的链接跳转,比如公司内部部署的git

配置文件中添加如下内容

  • MacOS:~/Library/Application\ Support/lazygit/config.yml
1
2
services:
'partner-gitlab.mioffice.cn': 'gitlab:partner-gitlab.mioffice.cn'

其他实用命令

变更

1
git ci --amend --reset-author --no-edit -a

同步远程分支情况到本地

适用情况:某个分支在远程被删除了,但是本地git log的时候还是有显示

1
git fetch --prune origin

push 到远程同名分支

1
git push -u origin $(git branch --show-current)
Tags: git