How to `git apply` hunk by hunk like `git add --patch`?
Yesterday 7:39am

To apply a patch hunk by hunk (interactively) like git add --patch, you can use the --interactive or -i flag with git apply. However, git apply does not natively support an interactive mode like git add -p or git checkout -p.

Workaround: Use git checkout -p or git stash -p

If you want to selectively apply parts of a patch, the best approach is to use:

1. git checkout -p (or git restore -p in newer Git versions)

  • This lets you interactively apply or discard hunks from a patch file.
  • Example:
    bash
    git checkout -p <branch> -- <file>  # For changes from a branch
    or
    bash
    git stash show -p <stash> | git checkout -p --reverse -- <file>  # For stashed changes

2. git stash apply -p

  • If your patch is stashed, you can apply it interactively:
    bash
    git stash apply -p

3. git diff + Manual Editing

  • If you have a patch file (e.g., changes.patch), you can:
    1. Apply it normally:
      bash
      git apply --check changes.patch  # Test if it applies cleanly
      git apply changes.patch
    2. If you want to selectively apply hunks, edit the patch file manually (remove unwanted hunks) and then apply it.

4. Use git add -p After Applying

  • If you want to stage only some of the applied changes:
    bash
    git apply changes.patch
    git add -p  # Interactively stage hunks

Why Not git apply --interactive?

  • git apply is designed for non-interactive patch application. It either applies the entire patch or fails.
  • For interactive hunk selection, Git relies on commands like checkout -p, stash -p, or add -p.

Summary Table

Apply patch interactively
git checkout -p <branch> -- <file> or git stash apply -p
Stage applied changes interactively
git add -p
Test patch before applying
git apply --check changes.patch
Apply entire patch
git apply changes.patch
Yesterday 7:39am

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Le Chat can make mistakes. Check answers. Learn more