Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions cli.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ set -u

# Simple CLI wrapper that discovers scripts in the commands/ directory

# Get the directory of this script, so it can be run from anywhere
realpath="$(realpath "$0")" || { echo "Failed to get realpath"; exit 1; }

# `CLIROOT` is the directory of the cli script.
# Commands are run from the directory the user is in,
# use `$CLIROOT` to cd to the directory of the cli script.
CLIROOT="${realpath%/*}"
# `CLIROOT` is the directory of the CLI script when executed, or the current
# directory when sourced.
if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then
CLIROOT="$PWD"
else
realpath="$(realpath "$0")" || { echo "Failed to get realpath"; exit 1; }
CLIROOT="${realpath%/*}"
fi

# `CMDROOT` absolute path to commands directory.
CMDROOT="$CLIROOT/commands"
Expand Down Expand Up @@ -75,6 +76,11 @@ if [ -d "$CMDROOT" ]; then
fi
commands+=("help" "list")

# Sourcing the CLI loads its helpers and command list without dispatching a command.
if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then
return 0
fi

# CMD is $1 lowercased, default to "list"
CMD=${1:-list}
CMD=${CMD,,}
Expand Down
19 changes: 19 additions & 0 deletions tests/test-cli-0.sh
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,25 @@ test_cli_list_output() {
fi
}

test_sourcing_cli_is_silent_and_uses_current_directory() {
echo "Testing sourcing cli.sh is silent and sets CLIROOT to the current directory"
local output expected_cli_root
expected_cli_root="$(cd "$TEST_DIR/.." && pwd)" || return 1
output=$(bash -c '
cd "$1" || exit 1
source "$2"
command_exists "test-cmd" || exit 1
printf "%s" "$CLIROOT"
' bash "$expected_cli_root" "$expected_cli_root/cli.sh" 2>&1) || {
echo "FAIL: Sourcing cli.sh did not expose its helpers."
return 1
}
if [[ "$output" != "$expected_cli_root" ]]; then
echo "FAIL: Expected only CLIROOT ($expected_cli_root), got: $output"
return 1
fi
}

test_list_output_for_test_cmd_help() {
echo "Testing help text file file for test command"
if [[ "$(./../cli.sh list)" != *"this is a test command"* ]]; then
Expand Down
Loading