OpenSDE Framework (without history before r20070)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.0 KiB

  1. # --- SDE-COPYRIGHT-NOTE-BEGIN ---
  2. # This copyright note is auto-generated by ./scripts/Create-CopyPatch.
  3. #
  4. # Filename: lib/libsde-ini.in
  5. # Copyright (C) 2006 The OpenSDE Project
  6. #
  7. # More information can be found in the files COPYING and README.
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; version 2 of the License. A copy of the
  12. # GNU General Public License can be found in the file COPYING.
  13. # --- SDE-COPYRIGHT-NOTE-END ---
  14. # this file has to be sourced only by tools which really want to
  15. # write ini formated files. reading methods are available at libsde.in
  16. # writes a list of variables into a section of an ini file
  17. # USAGE: ini_write "file" "section" var1 var2 var3 ...
  18. #
  19. ini_write() {
  20. local file="$1" section="$2" var= c=
  21. local tmpfile=
  22. shift 2
  23. # something to write?
  24. [ $# -gt 0 ] || return
  25. # make sure the file exists
  26. [ -f "$file" ] || touch "$file"
  27. tmpfile="$file.$$"
  28. # FIXME: a lock may be needed
  29. if grep -q "^\[$section\][ \t]*$" "$file"; then
  30. # known section
  31. #
  32. #FIXME: better performance may be required
  33. # split the file
  34. rm -rf $tmpfile.{0,1,2}
  35. gawk "BEGIN { level=0; }
  36. /^\[/ {
  37. if ( level == 0 && \$0 ~ /^\[$section\][ \t]*\$/ )
  38. level=1;
  39. else if ( level == 1 )
  40. level=2;
  41. }
  42. { print > \"$tmpfile.\" level }
  43. " "$file"
  44. # remove empty lines
  45. sed -i -e '/^[ \t]*$/d;' $tmpfile.1
  46. # edit the section
  47. for var; do
  48. if grep -q "^$var=" $tmpfile.1; then
  49. sed -i -e "s|^$var=.*|$var=$( eval echo \$$var )|" $tmpfile.1
  50. else
  51. echo "$var=$( eval echo \$$var )" >> $tmpfile.1
  52. fi
  53. done
  54. # and finally write the new file!
  55. (
  56. cat $tmpfile.0
  57. cat $tmpfile.1
  58. if [ -s $tmpfile.2 ]; then
  59. echo
  60. cat $tmpfile.2
  61. fi
  62. ) > "$file"
  63. rm -rf $tmpfile.{0,1,2}
  64. else
  65. # new section
  66. #
  67. echo -e "\n[$section]" >> "$file"
  68. for var; do
  69. echo "$var=$( eval echo \$$var )"
  70. done >> "$file"
  71. fi
  72. }