-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiffer
More file actions
executable file
·107 lines (94 loc) · 2.43 KB
/
Copy pathdiffer
File metadata and controls
executable file
·107 lines (94 loc) · 2.43 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/cli_common.sh
source "${SCRIPT_DIR}/lib/cli_common.sh"
TOOL_NAME="differ"
CONF_DIR="$(cli_conf_dir "${TOOL_NAME}")"
CONF_PATH="${CONF_DIR}/differ.json"
help() {
cli_print_help "${TOOL_NAME}" "quickly compare two texts" \
"f1 f2|Diff two files or URLs" \
"f1|Diff file against stored main" \
"store <f1>|Store a main file to diff against" \
"conf|Print the configuration file" \
"-h, --help|Show this help"
printf "Input files must be fully qualified paths or URLs.\n"
printf "Configuration file: %s\n" "${CONF_PATH}"
}
resolve_file() {
local path="$1"
local tmp_name="$2"
if [[ -f "${path}" ]]; then
echo "${path}"
return
fi
if [[ "${path}" =~ ^https?:// ]]; then
printf "Downloading %s\n" "${path}" >&2
curl -s "${path}" > "/tmp/${tmp_name}"
echo "/tmp/${tmp_name}"
return
fi
printf "%s does not exist\n" "${path}" >&2
exit 1
}
do_diff() {
local file1 file2
file1="$(resolve_file "$1" "differ1")"
file2="$(resolve_file "$2" "differ2")"
git diff --no-index --color-words "${file1}" "${file2}" || true
}
diff_with_main() {
local main
main="$(jq -r '.main // empty' "${CONF_PATH}")"
if [[ -z "${main}" ]]; then
printf "No main file stored, please store a main file first\n" >&2
help
exit 1
fi
do_diff "${main}" "$1"
}
# Handle help
case "${1:-}" in
-h|--help|help) help; exit 0 ;;
esac
# Ensure config exists (auto-init)
if [[ ! -f "${CONF_PATH}" ]]; then
cli_ensure_conf "${TOOL_NAME}" "differ.json:{}"
printf "Configuration file generated at %s\n" "${CONF_PATH}"
fi
case "${1:-}" in
store)
if [[ -z "${2:-}" ]]; then
printf "Error: no file given to store\n" >&2
help
exit 1
fi
file="$2"
if [[ -f "$2" ]]; then
file="$(realpath "$2")"
elif [[ ! "$2" =~ ^https?:// ]]; then
printf "%s does not exist\n" "$2" >&2
exit 1
fi
jq --arg f "${file}" '.main = $f' "${CONF_PATH}" > "${CONF_PATH}.tmp"
mv "${CONF_PATH}.tmp" "${CONF_PATH}"
printf "Main file stored as %s\n" "$2"
;;
conf)
cat "${CONF_PATH}"
;;
"")
printf "Error: no file given to diff against\n" >&2
help
exit 1
;;
*)
if [[ -z "${2:-}" ]]; then
printf "Comparing with %s\n" "$(jq -r '.main' "${CONF_PATH}")"
diff_with_main "$1"
else
do_diff "$1" "$2"
fi
;;
esac