2

I recently committed a file to the master branch of my work's repository.

I then created a new local branch to work on other things, but realised I had missed something on the original commit. I made the changes while in the new branch. Would git commit --amend work, or will I need to make a fresh commit? Am I right in assuming that git commit --amend with just amend the the file on the git from my new file in my new local branch

Oscar Chambers
  • 899
  • 9
  • 25

1 Answers1

1

Branch is 'the problem' here

Amending is still committing - it still happens on same branch, so:

  • committing on master
  • switching branches to "new local branch"
  • making changes there

Means that if you do git commit, it adds a new node on "new local branch", not even touching the master.

Option 1: git commit --amend on master branch

$ git checkout master
// apply changes here
$ git commit --amend

This creates new commit REPLACING current tip of master branch (most likely previous commit you did there, unless you or others worked there already, previous commit was pushed, etc.).

Option 2: git commit on master branch

$ git checkout master
// apply changes here
$ git commit -m "New commit, new commit message"

Less elegant. But if you pushed? VERY attractive.

Option 3: git commit on "new local branch" and cherry pick and squash

// changes applied on local branch creating commit with SOME_SHA
$ git checkout master
$ git cherry-pick "new local branch name here"

This applies changes introduced by the commit at the tip of the "new local branch". You may have conflicts, if branches are too different.

$ git rebase -i

And here you need to squash the commits into one. ONLY DO SO IF YOU HAVEN'T PUSHED THE CHANGES!

Somewhat over the top option if you ask me. :-)

"Oh no! I pushed!" options

Either Option 2, or... git revert SHA-of-original-commit followed by making ALL the changes and committing.

I'd only use it if something in that original commit was actually bad/harmful.