12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- ffoo import core
-
-
- FFOO_CHARMENU_FILE="${FFOO_CHARMENU_FILE:-}"
-
-
- charmenu() {
- #
- # Present "1-char-menu" (but actually N-char) or its parts
- #
- # Read file in FFOO_CHARMENU_FILE or given as -f parameter,
- # and do what either `full` menu, `prompt`, or just terse
- # list of `items` (like "y,n,q,?").
- #
- # Format of menu file is one item per line, where item is
- # delimited from its description by single colon. Leading
- # and trailing spaces and spaces around the colon are
- # stripped.
- #
- # You can use printf symbols like `%s` in menu and then
- # call `charmenu full arg1 arg2...` to have your arguments
- # expanded in the full menu.
- #
- # Similarly, you can specify single `%s` in the prompt
- # parameter like `charmenu -p "choose from %s" and it will
- # be replaced by list of items read from menu file,
- # delimited either by comma or character provided as `-d`
- # parameter.
- #
- # `has` checks if given string is a valid menu item.
- #
- local mfile="$FFOO_CHARMENU_FILE"
- local prompt="What to do next [%s]? "
- local delim=","
- local cmd cases
- while true; do case $1 in
- -d|--delimiter) delim="$2"; shift 2 ;;
- -f|--file) mfile="$2"; shift 2 ;;
- -i|--ignore-case) cases="-i"; shift ;;
- -p|--prompt) prompt="$2"; shift 2 ;;
- full|items|prompt|has) cmd=$1; shift; break ;;
- *) usage_is "full [PRINTF_ARG...]" \
- "items [DELIM]" \
- "prompt [PRINTF_FMT]" \
- "has ITEM" ;;
- esac done
-
- local menu="$(cat "$mfile")"
- local alist="$(echo "$menu" | cut -d: -f1 | sed -re 's/^ +//; s/ +$//')"
- debug -v alist
-
- case $cmd in
- full) # print the full menu, with any printf notation expanded
- printf "$menu\n" "$@"
- ;;
- items) # print just the list of actions
- paste -sd"$delim" <<<"$alist"
- ;;
- prompt) # print prompt for user
- printf "$prompt" "$(charmenu items)"
- ;;
- has) # check if response is valid ("on the menu")
- local res="$1"
- test -n "$res" || return 1 # "" is not valid
- grep $cases -e "^$res$" <<<"$alist"
- return $?
- ;;
- esac
- }
|