How to make patch ignore already applied hunks

patch

I have a very large patch file that I'm trying to apply to my code. The problem is, some of the changes in my patch already exist in the code. Is there a way to make patch gracefully ignore the changes that have already been applied?

The -N option doesn't do what I want. If it encounters an already applied hunk it will generate a reject file and will not apply any more hunks to that file. I want it to just ignore that hunk and continue applying the rest of the patch. The only time I want it to generate a .rej file is if a hunk can't be applied and doesn't appear to already be applied.

Is there a way to do this?

Best Answer

You'll need patchutils installed for this.

This script will split one large patch into smaller separate paches, each of them containing only one hunk for one file. You can then apply these patches with patch --forward.

#!/bin/sh -eu

PATCH=$1
OUTDIR=$2

test -f "$PATCH" && test -d "$OUTDIR"

TDIR=$(mktemp -d)
trap 'rm -rf $TDIR' 0

INDEX=0
TEMPHUNK=$TDIR/current_hunk

lsdiff $1 | while read FNAME
do
    HUNK=1
    while :
    do
        filterdiff --annotate --hunks=$HUNK -i "$FNAME" "$PATCH" > "$TEMPHUNK"
        HUNK=$((HUNK+1))
        test -s "$TEMPHUNK" && \
            {
                mv "$TEMPHUNK" "$OUTDIR/$INDEX.diff"
                INDEX=$((INDEX+1))
            } || break
    done
done

Edit: save script to hunks.sh, and call it:

./hunks.sh path/to/big.diff path/to/output/directory
Related Question