DrNo
DrNo

Reputation: 11

Is there a better way to squash a feature branch that has many non relevant commits

I am working on a long running feature branch where I have many commits that sum to one new feature. The small commits I have been making as I progress are thoroughly intermixed with commits that I have merged in from our development branch as I was working. I would like to squash the commits into one commit that contains all code changes for the new functionality while maintaining the commits of my coworkers.

Normally I would used git rebase interactive and reorder/squash my commits to accomplish this. However given the number of commits from the beginning of this branch to the completion of the feature I am hesitant to do so. Is there a more efficient way to accomplish my goal?

Upvotes: 1

Views: 55

Answers (1)

IMSoP
IMSoP

Reputation: 97793

You can take advantage of the fact that git doesn't store changes, it stores states.

So to create a single commit which applies all your changes, and all the changes from develop, you can:

  1. Make sure your branch (let's call it "feature") has all the latest changes from develop incorporated
  2. Create a new branch (let's call it "feature-new") from the latest develop
  3. Overwrite all your working copy files with the code from "feature"
  4. Commit them as though you've edited them all just now

This is basically what you'd be left with after a "squash" anyway. The only part that should need further explanation is step 3, which can be achieved in one command:

git restore --source=feature --worktree --staged .

This will fetch all the files in the current directory (.) from the current state of branch "feature" (--source=feature), write them to the working copy (--worktree) and stage them for commit (--staged).

(If your version of git is too old to support git restore, you'll need to use git reset --mixed feature, which will stage the changes but not update the working copy. The different modes for "git reset" are rather confusing, which is why "git restore" was added.)

Upvotes: 1

Related Questions