test: Test less detection when given a file path

less called as `less /path/file` shows up in `ps` with the path
appended; basename-ing the whole command line returns the file name
instead of `less`, so batpipe fails to detect less and disables color.
The `less` shim is extended to honor a piped LESSOPEN and report itself
as `less` (like the fish/nu shims) so the test can exercise this.
This commit is contained in:
Andreas Hartl 2026-06-16 11:00:21 +02:00
parent 3860f0f148
commit 6e75459c1a
2 changed files with 39 additions and 5 deletions

View file

@ -12,10 +12,27 @@ EOF
exit 0
fi
FILES=()
while [[ $# -gt 0 ]]; do
-*) : ;;
*) FILES+=("$1")
# Re-exec with argv[0] set to `less` (like the fish/nu shims) so this process
# is reported as `less` by `ps`. batpipe identifies its parent process by name;
# a plain script would show up as `bash .../less` and hide us.
if [[ -z "${_LESS_SHIM_REEXEC:-}" ]]; then
export _LESS_SHIM_REEXEC=1
exec -a "${SHIM_ARGV0:-less}" bash "$0" "$@"
fi
# Collect file operands, ignoring options -- like the real less CLI.
files=()
for arg; do
[[ "$arg" == -* ]] || files+=("$arg")
done
cat "${FILES[@]}"
# Honor an input-pipe LESSOPEN preprocessor (`|command %s`) the way real less
# does: feed each file through it. Otherwise just print the file.
for file in "${files[@]}"; do
if [[ "${LESSOPEN-}" == "|"* ]]; then
command="${LESSOPEN#|}"
eval "${command//%s/$file}"
else
cat "$file"
fi
done

View file

@ -42,6 +42,23 @@ test:detected_nu_shell() {
grep '^\$env' <<< "$output" >/dev/null || fail 'Detected wrong shell when checking parent process.'
}
test:detected_less_with_path_argument() {
description "Test it detects less when less opens a file by an absolute path."
# Drive less, letting it invoke batpipe as its LESSOPEN preprocessor, with a
# file opened by an absolute path -- exactly how files are normally opened
# (`less /home/user/file.txt`). less's command line then ends in that path;
# batpipe must detect "less" from the executable name only. Taking the
# basename of the *whole* command line yields the file's basename instead,
# so batpipe wrongly concludes it is not inside less and disables color.
export BATPIPE_DEBUG=1
export LESSOPEN="|$(batpipe_path) %s"
output="$(less "${PWD}/file.txt" 2>&1)"
grep 'BATPIPE_INSIDE_LESS: true' <<< "$output" >/dev/null \
|| fail "Did not detect less as the parent when opening a file by an absolute path."
}
test:viewer_gzip() {
description "Test it can view .gz files."
command -v "gunzip" &>/dev/null || skip "Test requires gunzip."