Improve argument/command handling

This commit is contained in:
2013-06-27 00:08:17 +02:00
parent 9d65d7831e
commit 46f395fbb7
2 changed files with 47 additions and 22 deletions

View File

@@ -35,30 +35,57 @@ source "../lib/dotify-help.sh"
source "../lib/dotify-info.sh"
source "../lib/dotify-install.sh"
#
# Argument Parsing
#
DOTFILE="" # --dotfile / -f
TARGET="" # --target / -t
HELP="" # --help / -h
VERSION="" # --version / -v
if has-argument dotfile f "$@"; then
DOTFILE="$(parse-argument dotfile f "$@")"
fi
if has-argument target t "$@"; then
TARGET="$(parse-argument target t "$@")"
fi
if has-argument help h "$@"; then
HELP="1"
fi
if has-argument version v "$@"; then
VERSION="1"
fi
#
# Command Parsing
#
# If arguments include "--help" or "-h" display help and exit.
if has-argument help h "$@"; then
dotify-help "$@"
exit
fi
# Command is first argument that does not start with a dash.
# Command is first argument that does not start with a dash or plus.
for arg in "$@"; do
if [[ "$arg" != "-"* ]]; then
if [[ "$arg" != "-"* ]] && [[ "$arg" != "+"* ]]; then
command="$arg"
break
fi
done
if [ -n "$HELP" ] || [ "$command" == "help" ]; then
dotify-help
exit
fi
if [ -n "$VERSION" ] || [ "$command" == "version" ]; then
dotify-help | head -1
exit
fi
case "$command" in
"help" )
dotify-help "$@"
;;
"info" )
dotify-info "$@"
dotify-info
;;
"" | "install" )
dotify-install

View File

@@ -4,9 +4,8 @@
locate-dotfile() {
local dotfile
if has-argument dotfile f "$@"; then
dotfile="$(parse-argument dotfile f "$@")"
dotfile="$(expand-path "$dotfile")"
if [ -n "$DOTFILE" ]; then
dotfile="$DOTFILE"
if [ ! -f "$dotfile" ]; then
echo "ERROR: \"$dotfile\" does not exist." >&2
return 1
@@ -23,19 +22,18 @@ locate-dotfile() {
locate-target() {
local target
if has-argument target t "$@"; then
target="$(parse-argument target t "$@")"
target="$(expand-path "$target")"
if [ -n "$DOTFILE" ]; then
target="$TARGET"
if [ ! -d "$target" ]; then
echo "ERROR: Target \"$target\" is not a directory."
echo "ERROR: Target \"$target\" is not a directory." >&2
return 1
fi
elif [ -n "$HOME" ] && [ -d "$HOME" ]; then
target="$HOME"
elif [ -d "$(expand-path "~")" ]; then
target="$HOME"
elif [ -d ~ ]; then
target=~
else
echo "ERROR: Your \$HOME folder could not be found."
echo "ERROR: Your \$HOME folder could not be found." >&2
return 1
fi