Parse options so they can be combined (e.g. -kv) and occur anywhere on the command line

This commit is contained in:
Sam Stephenson 2012-08-15 13:28:01 -05:00
parent aee4782095
commit 8446df21c1

View file

@ -5,6 +5,39 @@ RUBY_BUILD_VERSION="20120524"
set -E set -E
exec 3<&2 # preserve original stderr at fd 3 exec 3<&2 # preserve original stderr at fd 3
lib() {
parse_options() {
OPTIONS=()
ARGUMENTS=()
local arg option index
for arg in "$@"; do
if [ "${arg:0:1}" = "-" ]; then
if [ "${arg:1:1}" = "-" ]; then
OPTIONS[${#OPTIONS[*]}]="${arg:2}"
else
index=1
while option="${arg:$index:1}"; do
[ -n "$option" ] || break
OPTIONS[${#OPTIONS[*]}]="$option"
index=$(($index+1))
done
fi
else
ARGUMENTS[${#ARGUMENTS[*]}]="$arg"
fi
done
}
if [ "$1" == "--$FUNCNAME" ]; then
declare -f "$FUNCNAME"
exit
fi
}
lib "$1"
resolve_link() { resolve_link() {
$(type -p greadlink readlink | head -1) "$1" $(type -p greadlink readlink | head -1) "$1"
} }
@ -332,7 +365,7 @@ version() {
usage() { usage() {
{ version { version
echo "usage: ruby-build [-v|--verbose] definition prefix" echo "usage: ruby-build [-k|--keep] [-v|--verbose] definition prefix"
echo " ruby-build --definitions" echo " ruby-build --definitions"
} >&2 } >&2
@ -351,34 +384,41 @@ list_definitions() {
unset VERBOSE unset VERBOSE
unset KEEP_BUILD_PATH
RUBY_BUILD_ROOT="$(abs_dirname "$0")/.." RUBY_BUILD_ROOT="$(abs_dirname "$0")/.."
case "$1" in parse_options "$@"
"-h" | "--help" )
for option in "${OPTIONS[@]}"; do
case "$option" in
"h" | "help" )
usage without_exiting usage without_exiting
{ echo { echo
echo " -k/--keep Do not remove source tree after installation"
echo " -v/--verbose Verbose mode: print compilation status to stdout" echo " -v/--verbose Verbose mode: print compilation status to stdout"
echo " --definitions List all built-in definitions" echo " --definitions List all built-in definitions"
echo echo
} >&2 } >&2
exit 0 exit 0
;; ;;
"--definitions" ) "definitions" )
list_definitions list_definitions
exit 0 exit 0
;; ;;
"--version" ) "k" | "keep" )
KEEP_BUILD_PATH=true
;;
"v" | "verbose" )
VERBOSE=true
;;
"version" )
version version
exit 0 exit 0
;; ;;
"-v" | "--verbose" )
VERBOSE=true
shift
;;
esac esac
done
DEFINITION_PATH="${ARGUMENTS[0]}"
DEFINITION_PATH="$1"
if [ -z "$DEFINITION_PATH" ]; then if [ -z "$DEFINITION_PATH" ]; then
usage usage
elif [ ! -e "$DEFINITION_PATH" ]; then elif [ ! -e "$DEFINITION_PATH" ]; then
@ -391,20 +431,11 @@ elif [ ! -e "$DEFINITION_PATH" ]; then
fi fi
fi fi
PREFIX_PATH="$2" PREFIX_PATH="${ARGUMENTS[1]}"
if [ -z "$PREFIX_PATH" ]; then if [ -z "$PREFIX_PATH" ]; then
usage usage
fi fi
OPTIONS="$3"
for option in $OPTIONS; do
case "$option" in
"-k" | "--keep" )
KEEP_BUILD_PATH="y"
;;
esac
done
if [ -z "$TMPDIR" ]; then if [ -z "$TMPDIR" ]; then
TMP="/tmp" TMP="/tmp"
else else