如何在一个分支中压缩提交记录而保留在另一个分支中?

4

我经常提交代码。我想在本地Git仓库的一个分支中保留我细粒度提交的历史记录,并只将较粗粒度的提交推送到远程仓库。

我希望能够在我的“细粒度”本地分支中找到相应的提交记录。

我该如何做到这一点?

1个回答

2
为了将本地分支与远程分离:
  1. Create and checkout the local branch (let's call it Ruby branch). Commit as needed all your fine-grained commits.

    m1 - m2     <- master, origin/master
      \
       r1 - r2 - r3  <- Ruby (fine grained commits - no origin/Ruby)
    
  2. Whenever you have a coarse-grained piece of work complete in Ruby that you want to send to the remote, merge it an appropriate branch on your local repo that is also a branch on the remote. Let's assume this branch is master, but it might be something else like dev, release-xyz, feature-123, etc.)

    m1 - m2 ------- m3   <- master (new merge m3 from Ruby)
      \            /
       r1 - r2 - r3  <- Ruby
    
  3. To create merge commit (m3 in diagram above), checkout the branch to be merged (i.e. master, etc.) and don't rebase the Ruby branch onto master, which would copy all of the commits r1, r2, and r3 onto master. Instead, just do a normal merge with a commit (i.e. git merge Ruby). In the merge commit, summarize the group of changes in the commit message as you see fit.

  4. Make sure that master is checked out, and push to the remote - or use specific push commands to make sure you are pushing master, and not Ruby.

    m1 - m2 ------- m3   <- master (origin/master updated to m3 from push)
      \            /
       r1 - r2 - r3  <- Ruby (still no origin/Ruby - local only)
    

我们的想法是将Ruby作为本地分支,不要将其推送到远程。当然,如果其他人需要访问这些细粒度的提交,推送Ruby也没有坏处。此外,通过推送Ruby,它将作为备份保存,以防您的电脑出现故障,如果需要,可以将其克隆到另一台电脑上并使用。因此,您可能希望考虑将Ruby作为一个推送到远程的分支 - 但即使如此,您还是可能希望按照上述方式合并为单个提交。


添加了一些图表以帮助可视化。像往常一样,我强烈推荐使用可视化的Git工具,如Git Extensions(开源、跨平台),以便轻松地查看分支、索引和提交差异等。 - LightCC
我试过了,它没有起作用。git merge Ruby会将所有中间提交复制到main分支中。 - Irina Rapoport
我可以在一个干净的仓库上重新测试这个问题,但这并不是正常的合并行为,你应该需要特别挑选或变基来复制任何提交。合并不会查看单个提交,它只会查看自最后一个共同父级以来的总差异和,在单个提交中提交所有差异。你可能在这个仓库或全局设置了一些特殊的宏或配置设置,导致不同的行为。你是否直接在命令行使用 git merge Ruby?你可能需要发布控制台中该命令的输出以获得更多帮助。 - LightCC
你可能想在一个干净的代码库上尝试一下,进行一些简单的测试提交,直到理解了这个行为。 - LightCC
2
git merge --squash Ruby 对我来说达到了预期的效果。 - bbeecher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接