ini.sh 2.5KB

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