From 0c960fca545dbc48b7c2d7ba094dfb5fb2f85f3a Mon Sep 17 00:00:00 2001 From: Denis Isidoro Date: Mon, 30 Sep 2019 11:27:03 -0300 Subject: [PATCH] Interpolation: only quote multi-word values (#100) - Fixes #99 - adds `platform::existing_command` --- src/arg.sh | 8 +++++++- src/misc.sh | 21 ++++++++++++--------- test/arg_test.sh | 18 ++++++++++++++++++ test/platform_test.sh | 9 +++++++++ 4 files changed, 46 insertions(+), 10 deletions(-) create mode 100644 test/arg_test.sh create mode 100644 test/platform_test.sh diff --git a/src/arg.sh b/src/arg.sh index f01fd40e..466ae79f 100644 --- a/src/arg.sh +++ b/src/arg.sh @@ -18,7 +18,13 @@ arg::interpolate() { local -r arg="$1" local -r value="$2" - sed "s|<${arg}>|\"${value}\"|g" + local -r words="$(echo "$value" | wc -w | xargs)" + + if [[ $words > 1 ]]; then + sed "s|<${arg}>|\"${value}\"|g" + else + sed "s|<${arg}>|${value}|g" + fi } arg::next() { diff --git a/src/misc.sh b/src/misc.sh index 27b8a701..669fcd70 100644 --- a/src/misc.sh +++ b/src/misc.sh @@ -9,18 +9,21 @@ command_exists() { type "$1" &> /dev/null } +platform::existing_command() { + for cmd in "$@"; do + if command_exists "$cmd"; then + echo "$cmd" + return 0 + fi + done + return 1 +} + echoerr() { echo "$@" 1>&2 } url::open() { - if command_exists xdg-open; then - xdg-open "$@" - elif command_exists open; then - open "$@" - elif command_exists google-chrome; then - google-chrome "$@" - elif command_exists firefox; then - firefox "$@" - fi + local -r cmd="$(platform::existing_command "${BROWSER:-}" xdg-open open google-chrome firefox)" + "$cmd" "$@" } \ No newline at end of file diff --git a/test/arg_test.sh b/test/arg_test.sh new file mode 100644 index 00000000..6998cc0b --- /dev/null +++ b/test/arg_test.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +interpolation_one_word() { + echo "curl http://mysite.com//profile" \ + | arg::interpolate "user" "john" \ + | test::equals "curl http://mysite.com/john/profile" +} + +interpolation_multiple_words() { + echo "cp " \ + | arg::interpolate "file" "C:/Program Files/app/foo.exe" \ + | arg::interpolate "new_file" "/mnt/c/Users/john/foo.exe" \ + | test::equals 'cp "C:/Program Files/app/foo.exe" /mnt/c/Users/john/foo.exe' +} + +test::set_suite "arg" +test::run "if there's only one word, interpolation doesn't include quotes" interpolation_one_word +test::run "if there are multiple words, interpolation includes quotes" interpolation_multiple_words diff --git a/test/platform_test.sh b/test/platform_test.sh new file mode 100644 index 00000000..6443d8be --- /dev/null +++ b/test/platform_test.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +existing() { + platform::existing_command oasida fngo ni awk aoisdn oafm \ + | test::equals awk +} + +test::set_suite "platform" +test::run "existing_command" existing