From ed4d8acb493dc972764485d67662e57121ef4f2f Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Thu, 27 Nov 2014 22:58:50 -0500 Subject: Add proper option parsing to chardiff --- chardiff.sh | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++---- chardiff_post.c | 1 + chardiff_pre.c | 1 + 3 files changed, 66 insertions(+), 4 deletions(-) diff --git a/chardiff.sh b/chardiff.sh index 7d885b9..c79a102 100644 --- a/chardiff.sh +++ b/chardiff.sh @@ -1,7 +1,67 @@ #!/bin/bash -file1=${1?usage: chardiff FILE1 FILE2 [FLAGS]} -file2=${2?usage: chardiff FILE1 FILE2 [FLAGS]} -shift 2 +# Basically run getopt(1) with arguments that reflect wdiff(1)'s usage +# Except for -d|--diff-input, chardiff doesn't support that. +wdiff_getopt() { + declare ifs="$IFS" + IFS=$'\n' -wdiff "$@" <(chardiff_pre < "$file1") <(chardiff_pre < "$file2") | chardiff_post + declare -a wdiff_flags + wdiff_flags=($( + LC_ALL=C wdiff --help | + sed -rn 's/^ (-.*\S)\s\s.*/\1/p' | + grep -v diff-input | + sed -r \ + -e '/=/{ s/, /:\n/g; s/=.*/:/ }' \ + -e '/^[^=]*$/{ s/, /\n/g }')) + declare -a flags_o flags_l + flags_o=($(printf '%s\n' "${widff_flags[@]}"|sed -n 's/^-[^-]//p')) + flags_l=($(printf '%s\n' "${widff_flags[@]}"|sed -n 's/^--//p')) + + declare o l + IFS='' o="${flags_o[*]}" + IFS=',' l="${flags_l[*]}" + + IFS=$ifs + + declare args + args="$(getopt -n "$0" -o "$o" -l "$l" -- "$@")" || return 1 + + # Check the number of file arguments + eval set -- "$args" + while true; do + case "$1" in + --) shift; break;; + *) shift;; + esac + done + if [[ $# -lt 2 ]]; then + printf '%s: %s\n' "$0" "$(gettext 'missing file arguments')" >&2 + return 1 + elif [[ $# -gt 2 ]]; then + printf '%s: %s\n' "$0" "$(gettext 'too many file arguments')" >&2 + return 1 + fi + + # Return the result + printf '%s' "$args" +} + +main() { + # Normalize the arguments + declare flags + flags="$(wdiff_getopt "$@")" || { wdiff --help >&2; return 1; } + eval set -- "$flags" + + # Run wdiff with our filters + declare -a args=("$@") + declare file2=${args[-1]}; unset args[-1] + declare file1=${args[-1]}; unset args[-1] + set -o pipefail + wdiff "${args[@]}" \ + <(chardiff_pre <"$file1") \ + <(chardiff_pre <"$file2") \ + | chardiff_post +} + +main "$@" diff --git a/chardiff_post.c b/chardiff_post.c index 9a71eeb..8abc3f7 100644 --- a/chardiff_post.c +++ b/chardiff_post.c @@ -15,4 +15,5 @@ main (int argc, char* argv[]) { putchar(c); } } + return 0; } diff --git a/chardiff_pre.c b/chardiff_pre.c index baf7835..6b682bf 100644 --- a/chardiff_pre.c +++ b/chardiff_pre.c @@ -10,4 +10,5 @@ main (int argc, char* argv[]) { default: printf("%c\n",c); break; } } + return 0; } -- cgit v1.2.3