blob: 616674bc55c214a25e678efac7925ec75c6c527c [file] [log] [blame]
LaMont Jonesb9014c72024-04-11 17:41:15 -07001package main
2
3import (
4 "flag"
5 "fmt"
6 "io/fs"
7 "os"
8 "path/filepath"
9 "regexp"
10 "strings"
11
12 rc_lib "android/soong/cmd/release_config/release_config_lib"
13 rc_proto "android/soong/cmd/release_config/release_config_proto"
14 "google.golang.org/protobuf/encoding/prototext"
15 "google.golang.org/protobuf/proto"
16)
17
18// When a flag declaration has an initial value that is a string, the default workflow is PREBUILT.
19// If the flag name starts with any of prefixes in manualFlagNamePrefixes, it is MANUAL.
20var manualFlagNamePrefixes []string = []string{
21 "RELEASE_ACONFIG_",
22 "RELEASE_PLATFORM_",
23}
24
25var defaultFlagNamespace string = "android_UNKNOWN"
26
27func RenameNext(name string) string {
28 if name == "next" {
29 return "ap3a"
30 }
31 return name
32}
33
34func WriteFile(path string, message proto.Message) error {
35 data, err := prototext.MarshalOptions{Multiline: true}.Marshal(message)
36 if err != nil {
37 return err
38 }
39
40 err = os.MkdirAll(filepath.Dir(path), 0775)
41 if err != nil {
42 return err
43 }
44 return os.WriteFile(path, data, 0644)
45}
46
47func WalkValueFiles(dir string, Func fs.WalkDirFunc) error {
48 valPath := filepath.Join(dir, "build_config")
49 if _, err := os.Stat(valPath); err != nil {
50 fmt.Printf("%s not found, ignoring.\n", valPath)
51 return nil
52 }
53
54 return filepath.WalkDir(valPath, func(path string, d fs.DirEntry, err error) error {
55 if err != nil {
56 return err
57 }
58 if strings.HasSuffix(d.Name(), ".scl") && d.Type().IsRegular() {
59 return Func(path, d, err)
60 }
61 return nil
62 })
63}
64
65func ProcessBuildFlags(dir string, namespaceMap map[string]string) error {
66 var rootAconfigModule string
67
68 path := filepath.Join(dir, "build_flags.scl")
69 if _, err := os.Stat(path); err != nil {
70 fmt.Printf("%s not found, ignoring.\n", path)
71 return nil
72 } else {
73 fmt.Printf("Processing %s\n", path)
74 }
75 commentRegexp, err := regexp.Compile("^[[:space:]]*#(?<comment>.+)")
76 if err != nil {
77 return err
78 }
79 declRegexp, err := regexp.Compile("^[[:space:]]*flag.\"(?<name>[A-Z_0-9]+)\",[[:space:]]*(?<container>[_A-Z]*),[[:space:]]*(?<value>(\"[^\"]*\"|[^\",)]*))")
80 if err != nil {
81 return err
82 }
83 declIn, err := os.ReadFile(path)
84 if err != nil {
85 return err
86 }
87 lines := strings.Split(string(declIn), "\n")
88 var description string
89 for _, line := range lines {
90 if comment := commentRegexp.FindStringSubmatch(commentRegexp.FindString(line)); comment != nil {
91 // Description is the text from any contiguous series of lines before a `flag()` call.
92 description += fmt.Sprintf(" %s", strings.TrimSpace(comment[commentRegexp.SubexpIndex("comment")]))
93 continue
94 }
95 matches := declRegexp.FindStringSubmatch(declRegexp.FindString(line))
96 if matches == nil {
97 // The line is neither a comment nor a `flag()` call.
98 // Discard any description we have gathered and process the next line.
99 description = ""
100 continue
101 }
102 declValue := matches[declRegexp.SubexpIndex("value")]
103 declName := matches[declRegexp.SubexpIndex("name")]
104 container := rc_proto.Container(rc_proto.Container_value[matches[declRegexp.SubexpIndex("container")]])
105 description = strings.TrimSpace(description)
106 var namespace string
107 var ok bool
108 if namespace, ok = namespaceMap[declName]; !ok {
109 namespace = defaultFlagNamespace
110 }
111 flagDeclaration := &rc_proto.FlagDeclaration{
112 Name: proto.String(declName),
113 Namespace: proto.String(namespace),
114 Description: proto.String(description),
115 Container: &container,
116 }
117 description = ""
118 // Most build flags are `workflow: PREBUILT`.
119 workflow := rc_proto.Workflow(rc_proto.Workflow_PREBUILT)
120 switch {
121 case declName == "RELEASE_ACONFIG_VALUE_SETS":
122 rootAconfigModule = declValue[1 : len(declValue)-1]
123 continue
124 case strings.HasPrefix(declValue, "\""):
125 // String values mean that the flag workflow is (most likely) either MANUAL or PREBUILT.
126 declValue = declValue[1 : len(declValue)-1]
127 flagDeclaration.Value = &rc_proto.Value{Val: &rc_proto.Value_StringValue{declValue}}
128 for _, prefix := range manualFlagNamePrefixes {
129 if strings.HasPrefix(declName, prefix) {
130 workflow = rc_proto.Workflow(rc_proto.Workflow_MANUAL)
131 break
132 }
133 }
134 case declValue == "False" || declValue == "True":
135 // Boolean values are LAUNCH flags.
136 flagDeclaration.Value = &rc_proto.Value{Val: &rc_proto.Value_BoolValue{declValue == "True"}}
137 workflow = rc_proto.Workflow(rc_proto.Workflow_LAUNCH)
138 case declValue == "None":
139 // Use PREBUILT workflow with no initial value.
140 default:
141 fmt.Printf("%s: Unexpected value %s=%s\n", path, declName, declValue)
142 }
143 flagDeclaration.Workflow = &workflow
144 if flagDeclaration != nil {
145 declPath := filepath.Join(dir, "flag_declarations", fmt.Sprintf("%s.textproto", declName))
146 err := WriteFile(declPath, flagDeclaration)
147 if err != nil {
148 return err
149 }
150 }
151 }
152 if rootAconfigModule != "" {
153 rootProto := &rc_proto.ReleaseConfig{
154 Name: proto.String("root"),
155 AconfigValueSets: []string{rootAconfigModule},
156 }
157 return WriteFile(filepath.Join(dir, "release_configs", "root.textproto"), rootProto)
158 }
159 return nil
160}
161
162func ProcessBuildConfigs(dir, name string, paths []string, releaseProto *rc_proto.ReleaseConfig) error {
163 valRegexp, err := regexp.Compile("[[:space:]]+value.\"(?<name>[A-Z_0-9]+)\",[[:space:]]*(?<value>[^,)]*)")
164 if err != nil {
165 return err
166 }
167 for _, path := range paths {
168 fmt.Printf("Processing %s\n", path)
169 valIn, err := os.ReadFile(path)
170 if err != nil {
171 fmt.Printf("%s: error: %v\n", path, err)
172 return err
173 }
174 vals := valRegexp.FindAllString(string(valIn), -1)
175 for _, val := range vals {
176 matches := valRegexp.FindStringSubmatch(val)
177 valValue := matches[valRegexp.SubexpIndex("value")]
178 valName := matches[valRegexp.SubexpIndex("name")]
179 flagValue := &rc_proto.FlagValue{
180 Name: proto.String(valName),
181 }
182 switch {
183 case valName == "RELEASE_ACONFIG_VALUE_SETS":
184 flagValue = nil
185 if releaseProto.AconfigValueSets == nil {
186 releaseProto.AconfigValueSets = []string{}
187 }
188 releaseProto.AconfigValueSets = append(releaseProto.AconfigValueSets, valValue[1:len(valValue)-1])
189 case strings.HasPrefix(valValue, "\""):
190 valValue = valValue[1 : len(valValue)-1]
191 flagValue.Value = &rc_proto.Value{Val: &rc_proto.Value_StringValue{valValue}}
192 case valValue == "None":
193 // nothing to do here.
194 case valValue == "True":
195 flagValue.Value = &rc_proto.Value{Val: &rc_proto.Value_BoolValue{true}}
196 case valValue == "False":
197 flagValue.Value = &rc_proto.Value{Val: &rc_proto.Value_BoolValue{false}}
198 default:
199 fmt.Printf("%s: Unexpected value %s=%s\n", path, valName, valValue)
200 }
201 if flagValue != nil {
202 valPath := filepath.Join(dir, "flag_values", RenameNext(name), fmt.Sprintf("%s.textproto", valName))
203 err := WriteFile(valPath, flagValue)
204 if err != nil {
205 return err
206 }
207 }
208 }
209 }
210 return err
211}
212
213func ProcessReleaseConfigMap(dir string, descriptionMap map[string]string) error {
214 path := filepath.Join(dir, "release_config_map.mk")
215 if _, err := os.Stat(path); err != nil {
216 fmt.Printf("%s not found, ignoring.\n", path)
217 return nil
218 } else {
219 fmt.Printf("Processing %s\n", path)
220 }
221 configRegexp, err := regexp.Compile("^..call[[:space:]]+declare-release-config,[[:space:]]+(?<name>[_a-z0-0A-Z]+),[[:space:]]+(?<files>[^,]*)(,[[:space:]]*(?<inherits>.*)|[[:space:]]*)[)]$")
222 if err != nil {
223 return err
224 }
225 aliasRegexp, err := regexp.Compile("^..call[[:space:]]+alias-release-config,[[:space:]]+(?<name>[_a-z0-9A-Z]+),[[:space:]]+(?<target>[_a-z0-9A-Z]+)")
226 if err != nil {
227 return err
228 }
229
230 mapIn, err := os.ReadFile(path)
231 if err != nil {
232 return err
233 }
234 cleanDir := strings.TrimLeft(dir, "../")
235 var defaultContainer rc_proto.Container
236 switch {
237 case strings.HasPrefix(cleanDir, "build/") || cleanDir == "vendor/google_shared/build":
238 defaultContainer = rc_proto.Container(rc_proto.Container_ALL)
239 case cleanDir == "vendor/google/release":
240 defaultContainer = rc_proto.Container(rc_proto.Container_ALL)
241 default:
242 defaultContainer = rc_proto.Container(rc_proto.Container_VENDOR)
243 }
244 releaseConfigMap := &rc_proto.ReleaseConfigMap{DefaultContainer: &defaultContainer}
245 // If we find a description for the directory, include it.
246 if description, ok := descriptionMap[cleanDir]; ok {
247 releaseConfigMap.Description = proto.String(description)
248 }
249 lines := strings.Split(string(mapIn), "\n")
250 for _, line := range lines {
251 alias := aliasRegexp.FindStringSubmatch(aliasRegexp.FindString(line))
252 if alias != nil {
253 fmt.Printf("processing alias %s\n", line)
254 name := alias[aliasRegexp.SubexpIndex("name")]
255 target := alias[aliasRegexp.SubexpIndex("target")]
256 if target == "next" {
257 if RenameNext(target) != name {
258 return fmt.Errorf("Unexpected name for next (%s)", RenameNext(target))
259 }
260 target, name = name, target
261 }
262 releaseConfigMap.Aliases = append(releaseConfigMap.Aliases,
263 &rc_proto.ReleaseAlias{
264 Name: proto.String(name),
265 Target: proto.String(target),
266 })
267 }
268 config := configRegexp.FindStringSubmatch(configRegexp.FindString(line))
269 if config == nil {
270 continue
271 }
272 name := config[configRegexp.SubexpIndex("name")]
273 releaseConfig := &rc_proto.ReleaseConfig{
274 Name: proto.String(RenameNext(name)),
275 }
276 configFiles := config[configRegexp.SubexpIndex("files")]
277 files := strings.Split(strings.ReplaceAll(configFiles, "$(local_dir)", dir+"/"), " ")
278 configInherits := config[configRegexp.SubexpIndex("inherits")]
279 if len(configInherits) > 0 {
280 releaseConfig.Inherits = strings.Split(configInherits, " ")
281 }
282 err := ProcessBuildConfigs(dir, name, files, releaseConfig)
283 if err != nil {
284 return err
285 }
286
287 releasePath := filepath.Join(dir, "release_configs", fmt.Sprintf("%s.textproto", RenameNext(name)))
288 err = WriteFile(releasePath, releaseConfig)
289 if err != nil {
290 return err
291 }
292 }
293 return WriteFile(filepath.Join(dir, "release_config_map.textproto"), releaseConfigMap)
294}
295
296func main() {
297 var err error
298 var top string
299 var dirs rc_lib.StringList
300 var namespacesFile string
301 var descriptionsFile string
302
303 flag.StringVar(&top, "top", ".", "path to top of workspace")
304 flag.Var(&dirs, "dir", "directory to process, relative to the top of the workspace")
305 flag.StringVar(&namespacesFile, "namespaces", "", "location of file with 'flag_name namespace' information")
306 flag.StringVar(&descriptionsFile, "descriptions", "", "location of file with 'directory description' information")
307 flag.Parse()
308
309 if err = os.Chdir(top); err != nil {
310 panic(err)
311 }
312 if len(dirs) == 0 {
313 dirs = rc_lib.StringList{"build/release", "vendor/google_shared/build/release", "vendor/google/release"}
314 }
315
316 namespaceMap := make(map[string]string)
317 if namespacesFile != "" {
318 data, err := os.ReadFile(namespacesFile)
319 if err != nil {
320 panic(err)
321 }
322 for idx, line := range strings.Split(string(data), "\n") {
323 fields := strings.Split(line, " ")
324 if len(fields) > 2 {
325 panic(fmt.Errorf("line %d: too many fields: %s", idx, line))
326 }
327 namespaceMap[fields[0]] = fields[1]
328 }
329
330 }
331
332 descriptionMap := make(map[string]string)
333 descriptionMap["build/release"] = "Published open-source flags and declarations"
334 if descriptionsFile != "" {
335 data, err := os.ReadFile(descriptionsFile)
336 if err != nil {
337 panic(err)
338 }
339 for _, line := range strings.Split(string(data), "\n") {
340 if strings.TrimSpace(line) != "" {
341 fields := strings.SplitN(line, " ", 2)
342 descriptionMap[fields[0]] = fields[1]
343 }
344 }
345
346 }
347
348 for _, dir := range dirs {
349 err = ProcessBuildFlags(dir, namespaceMap)
350 if err != nil {
351 panic(err)
352 }
353
354 err = ProcessReleaseConfigMap(dir, descriptionMap)
355 if err != nil {
356 panic(err)
357 }
358 }
359}