123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #!/bin/bash
  2. ini() {
  3. #
  4. # do ini operation
  5. #
  6. local op=$1
  7. local arg=$2
  8. local fn
  9. local limit=_ini_cat
  10. debug_var op arg
  11. case $op in
  12. lskeys) fn=_ini_lskeys ;;
  13. sec) fn=_ini_grepsec ;;
  14. values) fn=_ini_greppath ;;
  15. 1value) fn=_ini_greppath; limit="tail -1" ;;
  16. *) die "incorrect use of \`ini()\`"
  17. esac
  18. <"$MKIT_INI" $fn "$arg" | $limit
  19. }
  20. _ini_cat() {
  21. #
  22. # A no-op for text stream
  23. #
  24. while read line;
  25. do
  26. printf -- "%s\n" "$line"
  27. done
  28. }
  29. _ini_expand() {
  30. #
  31. # Expand reference value (prefix only)
  32. #
  33. local line suffix ref value
  34. while read line; # [foo:bar]/path
  35. do
  36. suffix="${line#\[*\]}" # /path
  37. ref="${line%$suffix}" # [foo:bar]
  38. ref="${ref%\]}" # [foo:bar
  39. ref="${ref#\[}" # foo:bar
  40. value="$(ini 1value "$ref")" # foo_bar_value
  41. printf -- "%s\n" "$value$suffix" # foo_bar_value/path
  42. done
  43. }
  44. _ini_grepkey() {
  45. #
  46. # Read key from a section
  47. #
  48. local wnt=$1
  49. grep '.' \
  50. | grep -v '\s*#' \
  51. | sed -e 's/ *= */=/; s/ +$//; s/^//;' \
  52. | grep -e "^$wnt=" \
  53. | cut -d= -f2- \
  54. | _ini_maybe_expand
  55. }
  56. _ini_greppath() {
  57. #
  58. # Read key from the right section
  59. #
  60. # E.g. `files:share:my/lib.sh` should read
  61. #
  62. # [files:share]
  63. # my/lib.sh = proj/my/lib.sh
  64. #
  65. local wnt="$1"
  66. local wntkey="${wnt##*:}"
  67. local wntsec="${wnt%:$wntkey}"
  68. if test "$wntsec" = 'ENV';
  69. then
  70. local override="${!wntkey}"
  71. if test -n "$override";
  72. then
  73. echo "$override"
  74. return
  75. fi
  76. fi
  77. _ini_grepsec "$wntsec" | _ini_grepkey "$wntkey"
  78. }
  79. _ini_grepsec() {
  80. #
  81. # Read one INI section
  82. #
  83. local wnt="$1"
  84. local ok=false
  85. grep '.' \
  86. | grep -v '\s*#' \
  87. | while read line;
  88. do
  89. case "$line" in
  90. \[$wnt\]) ok=true; continue ;;
  91. \[*\]) ok=false; continue ;;
  92. esac
  93. $ok || continue
  94. printf -- "%s\n" "$line"
  95. done \
  96. | sed -e 's/ *= */=/; s/ +$//; s/^//;'
  97. }
  98. _ini_lskeys() {
  99. #
  100. # List keys from a section
  101. #
  102. local sct="$1"
  103. _ini_grepsec "$sct" | cut -d= -f1 | sort | uniq
  104. }
  105. _ini_maybe_expand() {
  106. #
  107. # Decide whether or not to expand
  108. #
  109. if test "$MKIT_INI_EXPAND" -gt 0;
  110. then
  111. MKIT_INI_EXPAND=$(( --MKIT_INI_EXPAND )) _ini_expand
  112. else
  113. _ini_cat
  114. fi
  115. }