Scenario
Multiple developers are working on a single repo simultaneously, there’s to be a lot of pushes and pulls, what the best way to keep your git commits linear, i.e, each time someone makes a change, pull the remote repo and pushes it, you want it to be a single clean commit.
Solutions
Rebase before pushing (method 1)
Before pushing your changes, rebase your local branch on top of the remote branch to get the latest changes. Resolve any conflicts that arise and then push your changes.
git fetch origin
git checkout your_branch
git rebase origin/your_branch
Stash local changes and then pull (method 2)
When you’re done with your local changes, stash them, pull the remote changes and then apply the stash on top. Resolve any conflicts that arise and then push your changes.
Using Merge and Squash (method 3)
Danger
You can really mess up your git info and logs if you make any mistakes. It is advisable to use rebase instead.
- Merging changes from the remote branch onto your local branch creates a merge commit.
- In case you have multiple local commits squash then into one single commit.
- Using interactive rebase rewrite the git history! Squash the merge commit and the local commit as one.
git fetch origin
git checkout your_branch
git merge origin/your_branch
git rebase -i HEAD~n
# replace n with the number of commits you want
A git pull is simply a fetch followed by a merge and can be used in the above example