Blob Blame History Raw
#!/bin/bash
#
# remove the number prefix from patches like 0001-xyz.patch
#

MV="mv"
with_patch=1
verbose=
copy_patch=
add_shaid=
smart_rename=
target=.

usage () {
    echo "strip-number-prefix: remove the number prefix from patches like 0001-xyz.patch"
    echo "options:"
    echo "  -v: verbose"
    echo "  -p: keep .patch extension (default)"
    echo "  -x: drop .patch extension"
    echo "  -a: add SHA1 ID suffix to the patch"
    echo "  -g: git mv to rename"
    echo "  -s: smart rename; when a file name conflicts, add SHA1 ID suffix"
    echo "  -c: copy patches to patches.suse/, implying -s"
    exit 0
}

while test -n "$1"; do
    case "$1" in
	-v)
	    verbose=-v; shift;;
	-x)
	    with_patch=""; shift;;
	-p)
	    with_patch=1; shift;;
	-c)
	    target=patches.suse; smart_rename=1; shift;;
	-s)
	    smart_rename=1; shift;;
	-a)
	    add_shaid=1; shift;;
	-g)
	    MV="git mv"; shift;;
	-h)
	    usage;;
	*)
	    break;;
    esac
done

added=""
list=""
declare -A renamed

get-commit-id () {
    grep -h -m1 '^Git-[cC]ommit: ' "$@" | sed -e's/^Git-[cC]ommit: //g'
}

add_shaid () {
    local old="$1"
    local id=$(get-commit-id "$2" | cut -b 1-7)
    if [ -n "$with_patch" ]; then
	echo ${old%.patch}-$id.patch
    else
	echo $old-$id
    fi
}

patch_present () {
    local f="$1"
    local x

    test -f $target/$f && return 0
    for x in $added; do
	test "$x" = "$target/$f" && return 0
    done
    return 1
}

do_strip () {
    i="$1"
    case "$i" in
	[0-9]*-*)
		;;
	*)
	    return 0
    esac

    n=${i#[0-9]*-}
    test -z "$with_patch" && n=${n%.patch}
    if [ -n "$add_shaid" ]; then
	n=$(add_shaid $n $i)
    fi

    if patch_present $n; then
	if [ -z "$smart_rename" ]; then
	    echo "$target/$n already present!"
	    return 1
	fi
	n=$(add_shaid $n $i)
	if patch_present $n; then
	    echo "Renamed patch $n already present!"
	    return 1
	fi
    fi

    list="$list $i"
    added="$added $target/$n"
    renamed[$i]=$n
    (( nums++ ))
    return 0
}

nums=0
conflict=
if [ -z "$1" ]; then
    for i in [0-9]*-*.patch; do
	test -f $i || break
	do_strip $i || conflict=1
    done
else
    for i in $*; do
	do_strip $i || conflict=1
    done
fi

test -n "$conflict" && exit 1
echo "$nums patches converted"

for i in $list; do
    $MV $verbose $i $target/${renamed[$i]}
done

exit 0