How to Fix Git PR Errors: When a New PR Includes Commits from a Previous PR

How to Fix Git PR Errors: When a New PR Includes Commits from a Previous PR

When working with multiple pull requests (PRs) in Git, you may encounter an issue where a newer PR includes commits from a previous PR. This happens when a new branch is created from another feature branch instead of from master (or main). This guide will walk you through the best practices to avoid and fix this issue.


Understanding the Problem

Why Does This Happen?

  • You created feature-1 branch and opened a PR.
  • Then, you created feature-2 from feature-1 instead of master.
  • When you opened a PR for feature-2, it contained commits from feature-1.

This results in an unwanted dependency where feature-2‘s PR includes unrelated commits.


How to Fix It

Step 1: Ensure Your master (or main) is Up-to-Date

Before creating a new branch, always update your local master branch:

# Switch to master/main
git checkout master

# Fetch the latest changes
git pull origin master

Step 2: Delete the Incorrect Branch and Create a New One

If your feature-2 branch contains commits from feature-1, delete it and create a fresh branch from master:

# Delete the incorrect branch (if you already pushed it, use --force later)
git branch -D feature-2

# Create a new branch from master
git checkout -b feature-2

Step 3: Apply Only the Relevant Changes for the New PR

Now, add only the changes relevant to feature-2:

git add .
git commit -m "feat: Add new feature 2"

Step 4: Push the Fixed Branch

If the incorrect branch was already pushed to GitHub, you need to force-push the corrected branch:

git push origin feature-2 --force

⚠️ Warning: Be cautious when using --force, especially if working in a shared repository.

Step 5: Verify the PR on GitHub

  • Go to GitHub and check the Commits tab in the PR.
  • Ensure that only the intended commits are present.
  • If extra commits still appear, recheck your branch history.

Best Practices to Avoid This Issue

Always Create New Branches from master

Instead of:

git checkout feature-1
git checkout -b feature-2  # ❌ Incorrect

Use:

git checkout master
git checkout -b feature-2  # ✅ Correct

Use git log --oneline --graph to Check Your History

This command helps visualize your branches and detect unwanted dependencies:

git log --oneline --graph --all

Use Interactive Rebase to Clean Up Commits

If you already committed but want to remove extra commits, you can use:

git rebase -i master

Then, remove or squash unwanted commits before pushing.


Conclusion

Fixing PR errors where extra commits appear is a common challenge in Git workflows. By following these steps and best practices, you can ensure clean, independent pull requests and avoid unnecessary complications.

If you encounter further issues, consider using Git tools like git reflog to inspect branch history or seek help from your team before force-pushing changes.

Happy coding! 🚀

Leave a Comment