Keywords: Git Branch Management | Rebase Operation | Version Control
Abstract: This technical article provides an in-depth analysis of migrating locally committed but unpushed changes to a new branch in Git. Focusing on scenarios where developers need to restructure branch organization after making local commits on the main branch, it systematically examines the coordinated use of core commands including git rebase, git branch, and git reset. By comparing the advantages and disadvantages of different solutions, it highlights best practices based on rebasing onto origin/master, covering conflict resolution, history optimization, and branch management strategies to offer professional guidance for Git workflow optimization.
Problem Scenario Analysis
In distributed version control systems, developers often encounter situations where temporary work on the main branch (master) later proves better suited for an independent branch. A typical scenario involves accumulating 37 local commits that haven't been pushed to the remote repository, while other developers have pushed new content to origin/master. This requires complete migration of local commits to a new branch while maintaining main branch synchronization with the remote.
Core Solution Approach
Leveraging Git's version control characteristics, the recommended approach combines rebase operations with branch management commands. Begin by executing git fetch origin to ensure the local remote-tracking branch is up-to-date, then run git rebase origin/master to reapply local commits onto origin/master. This operation replays commits sequentially and may require resolving code conflicts.
Detailed Operational Steps
After completing the rebase, create a new branch to preserve work results: git branch new-work. Subsequently reset the main branch to the remote state: git reset --hard origin/master. Before resetting, ensure the working directory is clean and you're on the master branch, as this operation discards unique commits from local master.
Visual Verification
During branch manipulation, continuously monitor the commit graph using gitk --all or similar tools to intuitively understand reference pointers. This helps prevent misoperations and ensures branch structure adjustments meet expectations.
Alternative Method Comparison
Method two directly creates a branch containing merge commits: git checkout -b mybranch, followed by resetting master. This approach is simpler but retains redundant merge history. Method three uses git reset --soft HEAD~1 to uncommit changes before recommitting to a new branch, suitable for few commits where compressed history is acceptable.
Best Practice Recommendations
The rebase solution produces linear commit history, facilitating subsequent code review and issue tracking. In team collaboration environments, clear historical records outweigh operational simplicity. After branch migration, promptly push the new branch to the remote repository for backup and collaboration.