From a77e18d9087e3accd359977c7ab2a76b242e40d2 Mon Sep 17 00:00:00 2001 From: fbt Date: Fri, 27 Jul 2018 17:35:51 +0300 Subject: [PATCH] nify the handler functions Signed-off-by: fbt --- sx-open | 79 +++++++++++++++++++++------------------------------------ 1 file changed, 29 insertions(+), 50 deletions(-) diff --git a/sx-open b/sx-open index cf3a5ad..7f2ec5a 100755 --- a/sx-open +++ b/sx-open @@ -18,53 +18,36 @@ act() { return 0 } -# handle_uri +# handle_target # 1: cmd failed # 3: no handler -handle_uri() { +handle_target() { declare -n result=$1 - declare h cmd regex target=$2 - - set -- "${uri_handlers[@]}" - - while (( $# )); do - cmd=$1; regex=$2 - - if [[ "$target" =~ $regex ]]; then - act ${cmd} "$target"; result=$? - (( result )) && return 1 - - return 0 - fi - - shift 2 - done - - return 3 -} - -# handle_file -# 1: cmd failed -# 2: no such file -# 3: no handler -handle_file() { - declare -n result=$1 - declare m \ - target_mimetype charset \ - cmd regex \ + declare h cmd regex target_is_file target target_left + target_is_file=0 target=$2 + target_left=$target - [[ -e "$target" ]] || return 3 + if [[ -e "$target" ]]; then + target_is_file=1 - IFS=';' read target_mimetype charset <<< $( file -ib "$target" ) + [[ "$target" =~ ^/.* ]] || { target="${PWD}/${target}"; } # Turn relative paths to absolute ones. - set -- "${mime_handlers[@]}" + IFS=';' read target_mimetype charset <<< $( file -ib "$target" ) + target_left=$target_mimetype + + set -- "${mime_handlers[@]}" + elif is_uri "$target"; then + set -- "${uri_handlers[@]}" + else + return 2 + fi while (( $# )); do - cmd=$1; regex=$2 + cmd=( $1 ); regex=$2 - if [[ "$target_mimetype" =~ $regex ]]; then - act ${cmd} "$target"; result=$? + if [[ "$target_left" =~ $regex ]]; then + act "${cmd[@]}" "$target"; result=$? (( result )) && return 1 return 0 @@ -89,7 +72,7 @@ mime() { declare r handler=$1; shift for r in "$@"; do - uri_handlers+=( "$handler" "$r" ) + mime_handlers+=( "$handler" "$r" ) done } @@ -130,25 +113,21 @@ main() { # Treat file:// as local paths. [[ "$target" =~ ^file:(//)?(/.+) ]] && target=${BASH_REMATCH[2]} - if [[ -e "$target" ]]; then - [[ "$target" =~ ^/.* ]] || { target="${PWD}/${target}"; } # Turn relative paths to absolute ones. - - handle_file cmd_result "$target" - elif is_uri "$target"; then - handle_uri cmd_result "$target" - else - printf 'No such file or directory: %s\n' "$target" >&2 - return 2 - fi + handle_target cmd_result "$target" case $? in (1) - printf 'Action failed with exit code: %s\n' "$cmd_result" >&2 + printf 'Action failed with exit code: “%s”\n' "$cmd_result" >&2 return 4 ;; + (2) + printf 'No such file or directory: “%s”\n' "$target" >&2 + return 2 + ;; + (3) - printf 'No handlers found\n' >&2 + printf 'No handlers found for “%s”\n' "$target" >&2 return 3 ;; esac