summaryrefslogtreecommitdiff
path: root/chardiff.sh
blob: 7eca8428ae0c16783711c39d8dd465b427e2d2f2 (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/bin/bash
# Copyright (C) 2011-2014 Luke Shumaker <lukeshu@lukeshu.com>

# 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
			-C|--copyright|-h|--help|-v|--version)
				printf -- '%s' "$1"; return;;
			--) 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
	if ! flags="$(wdiff_getopt "$@")"; then
		printf "$(gettext 'Try `%s'\'' for my information.\n')" "${0##*/} --help" >&2
		return 2
	fi
	eval set -- "$flags"

	case "$1" in
		-C|--copyright)
			wdiff --copyright
			return
			;;
		-h|--help)
			printf "$(gettext 'chardiff - Compares characters in two files and report differences.\n')"
			wdiff --help | sed -e 1d -e '/\s-d\b/d' -e /diff-input/d -e '/@gnu\.org/d' -e "s/wdiff/${0##*/}/g"
			printf "$(gettext 'Report bugs to <lukeshu@lukeshu.com>.\n')"
			return 0
			;;
		-v|--version)
			printf "$(gettext 'chardiff (thingutils chardiff) %s\n')" 0
			printf "$(gettext 'Using:\n')"
			wdiff --version
			return 0
			;;
	esac

	# 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 "$@"