git - 如何编辑以前的 git 提交?

标签 git

<分区>

我刚刚意识到我遗漏了一个我应该添加到提交中的文件,比如 5 次提交。在提交消息中,我说过该文件已包含在内,但我不想使用文本“哎呀忘记在提交#XXXXX 中添加此文件”进行新提交

编辑以前的提交以便我可以添加文件的最佳方法是什么?

最佳答案

提交你的修复,然后使用 git rebase --interactive 重新排序你的提交并将两个提交压缩在一起。参见 the git book了解详情。

请注意,如果这些提交已经被推送到某个地方,那么这样做是个坏主意,因为您将更改存储库历史记录。

示例 session 可能如下所示:

% git init
Initialized empty Git repository in /home/user/repo/.git/
% echo "A line" > a.txt
% echo "A line" > b.txt
% git add a.txt b.txt
% git commit -m "Initial commit"
[master (root-commit) c6329d0] Initial commit
 2 files changed, 2 insertions(+), 0 deletions(-)
 create mode 100644 a.txt
 create mode 100644 b.txt

你不完整的提交:

% echo "Another line" >> a.txt
% git add a.txt
% git commit -m "Important changes"
[master 0d28cfa] Important changes
 1 files changed, 1 insertions(+), 0 deletions(-)

一些其他提交:

% echo "Yet another line" >> b.txt
% git add b.txt
% git commit -m "Other changes"
[master 96a092d] Other changes
 1 files changed, 1 insertions(+), 0 deletions(-)

注意你忘记了一些东西:

% echo "Important line forgotten previously" >> a.txt
% git add a.txt
% git commit -m "Oops"
[master 9dce889] Oops
 1 files changed, 1 insertions(+), 0 deletions(-)

git rebase -i 修复历史:

% git rebase -i HEAD~3

您将被放入您选择的编辑器中,内容类似于以下内容:

pick 0d28cfa Important changes
pick 96a092d Other changes
pick 9dce889 Oops

更改它以便将“oops”提交移到上方一行并将pick更改为squash(或只是s)以组合它与前面的提交:

pick 0d28cfa Important changes
s 9dce889 Oops
pick 96a092d Other changes

然后保存文件并退出编辑。这将 pop 另一个编辑器,您可以在其中编辑 merge 提交的提交消息。它看起来像这样:

# This is a combination of 2 commits.
# The first commit's message is:

Important changes

# This is the 2nd commit message:

Oops

根据您的需要进行更改,然后保存并退出。

最后,检查新提交确实是两个提交的组合:

% git log -p HEAD~2..HEAD~1
commit 7a4c496956eb269c551bbf027db8b0f2320b65e4
Author: User Name <user@host.tld>
Date:   Fri Feb 3 22:57:31 2012 +0100

    Important changes

diff --git a/a.txt b/a.txt
index 8d7158c..54df739 100644
--- a/a.txt
+++ b/a.txt
@@ -1 +1,3 @@
 A line
+Another line
+Important line forgotten previously

关于git - 如何编辑以前的 git 提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9103396/

相关文章:

git - 为什么 git 会推送这么多数据?

windows - 如何在 Windows 上更改 git bash 用户名?

git - 使用 git : committed changes in one branch affect 'master'

git 日志 : contributors list since certain tag?

git - 在 Mercurial 或 Git 中无需提交即可推送

python - 通过 Python 获取 Git 存储库文件的最后一次提交时间?

git - 是否有像 svn 一样的 git 忽略命令?

git - 如何查看 Git 扩展中 pull 了哪些更改?

亚搏体育实验室: how to fork a private repository from server A to a server B?

Git 速查表