summaryrefslogtreecommitdiff
path: root/scripts/env2string.awk
blob: de470a49941b92066308b1b3e445b8e3d20cd235 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# SPDX-License-Identifier: GPL-2.0+
#
# Copyright 2021 Google, Inc
#
# SPDX-License-Identifier:	GPL-2.0+
#
# Awk script to parse a text file containing an environment and convert it
# to a C string which can be compiled into U-Boot.

# The resulting output is:
#
#   #define CONFIG_EXTRA_ENV_TEXT "<environment here>"
#
# If the input is empty, this script outputs a comment instead.

BEGIN {
	# env holds the env variable we are currently processing
	env = "";
	ORS = ""
}

# Skip empty lines, as these are generated by the clang preprocessor
NF {
	do_output = 0

	# Quote quotes
	gsub("\"", "\\\"")

	# Avoid using the non-POSIX third parameter to match(), by splitting
	# the work into several steps.
	has_var = match($0, "^([^ \t=][^ =]*)=(.*)$")

	# Is this the start of a new environment variable?
	if (has_var) {
		if (length(env) != 0) {
			# Record the value of the variable now completed
			vars[var] = env
			do_output = 1
		}

		# Collect the variable name. The value follows the '='
		match($0, "^([^ \t=][^ =]*)=")
		var = substr($0, 1, RLENGTH - 1)
		env = substr($0, RLENGTH + 1)

		# Deal with += which concatenates the new string to the existing
		# variable. Again we are careful to use POSIX match()
		if (length(env) != 0 && match(var, "^(.*)[+]$")) {
			plusname = substr(var, RSTART, RLENGTH - 1)
			# Allow var\+=val to indicate that the variable name is
			# var+ and this is not actually a concatenation
			if (substr(plusname, length(plusname)) == "\\") {
				# Drop the backslash
				sub(/\\[+]$/, "+", var)
			} else {
				var = plusname
				env = vars[var] env
			}
		}
	} else {
		# Change newline to space
		gsub(/^[ \t]+/, "")

		# Don't keep leading spaces generated by the previous blank line
		if (length(env) == 0) {
			env = $0
		} else {
			env = env " " $0
		}
	}
}

END {
	# Record the value of the variable now completed. If the variable is
	# empty it is not set.
	if (length(env) != 0) {
		vars[var] = env
		do_output = 1
	}

	if (do_output) {
		printf("%s", "#define CONFIG_EXTRA_ENV_TEXT \"")

		# Print out all the variables by alphabetic order, if using
		# gawk. This allows test_env_test.py to work on both awk (where
		# this next line does nothing)
		PROCINFO["sorted_in"] = "@ind_str_asc"
		for (var in vars) {
			env = vars[var]
			print var "=" vars[var] "\\0"
		}
		print "\"\n"
	}
}