Search code examples
gitgit-addgit-patchgit-apply

Git one-liner for applying a patch interactively


I have this patch file, it contains a bunch of modifications that I'd like to apply to a git branch. But I don't want to make one unique commit with all those modifications, instead I'd like to split it into 2 or 3 commits.

I know I can achieve this by first applying the patch, then doing an interactive add (hunk by hunk), like so:

git apply mypatch
git add -p

I was just wondering if it's possible to do that in one git command. I found nothing in the manpages of git apply, nor in git add.

EDIT

I don't think this question should be considered as a duplicate of Syntax for Git aliases with multiple commands as that question (and its answer) does not need does not involve a parameter passed to the alias.


Solution

  • I'm replying to my own question, thanks to the comment of @8bittree.

    There are at least 2 ways to do that:

    • using a shell function (see 8bittree's answer)
    • using a git alias. I prefer this solution as it only involves .gitconfig, no need to modify .bashrc, and git shell completion works for the new alias, it is shown alongside other standard git commands in the completion list

    So this is what I ended to add to my global .gitconfig:

    [alias]
        # interactive apply patch
        ipatch = "!f() { git apply $1; git add -p; }; f"
    

    I then just have to do:

    git ipatch mypatchfile