Skip to content

Instantly share code, notes, and snippets.

@psenger
Created November 3, 2024 22:41
Show Gist options
  • Save psenger/d7e3861856a6d57950d81bf6973292bb to your computer and use it in GitHub Desktop.
Save psenger/d7e3861856a6d57950d81bf6973292bb to your computer and use it in GitHub Desktop.
[How to Separate changes to individual Branches] #git

Splitting Mixed Changes into Separate Feature Branches in Git

You have a git project, based on main. With mixed changes in your local copy of the project for two different features none of the changes are pushed to the origin git server. You want to create two branches and check the two branches to the origin git server, separating the two sets of changes.

This guide helps you separate mixed local changes into two different branches and push them individually to the origin Git server.

Steps

  1. Stash Your Changes Temporarily

    Use git stash to save your current mixed changes without committing them:

    git stash

    This command saves your changes and resets your working directory to match the main branch.

  2. Create and Check Out the First Feature Branch

    Create a new branch for the first feature and switch to it:

    git checkout -b feature-branch-1
  3. Apply the Stash and Stage Changes for the First Feature

    • Apply the stash without removing it from the stash list (to reuse it for the second branch):

      git stash apply
    • Stage only the files or changes related to the first feature:

      git add path/to/file1 path/to/file2

      Or, stage changes interactively by selecting specific lines:

      git add -p
  4. Commit the First Feature

    Commit the staged changes:

    git commit -m "Add feature 1 changes"
  5. Push the First Feature Branch to the Origin

    Push the first feature branch to the origin Git server:

    git push -u origin feature-branch-1
  6. Switch Back to Main and Create the Second Feature Branch

    • Discard the unstaged changes and reapply the stash for the second feature:

      git restore --staged .
      git stash apply
    • Create and switch to the second feature branch:

      git checkout -b feature-branch-2
  7. Stage, Commit, and Push the Second Feature

    • Stage and commit the remaining changes for the second feature:

      git add .
      git commit -m "Add feature 2 changes"
    • Push the second feature branch to the origin:

      git push -u origin feature-branch-2

Summary

This approach results in two separate branches, each containing the changes for a distinct feature, both pushed to the origin repository.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment