shell dot on steroids https://pagure.io/shellfu

charmenu.sh 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. ffoo import core
  2. FFOO_CHARMENU_FILE="${FFOO_CHARMENU_FILE:-}"
  3. charmenu() {
  4. #
  5. # Present "1-char-menu" (but actually N-char) or its parts
  6. #
  7. # Read file in FFOO_CHARMENU_FILE or given as -f parameter,
  8. # and do what either `full` menu, `prompt`, or just terse
  9. # list of `items` (like "y,n,q,?").
  10. #
  11. # Format of menu file is one item per line, where item is
  12. # delimited from its description by single colon. Leading
  13. # and trailing spaces and spaces around the colon are
  14. # stripped.
  15. #
  16. # You can use printf symbols like `%s` in menu and then
  17. # call `charmenu full arg1 arg2...` to have your arguments
  18. # expanded in the full menu.
  19. #
  20. # Similarly, you can specify single `%s` in the prompt
  21. # parameter like `charmenu -p "choose from %s" and it will
  22. # be replaced by list of items read from menu file,
  23. # delimited either by comma or character provided as `-d`
  24. # parameter.
  25. #
  26. # `has` checks if given string is a valid menu item.
  27. #
  28. local mfile="$FFOO_CHARMENU_FILE"
  29. local prompt="What to do next [%s]? "
  30. local delim=","
  31. local cmd cases
  32. while true; do case $1 in
  33. -d|--delimiter) delim="$2"; shift 2 ;;
  34. -f|--file) mfile="$2"; shift 2 ;;
  35. -i|--ignore-case) cases="-i"; shift ;;
  36. -p|--prompt) prompt="$2"; shift 2 ;;
  37. full|items|prompt|has) cmd=$1; shift; break ;;
  38. *) usage_is "full [PRINTF_ARG...]" \
  39. "items [DELIM]" \
  40. "prompt [PRINTF_FMT]" \
  41. "has ITEM" ;;
  42. esac done
  43. local menu="$(cat "$mfile")"
  44. local alist="$(echo "$menu" | cut -d: -f1 | sed -re 's/^ +//; s/ +$//')"
  45. debug -v alist
  46. case $cmd in
  47. full) # print the full menu, with any printf notation expanded
  48. printf "$menu\n" "$@"
  49. ;;
  50. items) # print just the list of actions
  51. paste -sd"$delim" <<<"$alist"
  52. ;;
  53. prompt) # print prompt for user
  54. printf "$prompt" "$(charmenu items)"
  55. ;;
  56. has) # check if response is valid ("on the menu")
  57. local res="$1"
  58. test -n "$res" || return 1 # "" is not valid
  59. grep $cases -e "^$res$" <<<"$alist"
  60. return $?
  61. ;;
  62. esac
  63. }