【问题标题】:Git - exclude specific commit and pushGit - 排除特定的提交和推送
【发布时间】:2016-07-06 20:50:45
【问题描述】:

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

【问题讨论】:

标签: git git-push git-commit


【解决方案1】:

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

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


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 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

【讨论】:

  • 所以,如前所述,我需要创建新分支才能做到这一点。这意味着从 10 个提交中推送 9 个。我需要遵循相同的方法。?
  • 没错。将所需的提交推送到新分支
  • 这很累。有没有办法只排除我不想推送的提交?
  • @Ved 是的,有,请参阅下面的答案。
【解决方案2】:

使用(将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

【讨论】:

  • 我喜欢补丁方法 - 没有隐藏状态。
  • :chef_kisses: for git push origin HEAD~1:$(git rev-parse --abbrev-ref HEAD)
猜你喜欢
  • 2021-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-01
  • 2011-01-29
  • 1970-01-01
  • 2013-12-17
  • 1970-01-01
相关资源
最近更新 更多