Git - 排除特定的提交和推送

Git - exclude specific commit and push

如何从一系列提交中排除特定提交。我的意思是如果我有 5 次提交,而我只想推送 4 次提交。这该怎么做。请帮助解决这个问题。

您将需要一个包含所需提交的新分支。

您可以通过多种方式做到这一点


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 revert

git revert SHA-1

使用git恢复到撤消您在不需要的提交中所做的更改,结果将是旧代码和新代码的分支,但当前状态将是原始代码


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