blob: 4d763c8d718b7cec204feb458a5aa76d967bd612 [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
LaMont Jonesdc868192024-04-30 09:06:20 -070018var (
19 // When a flag declaration has an initial value that is a string, the default workflow is PREBUILT.
20 // If the flag name starts with any of prefixes in manualFlagNamePrefixes, it is MANUAL.
21 manualFlagNamePrefixes []string = []string{
22 "RELEASE_ACONFIG_",
23 "RELEASE_PLATFORM_",
LaMont Jones15902f22024-05-01 10:06:32 -070024 "RELEASE_BUILD_FLAGS_",
LaMont Jonesdc868192024-04-30 09:06:20 -070025 }
LaMont Jonesb9014c72024-04-11 17:41:15 -070026
LaMont Jonesdc868192024-04-30 09:06:20 -070027 // Set `aconfig_flags_only: true` in these release configs.
28 aconfigFlagsOnlyConfigs map[string]bool = map[string]bool{
29 "trunk_food": true,
30 }
31
32 // Default namespace value. This is intentionally invalid.
33 defaultFlagNamespace string = "android_UNKNOWN"
34
35 // What is the current name for "next".
36 nextName string = "ap3a"
37)
LaMont Jonesb9014c72024-04-11 17:41:15 -070038
39func RenameNext(name string) string {
40 if name == "next" {
LaMont Jonesdc868192024-04-30 09:06:20 -070041 return nextName
LaMont Jonesb9014c72024-04-11 17:41:15 -070042 }
43 return name
44}
45
46func WriteFile(path string, message proto.Message) error {
47 data, err := prototext.MarshalOptions{Multiline: true}.Marshal(message)
48 if err != nil {
49 return err
50 }
51
52 err = os.MkdirAll(filepath.Dir(path), 0775)
53 if err != nil {
54 return err
55 }
56 return os.WriteFile(path, data, 0644)
57}
58
59func WalkValueFiles(dir string, Func fs.WalkDirFunc) error {
60 valPath := filepath.Join(dir, "build_config")
61 if _, err := os.Stat(valPath); err != nil {
62 fmt.Printf("%s not found, ignoring.\n", valPath)
63 return nil
64 }
65
66 return filepath.WalkDir(valPath, func(path string, d fs.DirEntry, err error) error {
67 if err != nil {
68 return err
69 }
70 if strings.HasSuffix(d.Name(), ".scl") && d.Type().IsRegular() {
71 return Func(path, d, err)
72 }
73 return nil
74 })
75}
76
77func ProcessBuildFlags(dir string, namespaceMap map[string]string) error {
78 var rootAconfigModule string
79
80 path := filepath.Join(dir, "build_flags.scl")
81 if _, err := os.Stat(path); err != nil {
82 fmt.Printf("%s not found, ignoring.\n", path)
83 return nil
84 } else {
85 fmt.Printf("Processing %s\n", path)
86 }
87 commentRegexp, err := regexp.Compile("^[[:space:]]*#(?<comment>.+)")
88 if err != nil {
89 return err
90 }
91 declRegexp, err := regexp.Compile("^[[:space:]]*flag.\"(?<name>[A-Z_0-9]+)\",[[:space:]]*(?<container>[_A-Z]*),[[:space:]]*(?<value>(\"[^\"]*\"|[^\",)]*))")
92 if err != nil {
93 return err
94 }
95 declIn, err := os.ReadFile(path)
96 if err != nil {
97 return err
98 }
99 lines := strings.Split(string(declIn), "\n")
100 var description string
101 for _, line := range lines {
102 if comment := commentRegexp.FindStringSubmatch(commentRegexp.FindString(line)); comment != nil {
103 // Description is the text from any contiguous series of lines before a `flag()` call.
LaMont Jones11209e12024-04-19 17:26:27 -0700104 descLine := strings.TrimSpace(comment[commentRegexp.SubexpIndex("comment")])
105 if !strings.HasPrefix(descLine, "keep-sorted") {
106 description += fmt.Sprintf(" %s", descLine)
107 }
LaMont Jonesb9014c72024-04-11 17:41:15 -0700108 continue
109 }
110 matches := declRegexp.FindStringSubmatch(declRegexp.FindString(line))
111 if matches == nil {
112 // The line is neither a comment nor a `flag()` call.
113 // Discard any description we have gathered and process the next line.
114 description = ""
115 continue
116 }
LaMont Jonesb9014c72024-04-11 17:41:15 -0700117 declName := matches[declRegexp.SubexpIndex("name")]
LaMont Jonesdb600992024-04-26 14:19:19 -0700118 declValue := matches[declRegexp.SubexpIndex("value")]
LaMont Jonesb9014c72024-04-11 17:41:15 -0700119 description = strings.TrimSpace(description)
LaMont Jonesdb600992024-04-26 14:19:19 -0700120 containers := []string{strings.ToLower(matches[declRegexp.SubexpIndex("container")])}
121 if containers[0] == "all" {
122 containers = []string{"product", "system", "system_ext", "vendor"}
123 }
LaMont Jonesb9014c72024-04-11 17:41:15 -0700124 var namespace string
125 var ok bool
126 if namespace, ok = namespaceMap[declName]; !ok {
127 namespace = defaultFlagNamespace
128 }
129 flagDeclaration := &rc_proto.FlagDeclaration{
130 Name: proto.String(declName),
131 Namespace: proto.String(namespace),
132 Description: proto.String(description),
LaMont Jonesdb600992024-04-26 14:19:19 -0700133 Containers: containers,
LaMont Jonesb9014c72024-04-11 17:41:15 -0700134 }
135 description = ""
136 // Most build flags are `workflow: PREBUILT`.
137 workflow := rc_proto.Workflow(rc_proto.Workflow_PREBUILT)
138 switch {
139 case declName == "RELEASE_ACONFIG_VALUE_SETS":
140 rootAconfigModule = declValue[1 : len(declValue)-1]
141 continue
142 case strings.HasPrefix(declValue, "\""):
143 // String values mean that the flag workflow is (most likely) either MANUAL or PREBUILT.
144 declValue = declValue[1 : len(declValue)-1]
145 flagDeclaration.Value = &rc_proto.Value{Val: &rc_proto.Value_StringValue{declValue}}
146 for _, prefix := range manualFlagNamePrefixes {
147 if strings.HasPrefix(declName, prefix) {
148 workflow = rc_proto.Workflow(rc_proto.Workflow_MANUAL)
149 break
150 }
151 }
152 case declValue == "False" || declValue == "True":
153 // Boolean values are LAUNCH flags.
154 flagDeclaration.Value = &rc_proto.Value{Val: &rc_proto.Value_BoolValue{declValue == "True"}}
155 workflow = rc_proto.Workflow(rc_proto.Workflow_LAUNCH)
156 case declValue == "None":
157 // Use PREBUILT workflow with no initial value.
158 default:
159 fmt.Printf("%s: Unexpected value %s=%s\n", path, declName, declValue)
160 }
161 flagDeclaration.Workflow = &workflow
162 if flagDeclaration != nil {
163 declPath := filepath.Join(dir, "flag_declarations", fmt.Sprintf("%s.textproto", declName))
164 err := WriteFile(declPath, flagDeclaration)
165 if err != nil {
166 return err
167 }
168 }
169 }
170 if rootAconfigModule != "" {
171 rootProto := &rc_proto.ReleaseConfig{
172 Name: proto.String("root"),
173 AconfigValueSets: []string{rootAconfigModule},
174 }
175 return WriteFile(filepath.Join(dir, "release_configs", "root.textproto"), rootProto)
176 }
177 return nil
178}
179
180func ProcessBuildConfigs(dir, name string, paths []string, releaseProto *rc_proto.ReleaseConfig) error {
LaMont Jones15788822024-04-24 16:01:44 -0700181 valRegexp, err := regexp.Compile("[[:space:]]+value.\"(?<name>[A-Z_0-9]+)\",[[:space:]]*(?<value>(\"[^\"]*\"|[^\",)]*))")
LaMont Jonesb9014c72024-04-11 17:41:15 -0700182 if err != nil {
183 return err
184 }
185 for _, path := range paths {
186 fmt.Printf("Processing %s\n", path)
187 valIn, err := os.ReadFile(path)
188 if err != nil {
189 fmt.Printf("%s: error: %v\n", path, err)
190 return err
191 }
192 vals := valRegexp.FindAllString(string(valIn), -1)
193 for _, val := range vals {
194 matches := valRegexp.FindStringSubmatch(val)
195 valValue := matches[valRegexp.SubexpIndex("value")]
196 valName := matches[valRegexp.SubexpIndex("name")]
197 flagValue := &rc_proto.FlagValue{
198 Name: proto.String(valName),
199 }
200 switch {
201 case valName == "RELEASE_ACONFIG_VALUE_SETS":
202 flagValue = nil
203 if releaseProto.AconfigValueSets == nil {
204 releaseProto.AconfigValueSets = []string{}
205 }
206 releaseProto.AconfigValueSets = append(releaseProto.AconfigValueSets, valValue[1:len(valValue)-1])
207 case strings.HasPrefix(valValue, "\""):
208 valValue = valValue[1 : len(valValue)-1]
209 flagValue.Value = &rc_proto.Value{Val: &rc_proto.Value_StringValue{valValue}}
210 case valValue == "None":
211 // nothing to do here.
212 case valValue == "True":
213 flagValue.Value = &rc_proto.Value{Val: &rc_proto.Value_BoolValue{true}}
214 case valValue == "False":
215 flagValue.Value = &rc_proto.Value{Val: &rc_proto.Value_BoolValue{false}}
216 default:
217 fmt.Printf("%s: Unexpected value %s=%s\n", path, valName, valValue)
218 }
219 if flagValue != nil {
LaMont Jonesff387ea2024-04-29 16:20:59 -0700220 if releaseProto.GetAconfigFlagsOnly() {
LaMont Jonesdc868192024-04-30 09:06:20 -0700221 return fmt.Errorf("%s does not allow build flag overrides", RenameNext(name))
222 }
LaMont Jonesb9014c72024-04-11 17:41:15 -0700223 valPath := filepath.Join(dir, "flag_values", RenameNext(name), fmt.Sprintf("%s.textproto", valName))
224 err := WriteFile(valPath, flagValue)
225 if err != nil {
226 return err
227 }
228 }
229 }
230 }
231 return err
232}
233
LaMont Jonesdb600992024-04-26 14:19:19 -0700234var (
235 allContainers = func() []string {
236 return []string{"product", "system", "system_ext", "vendor"}
237 }()
238)
239
LaMont Jonesb9014c72024-04-11 17:41:15 -0700240func ProcessReleaseConfigMap(dir string, descriptionMap map[string]string) error {
241 path := filepath.Join(dir, "release_config_map.mk")
242 if _, err := os.Stat(path); err != nil {
243 fmt.Printf("%s not found, ignoring.\n", path)
244 return nil
245 } else {
246 fmt.Printf("Processing %s\n", path)
247 }
LaMont Jones11209e12024-04-19 17:26:27 -0700248 configRegexp, err := regexp.Compile("^..call[[:space:]]+declare-release-config,[[:space:]]+(?<name>[_a-z0-9A-Z]+),[[:space:]]+(?<files>[^,]*)(,[[:space:]]*(?<inherits>.*)|[[:space:]]*)[)]$")
LaMont Jonesb9014c72024-04-11 17:41:15 -0700249 if err != nil {
250 return err
251 }
252 aliasRegexp, err := regexp.Compile("^..call[[:space:]]+alias-release-config,[[:space:]]+(?<name>[_a-z0-9A-Z]+),[[:space:]]+(?<target>[_a-z0-9A-Z]+)")
253 if err != nil {
254 return err
255 }
256
257 mapIn, err := os.ReadFile(path)
258 if err != nil {
259 return err
260 }
261 cleanDir := strings.TrimLeft(dir, "../")
LaMont Jonesdb600992024-04-26 14:19:19 -0700262 var defaultContainers []string
LaMont Jonesb9014c72024-04-11 17:41:15 -0700263 switch {
264 case strings.HasPrefix(cleanDir, "build/") || cleanDir == "vendor/google_shared/build":
LaMont Jonesdb600992024-04-26 14:19:19 -0700265 defaultContainers = allContainers
LaMont Jonesb9014c72024-04-11 17:41:15 -0700266 case cleanDir == "vendor/google/release":
LaMont Jonesdb600992024-04-26 14:19:19 -0700267 defaultContainers = allContainers
LaMont Jonesb9014c72024-04-11 17:41:15 -0700268 default:
LaMont Jonesdb600992024-04-26 14:19:19 -0700269 defaultContainers = []string{"vendor"}
LaMont Jonesb9014c72024-04-11 17:41:15 -0700270 }
LaMont Jonesdb600992024-04-26 14:19:19 -0700271 releaseConfigMap := &rc_proto.ReleaseConfigMap{DefaultContainers: defaultContainers}
LaMont Jonesb9014c72024-04-11 17:41:15 -0700272 // If we find a description for the directory, include it.
273 if description, ok := descriptionMap[cleanDir]; ok {
274 releaseConfigMap.Description = proto.String(description)
275 }
276 lines := strings.Split(string(mapIn), "\n")
277 for _, line := range lines {
278 alias := aliasRegexp.FindStringSubmatch(aliasRegexp.FindString(line))
279 if alias != nil {
280 fmt.Printf("processing alias %s\n", line)
281 name := alias[aliasRegexp.SubexpIndex("name")]
282 target := alias[aliasRegexp.SubexpIndex("target")]
283 if target == "next" {
284 if RenameNext(target) != name {
285 return fmt.Errorf("Unexpected name for next (%s)", RenameNext(target))
286 }
287 target, name = name, target
288 }
289 releaseConfigMap.Aliases = append(releaseConfigMap.Aliases,
290 &rc_proto.ReleaseAlias{
291 Name: proto.String(name),
292 Target: proto.String(target),
293 })
294 }
295 config := configRegexp.FindStringSubmatch(configRegexp.FindString(line))
296 if config == nil {
297 continue
298 }
299 name := config[configRegexp.SubexpIndex("name")]
300 releaseConfig := &rc_proto.ReleaseConfig{
301 Name: proto.String(RenameNext(name)),
302 }
LaMont Jonesdc868192024-04-30 09:06:20 -0700303 if aconfigFlagsOnlyConfigs[name] {
LaMont Jonesff387ea2024-04-29 16:20:59 -0700304 releaseConfig.AconfigFlagsOnly = proto.Bool(true)
LaMont Jonesdc868192024-04-30 09:06:20 -0700305 }
LaMont Jonesb9014c72024-04-11 17:41:15 -0700306 configFiles := config[configRegexp.SubexpIndex("files")]
307 files := strings.Split(strings.ReplaceAll(configFiles, "$(local_dir)", dir+"/"), " ")
308 configInherits := config[configRegexp.SubexpIndex("inherits")]
309 if len(configInherits) > 0 {
310 releaseConfig.Inherits = strings.Split(configInherits, " ")
311 }
312 err := ProcessBuildConfigs(dir, name, files, releaseConfig)
313 if err != nil {
314 return err
315 }
316
317 releasePath := filepath.Join(dir, "release_configs", fmt.Sprintf("%s.textproto", RenameNext(name)))
318 err = WriteFile(releasePath, releaseConfig)
319 if err != nil {
320 return err
321 }
322 }
323 return WriteFile(filepath.Join(dir, "release_config_map.textproto"), releaseConfigMap)
324}
325
326func main() {
327 var err error
328 var top string
329 var dirs rc_lib.StringList
330 var namespacesFile string
331 var descriptionsFile string
LaMont Jonesff387ea2024-04-29 16:20:59 -0700332 var debug bool
LaMont Jonese41ea1e2024-04-29 14:16:19 -0700333 defaultTopDir, err := rc_lib.GetTopDir()
LaMont Jonesb9014c72024-04-11 17:41:15 -0700334
LaMont Jonese41ea1e2024-04-29 14:16:19 -0700335 flag.StringVar(&top, "top", defaultTopDir, "path to top of workspace")
LaMont Jonesb9014c72024-04-11 17:41:15 -0700336 flag.Var(&dirs, "dir", "directory to process, relative to the top of the workspace")
337 flag.StringVar(&namespacesFile, "namespaces", "", "location of file with 'flag_name namespace' information")
338 flag.StringVar(&descriptionsFile, "descriptions", "", "location of file with 'directory description' information")
LaMont Jonesff387ea2024-04-29 16:20:59 -0700339 flag.BoolVar(&debug, "debug", false, "turn on debugging output for errors")
LaMont Jonesb9014c72024-04-11 17:41:15 -0700340 flag.Parse()
341
LaMont Jonesff387ea2024-04-29 16:20:59 -0700342 errorExit := func(err error) {
343 if debug {
344 panic(err)
345 }
346 fmt.Fprintf(os.Stderr, "%s\n", err)
347 os.Exit(1)
348 }
349
LaMont Jonesb9014c72024-04-11 17:41:15 -0700350 if err = os.Chdir(top); err != nil {
LaMont Jonesff387ea2024-04-29 16:20:59 -0700351 errorExit(err)
LaMont Jonesb9014c72024-04-11 17:41:15 -0700352 }
353 if len(dirs) == 0 {
354 dirs = rc_lib.StringList{"build/release", "vendor/google_shared/build/release", "vendor/google/release"}
355 }
356
357 namespaceMap := make(map[string]string)
358 if namespacesFile != "" {
359 data, err := os.ReadFile(namespacesFile)
360 if err != nil {
LaMont Jonesff387ea2024-04-29 16:20:59 -0700361 errorExit(err)
LaMont Jonesb9014c72024-04-11 17:41:15 -0700362 }
363 for idx, line := range strings.Split(string(data), "\n") {
364 fields := strings.Split(line, " ")
365 if len(fields) > 2 {
LaMont Jonesff387ea2024-04-29 16:20:59 -0700366 errorExit(fmt.Errorf("line %d: too many fields: %s", idx, line))
LaMont Jonesb9014c72024-04-11 17:41:15 -0700367 }
368 namespaceMap[fields[0]] = fields[1]
369 }
370
371 }
372
373 descriptionMap := make(map[string]string)
374 descriptionMap["build/release"] = "Published open-source flags and declarations"
375 if descriptionsFile != "" {
376 data, err := os.ReadFile(descriptionsFile)
377 if err != nil {
LaMont Jonesff387ea2024-04-29 16:20:59 -0700378 errorExit(err)
LaMont Jonesb9014c72024-04-11 17:41:15 -0700379 }
380 for _, line := range strings.Split(string(data), "\n") {
381 if strings.TrimSpace(line) != "" {
382 fields := strings.SplitN(line, " ", 2)
383 descriptionMap[fields[0]] = fields[1]
384 }
385 }
386
387 }
388
389 for _, dir := range dirs {
390 err = ProcessBuildFlags(dir, namespaceMap)
391 if err != nil {
LaMont Jonesff387ea2024-04-29 16:20:59 -0700392 errorExit(err)
LaMont Jonesb9014c72024-04-11 17:41:15 -0700393 }
394
395 err = ProcessReleaseConfigMap(dir, descriptionMap)
396 if err != nil {
LaMont Jonesff387ea2024-04-29 16:20:59 -0700397 errorExit(err)
LaMont Jonesb9014c72024-04-11 17:41:15 -0700398 }
399 }
400}