Git - working on wrong branch - how to copy changes to existing topic branch
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Working collaboratively on a software project often involves juggling multiple branches in Git. While it’s a powerful tool for version control, mistakes can happen, such as committing changes to the wrong branch. This article focuses on addressing the common issue of accidentally making changes on the wrong branch and explains how you can transfer those changes to the correct topic branch.
Understanding Git Branches
Before diving into solutions, it's useful to have a brief understanding of what branches are in Git. Each branch in a Git repository represents an independent line of development. Developers create branches for specific tasks (often referred to as "topic branches"), allowing them to work on features or bug fixes in isolation.
Key Terms
- Master/Main Branch: The default branch where the stable code resides.
- Feature/Topic Branch: A branch created from the master/main branch to implement a new feature or fix a bug.
- HEAD: A special pointer that represents the currently checked-out commit or branch.
Problem Scenario
Imagine you’re working on a feature and you realize you’ve made several commits on the wrong branch. Instead of a dedicated topic branch, you've committed changes directly to the main branch. This mistake can lead to conflicts or stability issues, so timely correction is crucial.
Solution Steps: Moving Changes to the Correct Branch
Follow these steps to move your changes from the incorrect branch to the correct topic branch.
1. Identify the Point When the Mistake Started
First, ascertain the last correct commit you made on the wrong branch (before you started diverging).
- Use `--hard` to reset the branch completely, including the working directory, but be cautious as this will discard changes.
- Opt for `--soft` to keep all changes staged.
- Always Backup: Before performing operations like reset, ensure you have backed up your work.
- Use Stash: If you are uncomfortable with resets, consider using `git stash` to temporarily store your changes instead.
- Automation Tools: Tools like GitHub Desktop or SourceTree provide graphical interfaces with options to expedite and monitor these processes.

