saturnin.sh 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. #!/bin/bash
  2. shellfu import exit
  3. shellfu import inigrep
  4. shellfu import pretty
  5. #
  6. # Git commit hash of application source tree
  7. #
  8. # This is supposed to be set by your build scripts when building your
  9. # application. The string is returned by calling your meta-command
  10. # with option --saturnin-app-git-hash.
  11. #
  12. # Look for 'satcmd' template for a working example.
  13. #
  14. SATURNIN_APP_GIT_HASH=${SATURNIN_APP_GIT_HASH:-}
  15. #
  16. # Your application version
  17. #
  18. # This is supposed to be set by your build scripts when building your
  19. # application. The string is returned by calling your meta-command
  20. # with options --version, --version-semver or --saturnin-app-version.
  21. #
  22. # Look for 'satcmd' template for a working example.
  23. #
  24. SATURNIN_APP_VERSION=${SATURNIN_APP_VERSION:-}
  25. #
  26. # Path to user cache
  27. #
  28. SATURNIN_CACHE_HOME=${SATURNIN_CACHE_HOME:-}
  29. #
  30. # Path where saturnin__conf should look for files
  31. #
  32. # If filename does not contain slash, it is looked up in each
  33. # (or all, based on strategy--see saturnin__conf() doc) path in this
  34. # list. The list is colon-separated and non-dirs as well as
  35. # empty strings are silently ignored.
  36. #
  37. SATURNIN_CONF_PATH="${SATURNIN_CONF_PATH:-}"
  38. #
  39. # Expected config filename extension (for guessing from path head)
  40. #
  41. # If no filename to read is given, saturnin__conf() will guess
  42. # filename as the path head plus this suffix (e.g. `foo.ini` for
  43. # `saturnin__conf foo.bar.baz`)
  44. #
  45. SATURNIN_CONF_SUFFIX="${SATURNIN_CONF_SUFFIX:-.ini}"
  46. #
  47. # Directory where to look for subcommands
  48. #
  49. # Files here starting with $SATURNIN_LIBEXEC_PREFIX are considered subcommands
  50. #
  51. SATURNIN_LIBEXEC="${SATURNIN_LIBEXEC:-}"
  52. #
  53. # Subcommand file prefix
  54. #
  55. # This is recommended to be set to meta-command name plus dash. For example,
  56. # if your meta-command is `mykit`, this should be set to `mykit-`.
  57. #
  58. SATURNIN_LIBEXEC_PREFIX="${SATURNIN_LIBEXEC_PREFIX:-}"
  59. saturnin__conf() {
  60. #
  61. # inigrep smart loader
  62. #
  63. # Usage:
  64. # saturnin__conf [-j] [inigrep-query] [-- [file]..]
  65. #
  66. #
  67. # File arguments
  68. # ==============
  69. #
  70. # If omitted, *file* argument is inferred by taking part of
  71. # kpath name before first dot and appending value of
  72. # `$SATURNIN_CONF_SUFFIX`, (".ini" by default).
  73. #
  74. # Each *file* argument is then processed as follows:
  75. #
  76. # * `-` (single dash) is interpreted as reading from
  77. # STDIN.
  78. #
  79. # * If argument contains slash, it is expanded as a regular
  80. # path (relative or absolute).
  81. #
  82. # * Otherwise, it is taken as filename and searched for
  83. # in directories given in `$SATURNIN_CONF_PATH`. (This can
  84. # yield more than one path, which is equivalent as if
  85. # all paths were provided.)
  86. #
  87. # Not all files expanded based on `$SATURNIN_CONF_PATH`
  88. # are read by default; reading is governed by "merge
  89. # strategy": the default strategy "first" reads only
  90. # the first existing file.
  91. #
  92. # "join" strategy on the other hand, means that any
  93. # files are simply concatenated and prefixed with
  94. # comment (visible only in raw mode) containing path
  95. # to the file.
  96. #
  97. # This means that if a section is queried that is
  98. # present in both files, it is effectively concatenated
  99. # as well.
  100. #
  101. # Following calls are equivalent
  102. #
  103. # saturnin__conf foo.bar.baz
  104. # saturnin__conf foo.bar.baz foo.ini
  105. #
  106. # and both result in reading of key *baz* from section *foo.bar*
  107. # in file *foo.ini*, which is selected from *SATURNIN_CONF_PATH*.
  108. # Should there be more foo.ini's, the first is selected.
  109. # Using `-j` switch
  110. #
  111. # saturnin__conf -j foo.bar.baz
  112. #
  113. # would cause all foo.ini's on *SATURNIN_CONF_PATH* be
  114. # concatenated instead.
  115. #
  116. local ig_mode # retrieval mode
  117. local ig_query # keypath or section name (when listing keys)
  118. local ig_limit # line limit
  119. local files=() # file specification
  120. local Strategy=first # merge strategy
  121. while true; do case $1:$2 in
  122. "":*) break ;;
  123. -j:*) Strategy=join; shift 1 ;;
  124. -1:*) ig_limit=$1; shift 1 ;;
  125. -e:*.*) ig_mode=$1; ig_query=$2; shift 2; break ;;
  126. -r:*.*) ig_mode=$1; ig_query=$2; shift 2; break ;;
  127. -K:*) ig_mode=$1; ig_query=$2; shift 2; break ;;
  128. -S:*) ig_mode=$1; ig_query=""; shift 1; break ;;
  129. -P:*) ig_mode=$1; ig_query=""; shift 1; break ;;
  130. .*:*) warn "bad syntax: $*"; _saturnin__conf_usage ;;
  131. *.*:*) ig_mode=-e; ig_query=$1; shift 1; break ;;
  132. --help:*) _saturnin__conf_usage -e 0 ;;
  133. *) warn "bad syntax: $*"; _saturnin__conf_usage ;;
  134. esac done
  135. test -n "$ig_mode" || { warn "could not determine inigrep mode"; _saturnin__conf_usage; }
  136. debug -v ig_limit ig_query ig_mode Strategy
  137. if test -n "$*";
  138. then
  139. files=("$@")
  140. elif test -n "$ig_query";
  141. then
  142. files=("${ig_query%%.*}$SATURNIN_CONF_SUFFIX")
  143. else
  144. warn "dunno what to load"
  145. _saturnin__conf_usage
  146. fi
  147. debug -v files
  148. #shellcheck disable=SC2086
  149. _saturnin__conf__load "${files[@]}" | inigrep $ig_limit $ig_mode "$ig_query"
  150. return "${PIPESTATUS[0]}"
  151. }
  152. saturnin__get() {
  153. #
  154. # Show Saturnin Internal info by key $1 and exit
  155. #
  156. # Key $1 can be whole `--saturnin-get-stuff` argument or just
  157. # the part after `--saturnin-get-`.
  158. #
  159. # This is aimed to help debugging and testing the app (or
  160. # Saturnin itself) by showing packaging and deployment related
  161. # info.
  162. #
  163. local key=${1#--saturnin-get-}
  164. case "$key" in
  165. saturnin-conf-path) echo "$SATURNIN_CONF_PATH" ;;
  166. app-git-hash) echo "$SATURNIN_APP_GIT_HASH" ;;
  167. app-version) echo "$SATURNIN_APP_VERSION" ;;
  168. cache-home) echo "$SATURNIN_CACHE_HOME" ;;
  169. libexec) echo "$SATURNIN_LIBEXEC" ;;
  170. libexec-prefix) echo "$SATURNIN_LIBEXEC_PREFIX" ;;
  171. *) warn "unknown devel key: $key"
  172. exit "$EXIT_USAGE" ;;
  173. esac
  174. exit "$EXIT_OK"
  175. }
  176. saturnin__lssc() {
  177. #
  178. # List subcommands
  179. #
  180. echo conf
  181. find "$SATURNIN_LIBEXEC" \
  182. -mindepth 1 \
  183. -maxdepth 1 \
  184. -executable \
  185. | sed -e "s|^.*/||; s|^$SATURNIN_LIBEXEC_PREFIX||" \
  186. | sort
  187. }
  188. saturnin__main() {
  189. #
  190. # Main meta-command entry function
  191. #
  192. # After setting all mandatory environment variables, call this from
  193. # your main meta-command script.
  194. #
  195. local subcommand
  196. test -n "$SATURNIN_CACHE_HOME" || die "SATURNIN_CACHE_HOME is not set"
  197. test -n "$SATURNIN_LIBEXEC" || die "SATURNIN_LIBEXEC is not set"
  198. test -n "$SATURNIN_LIBEXEC_PREFIX" || die "SATURNIN_LIBEXEC_PREFIX is not set"
  199. while true; do case $1 in
  200. -d|--debug) export PRETTY_DEBUG=true; shift ;;
  201. -v|--verbose) export PRETTY_VERBOSE=true; shift ;;
  202. -h|--help) saturnin__usage -e 0; exit ;;
  203. --version) saturnin__version; exit ;;
  204. --version-semver) saturnin__get app-version ;;
  205. --saturnin-get-*) saturnin__get "$1" ;;
  206. -*) saturnin__usage; ;;
  207. --*) saturnin__usage; ;;
  208. --) shift; break ;;
  209. "") saturnin__usage; ;;
  210. *) break; ;;
  211. esac done
  212. subcommand="$1"; shift
  213. debug -v SATURNIN_LIBEXEC SATURNIN_CONF_PATH
  214. case "$subcommand" in
  215. conf) saturnin__conf "$@" ;;
  216. _ls_sc) saturnin__lssc ;;
  217. _lsfun) shellfu-get lsfun ;;
  218. _lsmod) shellfu-get lsmod ;;
  219. *) saturnin__runsc "$subcommand" "$@" ;;
  220. esac
  221. }
  222. saturnin__conf_mkpath() {
  223. #
  224. # Assemble SATURNIN_CONF_PATH from locations $@
  225. #
  226. # For each location, print colon-delimited list of
  227. # directories. If location ends with "/ini.d", list of
  228. # subfolders, sorted by C locale is printed--this allows
  229. # for modular configuration. Otherwise the location
  230. # is printed. Non-existent or non-directory locations
  231. # are silently ignored.
  232. #
  233. local location # one location argument
  234. local path # one path listed
  235. for location in "$@";
  236. do
  237. test -d "$location" || continue
  238. case "$location" in
  239. */ini.d) # modular location--sort subfolders
  240. find -L "$location" -mindepth 1 -maxdepth 1 -type d \
  241. | LC_ALL=C sort
  242. ;;
  243. *)
  244. echo "$location"
  245. ;;
  246. esac
  247. done \
  248. | _saturnin__nl2colon
  249. }
  250. saturnin__runhook() {
  251. #
  252. # Run custom hook
  253. #
  254. local hname="$1"
  255. local hook_code
  256. test -n "$SATURNIN_SUBCOMMAND" || {
  257. warn "unknown subcommand, ignoring hook: $hname"
  258. return 0
  259. }
  260. hook_code="$(saturnin__conf -j "hook.$SATURNIN_SUBCOMMAND.$hname")"
  261. debug -v SATURNIN_SUBCOMMAND hook_code hname
  262. bash -n <<<"$hook_code" || {
  263. warn "syntax errors, ignoring hook: $hname"
  264. return 0
  265. }
  266. eval "$hook_code"
  267. }
  268. saturnin__runsc() {
  269. #
  270. # Run subcommand $SATURNIN_SUBCOMMAND
  271. #
  272. local subcommand="$1"; shift
  273. local binpath # path to subcommand's binary
  274. binpath+="$SATURNIN_LIBEXEC/"
  275. binpath+="$SATURNIN_LIBEXEC_PREFIX$subcommand"
  276. debug -v binpath
  277. debug "\$*='$*'"
  278. test -x "$binpath" || {
  279. warn "invalid sub-command: $subcommand"
  280. saturnin__usage
  281. }
  282. SATURNIN_SUBCOMMAND="$subcommand" "$binpath" "$@"
  283. }
  284. saturnin__usage() {
  285. #
  286. # Show usage message and exit
  287. #
  288. #shellcheck disable=SC2046
  289. mkusage "$@" \
  290. "[options] COMMAND [ARG...]" \
  291. -o \
  292. "-d, --debug turn on debugging" \
  293. "-h, --help show this help message and exit"\
  294. "-v, --verbose turn on verbosity" \
  295. "--version show version and exit" \
  296. -c \
  297. $(saturnin__lssc)
  298. }
  299. saturnin__version() {
  300. #
  301. # Print version info
  302. #
  303. local tagline=${SATURNIN_APP_TAGLINE:-Some app with default tagline}
  304. local maybe_codename=""
  305. test -n "$SATURNIN_APP_CODENAME" && maybe_codename=" - $SATURNIN_APP_CODENAME"
  306. echo "$(basename "$0") ($tagline) $SATURNIN_APP_VERSION$maybe_codename"
  307. return "$EXIT_OK"
  308. }
  309. saturnin__wraphook() {
  310. #
  311. # Wrap command "$@" in hooks
  312. #
  313. # Run pre hook, then "$@", then post hook. Always exit
  314. # with status of "$@", even if hooks fail. Ignore
  315. # post-hook if "$@" failed.
  316. #
  317. local es=0
  318. saturnin__runhook pre
  319. "$@" || return $?
  320. es=$?
  321. saturnin__runhook post
  322. return $es
  323. }
  324. # # that what you see below this line #
  325. # INTERNAL # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
  326. # # use in your code to anger the divine #
  327. _saturnin__conf__merge() {
  328. #
  329. # Take paths and applying merge strategy, load file(s)
  330. #
  331. local path
  332. local found=false
  333. while read -r path;
  334. do
  335. test -f "$path" || continue
  336. found=true
  337. case $Strategy in
  338. first)
  339. debug "winner: $path"
  340. cat "$path"
  341. cat >/dev/null # throw away rest of paths
  342. ;;
  343. join)
  344. echo "# file: ${path/$HOME/~}"
  345. cat "$path" 2>/dev/null
  346. ;;
  347. esac
  348. done
  349. $found
  350. }
  351. _saturnin__conf__load() {
  352. #
  353. # Print contents of files specified in $@
  354. #
  355. # Each argument means possible file candidate. If candidate
  356. # contains slash, it's treated as file path and is printed
  357. # directly. If it's single dash, standard input is copied.
  358. #
  359. # In all other cases, filename is searched in all elements
  360. # of SATURNIN_CONF_PATH; output then depends on chosen $Strategy:
  361. # with 'first' strategy, first existing file is printed, with
  362. # 'join' strategy. all existing files are printed.
  363. #
  364. local arg trydir trypath es
  365. es=0
  366. for arg in "$@";
  367. do
  368. case $arg in
  369. -|*/*) # stdin, or path (with slash)
  370. cat "$arg" || es=3
  371. ;;
  372. *) # name given, find all its incarnations
  373. debug -v SATURNIN_CONF_PATH
  374. echos "$SATURNIN_CONF_PATH" \
  375. | tr ':' '\n' \
  376. | while read -r trydir;
  377. do
  378. test -n "$trydir" || continue
  379. trypath="$trydir/$arg"
  380. echos "$trypath"
  381. done \
  382. | _saturnin__conf__merge; es=$?
  383. ;;
  384. esac
  385. done
  386. return $es
  387. }
  388. _saturnin__conf_usage() {
  389. #
  390. # Show usage message and exit
  391. #
  392. PRETTY_USAGE="self=${0##*/} conf" \
  393. mkusage "$@" \
  394. "[options] [-e] SECTION.KEY [FNAME]" \
  395. "[options] -r SECTION.KEY [FNAME]" \
  396. "[options] -K SECTION [FNAME]" \
  397. "[options] -P FNAME" \
  398. "[options] -S FNAME" \
  399. -- \
  400. "Use inigrep to query config files." \
  401. -o \
  402. "-j join all files before applying query" \
  403. "-1 ensure single line is returned" \
  404. -c \
  405. "-e use normal mode (default)" \
  406. "-r use raw mode (preserves RHS whitespace and some comments)" \
  407. "-K list available keys in SECTION" \
  408. "-S list available sections in FNAME" \
  409. "-P list available keypaths (SECTION.KEY) in FNAME" \
  410. -- \
  411. "FNAME is filename, which is then searched on all paths specified" \
  412. "in SATURNIN_CONF_PATH and depending on -j parameter, first one" \
  413. "wins or all are joined. If FNAME contains slash, this search is" \
  414. "not done and FNAME is taken as path to file that is then queried."\
  415. "" \
  416. "If FNAME is omitted, it is inferred from SECTION (e.g. .'foo.ini'"\
  417. "if 'foo.bar' was section name; note that section name may contain"\
  418. "dot)."
  419. }
  420. _saturnin__nl2colon() {
  421. #
  422. # Convert newline-based list of paths to colon:based:list
  423. #
  424. # Empty paths must not be included in the resulting list,
  425. # so we need to drop them and also get the colons right.
  426. #
  427. local idx=0 # current item index (zero-based)
  428. local path
  429. while read -r path;
  430. do
  431. test -z "$path" && continue
  432. test $idx -gt 0 && echo -n ':'
  433. echo -n "$path"
  434. ((idx++))
  435. done
  436. }