Mazeryt
Mazeryt

Reputation: 915

git move part of changes from "to be comitted" to local changes

I have a file that I modified with 2 set of changes: formatting and adding new feature.

I need to turn them into 2 commits.
- Formatting changes
- New Feature A.

Now I used git add --patch and staged all the formatting stuff. So I have:

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   FileA   <-- formatting changes

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   FileA  <-- Feature A

Now before commit, I realized that I put one function (few lines) to the formatting changes (it should land inside Feature changes).

Can I somehow edit now changes to be committed? The file is significant and I don't want to go over again with git add --patch.

The only solution that I can think of to omit running through git add --patch is to commit current changes and then remove these lines from the commit itself.

Is any other way to do that?

Upvotes: 1

Views: 231

Answers (2)

kapsiR
kapsiR

Reputation: 3186

I would suggest the following:
Use git stash (https://www.git-scm.com/docs/git-stash):

  1. git stash --keep-index
    This pushes your current working tree on the stash and keeps your staged changes
    Be aware of untracked files. By default untracked files don't get pushed on the stash! (There is another option for that: --include-untracked)
  2. Change FileA accordingly
  3. git add -p -- FileA
    Stage your new changes - You have now your first commit ready
  4. git stash pop or git stash apply (wheter you want to keep your changes in the stash or not)
  5. You have now your second commit almost ready in the working tree (make necessary changes, stage, commit, ...)

Upvotes: 0

Jan Kr&#252;ger
Jan Kr&#252;ger

Reputation: 18530

There's also git reset --patch which is the reverse of git add --patch.

For a single small change, using git gui can be easier, though - you can interactively stage/unstage individual lines of code just by right-clicking them. Some of the other Git GUIs might have similar features.

Failing that, here's a slightly ugly way to do this without going through everything again:

  • git diff --cached >temp.diff
  • git reset
  • Edit temp.diff and remove the hunk with the change you didn't want to commit
  • git apply --cached --recount temp.diff
  • Commit

Upvotes: 4

Related Questions