将多个本地提交合并为一个最终提交以进行推送

Combine multiple local commits into a single final commit for push

我的 pushes/commits.

结构如下
UnpushedLocalCommit1  <--- most recent local commit, but not yet pushed
 ^
 |
UnpushedLocalCommit0  <--- committed locally, but not yet pushed
 ^
 |
Commit1 <---origin/master, most recent pushed commit
 ^
 |
Commit0 <---first ever pushed commit

UnpushedLocalCommit0 有以下文件

File1 with 2 lines
File2

UnpushedLocalCommit1 有以下文件

File1 with 3 lines

具体来说,最近的本地提交更改了 File1 而没有更改 File2。我现在想远程推送一个提交,其中包含:

File1 with 3 lines
File2

这可以做到吗?

我看过 rebasinggit merge。这些用例似乎涉及将多个分支合二为一。但是,就我而言,只有一个线性分支。所以,我不清楚我应该使用 rebase 还是 git merge.

Squashing commits 似乎对我的情况有帮助,但是否可以保证 File1 with 3 lines(而不是 File1 with 2 lines)和 File2 将是最终压缩的提交?另外,我不清楚 UnpushedLocalCommit0UnpushedLocalCommit1 压缩后会发生什么。理想情况下,我不希望在本地或远程记录它们。

也就是我最终想要如下结构:

UnpushedLocalCommit2  <--- new commit with File1 with 3 lines and File2
 ^
 |
Commit1 <---origin/master, most recent pushed commit
 ^
 |
Commit0 <---first ever pushed commit

你的疑惑是因为不理解Git是什么,commit是什么。停止思考每次提交“改变”的内容。那只是你编造的东西; Git 不传送更改。它以 提交 进行交易。提交是 整个 项目当前状态的快照。因此,如果您喜欢项目的当前状态并且压缩了当前状态的父历史中的任何提交序列,您仍然会获得该状态。

对于您的任务,压缩为一次提交的最简单方法是软重置。所以在这里,你会说

git reset --soft <commit1>
git commit -m 'new message for squashed commits`