test/fakemenu (1763 bytes)
1 #!/bin/sh 2 3 # Scripted stand-in for a menu program. Each call consumes the first line of 4 # $SBM_TEST_ANSWERS as the "user's" answer; an empty or missing line means the 5 # menu was closed without choosing. The answer <default> accepts whatever the 6 # menu offered first. With $SBM_TEST_LOG set, every call's name and arguments 7 # are appended to that file. 8 # 9 # Works as a custom $SBM_MENU (called as: fakemenu pick|multi|ask <prompt>) and, 10 # when installed under the name dmenu, as a fake dmenu. 11 12 name=$(basename "$0") 13 [ -z "$SBM_TEST_LOG" ] || printf '%s %s\n' "$name" "$*" >> "$SBM_TEST_LOG" 14 15 case $name in 16 dmenu) kind=dmenu ;; 17 *) kind=$1 ;; 18 esac 19 20 choices=$(cat) 21 # With $SBM_TEST_SEEN set, what each menu offered is appended to that file. 22 [ -z "$SBM_TEST_SEEN" ] || printf -- '--- %s\n%s\n' "$*" "$choices" >> "$SBM_TEST_SEEN" 23 answer=$(sed -n 1p "$SBM_TEST_ANSWERS") 24 sed 1d "$SBM_TEST_ANSWERS" > "$SBM_TEST_ANSWERS.next" 25 mv "$SBM_TEST_ANSWERS.next" "$SBM_TEST_ANSWERS" 26 27 [ -n "$answer" ] || exit 1 28 29 if [ "$answer" = '<default>' ]; then 30 printf '%s\n' "$choices" | sed -n 1p 31 exit 0 32 fi 33 34 # Print the first choice containing $1, or $1 itself when nothing matches 35 # (menus let the user type text that is not in the list). 36 choose () { 37 match=$(printf '%s\n' "$choices" | grep -F -- "$1" | head -n 1) 38 printf '%s\n' "${match:-$1}" 39 } 40 41 case $kind in 42 ask) 43 printf '%s\n' "$answer" 44 ;; 45 multi) 46 # The answer is a space separated list of tag names; unknown ones are 47 # typed in by the "user". 48 for word in $answer; do 49 match=$(printf '%s\n' "$choices" | grep -- "^$word " | head -n 1) 50 printf '%s\n' "${match:-$word}" 51 done 52 ;; 53 *) 54 choose "$answer" 55 ;; 56 esac