我有以下提交历史记录:
头部头部~头部~2头部~3
gitcommit--修改当前HEAD提交。但是如何修改HEAD~3?
我有以下提交历史记录:
头部头部~头部~2头部~3
gitcommit--修改当前HEAD提交。但是如何修改HEAD~3?
当前回答
如果出于某种原因,您不喜欢交互式编辑器,可以使用gitrebase--on。
假设您要修改Commit1。首先,从Commit1之前分支:
git checkout -b amending [commit before Commit1]
第二,用樱桃核抓取Commit1:
git cherry-pick Commit1
现在,修改您的更改,创建Commit1':
git add ...
git commit --amend -m "new message for Commit1"
最后,在隐藏了任何其他更改后,将其余的提交移植到master之上新提交:
git rebase --onto amending Commit1 master
阅读:“将Commit1(不包括在内)和master(包括在内)之间的所有提交重新纳入修改分支”。即Commit2和Commit3,将旧的Commit1完全删除。你可以随便摘,但这样更容易。
记得清理你的树枝!
git branch -d amending
其他回答
如果出于某种原因,您不喜欢交互式编辑器,可以使用gitrebase--on。
假设您要修改Commit1。首先,从Commit1之前分支:
git checkout -b amending [commit before Commit1]
第二,用樱桃核抓取Commit1:
git cherry-pick Commit1
现在,修改您的更改,创建Commit1':
git add ...
git commit --amend -m "new message for Commit1"
最后,在隐藏了任何其他更改后,将其余的提交移植到master之上新提交:
git rebase --onto amending Commit1 master
阅读:“将Commit1(不包括在内)和master(包括在内)之间的所有提交重新纳入修改分支”。即Commit2和Commit3,将旧的Commit1完全删除。你可以随便摘,但这样更容易。
记得清理你的树枝!
git branch -d amending
使用git-rebase。例如,要修改提交bbc643cd,请运行:
$ git rebase --interactive 'bbc643cd^'
请注意命令末尾的插入符号^,因为您实际上需要在要修改的提交之前重新返回提交。
在默认编辑器中,在提到bbc643cd的行中修改pick以进行编辑。
保存文件并退出。git将解释并自动执行文件中的命令。您将发现自己处于之前创建提交bbc643cd的情况。
此时,bbc643cd是您最后一次提交,您可以很容易地修改它。进行更改,然后使用以下命令进行提交:
$ git commit --all --amend --no-edit
之后,使用以下命令返回到上一个HEAD提交:
$ git rebase --continue
警告:请注意,这将更改该提交的SHA-1以及所有子项——换句话说,这将重写从此点开始的历史。如果使用命令gitpush-force进行推送,则可以断开repos。
对我来说,这是为了从回购中删除一些凭证。我试着换基,在换基的过程中遇到了一大堆看似无关的冲突——继续。不要费心尝试重新设置自己的基础,在mac上使用名为BFG(brew-install-BFG)的工具。
自动交互式重新基础编辑,然后提交恢复,以备重做
我发现自己经常修复一个过去的错误,为此我写了一个脚本。
以下是工作流程:
git提交编辑<提交哈希>这将在您要编辑的提交时将您丢弃。修复并按您希望的方式进行提交。(您可能希望使用git存储保存来保存未提交的文件)重新提交--修改,如:修改最后一次提交完成重新基准:git rebase—继续
为了实现上述功能,请将以下脚本放入$PATH中名为gitcommitedit的可执行文件中:
#!/bin/bash
set -euo pipefail
script_name=${0##*/}
warn () { printf '%s: %s\n' "$script_name" "$*" >&2; }
die () { warn "$@"; exit 1; }
[[ $# -ge 2 ]] && die "Expected single commit to edit. Defaults to HEAD~"
# Default to editing the parent of the most recent commit
# The most recent commit can be edited with `git commit --amend`
commit=$(git rev-parse --short "${1:-HEAD~}")
message=$(git log -1 --format='%h %s' "$commit")
if [[ $OSTYPE =~ ^darwin ]]; then
sed_inplace=(sed -Ei "")
else
sed_inplace=(sed -Ei)
fi
export GIT_SEQUENCE_EDITOR="${sed_inplace[*]} "' "s/^pick ('"$commit"' .*)/edit \\1/"'
git rebase --quiet --interactive --autostash --autosquash "$commit"~
git reset --quiet @~ "$(git rev-parse --show-toplevel)" # Reset the cache of the toplevel directory to the previous commit
git commit --quiet --amend --no-edit --allow-empty # Commit an empty commit so that that cache diffs are un-reversed
echo
echo "Editing commit: $message" >&2
echo
如果您还没有推送提交,则可以使用git reset HEAD^[1,2,3,4…]返回到上一次提交
例如
git commit <file1> -m "Updated files 1 and 2"
git commit <file3> -m "Updated file 3"
抱歉,忘记在第一次提交时添加file2。。。
git reset HEAD^1 // because I only need to go back 1 commit
git add <file2>
这将在第一次提交时添加file2。