### vim:ft=zsh:foldmethod=marker
###
### wrapper for git's format-patch, which basically does this:
###     git format-patch + summary-mail + hook functions/scripts
###
### Frank Terbeck <ft@bewatermyfriend.org>
### Last-Modified: Fri Jun 26 18:01:36 2009
###
### URI: <http://ft.bewatermyfriend.org/comp/zsh.html>
###

emulate -L zsh
setopt extendedglob

local hook patch line summary from origin outpath
local -i ret
local -a patches fp_opts fp_hooks

if (( ${#argv} == 0 )) ; then
    printf 'usage: gitfp <git-format-patch-arguments>\n'
    return 1
fi

# create patch-series.
zstyle -a ":functions:gitfp:$PWD" options fp_opts
(( ${#fp_opts} > 0 )) &&
    printf 'gitfp(): Using special options from zstyle: %s\n' "${fp_opts}"
command git format-patch ${fp_opts} "$@" | while IFS= read -r line; do
    printf 'gitfp(): %s\n' ${line}
    patches+=( ${line} )
done
ret="$?"

if (( ret != 0 )) ; then
    return ${ret}
fi

# create summary mail, if we generated more than one patch.
if (( ${#patches} > 1 )) ; then
    origin=${argv[-1]}
    from="$(git config --get user.name) <$(git config --get user.email)>"
    outpath=''
    [[ ${patches[1]:h} != . ]] && outpath="${{patches[1]:h}/"
    summary="${outpath}0000-patch-series-summary.patch"

    cat << __EOF0__ > ${summary}
From ${from} # This line is ignored.
From: ${from}
Subject: [PATCH 0/${#patches}] 
In-Reply-To:
GIT:
GIT: Lines beginning in "GIT: " will NOT be removed!
GIT: Please remove these lines manually before sending!
GIT:
GIT: Consider including an overall diffstat and table of contents
GIT: for the patch series you are sending.

__EOF0__
    if [[ $1 == -<-> ]] ; then
        printf 'gitfp(): Creating summary using "%s"\n' ${origin}
        git shortlog ${origin} | sed -e 's,^   *,  ,' >> ${summary}
        git diff --stat "HEAD~${origin#-}" >> ${summary}
    else
        printf 'gitfp(): Creating summary using "%s.."\n' ${origin}
        git shortlog ${origin}.. | sed -e 's,^   *,  ,' >> ${summary}
        git diff --stat ${origin}.. >> ${summary}
    fi

    patches+=( ${summary} )
fi

# run hooks if base directory matches.
zstyle -a ":functions:gitfp:${CHPWD_PROFILE}" hooks fp_hooks
(( ${#fp_hooks} > 0 )) &&
    printf 'gitfp(): --- executing hooks ---\n'
for hook in ${fp_hooks}; do
    for patch in ${patches} ; do
        printf 'gitfp(): %s %s\n' ${hook} ${patch}
        ${hook} ${patch}
    done
done

return ${ret}