Skip to content

Commit

Permalink
Interpolation: only quote multi-word values (#100)
Browse files Browse the repository at this point in the history
- Fixes #99 
- adds `platform::existing_command`
  • Loading branch information
denisidoro committed Sep 30, 2019
1 parent 97329b9 commit 0c960fc
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 10 deletions.
8 changes: 7 additions & 1 deletion src/arg.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
21 changes: 12 additions & 9 deletions src/misc.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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" "$@"
}
18 changes: 18 additions & 0 deletions test/arg_test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/usr/bin/env bash

interpolation_one_word() {
echo "curl http://mysite.com/<user>/profile" \
| arg::interpolate "user" "john" \
| test::equals "curl http://mysite.com/john/profile"
}

interpolation_multiple_words() {
echo "cp <file> <new_file>" \
| 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
9 changes: 9 additions & 0 deletions test/platform_test.sh
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 0c960fc

Please sign in to comment.