Skip to content

Commit

Permalink
ask: close #248
Browse files Browse the repository at this point in the history
- fix `--required` causing infinite loop, this was due to `option_timeout` being empty, which causes `-t ''` to be send to `read` which causes it to exit immediately and try again for input
- clarified some comments
  • Loading branch information
balupton committed Aug 27, 2024
1 parent 332bc46 commit 5d6d2cc
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions commands/ask
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ function ask_() (
fi
}
function do_prompt { # has sideffects: RESULT, ASKED
local programmatic_stdin input_prompt __read_status __input_result result_prompt result_prompt_row_count
local programmatic_stdin input_prompt __read_status __input_result result_prompt result_prompt_row_count clear='' p='' read_args=('-r')
if test ! -t 0; then
programmatic_stdin='yes'
else
Expand All @@ -267,19 +267,26 @@ function ask_() (
fi
input_prompt+="$style__icon_prompt"
fi
if test -n "$option_timeout"; then
read_args+=(
-t "$option_timeout"
)
fi

local clear='' p=''
ASKED='yes' # not local
while true; do
# reset
__read_status=0
__input_result=''

# test for stdin technique, as [read -i] does not support programatic stdin
# adapt according to read mode
if test "$programmatic_stdin" = 'yes'; then
# we have programatic stdin, so manually read the line without a tty prompt
# don't read multiple lines, as other lines are for subequent prompts, such as confirmations or the next program
IFS='' read -r -t "$option_timeout" __input_result || __read_status=$?
# read in programmatic stdin mode behaves differently, so we have to account for that:
# [-p <prompt>] is discarded, no prompt is shown
# [-i <default>] is discarded, no default value is handled
# as such, do not pass such to read, do not manually bother with a prompt, and handle the default value ourself
# trunk-ignore(shellcheck/SC2162)
IFS='' read "${read_args[@]}" __input_result || __read_status=$?
if test -z "$__input_result" -o "$__input_result" = $'\n'; then
# treat empty string and newline as default
:
Expand All @@ -300,7 +307,8 @@ function ask_() (
clear=''

# clear and prompt
IFS= read -r -t "$option_timeout" -ei "$RESULT" -p "$p" __input_result || __read_status=$?
# trunk-ignore(shellcheck/SC2162)
IFS= read "${read_args[@]}" -ei "$RESULT" -p "$p" __input_result || __read_status=$?

# update the value on successful read, and prepare the clear
# note if there was a default value, pressing enter will set [__input_result] to it
Expand Down Expand Up @@ -328,7 +336,7 @@ function ask_() (
# ask again
continue
else
# no result, optional, set value to empty, and proceed
# no result, optional, set value to empty, exit read loop, and continue with program
RESULT=''
break
fi
Expand Down

0 comments on commit 5d6d2cc

Please sign in to comment.