2

I made a commit containing ten files recently. One of the files shouldn't have been committed: it has my local test changes that won't work for anyone else.

I'd like to check out that file from a previous commit, then re-commit it as the original, then reapply my changes locally.

git revert sounds good, but it appears to be for entire commits, rather than one file in a commit. Is there a good way to go about this while keeping the git chatter/logs to a minimum? Amend the previous commit perhaps?

None of this has been pushed yet, if that helps.

jub0bs
  • 60,866
  • 25
  • 183
  • 186
jkj2000
  • 1,563
  • 4
  • 19
  • 26

2 Answers2

4

git revert sounds good, but it appears to be for entire commits, rather than one file in a commit.

There is no light-touch way of changing a commit. If you want to change even a tiny little thing in an existing commit, you have to create a new one (with a new SHA) that merely resembles the original one.

Is there a good way to go about this while keeping the git chatter/logs to a minimum? (Amend the previous commit perhaps?)

If the commit in question is not the last one on the branch, git commit --amend won't help you much; see this for an explanation. You can either use git revert or...

None of this has been pushed yet, if that helps...

Since you haven't pushed to remote yet (yes, it does help), you can always do an interactive rebase to rewrite the history of your branch from the point where the offending file was first introduced onwards.

Community
  • 1
  • 1
jub0bs
  • 60,866
  • 25
  • 183
  • 186
3

If it hasn't been pushed - you're golden, you can rewrite history as you please.

Amending the commit is a great idea, if your commit is the last one on the branch (if not - don't worry, as it isn't pushed you can rewrite history fairly simply anyway). To get the "old" version of the file you can just check it out from the previous commit with command git checkout COMMIT-HASH-ID path_to_file.

So, if your git log --oneline looks output looks like this -

 $ git log --oneline
9ab100f Your awesome 10-file commit message
e62c6d5 Merge pull request #607 from origin/someone-elses-feature
cfdf47a someone elses commit message

Just do

git checkout e62c6d5 path/to/your_file_name.js

Then add it to stage

git add .

then amend

git commit --amend

Look at the history, you should be all good.

apprenticeDev
  • 8,029
  • 3
  • 23
  • 25
  • 1
    Whether the offending commit is the last one on the OP's branch is unclear. If that's not the case, `git commit --amend` is not the right command, here. – jub0bs Mar 19 '15 at 15:15
  • You're right, good point. Gave your answer an upvote for better formatting and a link to rebasing chapter. – apprenticeDev Mar 19 '15 at 15:18
  • Now that your answer mentions the "last-commit" limitation, you can get my upvote too :) – jub0bs Mar 19 '15 at 15:19