#!/usr/bin/env zsh

# Wrapper to "svn diff".
# Copyright 2009-2022 Vincent Lefevre <vincent@vinc17.net>.

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA

# The -w option can be used for colorized word diff, in which case
# François Pinard's wdiff utility is needed. Otherwise this script
# needs Vincent Lefevre's tdiff utility to process the diff output.
# It also needs an ext-diff utility to support non-textual files.
# See <https://www.vinc17.net/unix/> for tdiff and ext-diff.

# Example of svncdiff usage:
#   svncdiff -5 -x -p file
# for 5 lines of unified context and function information.
#
# History:
#   2009-05-29  Initial version.
#   2009-09-28  Syntax improvement (=~ from zsh 4.3.5+).
#   2014-01-31  First published version. Use ext-diff and $SVN_CMD if defined.
#   2020-04-11  Added word diff support with wdiff (option -w).
#   2022-07-13  Use the zsh function or command cwdiff instead of wdiff.

emulate -LR zsh
local -a args xopt
setopt EXTENDED_GLOB

args=(--force --diff-cmd ext-diff)
cmd=tdiff

# The user may prefer his own cwdiff function (or external command) rather
# than the following one, provided in case cwdiff is not available.
# Changing '30;41' to 97;41' and '30;42' to '97;48;5;28' makes text more
# readable (tested on various devices), but needs a 256-color terminal,
# which are common nowadays.
cwdiff_fallback()
{
  wdiff -n -w $'\033[30;41m' -x $'\033[0m' \
           -y $'\033[30;42m' -z $'\033[0m' -d "$@"
  return $(( $? == 1 ? 0 : $? ))
}

while [[ $# -ge 1 ]]
do
  if [[ "$1" == -[0-9]# ]] then
    xopt=($xopt -U${1[2,-1]})
  elif [[ "$1" == -w ]] then
    eval "autoload -R cwdiff 2> /dev/null"
    if [[ $? == 0 ]] || whence -p cwdiff > /dev/null; then
      cmd=cwdiff
    else
      cmd=cwdiff_fallback
    fi
  elif [[ $# -ge 2 && "$1" == -x ]] then
    shift
    xopt=($xopt $1)
  else
    args=($args $1)
  fi
  shift
done

[[ $#xopt -ge 1 ]] && args=(-x "$xopt" $args)
${SVN_CMD:-svn} diff "$args[@]" | $cmd

# $Id: svncdiff 150114 2022-07-13 13:29:25Z vinc17/zira $