Rework argument parsing to support position-independent arguments

This commit is contained in:
Salt 2020-02-20 00:17:22 -06:00
parent 56fb8bfa50
commit 3086d9a5c5
1 changed files with 39 additions and 33 deletions

72
ptgdp
View File

@ -320,34 +320,45 @@ playlist() {
# Main # Main
main() { main() {
# Getopts before anything else # Parse out arguments
while getopts ":c:dhmpv" opt; do # Done in a nested loop so that flags are position-independent
case $opt in while [ -n "$1" ]; do
c) # Parse out flags
_optconfigfile="$OPTARG" while getopts ":c:dhmpv" opt; do
;; case $opt in
d) c)
_optdlonly=1 _optconfigfile="$OPTARG"
;; ;;
h) d)
_opthelp=1 _optdlonly=1
;; ;;
m) h)
_optmachinemode=1 _opthelp=1
;; ;;
p) m)
_optautoplay=1 _optmachinemode=1
;; ;;
v) p)
_optverbose+=1 _optautoplay=1
;; ;;
:) v)
error "Option requires argument: -$OPTARG" 2 _optverbose+=1
;; ;;
*) :)
error "Invalid option: -$OPTARG" 2 error "Option requires argument: -$OPTARG" 2
;; ;;
esac *)
error "Invalid option: -$OPTARG" 2
;;
esac
done
# Store arguments
shift $((OPTIND - 1))
if [ -n "$1" ]; then
_args+=("$1")
shift
fi
unset OPTIND
done done
# Early hook for help # Early hook for help
[ -n "$_opthelp" ] && printhelp && exit 0 [ -n "$_opthelp" ] && printhelp && exit 0
@ -366,11 +377,6 @@ main() {
else else
warn "Could not find configuration file" 2 warn "Could not find configuration file" 2
fi fi
# Store arguments
shift $((OPTIND - 1))
for arg in "$@"; do
_args+=("$arg")
done
# Validate critical options # Validate critical options
if [ -z "$_optmachinemode" ]; then if [ -z "$_optmachinemode" ]; then
# Ensure we have a good backend, assuming we're not in a scripting mode # Ensure we have a good backend, assuming we're not in a scripting mode