When working with Git, you may encounter a situation where your push is rejected because someone else has pushed their changes before you. This tutorial explains how to handle this situation properly using git pull –rebase instead of a regular git pull, ensuring a clean commit history.
Step 1: Understanding the Problem
You and another developer (let’s call them John) are working on the same branch. Both of you start from the same commit, make local changes, and commit them. However, John pushes his changes first. When you attempt to push your changes, Git rejects your push because the remote branch is ahead of your local branch.
Step 2: Why git pull Causes Issues
A common approach to fixing this issue is running:
git pull
However, this creates a merge commit, which combines both your commit and John’s commit into a new commit. Over time, repeated merge commits clutter the Git history, making it difficult to track specific changes.
Step 3: The Better Approach – git pull –rebase
Instead of merging, we can rebase our commits onto the latest remote branch:
git pull --rebase
What Happens During Rebase?
- Your local commit is temporarily set aside.
- Git pulls the latest changes from the remote branch.
- Your commit is reapplied on top of the latest remote changes, maintaining a linear history.
Step 4: Handling Merge Conflicts During Rebase
If there are conflicting changes between your commit and John’s commit, Git will pause and prompt you to resolve them manually.
- Use
git status
to see the conflicting files.
- Edit the files to resolve conflicts.
- Once resolved, run:
git rebase --continue
If you want to abort the rebase and return to the previous state, run:
git rebase --abort
This restores your branch to its state before the rebase attempt.
Step 5: Pushing Your Rebased Commit
Once the rebase is successful, you can push your changes:
git push --force-with-lease
The –force-with-lease flag ensures you don’t accidentally overwrite new remote changes.
Step 6: Creating a Shortcut Alias
Since git pull –rebase is long to type, you can create a shortcut alias:
git config --global alias.pr "pull --rebase"
Now, you can simply run:
git pr
Summary
- Avoid git pull because it creates unnecessary merge commits.
- Use git pull –rebase to maintain a clean history.
- Handle conflicts by resolving them and continuing the rebase.
- Use git rebase –abort if something goes wrong.
- Push changes using git push –force-with-lease.
- Set up an alias to simplify the process.
By following this approach, your Git history remains linear and easy to read, improving collaboration and code maintenance.
Leave a Reply