env2string.awk 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # SPDX-License-Identifier: GPL-2.0+
  2. #
  3. # Copyright 2021 Google, Inc
  4. #
  5. # SPDX-License-Identifier: GPL-2.0+
  6. #
  7. # Awk script to parse a text file containing an environment and convert it
  8. # to a C string which can be compiled into U-Boot.
  9. # The resulting output is:
  10. #
  11. # #define CONFIG_EXTRA_ENV_TEXT "<environment here>"
  12. #
  13. # If the input is empty, this script outputs a comment instead.
  14. BEGIN {
  15. # env holds the env variable we are currently processing
  16. env = "";
  17. ORS = ""
  18. }
  19. # Skip empty lines, as these are generated by the clang preprocessor
  20. NF {
  21. do_output = 0
  22. # Quote quotes
  23. gsub("\"", "\\\"")
  24. # Avoid using the non-POSIX third parameter to match(), by splitting
  25. # the work into several steps.
  26. has_var = match($0, "^([^ \t=][^ =]*)=(.*)$")
  27. # Is this the start of a new environment variable?
  28. if (has_var) {
  29. if (length(env) != 0) {
  30. # Record the value of the variable now completed
  31. vars[var] = env
  32. do_output = 1
  33. }
  34. # Collect the variable name. The value follows the '='
  35. match($0, "^([^ \t=][^ =]*)=")
  36. var = substr($0, 1, RLENGTH - 1)
  37. env = substr($0, RLENGTH + 1)
  38. # Deal with += which concatenates the new string to the existing
  39. # variable. Again we are careful to use POSIX match()
  40. if (length(env) != 0 && match(var, "^(.*)[+]$")) {
  41. plusname = substr(var, RSTART, RLENGTH - 1)
  42. # Allow var\+=val to indicate that the variable name is
  43. # var+ and this is not actually a concatenation
  44. if (substr(plusname, length(plusname)) == "\\") {
  45. # Drop the backslash
  46. sub(/\\[+]$/, "+", var)
  47. } else {
  48. var = plusname
  49. env = vars[var] env
  50. }
  51. }
  52. } else {
  53. # Change newline to space
  54. gsub(/^[ \t]+/, "")
  55. # Don't keep leading spaces generated by the previous blank line
  56. if (length(env) == 0) {
  57. env = $0
  58. } else {
  59. env = env " " $0
  60. }
  61. }
  62. }
  63. END {
  64. # Record the value of the variable now completed. If the variable is
  65. # empty it is not set.
  66. if (length(env) != 0) {
  67. vars[var] = env
  68. do_output = 1
  69. }
  70. if (do_output) {
  71. printf("%s", "#define CONFIG_EXTRA_ENV_TEXT \"")
  72. # Print out all the variables by alphabetic order, if using
  73. # gawk. This allows test_env_test.py to work on both awk (where
  74. # this next line does nothing)
  75. PROCINFO["sorted_in"] = "@ind_str_asc"
  76. for (var in vars) {
  77. env = vars[var]
  78. print var "=" vars[var] "\\0"
  79. }
  80. print "\"\n"
  81. }
  82. }