summaryrefslogtreecommitdiff
path: root/chardiff.sh
blob: 6d629d255b6174ab58ca84836ed990e73719ba36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/bin/bash
# Copyright (C) 2011-2014 Luke Shumaker <lukeshu@sbcglobal.net>

# 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'

	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' "${wdiff_flags[@]}"|sed -rn 's/^-([^-])/\1/p'))
	flags_l=($(printf -- '%s\n' "${wdiff_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 "$@"