【发布时间】:2016-07-06 20:50:45
【问题描述】:
如何从一系列提交中排除特定提交。我的意思是如果我有 5 个提交,我只想推送 4 个提交。这个怎么做。请帮助解决这个问题。
【问题讨论】:
-
@YaronIdan 我与合并无关。当我不需要推送少量提交时,我想知道如何推送我的提交。
标签: git git-push git-commit
如何从一系列提交中排除特定提交。我的意思是如果我有 5 个提交,我只想推送 4 个提交。这个怎么做。请帮助解决这个问题。
【问题讨论】:
标签: git git-push git-commit
您需要有一个包含所需提交的新分支。
您可以通过多种方式做到这一点
git cherry-pick为您要开始的特定 sha-1 签出一个新分支:
git checkout <origin branch>
git checkout -b <new branch>
# now cherry-pick the desired commits onto the new branch
git cherry-pick commit1 commit2 ... commitN
# now push to remote
git push origin remote <branch name>
git revertgit revert SHA-1
使用 git revert 来撤消您在不需要的提交中所做的更改,结果将是旧代码和新代码的分支,但当前状态将是原始代码
git rebase -i交互式变基。选择您不想要的提交并将其删除。
# X is the number of commits you wish to squash
git rebase -i HEAD~X
压缩提交后 - 选择 e 进行编辑并放置您想要的代码,添加并提交
git filter-branch过滤器分支可以用来过滤你想要的任何内容。
git filter-branch --env-filter '<do what ever you want on this commit range' SHA1..SHA1
【讨论】:
使用(将1替换为您要从顶部忽略的提交数):
git push origin HEAD~1:$(git rev-parse --abbrev-ref HEAD)
注意:要使此命令起作用,远程分支需要存在,否则您将获得error: unable to push to unqualified destination。如果您遇到错误,例如,您可以像往常一样开始推送分支(即包括您不想推送的提交),然后使用附加参数重复上述命令--force.
只是想说明一个替代方案,因为创建一个单独的分支,然后做一些魔术,然后删除它,听起来太麻烦了;特别是如果您已经打开了一个拉取请求,并且您需要准确推送您当前所在的分支。
更简单的方法是(但请不要将其与其他git命令穿插,否则您可能需要在reflog中挖掘才能恢复):
$ git reset --hard HEAD~1 # temporarily erase commits, use in place of "1" the number of commits you want to ignore
$ git push myorigin HEAD # do the push wherever you wanted
$ git reset --hard HEAD@{1} # restore commits
这里使用的技巧是 git 通常会在本地存储您所做的破坏性操作,称为 reflog。您可以使用git reflog 命令查看其内容(或通常更易读的git reflog --date=iso,尽管在这种情况下您不会看到更容易写标记HEAD@{n})。
如果您没有信心,更安全的版本可能是:
$ git format-patch -1 --stdout > 1.patch # store commits in a file, use in place of "1" the number of commits you want to ignore
$ git reset --hard HEAD~1 # temporarily erase commits, use in place of "1" the number of commits you want to ignore
$ git push myorigin HEAD # do the push wherever you wanted
$ git am 1.patch # restore commits
【讨论】:
git push origin HEAD~1:$(git rev-parse --abbrev-ref HEAD)