Skip to content

Commit

Permalink
Fix ici_quiet and ici_filter
Browse files Browse the repository at this point in the history
  • Loading branch information
rhaschke committed Aug 27, 2023
1 parent fa544b4 commit a102824
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/util.sh
Original file line number Diff line number Diff line change
Expand Up @@ -390,27 +390,33 @@ function ici_get_log_cmd {
done
}

# only show output on failure, otherwise be quiet
function ici_quiet {
local out; out=$(mktemp)
local err=0
"$@" &> "$out" || err=$?
if [ "$err" -ne 0 ]; then
ici_redirect cat "$out"
rm -rf "$out"
fi
rm -rf "$out"
rm -f "$out"
return "$err"
}

# show full output on failure, otherwise filtered stdout
function ici_filter {
local filter=$1; shift
local out; out=$(mktemp)
"$@" | grep -E "$filter" | ici_redirect cat || true
local out; out=$(mktemp) # stdout
local both; both=$(mktemp) # stdout+stderr
# redirect stdout+stderr to $both and stdout to $out
{ "$@" 2>&1 2>&3 3>&- | tee "$out" 3>&-; } > "$both" 3>&1

local err=${PIPESTATUS[0]}
if [ "$err" -ne 0 ]; then
ici_redirect cat "$out"
ici_redirect cat "$both"
else
ici_redirect cat "$out" | grep -E "$filter"
fi
rm -rf "$out"
rm -f "$out" "$both"
return "$err"
}

Expand Down
45 changes: 45 additions & 0 deletions test/util.bats
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ EOF
assert_output "$expected"
}

# shellcheck disable=SC2030
@test "ici_hook_on_appended_var" {
function ici_time_start() { true; }
function ici_time_end() { true; }
Expand All @@ -57,3 +58,47 @@ EOF
)
assert_output "$expected"
}

function test_filtering_helper {
local exit_code=$1
local expected_components=$2
local filter=${4:-xxx}
shift 2

local all; all=$(cat <<- EOF
good
bad
EOF
)
# shellcheck disable=SC2034,SC2155
local passed=$(echo "$all" | grep -E "$filter")
# shellcheck disable=SC2034
local error="stderr"
local expected=""
for var in $expected_components; do
ici_append expected "${!var}"
done

function sub_shell {
eval "$*"
}

run "$@" sub_shell "echo \"$all\"; echo \"stderr\" 1>&2; return $exit_code"
assert_output "$expected"
# shellcheck disable=SC2031
[ "$status" -eq "$exit_code" ]
}
@test "ici_quiet_true" {
test_filtering_helper 0 "" ici_quiet
}
@test "ici_quiet_false" {
test_filtering_helper 1 "all error" ici_quiet
}
@test "ici_filter_true" {
# stderr is dropped on success
test_filtering_helper 0 "passed" ici_filter "good"
}
@test "ici_filter_false" {
# order of stdout and stderr is changed due to extra filter step
test_filtering_helper 1 "error all" ici_filter "good"
}

0 comments on commit a102824

Please sign in to comment.