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

pretty.sh 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. #!/bin/bash
  2. shellfu import exit
  3. #
  4. # Application debug mode
  5. #
  6. PRETTY_DEBUG=${PRETTY_DEBUG:-false}
  7. #
  8. # List of module/function names to exclude from debuging
  9. #
  10. # For the sake of readability of your debug dumps, you can set this
  11. # variable to comma-separated list of module or function names that
  12. # you don't expect to get useful info from.
  13. #
  14. # If the caller has a qualified name (`modname__funcname()`, according
  15. # to Shellfu naming scheme it's possible to use just module name here
  16. # to mute all debug from that module (including internal functions).
  17. # Otherwise, full function name should be listed.
  18. #
  19. PRETTY_DEBUG_EXCLUDE=${PRETTY_DEBUG_EXCLUDE:-}
  20. #
  21. # Application verbosity mode
  22. #
  23. PRETTY_VERBOSE=${PRETTY_VERBOSE:-false}
  24. #
  25. # Name of pretty-printer module
  26. #
  27. # Friendly name of module used for decorating output. For
  28. # example, if the value is NAME, a _pretty_NAME module must
  29. # exist and be importable. Otherwise pretty will fall back
  30. # to plain, which is also the default value.
  31. #
  32. PRETTY=${PRETTY:-plain}
  33. #
  34. # Usage display mode
  35. #
  36. # How to determine program name for purposes of usage messages.
  37. #
  38. # If empty, use basename of "$0". Set to 'subcommand' to remove first
  39. # dash (so that `path/to/foo-bar becomes `foo bar` which may make more
  40. # sense in meta-command scenrarios). Set to self=NAME to force NAME.
  41. #
  42. PRETTY_USAGE=${PRETTY_USAGE:-}
  43. __shellfu_pretty__init() {
  44. #
  45. # Import proper submodule
  46. #
  47. if shellfu try_import "_pretty_${PRETTY}"; then
  48. shellfu import "_pretty_${PRETTY}"
  49. return 0
  50. else
  51. warn "falling back to _pretty_plain"
  52. PRETTY=plain
  53. shellfu import "_pretty_${PRETTY}"
  54. fi
  55. }
  56. ##--------------------##
  57. ## PRINTING FRONT-END ##
  58. ##--------------------##
  59. debug() {
  60. #
  61. # You already know what it does
  62. #
  63. # BTW, following are equivalent:
  64. #
  65. # debug "var1=$var1" "var2=$var2" "result=$result"
  66. # debug -v var1 var2 result
  67. #
  68. $PRETTY_DEBUG || return 0
  69. _pretty__echo "$@"
  70. }
  71. debug_pipe() {
  72. #
  73. # Debug the whole pipe.
  74. #
  75. while IFS= read -r line; do
  76. debug "|$1: '$line'"
  77. echos "$line"
  78. done
  79. }
  80. die() {
  81. #
  82. # A fatal error
  83. #
  84. _pretty__echo -t
  85. _pretty__echo "$@"
  86. exit_error
  87. }
  88. echos() {
  89. #
  90. # Safer version of echo able to echo "-n"
  91. #
  92. # Traditional echo is broken in that it does not
  93. # distinguish between string to print and its own switches
  94. # (-e, -E or -n), leading to unexpected behavior.
  95. #
  96. # This echo version circumvents this by using printf.
  97. #
  98. printf -- '%s\n' "$@"
  99. }
  100. mkusage() {
  101. #
  102. # Echo out usage patterns and (by default) `exit 2`
  103. #
  104. # mkusage [-w MSG] [-e STATUS] [-E] pattern [patern...]
  105. #
  106. # Each pattern is prefixed by "usage: " and a resolved
  107. # script/function name to produce traditional usage hint.
  108. # By default, will exit with status *EXIT_USAGE*, you
  109. # can use `-e STATUS` to specify other number. `-k` can be
  110. # used as shorthand for `-e 0` (e.g. if user asked for
  111. # the patterns)
  112. #
  113. # Use `-E` to prevent exiting; in that case, the status
  114. # that would be fed to `exit` will be used as exit status
  115. # of this function.
  116. #
  117. # Optionally, you can add -w MSG to add clarifying message
  118. # (presented as warning) to help user understand what is
  119. # wrong with arguments they have passed.
  120. #
  121. # Use "--" to delimit end of arguments processed by mkusage.
  122. #
  123. # Recommended usage is to define usage() in your script and
  124. # use this in its body. That way you only need to define
  125. # usage patterns once and skip to them from any place where
  126. # you detect incorrect usage. Optionally, this usage()
  127. # function can pass first argument as -w for clarification
  128. # messages.
  129. #
  130. local es=$EXIT_USAGE # our exit status
  131. local doexit=true # should we exit?
  132. local cmsg # clarification message
  133. while true; do case "$1" in
  134. -e) es="$2"; shift 2 || return 2 ;;
  135. -E) doexit=false; shift ;;
  136. -k) es=$EXIT_OK; shift ;;
  137. -w) cmsg="$2"; shift 2 || return 2 ;;
  138. --) shift; break ;;
  139. *) break ;;
  140. esac done
  141. _pretty__echo -u "$@";
  142. if test -n "$cmsg"; then
  143. test -n "$*" && echo >&2
  144. warn "bad usage: $cmsg"
  145. fi
  146. $doexit && exit "$es"
  147. return "$es"
  148. }
  149. mkhelp() {
  150. #
  151. # Echo out help text
  152. #
  153. # mkhelp [-e STATUS] [-E] arg...
  154. #
  155. # By default, will exit with status *EXIT_OK*, you
  156. # can use `-e STATUS` to specify other number.
  157. #
  158. # Use `-E` to prevent exiting; in that case, the status
  159. # that would be fed to `exit` will be used as exit status
  160. # of this function.
  161. #
  162. # Use "--" to delimit end of arguments processed by mkhelp
  163. #
  164. local es=$EXIT_OK
  165. local doexit=true
  166. while true; do case "$1" in
  167. -e) es="$2"; shift 2 || return 2 ;;
  168. -E) doexit=false; shift ;;
  169. --) shift; break ;;
  170. *) break ;;
  171. esac done
  172. _pretty__echo "$@"
  173. $doexit && exit "$es"
  174. return "$es"
  175. }
  176. think() {
  177. #
  178. # If verbose is on, think loud
  179. #
  180. # Use "-l" to split every parameter to separate line, (useful
  181. # or longer warnings)
  182. #
  183. $PRETTY_VERBOSE || return 0
  184. _pretty__echo "$@"
  185. }
  186. warn() {
  187. #
  188. # Warn them
  189. #
  190. # Use "-l" to split every parameter to separate line, (useful
  191. # or longer warnings)
  192. #
  193. _pretty__echo "$@"
  194. }
  195. ##----------##
  196. ## BACK-END ##
  197. ##----------##
  198. _pretty__cat() {
  199. #
  200. # `cat` but without starting a process
  201. #
  202. # Used to avoid spanning new process where stream handler is chosen
  203. # based on some logic
  204. #
  205. while IFS= read -r line;
  206. do echos "$line"; done
  207. }
  208. _pretty__get_caller() {
  209. #
  210. # Get first user function and negative index from stack
  211. #
  212. local fname
  213. local nidx="${#FUNCNAME[@]}"
  214. for fname in "${FUNCNAME[@]}"; do
  215. (( nidx-- ))
  216. _pretty__is_internal && continue
  217. _pretty__is_frontend && continue
  218. test "$fname" = "usage" && continue
  219. echos "$nidx $fname"
  220. return
  221. done
  222. }
  223. _pretty__get_frontend() {
  224. #
  225. # Get entry point function name from stack
  226. #
  227. local fname
  228. for fname in "${FUNCNAME[@]}"; do
  229. _pretty__is_internal && continue
  230. _pretty__is_frontend && echos "$fname" && return 0
  231. echo "do not call _pretty_* directly: $fname" >&2
  232. return "$EXIT_USAGE"
  233. done
  234. }
  235. _pretty__is_excluded() {
  236. #
  237. # True if $caller is excluded based on PRETTY_DEBUG_EXCLUDE
  238. #
  239. # Check PRETTY_DEBUG_EXCLUDE to see if $caller (using only module name
  240. # part, if possible) should be muted from debugging.
  241. #
  242. local listed # item listed in PRETTY_DEBUG_EXCLUDE
  243. local name # module part of caller's name
  244. local qualified # is caller "qualified" (ac. to shellfu scheme)?
  245. name="$caller"
  246. case "$name" in
  247. __*__*) qualified=true ;;
  248. __*) qualified=false ;;
  249. *__*) qualified=true ;;
  250. *) qualified=false ;;
  251. esac
  252. if $qualified; then
  253. # we'll use only the module part of the name
  254. name=${name#_} # drop one "internal" prefix
  255. name=${name#_} # drop yet another one
  256. name=${name%%__*} # drop funcname
  257. fi
  258. for listed in ${PRETTY_DEBUG_EXCLUDE//,/ }; do
  259. test "$name" = "$listed" && return 0
  260. done
  261. return 1
  262. }
  263. _pretty__is_frontend() {
  264. #
  265. # True if $fname is one of our "frontends"
  266. #
  267. case "$fname" in
  268. debug) return 0 ;;
  269. debug_pipe) return 0 ;;
  270. die) return 0 ;;
  271. mkhelp) return 0 ;;
  272. think) return 0 ;;
  273. mkusage) return 0 ;;
  274. warn) return 0 ;;
  275. esac
  276. return 1
  277. }
  278. _pretty__is_internal() {
  279. #
  280. # True if $fname is our internal function
  281. #
  282. case "$fname" in
  283. _pretty__*) return 0 ;;
  284. *) return 1 ;;
  285. esac
  286. }
  287. _pretty__echo() {
  288. #
  289. # A smarter echo backend
  290. #
  291. # A smarter backend for debug, warn, think, die and
  292. # mkusage.
  293. #
  294. # -c cmd echo output of a command
  295. # -f file echo output of a file (- for stdin)
  296. # -l line [line...] echo each line separately
  297. # -t add stack trace to output
  298. # -u patt [patt...] convert each patt to usage pattern
  299. # -v var [var...] show contents of each var
  300. #
  301. local frontend # who (of pretty.sh) was called (=> prettyprinter choice)
  302. local caller # which user's function (or script) called it
  303. # ^ ^ eg. if user calls 'debug hello' from function 'foo', then
  304. # : :.. * frontend is 'debug'
  305. # :......... * and caller is 'foo'.
  306. local caller_nidx # negative stack index of caller
  307. local caller_is_main # true if caller was main script or main() in it
  308. local provider # which provider (_pretty__echo_*()) to use
  309. frontend="$(_pretty__get_frontend)" || exit_usage
  310. read -r caller_nidx caller <<<"$(_pretty__get_caller)"
  311. test "$frontend" = debug && _pretty__is_excluded "$caller" && return 0
  312. #shellcheck disable=SC2034
  313. case $caller_nidx:$caller in
  314. 0:*) caller_is_main=true; caller="${0##*/}" ;;
  315. 1:main) caller_is_main=true; caller="${0##*/}" ;;
  316. *:usage) frontend=mkusage ;;
  317. *) caller_is_main=false ;;
  318. esac
  319. while true; do case $1 in
  320. -c|--cmd) provider=cmd; shift; break ;;
  321. -f|--files) provider=files; shift; break ;;
  322. -l|--lines) provider=lines; shift; break ;;
  323. -t|--trace) provider=trace; shift; break ;;
  324. -u|--usage) provider=usage; shift; break ;;
  325. -v|--vars) provider=vars; shift; break ;;
  326. *) provider=args; break ;;
  327. esac done
  328. _pretty__echo_$provider "$@" \
  329. | _pretty__$frontend >&2
  330. }
  331. _pretty__echo_args() {
  332. #
  333. # The simplest (but safe) printing of args
  334. #
  335. echos "$*"
  336. }
  337. _pretty__echo_cmd() {
  338. #
  339. # Print command line, launch it and report exit status
  340. #
  341. local es
  342. echo "-- begin command $* --"
  343. "$@"; es=$?
  344. echo "-- end command ($es) $* --"
  345. }
  346. _pretty__echo_files() {
  347. #
  348. # Print names and contents of existing files
  349. #
  350. local fp
  351. for fp in "$@"; do
  352. if test "$fp" = "-"; then
  353. echo "-- begin pipe --"
  354. cat
  355. echo "-- end pipe --"
  356. elif test -s "$fp" || test "$fp" = "/dev/stdin"; then
  357. echo "-- begin file $fp --"
  358. cat "$fp"
  359. echo "-- end file $fp --"
  360. fi
  361. done
  362. }
  363. _pretty__echo_lines() {
  364. #
  365. # Echo each argument as a separate line
  366. #
  367. local l;
  368. for l in "$@"; do _pretty__echo_args "$l"; done
  369. }
  370. _pretty__echo_trace() {
  371. #
  372. # Print "decorated" call trace (only in debug mode)
  373. #
  374. $PRETTY_DEBUG || return 0
  375. local depth
  376. echo "== trace =="
  377. for depth in $(seq 0 ${#FUNCNAME}); do
  378. caller "$depth" || break
  379. done \
  380. | tail -n +3 \
  381. | sed -e '
  382. s/^\([^ ]\+\) \([^ ]\+\) \(.*\)/\3:\1:\2()/
  383. # ^line^, ^func^, ^file^
  384. 1 s/^/ -> /g
  385. 2,$ s/^/ /
  386. ' \
  387. | tac
  388. }
  389. _pretty__echo_help() {
  390. local oldverbose="$PRETTY_VERBOSE"
  391. think -l "$@"
  392. PRETTY_VERBOSE=$oldverbose
  393. }
  394. _pretty__echo_usage() {
  395. #
  396. # Compose conventional usage guide
  397. #
  398. # The default mode treats each argument as usage pattern
  399. # (see below for details). Additional formatting can be
  400. # conveniently achieved by switching to other modes, which
  401. # automatically brings necessary headers and indentations
  402. # where needed.
  403. #
  404. # * option mode (`-o`) prints "options:" header and
  405. # indents next arguments,
  406. #
  407. # * command mode (`-c`) prints "commands:" header and
  408. # indents next arguments,
  409. #
  410. # * indent mode (`-i`) just indents next arguments,
  411. #
  412. # * plain mode (`--`) prints empty line (new paragraph)
  413. # and turns indentations off.
  414. #
  415. # * usage mode (`-u`, active by default), prints
  416. # "usage:" header, indents next arguments and prefixes
  417. # them with name of the script. See also $PRETTY_USAGE.
  418. #
  419. # A special case of usage mode is when only single
  420. # argument is passed to this function; then instead
  421. # printing "usage:" header on separate string, it is
  422. # joined with the argument to single line.
  423. #
  424. # In order to help avoid (rare) conflict between mkusage()
  425. # switches and your usage patterns, the very first argument,
  426. # and each argument that comes right after one of these
  427. # switches are guarranteed not to be interpreted as switch.
  428. #
  429. local self # the script name
  430. local mode=usage # mode
  431. local esc=1 # escape (take next argument as literal)
  432. local arg # argument to iterate
  433. case "$PRETTY_USAGE" in
  434. self=*) self=${PRETTY_USAGE#self=} ;;
  435. subcommand) self="${0##*/}"; self="${self/-/ }" ;;
  436. *) self="$caller" ;;
  437. esac
  438. case $# in
  439. 0) return 0 ;;
  440. 1) echo "usage: $self $1"; return 0 ;;
  441. esac
  442. echo usage:
  443. for arg in "$@"; do
  444. case $esc:$arg in
  445. 0:--) shift; mode=plain; esc=1; echo ;;
  446. 0:-c) shift; mode=indent; esc=1; echo; echo commands: ;;
  447. 0:-i) shift; mode=indent; esc=1 ;;
  448. 0:-o) shift; mode=indent; esc=1; echo; echo options: ;;
  449. 0:-u) shift; mode=usage; esc=1 ;;
  450. *) esc=0
  451. case $mode in
  452. usage) echo " $self $arg" ;;
  453. indent) echo " $arg" ;;
  454. plain) echos "$arg" ;;
  455. esac
  456. ;;
  457. esac
  458. done
  459. }
  460. _pretty__echo_vars() {
  461. #
  462. # Report value of each named variable
  463. #
  464. local varname
  465. local declare_str
  466. for varname in "$@"; do
  467. if ! _pretty__is_word "$varname"; then
  468. warn "unsafe value skipped: $varname";
  469. continue
  470. fi
  471. if declare_str=$(declare -p "$varname" 2>/dev/null); then
  472. _pretty__echo "${declare_str#declare ?? }"
  473. else
  474. _pretty__echo "$varname #Unset"
  475. fi
  476. done
  477. }
  478. _pretty__is_word() {
  479. #
  480. # Check if $1 contains only alphanumeric chars or _
  481. #
  482. local tainted="$1"
  483. local clean
  484. clean=$(tr -c -d '_[:alnum:]' <<< "$tainted")
  485. test "$tainted" = "$clean"
  486. }