common.sh: parse args automatically

This commit is contained in:
xiongdian.me
2022-12-06 16:16:55 +08:00
parent b1c2041f60
commit be3f999a5d
6 changed files with 38 additions and 36 deletions

View File

@@ -34,8 +34,8 @@ router()
apk-add ) apk_add ;;
set-timezone | set-tz ) set_timezone ;;
set-mirror ) set_mirror $2 ;;
* ) echo unknown command "$1". available: apk-add, set-timezone;;
* ) echo unknown command \"$1\". available: apk-add, set-timezone;;
esac
}
router $@
router "${GOT_OPTS[@]}"

View File

@@ -4,6 +4,33 @@ THIS_DIR_COMMON_SH=$( cd "$( dirname "${BASH_SOURCE[0]:-${(%):-%x}}" )" && pwd )
export DOTFILES=$( cd "$THIS_DIR_COMMON_SH/.." && pwd )
if [[ -f ~/.config/dotfiles/env ]]; then set -a; source ~/.config/dotfiles/env; set +a; fi
# parse args and set env, when it is sourced
if [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then
ORIGIN_ARGS="$@"
ARG=""
GOT_OPTS=()
while [[ $# > 0 || -n "$ARG" ]]; do
if [[ -z "$ARG" ]]; then ARG=$1; shift; fi
case $ARG in
-q*|--quite ) export DFS_QUIET=1 ;;
-l*|--lite ) export DFS_LITE=1 ;;
--color ) export DFS_COLOR=1 ;;
--*=* ) GOT_OPTS+=("${ARG%%=*}" "${ARG#*=}") ;;
--* ) GOT_OPTS+=("$ARG") ;;
-* ) GOT_OPTS+=("${ARG:0:2}") ;;
* ) GOT_OPTS+=("$ARG") ;;
esac
if [[ "$ARG" == "--"* || ! "$ARG" == "-"* || ${#ARG} -le 2 ]]; then
ARG=""
else
ARG=-${ARG:2}
fi
done
set -- "$ORIGIN_ARGS"
unset ARG
unset ORIGIN_ARGS
fi
# Color settings
# Source: https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh
if [[ -t 1 || "$DFS_COLOR" == "1" ]]; then
@@ -102,28 +129,6 @@ if [[ "$EUID" != "0" && -x $(command -v sudo) ]]; then
SUDO='sudo'
fi
parse_arg()
{
local ARG=""
PARSE_ARG_RET=()
while [[ $# > 0 || -n "$ARG" ]]; do
if [[ -z "$ARG" ]]; then ARG=$1; shift; fi
case $ARG in
-q*|--quite ) export DFS_QUIET=1 ;;
-l*|--lite ) export DFS_LITE=1 ;;
--color ) export DFS_COLOR=1; is_tty() { true }; setup_color ;;
--* ) PARSE_ARG_RET+=("$ARG") ;;
-* ) PARSE_ARG_RET+=("${ARG:0:2}") ;;
* ) PARSE_ARG_RET+=("$ARG") ;;
esac
if [[ "$ARG" == "--"* || ! "$ARG" == "-"* || ${#ARG} -le 2 ]]; then
ARG=""
else
ARG=-${ARG:2}
fi
done
}
ask_for_yN()
{
while [[ -z "$DFS_QUIET" || "$DFS_QUIET" == "0" ]]; do

View File

@@ -13,8 +13,8 @@ router()
{
case $1 in
brew-install ) brew_install ;;
* ) echo unknown command "$1". available: brew-install;;
* ) echo unknown command \"$1\". available: brew-install;;
esac
}
router $@
router "${GOT_OPTS[@]}"

View File

@@ -27,8 +27,8 @@ router()
case $1 in
pacman-S ) pacman_S ;;
set-mirror ) set_mirror $2 ;;
* ) echo unknown command "$1". available: pacman-S, set-mirror ;;
* ) echo unknown command \"$1\". available: pacman-S, set-mirror ;;
esac
}
router $@
router "${GOT_OPTS[@]}"

View File

@@ -35,8 +35,8 @@ router()
set-mirror ) set_mirror $2 ;;
set-timezone\
| set-tz ) set_timezone $2 ;;
* ) echo unknown command "$1". available: apt-install, set-mirror, set-timezone;;
* ) echo unknown command \"$1\". available: apt-install, set-mirror, set-timezone;;
esac
}
router $@
router "${GOT_OPTS[@]}"