Home > Enterprise >  Combine multiple local commits into a single final commit for push
Combine multiple local commits into a single final commit for push

Time:03-17

I have the following structure of my 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 had the following files

File1 with 2 lines
File2

UnpushedLocalCommit1 has the following files

File1 with 3 lines

Specifically, the most recent local commit changed File1 and did not change File2. I would now like to push a single commit remotely which contains:

File1 with 3 lines
File2

Can this be done?

I have looked at rebasing and git merge. The use cases of these seem to involve multiple branches into one. However, in my case, there is just a single linear branch. So, it is not clear to me if I should be using rebase or git merge.

Squashing commits seems like what would help in my case but is there a guarantee that File1 with 3 lines (and not File1 with 2 lines) and File2 would be the resultant squashed commit? Also, it is not clear to me what happens to UnpushedLocalCommit0 and UnpushedLocalCommit1 after squashing them. Ideally, I want no record of them locally or remotely.

That is, I would like the following structure eventually:

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

CodePudding user response:

Your doubts are due to not understanding what Git is or what a commit is. Stop thinking in terms of what each commit "changed". That's just something you made up; Git doesn't traffic in changes. It traffics in commits. A commit is a snapshot of the current state of the entire project. Therefore if you like the current state of the project and you squash any sequence of commits in the parental history of the current state, you will still get that state.

For your task, the simplest way to squash into one commit is a soft reset. So here, you would say

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