From efc5117009e499177bce9743dbfcc759e976d632 Mon Sep 17 00:00:00 2001 From: Aaron McHale Date: Sun, 1 Nov 2026 14:44:05 +0000 Subject: [PATCH] Issue #12 Allow cli to be sourced without producing any output --- cli.sh | 20 +++++++++++++------- tests/test-cli-0.sh | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/cli.sh b/cli.sh index a0f3754..de1f887 100755 --- a/cli.sh +++ b/cli.sh @@ -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" @@ -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,,} diff --git a/tests/test-cli-0.sh b/tests/test-cli-0.sh index fba02c9..a88e3d9 100644 --- a/tests/test-cli-0.sh +++ b/tests/test-cli-0.sh @@ -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