summaryrefslogtreecommitdiff
path: root/scripts/env2string.awk
blob: 57d0fc8f3ba6145f89fa5bdac6ce537c56753023 (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
# 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 {
	# Quote quotes
	gsub("\"", "\\\"")

	# Is this the start of a new environment variable?
	if (match($0, "^([^ \t=][^ =]*)=(.*)$", arr)) {
		if (length(env) != 0) {
			# Record the value of the variable now completed
			vars[var] = env
		}
		var = arr[1]
		env = arr[2]

		# Deal with += which concatenates the new string to the existing
		# variable
		if (length(env) != 0 && match(var, "^(.*)[+]$", var_arr))
		{
			# Allow var\+=val to indicate that the variable name is
			# var+ and this is not actually a concatenation
			if (substr(var_arr[1], length(var_arr[1])) == "\\") {
				# Drop the backslash
				sub(/\\[+]$/, "+", var)
			} else {
				var = var_arr[1]
				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
	}

	if (length(vars) != 0) {
		printf("%s", "#define CONFIG_EXTRA_ENV_TEXT \"")

		# Print out all the variables
		for (var in vars) {
			env = vars[var]
			print var "=" vars[var] "\\0"
		}
		print "\"\n"
	}
}