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

时间:2016-03-20 10:17:33

标签: git git-push git-commit

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

2 个答案:

答案 0 :(得分:5)

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

您可以通过多种方式实现

推荐的解决方案:

<强> git cherry-pick

将新分支签出到您想要开始的特定sha-1:

git checkout <origin branch>
git checkout -b <new branch>

# now cherry-pick the desired commits onto the nee branch
git cherry-pick commit1 commit2 ... commitN

# now push to remote
git push origin remote <branch name>

其他选项:

<强> git revert

git revert SHA-1

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

<强> git rebase -i

交互式变基。选择你不想要的提交并将其删除。

# X is the number of commits you wish to squash
git rebase -i HEAD~X

一旦你压缩你的提交 - 选择e进行编辑并放置你想要的代码,添加并提交

enter image description here

<强> git filter-branch

过滤分支可用于过滤您想要的任何内容。

git filter-branch --env-filter '<do what ever you want on this commit range' SHA1..SHA1

答案 1 :(得分:0)

使用(将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
相关问题