-
Notifications
You must be signed in to change notification settings - Fork 0
/
ask-yes-no
executable file
·85 lines (76 loc) · 2.51 KB
/
ask-yes-no
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env fish
# ask the user a yes or no question and return true (0) if yes, false (1) otherwise.
# FIX: implement default, etc
set -- script "$(path basename (status filename))"
argparse -n $script --ignore-unknown 'h/help' 'p/prompt=' 'e/exact' 'd/default=' 'u/unrecognized=' 'i/sigint=' -- $argv
if set -q _flag_h
echo "$script - ask the user a yes or no question and return true (0) if yes, false (1) otherwise."
echo "Usage: $script [arguments] [prompt]"
echo
echo " -h/--help - Print help and exit."
echo " -p/--prompt - Explicitly set prompt."
echo " -e/--exact - Don't show the \"(Y/n)\" hint."
echo " -d/--default - Set the default return value (i.e. if the user simply presses enter). Defaults to 1."
echo " -u/--unrecognized - Exit with this value on an unrecognized input (defaults to 2). If the value is \"retry\", ask the user again. If \"echo\", echo the input to stdout and exit with status 2."
echo " -i/--sigint - Exit with this value on SIGINT/ctrl+c (defaults to 255)."
echo
echo "Note: an unrecognized value for -d will cause $script to exit immediately with a status of 255."
exit
end
set prompt "$_flag_p"
if test -z "$prompt"
set prompt (string trim "$argv[1]")
end
if set -q _flag_d
if string match -qi 'y*' "$_flag_d"
set default 0
else if string match -qi 'n*' "$_flag_d"
set default 1
else if string match -qir '^[0-9]+$' "$_flag_d"
set default "$_flag_d"
else
echo "$script: unrecognized default: $_flag_d"
exit 255
end
else
set default 1
end
if not set -q _flag_e
if test "$default" = '0'
set prompt "$prompt (Y/n) "
else
set prompt "$prompt (y/N) "
end
end
read -lP "$prompt" y_or_n
if test $status = '1' # read returns 1 on sigint (ctrl+c)
if set -q _flag_sigint
exit $_flag_sigint
else
exit 255
end
end
if test -z "$y_or_n"
exit $default
else
if string match -qi 'y*' "$y_or_n"
exit 0
else if string match -qi 'n*' "$_flag_d"
exit 1
else
if set -q _flag_u
if test "$_flag_u" = 'retry'
set -l filename (status filename)
command $filename -e -p "$prompt" -d "$default" -u "$_flag_u"
exit $status
else if test "$_flag_u" = 'echo'
echo $y_or_n
exit 2
else
exit $_flag_u
end
else
exit 2
end
end
end