0%

git commit问题详解

怎样修改 commit user ?

问题描述

git的 user.name 和 user.email 配置错了,然后还提交了很多commit,怎么办?
不要慌,git支持修改历史commit记录的用户名和邮箱。

思路

参考Changing author info,使用脚本进行修改。

实现

以macos上操作为例。

1、clone项目

1
2
git clone --bare https://github.com/user/repo.git
cd repo

2、创建修改用户名的脚本 change-author.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/bin/sh

git filter-branch -f --env-filter '

OLD_EMAIL="your-old-email@example.com"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="your-correct-email@example.com"

if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

其中 OLD_EMAIL、CORRECT_NAME、CORRECT_EMAIL 三个变量需要替换。

3、执行脚本
sh change-author.sh

4、检查结果,强制同步到远程仓库

1
2
git log
git push --force --tags origin 'refs/heads/*'

怎样修改上次 commit message ?

问题描述

git commit -m "something",之后,想要修改“something”为“something_new”。

解决办法

使用git commit --amend,可以修改最后一次commit的附加信息。

怎样合并多次 commit ?

需求

最近三次提交:

  • 第一次以为完成了,commit message写了“完成了xxx功能”。
  • 结果发现有bug,修复后第二次提交,commit message写了“修复xxx功能的bug”。
  • 结果发现还有bug,修复后第三次提交,commit message写了“修复xxx功能的bug”。

这样的三次提交,没毛病,但是可以美化一下,合并成一次提交。

操作步骤

1、合并最新三次的提交

1
2
3
4
git rebase -i HEAD~3
# or
git log
git rebase -i 0861a7db58

自动进入vi编辑模式,此时看到的commit信息是按照时间顺序排列的,最新的commit在最下面。
按照提示的命令编辑commit信息,一般改成p s s即可。

如果修改完报错:error: cannot ‘squash’ without a previous commit
那么可以继续修改:

1
git rebase --edit-todo

2、解决冲突后提交(不使用git commit)

1
2
git add .
git rebase --continue

3、取消rebase

1
git rebase --abort

怎样删除某次 commit ?

需求

已知一些提交记录为:

1
2
3
4
commit efaec33c2a081e427c5201898b3fc61179475f69
commit 5fdf644e089dcb245b1f3dde5e8942fc935ffccc
commit 550ae58fc222c5c4cd99027a580423d2567969e6
commit f3e9a940df8371d5282f151a5c6e6e74a1e3dead

现在想要删除 550ae58fc222c5c4cd99027a580423d2567969e6 这次commit,该怎么操作?

操作步骤

1、rebase到要删除的commit的前一个commit

1
git rebase -i f3e9a940df8371d5282f151a5c6e6e74a1e3dead

2、找到删除的commit(第一个),标记为 drop,保存

1
2
3
drop 550ae58 add: xxx
pick 5fdf644 modify: xxx
pick efaec33 modify: xxx

3、解决冲突后提交(不使用git commit)

1
2
3
4
git status
git rm <conflict-file>
git add .
git rebase --continue
  • 本文作者: 好好学习的郝
  • 本文链接: https://www.voidking.com/dev-git-commit/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!源站会及时更新知识点及修正错误,阅读体验也更好。欢迎分享,欢迎收藏~