blob: 29290a414d292559a1171eeb71ba637b63bc3100 [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.
LaMont Jones11209e12024-04-19 17:26:27 -070092 descLine := strings.TrimSpace(comment[commentRegexp.SubexpIndex("comment")])
93 if !strings.HasPrefix(descLine, "keep-sorted") {
94 description += fmt.Sprintf(" %s", descLine)
95 }
LaMont Jonesb9014c72024-04-11 17:41:15 -070096 continue
97 }
98 matches := declRegexp.FindStringSubmatch(declRegexp.FindString(line))
99 if matches == nil {
100 // The line is neither a comment nor a `flag()` call.
101 // Discard any description we have gathered and process the next line.
102 description = ""
103 continue
104 }
105 declValue := matches[declRegexp.SubexpIndex("value")]
106 declName := matches[declRegexp.SubexpIndex("name")]
107 container := rc_proto.Container(rc_proto.Container_value[matches[declRegexp.SubexpIndex("container")]])
108 description = strings.TrimSpace(description)
109 var namespace string
110 var ok bool
111 if namespace, ok = namespaceMap[declName]; !ok {
112 namespace = defaultFlagNamespace
113 }
114 flagDeclaration := &rc_proto.FlagDeclaration{
115 Name: proto.String(declName),
116 Namespace: proto.String(namespace),
117 Description: proto.String(description),
118 Container: &container,
119 }
120 description = ""
121 // Most build flags are `workflow: PREBUILT`.
122 workflow := rc_proto.Workflow(rc_proto.Workflow_PREBUILT)
123 switch {
124 case declName == "RELEASE_ACONFIG_VALUE_SETS":
125 rootAconfigModule = declValue[1 : len(declValue)-1]
126 continue
127 case strings.HasPrefix(declValue, "\""):
128 // String values mean that the flag workflow is (most likely) either MANUAL or PREBUILT.
129 declValue = declValue[1 : len(declValue)-1]
130 flagDeclaration.Value = &rc_proto.Value{Val: &rc_proto.Value_StringValue{declValue}}
131 for _, prefix := range manualFlagNamePrefixes {
132 if strings.HasPrefix(declName, prefix) {
133 workflow = rc_proto.Workflow(rc_proto.Workflow_MANUAL)
134 break
135 }
136 }
137 case declValue == "False" || declValue == "True":
138 // Boolean values are LAUNCH flags.
139 flagDeclaration.Value = &rc_proto.Value{Val: &rc_proto.Value_BoolValue{declValue == "True"}}
140 workflow = rc_proto.Workflow(rc_proto.Workflow_LAUNCH)
141 case declValue == "None":
142 // Use PREBUILT workflow with no initial value.
143 default:
144 fmt.Printf("%s: Unexpected value %s=%s\n", path, declName, declValue)
145 }
146 flagDeclaration.Workflow = &workflow
147 if flagDeclaration != nil {
148 declPath := filepath.Join(dir, "flag_declarations", fmt.Sprintf("%s.textproto", declName))
149 err := WriteFile(declPath, flagDeclaration)
150 if err != nil {
151 return err
152 }
153 }
154 }
155 if rootAconfigModule != "" {
156 rootProto := &rc_proto.ReleaseConfig{
157 Name: proto.String("root"),
158 AconfigValueSets: []string{rootAconfigModule},
159 }
160 return WriteFile(filepath.Join(dir, "release_configs", "root.textproto"), rootProto)
161 }
162 return nil
163}
164
165func ProcessBuildConfigs(dir, name string, paths []string, releaseProto *rc_proto.ReleaseConfig) error {
LaMont Jones15788822024-04-24 16:01:44 -0700166 valRegexp, err := regexp.Compile("[[:space:]]+value.\"(?<name>[A-Z_0-9]+)\",[[:space:]]*(?<value>(\"[^\"]*\"|[^\",)]*))")
LaMont Jonesb9014c72024-04-11 17:41:15 -0700167 if err != nil {
168 return err
169 }
170 for _, path := range paths {
171 fmt.Printf("Processing %s\n", path)
172 valIn, err := os.ReadFile(path)
173 if err != nil {
174 fmt.Printf("%s: error: %v\n", path, err)
175 return err
176 }
177 vals := valRegexp.FindAllString(string(valIn), -1)
178 for _, val := range vals {
179 matches := valRegexp.FindStringSubmatch(val)
180 valValue := matches[valRegexp.SubexpIndex("value")]
181 valName := matches[valRegexp.SubexpIndex("name")]
182 flagValue := &rc_proto.FlagValue{
183 Name: proto.String(valName),
184 }
185 switch {
186 case valName == "RELEASE_ACONFIG_VALUE_SETS":
187 flagValue = nil
188 if releaseProto.AconfigValueSets == nil {
189 releaseProto.AconfigValueSets = []string{}
190 }
191 releaseProto.AconfigValueSets = append(releaseProto.AconfigValueSets, valValue[1:len(valValue)-1])
192 case strings.HasPrefix(valValue, "\""):
193 valValue = valValue[1 : len(valValue)-1]
194 flagValue.Value = &rc_proto.Value{Val: &rc_proto.Value_StringValue{valValue}}
195 case valValue == "None":
196 // nothing to do here.
197 case valValue == "True":
198 flagValue.Value = &rc_proto.Value{Val: &rc_proto.Value_BoolValue{true}}
199 case valValue == "False":
200 flagValue.Value = &rc_proto.Value{Val: &rc_proto.Value_BoolValue{false}}
201 default:
202 fmt.Printf("%s: Unexpected value %s=%s\n", path, valName, valValue)
203 }
204 if flagValue != nil {
205 valPath := filepath.Join(dir, "flag_values", RenameNext(name), fmt.Sprintf("%s.textproto", valName))
206 err := WriteFile(valPath, flagValue)
207 if err != nil {
208 return err
209 }
210 }
211 }
212 }
213 return err
214}
215
216func ProcessReleaseConfigMap(dir string, descriptionMap map[string]string) error {
217 path := filepath.Join(dir, "release_config_map.mk")
218 if _, err := os.Stat(path); err != nil {
219 fmt.Printf("%s not found, ignoring.\n", path)
220 return nil
221 } else {
222 fmt.Printf("Processing %s\n", path)
223 }
LaMont Jones11209e12024-04-19 17:26:27 -0700224 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 -0700225 if err != nil {
226 return err
227 }
228 aliasRegexp, err := regexp.Compile("^..call[[:space:]]+alias-release-config,[[:space:]]+(?<name>[_a-z0-9A-Z]+),[[:space:]]+(?<target>[_a-z0-9A-Z]+)")
229 if err != nil {
230 return err
231 }
232
233 mapIn, err := os.ReadFile(path)
234 if err != nil {
235 return err
236 }
237 cleanDir := strings.TrimLeft(dir, "../")
238 var defaultContainer rc_proto.Container
239 switch {
240 case strings.HasPrefix(cleanDir, "build/") || cleanDir == "vendor/google_shared/build":
241 defaultContainer = rc_proto.Container(rc_proto.Container_ALL)
242 case cleanDir == "vendor/google/release":
243 defaultContainer = rc_proto.Container(rc_proto.Container_ALL)
244 default:
245 defaultContainer = rc_proto.Container(rc_proto.Container_VENDOR)
246 }
247 releaseConfigMap := &rc_proto.ReleaseConfigMap{DefaultContainer: &defaultContainer}
248 // If we find a description for the directory, include it.
249 if description, ok := descriptionMap[cleanDir]; ok {
250 releaseConfigMap.Description = proto.String(description)
251 }
252 lines := strings.Split(string(mapIn), "\n")
253 for _, line := range lines {
254 alias := aliasRegexp.FindStringSubmatch(aliasRegexp.FindString(line))
255 if alias != nil {
256 fmt.Printf("processing alias %s\n", line)
257 name := alias[aliasRegexp.SubexpIndex("name")]
258 target := alias[aliasRegexp.SubexpIndex("target")]
259 if target == "next" {
260 if RenameNext(target) != name {
261 return fmt.Errorf("Unexpected name for next (%s)", RenameNext(target))
262 }
263 target, name = name, target
264 }
265 releaseConfigMap.Aliases = append(releaseConfigMap.Aliases,
266 &rc_proto.ReleaseAlias{
267 Name: proto.String(name),
268 Target: proto.String(target),
269 })
270 }
271 config := configRegexp.FindStringSubmatch(configRegexp.FindString(line))
272 if config == nil {
273 continue
274 }
275 name := config[configRegexp.SubexpIndex("name")]
276 releaseConfig := &rc_proto.ReleaseConfig{
277 Name: proto.String(RenameNext(name)),
278 }
279 configFiles := config[configRegexp.SubexpIndex("files")]
280 files := strings.Split(strings.ReplaceAll(configFiles, "$(local_dir)", dir+"/"), " ")
281 configInherits := config[configRegexp.SubexpIndex("inherits")]
282 if len(configInherits) > 0 {
283 releaseConfig.Inherits = strings.Split(configInherits, " ")
284 }
285 err := ProcessBuildConfigs(dir, name, files, releaseConfig)
286 if err != nil {
287 return err
288 }
289
290 releasePath := filepath.Join(dir, "release_configs", fmt.Sprintf("%s.textproto", RenameNext(name)))
291 err = WriteFile(releasePath, releaseConfig)
292 if err != nil {
293 return err
294 }
295 }
296 return WriteFile(filepath.Join(dir, "release_config_map.textproto"), releaseConfigMap)
297}
298
299func main() {
300 var err error
301 var top string
302 var dirs rc_lib.StringList
303 var namespacesFile string
304 var descriptionsFile string
305
306 flag.StringVar(&top, "top", ".", "path to top of workspace")
307 flag.Var(&dirs, "dir", "directory to process, relative to the top of the workspace")
308 flag.StringVar(&namespacesFile, "namespaces", "", "location of file with 'flag_name namespace' information")
309 flag.StringVar(&descriptionsFile, "descriptions", "", "location of file with 'directory description' information")
310 flag.Parse()
311
312 if err = os.Chdir(top); err != nil {
313 panic(err)
314 }
315 if len(dirs) == 0 {
316 dirs = rc_lib.StringList{"build/release", "vendor/google_shared/build/release", "vendor/google/release"}
317 }
318
319 namespaceMap := make(map[string]string)
320 if namespacesFile != "" {
321 data, err := os.ReadFile(namespacesFile)
322 if err != nil {
323 panic(err)
324 }
325 for idx, line := range strings.Split(string(data), "\n") {
326 fields := strings.Split(line, " ")
327 if len(fields) > 2 {
328 panic(fmt.Errorf("line %d: too many fields: %s", idx, line))
329 }
330 namespaceMap[fields[0]] = fields[1]
331 }
332
333 }
334
335 descriptionMap := make(map[string]string)
336 descriptionMap["build/release"] = "Published open-source flags and declarations"
337 if descriptionsFile != "" {
338 data, err := os.ReadFile(descriptionsFile)
339 if err != nil {
340 panic(err)
341 }
342 for _, line := range strings.Split(string(data), "\n") {
343 if strings.TrimSpace(line) != "" {
344 fields := strings.SplitN(line, " ", 2)
345 descriptionMap[fields[0]] = fields[1]
346 }
347 }
348
349 }
350
351 for _, dir := range dirs {
352 err = ProcessBuildFlags(dir, namespaceMap)
353 if err != nil {
354 panic(err)
355 }
356
357 err = ProcessReleaseConfigMap(dir, descriptionMap)
358 if err != nil {
359 panic(err)
360 }
361 }
362}