Blob Blame History Raw
#! /bin/sh

# Extract the description of a patch.
patch_description() {
    local patch_file=$1

    if [ -e "$patch_file" -o -z "$patch_file" ]
    then
        awk '
        $1 == "***" || $1 == "---"    { exit }
        /^Index:[ \t]|^diff[ \t]|^==*$/ \
            { eat = eat $0 "\n"
              next }
            { print eat $0
              eat = "" }
        ' $patch_file
    fi
}

usage() {
    echo "Usage: ${0##*/} <patch> <tree-1> [<tree-2>]"
    exit 2
}

if [ $# -lt 2 -o $# -gt 3 ]; then
    usage
fi

patch=$1

if [ ! -d "$2" ]; then
    echo "$2 is not a directory" >&2
    exit 1
fi

if [ $# -eq 2 ]; then
    if [ -d "$2.orig" ]; then
	tree1=$2.orig
	tree2=$2
	label=$tree2
    elif [ -d "${2%.*}.orig" ]; then
        tree1=${2%.*}.orig
	tree2=$2
	label=${tree2%.*}
    elif [ -d "${2%.*}" ]; then
	tree1=${2%.*}
	tree2=$2
	label=${2%.*}
    else
	echo "Could not guess name of second tree" >&2
	exit 1
    fi
else
    if [ ! -d "$3" ]; then
	echo "$3 is not a directory" >&2
	exit 1
    fi
    tree1=$2
    tree2=$3
fi

if [ "$tree1" -ef "$tree2" ]; then
    echo "$tree1 and $tree2 are the same directory" >&2
    exit 1
fi

tree1=${tree1%/}
tree2=${tree2%/}

basename=${patch##*/}
dir=${patch%/*}
if [ "$basename" = "$patch" ]; then
    dir=.
fi

tmp=$(mktemp "$dir/.$basename.XXXXXX")
trap 'rm -f $tmp' EXIT

if [ -f "$patch" ]; then
    echo "Refreshing patch $patch ($tree1 => $tree2)"
    patch_description $patch > $tmp
else
    echo "Creating patch $patch ($tree1 => $tree2)"
fi

# escape slashes
re_tree1=${tree1//\//\\\/}
re_tree2=${tree2//\//\\\/}
re_label=${label//\//\\\/}

EXCLUDE="--exclude='*.orig' --exclude='*.rej' --exclude='*~'"
diff -Nur -p $EXCLUDE "$tree1" "$tree2" \
| sed -e "s/^diff .* $re_tree1\/\(.*\) $re_tree2.*/Index: \1\n===================================================================/" \
      -e "s/^--- $re_tree1\([^$'\t']*\).*/--- $label.orig\1/" \
      -e "s/^+++ $re_tree2\([^$'\t']*\).*/+++ $label\1/" \
>> "$tmp"
cat "$tmp" > "$patch"