-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathargs
More file actions
226 lines (182 loc) · 6.94 KB
/
Copy pathargs
File metadata and controls
226 lines (182 loc) · 6.94 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# Copyright (c) 2025 Richard Bloch
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# -----------------------------------------------------------------------------
#
# Bash library (bash-lib) for command line argument loading/parsing/validating
# Version: 1.3.0
#
# This file is a LIBRARY and must be sourced, not executed:
# source "path/to/bash-lib/args"
#
# Dependency note: on fatal errors this file calls quit(), which is defined
# in the companion 'general' library file. Source both 'general' and 'args'
# before invoking any function below.
#
# Refuse to run if executed directly instead of sourced.
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
printf "Error: '%s' is a library and must be sourced, not executed.\n" "${BASH_SOURCE[0]}" >&2
exit 1
fi
# --- Constants and variables -----------------------------------------------
#
# EXEC_DIR resolves to the directory of the *calling* script, not this
# library file -- when sourced, $0 still refers to the entry-point script.
# This is intentional: config.json is expected to live alongside the script
# that uses this library, at <calling_script_dir>/data/config.json
EXEC_DIR="$(dirname "$(readlink -f "$0")")"
readonly EXEC_DIR
# Path to the config file
ARGS_FILE="${EXEC_DIR}/data/config.json"
readonly ARGS_FILE
# Associative array to hold parsed argument values
declare -gA ARG_VALUE
# --- Internal helper function(s) and cached data ----------------------------
#
# Cache so the config file is read and parsed by jq only once per run,
# regardless of how many times the getters below are called.
__config_json_cache=""
declare -gA __config_details_cache # details[key] -> value
declare -gA __config_arg_cache # arguments["<idx>:<key>"] -> value
__config_arg_count=-1
# -----------------------------------------------------------------------------
# _load_config reads the config file and flattens both the 'details' object
# and the 'arguments' array into associative arrays in a single pass. This
# means later lookups (get_config_arg, get_config_details, ...) are plain
# in-memory reads instead of forking a new 'jq' process per field, per call.
#
_load_config() {
# Already loaded -- nothing to do.
[[ -n "$__config_json_cache" ]] && return 0
if [[ ! -f "$ARGS_FILE" ]]; then
printf "Error: configuration file not found at '%s'.\n" "$ARGS_FILE" >&2
quit 1
fi
if ! command -v jq &>/dev/null; then
printf "Error: program 'jq' not installed.\n" >&2
quit 1
fi
__config_json_cache="$(<"$ARGS_FILE")"
if ! jq empty <<<"$__config_json_cache" &>/dev/null; then
printf "Error: '%s' does not contain valid JSON.\n" "$ARGS_FILE" >&2
quit 1
fi
__config_arg_count="$(jq -r '.arguments | length' <<<"$__config_json_cache")"
local key value
while IFS=$'\t' read -r key value; do
__config_details_cache["$key"]="$value"
done < <(jq -r '.details | to_entries[] | "\(.key)\t\(.value)"' <<<"$__config_json_cache")
local idx
while IFS=$'\t' read -r idx key value; do
__config_arg_cache["${idx}:${key}"]="$value"
done < <(jq -r '.arguments | to_entries[] | .key as $i | .value | to_entries[] | "\($i)\t\(.key)\t\(.value)"' <<<"$__config_json_cache")
}
# -----------------------------------------------------------------------------
# get_config_details() queries a top-level key from the 'details' object
# in the config file
#
get_config_details() {
_load_config
printf "%s" "${__config_details_cache[$1]:-}"
}
# -----------------------------------------------------------------------------
# get_config_arg() queries a specific key from an argument definition by its
# index in the config file
#
get_config_arg() {
_load_config
printf "%s" "${__config_arg_cache["$1:$2"]:-}"
}
# -----------------------------------------------------------------------------
# get_config_args_length() returns the total number of argument definitions
# in the config file
#
get_config_args_length() {
_load_config
printf "%s" "$__config_arg_count"
}
# -----------------------------------------------------------------------------
# get_config_arg_value() returns the parsed value for a given argument
# The argument is identified by its 'text_string' from the config
#
get_config_arg_value() {
printf "%s" "${ARG_VALUE[$1]:-}"
}
# -----------------------------------------------------------------------------
# scan_for_args() scans command-line arguments and populates ARG_VALUE.
#
scan_for_args() {
_load_config
local arg_count
arg_count=$(get_config_args_length)
# Pre-build lookup maps for short and long forms for efficiency
local -A short_form_map=()
local -A long_form_map=()
local i text_string short long
for ((i = 0; i < arg_count; i++)); do
text_string=$(get_config_arg "$i" "text_string")
short=$(get_config_arg "$i" "short_form")
long=$(get_config_arg "$i" "long_form")
[[ -n "$short" ]] && short_form_map["$short"]="$text_string"
[[ -n "$long" ]] && long_form_map["$long"]="$text_string"
done
local key consumed
while [[ $# -gt 0 ]]; do
key=""
consumed=1 # Default to consuming one argument
if [[ -n "${short_form_map[$1]:-}" ]]; then
key="${short_form_map[$1]}"
elif [[ -n "${long_form_map[$1]:-}" ]]; then
key="${long_form_map[$1]}"
fi
if [[ -n "$key" ]]; then
# Check if the next argument is a value (and not another flag)
if [[ $# -gt 1 ]] && [[ ! "${2-}" =~ ^- ]]; then
ARG_VALUE["$key"]="$2"
consumed=2 # Set to consume both the flag and its value
else
# A boolean flag with no value
ARG_VALUE["$key"]=""
fi
fi
# Consume the determined number of arguments
shift "$consumed"
done
}
# -----------------------------------------------------------------------------
# check_for_args_completeness() verifies all required arguments are present
#
check_for_args_completeness() {
_load_config
local err_count=0
local arg_count
arg_count=$(get_config_args_length)
local i is_required text_string short_form long_form
for ((i = 0; i < arg_count; i++)); do
is_required=$(get_config_arg "$i" "required")
if [[ "$is_required" == "true" ]]; then
text_string=$(get_config_arg "$i" "text_string")
if [[ -z "${ARG_VALUE[$text_string]:-}" ]]; then
short_form=$(get_config_arg "$i" "short_form")
long_form=$(get_config_arg "$i" "long_form")
printf "Error: argument '%s' (%s|%s) is missing.\n" \
"$text_string" "$short_form" "$long_form" >&2
err_count=$((err_count + 1))
fi
fi
done
if ((err_count > 0)); then
quit 1
fi
}