Search code examples
gitworkflow

Undo local changes interactive


I often add some debug code while developing so I need to remove these changes later.

Currently, I check the git diff and remove the changes manually or just type git checkout -- myfilename if I would like to undo the entire file.

I love the interactive patch function (git add -i). Is there a tool or a command in git which can undo changes interactive like git add -i?

In other words: I would like to interactively checkout files and hunks out of the index.


Solution

  • The command you are looking for is

    $git checkout -p
    

    The git checkout Manual Page says:

    -p

    --patch

    Interactively select hunks in the difference between the (or the index, if unspecified) and the working tree. The chosen hunks are then applied in reverse to the working tree (and if a was specified, the index).

    This means that you can use git checkout -p to selectively discard edits from your current working tree. See the “Interactive Mode” section of git-add(1) to learn how to operate the --patch mode.


    If you want to restore staged changes interactively, use git reset --patch or git reset -p.

    From the docs:

    git reset (--patch | -p) [] [--] [...]

    Interactively select hunks in the difference between the index and (defaults to HEAD). The chosen hunks are applied in reverse to the index.

    This means that git reset -p is the opposite of git add -p, i.e. you can use it to selectively reset hunks. See the “Interactive Mode” section of git-add(1) to learn how to operate the --patch mode.

    and about git add -p it says

    -p

    Interactively choose hunks of patch between the index and the work tree and add them to the index. This gives the user a chance to review the difference before adding modified contents to the index.

    This effectively runs add --interactive, but bypasses the initial command menu and directly jumps to the patch subcommand. See “Interactive mode” for details.

    So basically with git reset -p you can select what you reset.