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

pretty.sh 14KB

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