Commit 269d777c authored by Dom Sekotill's avatar Dom Sekotill
Browse files

Implemented positional argument parsing

Positional argument parsing implemented, named arguments are still not
done and will cause errors if used.
parent 1bf19fe7
Loading
Loading
Loading
Loading
+43 −1
Original line number Diff line number Diff line
@@ -131,7 +131,32 @@ add_option ()
	[ "$required" = yes ] || [ "$required" = no ] || \
		die "'required' must be one of 'yes' or 'no'"
	metavar=${metavar:-$dest}
	eval _OPTS_$dest=$dest,$metavar,$required,\"$default\"
	eval _OPTS_`printf '%03i' $arg_index`=$dest,$metavar,$required,\"$default\"
	arg_index=$((arg_index + 1))
}


##
# next_opt()
# Set the value of the next positional argument.
#
# Usage:
# next_opt "<value>"
#
# Parameters:
# $1
#   The value to set on the option
##
next_opt ()
{
	local arg dest metavar required default
	for arg in ${!_OPTS_*}; do
		IFS=, read dest metavar required default <<< "${!arg}"
		[ "${!dest}" ] && continue
		eval "$dest='$1'"
		return
	done
	die "unknown option $1"
}


@@ -190,8 +215,14 @@ sumarise_args ()
parse_args ()
{
	local command=$1
	local opts_only
	shift
	while [ "$1" ]; do
		if [ "$opts_only" ]; then
			next_opt "$1"
			shift
			continue
		fi
		case "$1" in
			--help|-h)
				printf "$BIN $command"
@@ -202,9 +233,20 @@ parse_args ()
				echo "$summary"
				return 1
				;;
			--) # everything subsequent is positional options
				opts_only=yes
				;;
			-*) # argument
				set_arg "$1" "$2"
				shift
				;;
			*) # positional option
				next_opt "$1"
				;;
		esac
		shift
	done
	return 0
}