Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1 | // Copyright 2021 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | // The application to convert product configuration makefiles to Starlark. |
| 16 | // Converts either given list of files (and optionally the dependent files |
| 17 | // of the same kind), or all all product configuration makefiles in the |
| 18 | // given source tree. |
| 19 | // Previous version of a converted file can be backed up. |
| 20 | // Optionally prints detailed statistics at the end. |
| 21 | package main |
| 22 | |
| 23 | import ( |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 24 | "bufio" |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 25 | "flag" |
| 26 | "fmt" |
| 27 | "io/ioutil" |
| 28 | "os" |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 29 | "os/exec" |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 30 | "path/filepath" |
| 31 | "regexp" |
| 32 | "runtime/debug" |
Sasha Smundak | 3880279 | 2021-08-01 14:38:07 -0700 | [diff] [blame] | 33 | "runtime/pprof" |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 34 | "sort" |
| 35 | "strings" |
| 36 | "time" |
| 37 | |
| 38 | "android/soong/androidmk/parser" |
| 39 | "android/soong/mk2rbc" |
| 40 | ) |
| 41 | |
| 42 | var ( |
| 43 | rootDir = flag.String("root", ".", "the value of // for load paths") |
| 44 | // TODO(asmundak): remove this option once there is a consensus on suffix |
| 45 | suffix = flag.String("suffix", ".rbc", "generated files' suffix") |
| 46 | dryRun = flag.Bool("dry_run", false, "dry run") |
| 47 | recurse = flag.Bool("convert_dependents", false, "convert all dependent files") |
| 48 | mode = flag.String("mode", "", `"backup" to back up existing files, "write" to overwrite them`) |
| 49 | warn = flag.Bool("warnings", false, "warn about partially failed conversions") |
| 50 | verbose = flag.Bool("v", false, "print summary") |
| 51 | errstat = flag.Bool("error_stat", false, "print error statistics") |
| 52 | traceVar = flag.String("trace", "", "comma-separated list of variables to trace") |
| 53 | // TODO(asmundak): this option is for debugging |
| 54 | allInSource = flag.Bool("all", false, "convert all product config makefiles in the tree under //") |
| 55 | outputTop = flag.String("outdir", "", "write output files into this directory hierarchy") |
| 56 | launcher = flag.String("launcher", "", "generated launcher path. If set, the non-flag argument is _product_name_") |
| 57 | printProductConfigMap = flag.Bool("print_product_config_map", false, "print product config map and exit") |
Sasha Smundak | 3880279 | 2021-08-01 14:38:07 -0700 | [diff] [blame] | 58 | cpuProfile = flag.String("cpu_profile", "", "write cpu profile to file") |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 59 | traceCalls = flag.Bool("trace_calls", false, "trace function calls") |
| 60 | ) |
| 61 | |
| 62 | func init() { |
| 63 | // Poor man's flag aliasing: works, but the usage string is ugly and |
| 64 | // both flag and its alias can be present on the command line |
| 65 | flagAlias := func(target string, alias string) { |
| 66 | if f := flag.Lookup(target); f != nil { |
| 67 | flag.Var(f.Value, alias, "alias for --"+f.Name) |
| 68 | return |
| 69 | } |
| 70 | quit("cannot alias unknown flag " + target) |
| 71 | } |
| 72 | flagAlias("suffix", "s") |
| 73 | flagAlias("root", "d") |
| 74 | flagAlias("dry_run", "n") |
| 75 | flagAlias("convert_dependents", "r") |
| 76 | flagAlias("warnings", "w") |
| 77 | flagAlias("error_stat", "e") |
| 78 | } |
| 79 | |
| 80 | var backupSuffix string |
| 81 | var tracedVariables []string |
| 82 | var errorLogger = errorsByType{data: make(map[string]datum)} |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 83 | var makefileFinder = &LinuxMakefileFinder{} |
Sasha Smundak | d7d07ad | 2021-09-10 15:42:34 -0700 | [diff] [blame] | 84 | var versionDefaultsMk = filepath.Join("build", "make", "core", "version_defaults.mk") |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 85 | |
| 86 | func main() { |
| 87 | flag.Usage = func() { |
| 88 | cmd := filepath.Base(os.Args[0]) |
| 89 | fmt.Fprintf(flag.CommandLine.Output(), |
| 90 | "Usage: %[1]s flags file...\n"+ |
| 91 | "or: %[1]s flags --launcher=PATH PRODUCT\n", cmd) |
| 92 | flag.PrintDefaults() |
| 93 | } |
| 94 | flag.Parse() |
| 95 | |
| 96 | // Delouse |
| 97 | if *suffix == ".mk" { |
| 98 | quit("cannot use .mk as generated file suffix") |
| 99 | } |
| 100 | if *suffix == "" { |
| 101 | quit("suffix cannot be empty") |
| 102 | } |
| 103 | if *outputTop != "" { |
| 104 | if err := os.MkdirAll(*outputTop, os.ModeDir+os.ModePerm); err != nil { |
| 105 | quit(err) |
| 106 | } |
| 107 | s, err := filepath.Abs(*outputTop) |
| 108 | if err != nil { |
| 109 | quit(err) |
| 110 | } |
| 111 | *outputTop = s |
| 112 | } |
| 113 | if *allInSource && len(flag.Args()) > 0 { |
| 114 | quit("file list cannot be specified when -all is present") |
| 115 | } |
| 116 | if *allInSource && *launcher != "" { |
| 117 | quit("--all and --launcher are mutually exclusive") |
| 118 | } |
| 119 | |
| 120 | // Flag-driven adjustments |
| 121 | if (*suffix)[0] != '.' { |
| 122 | *suffix = "." + *suffix |
| 123 | } |
| 124 | if *mode == "backup" { |
| 125 | backupSuffix = time.Now().Format("20060102150405") |
| 126 | } |
| 127 | if *traceVar != "" { |
| 128 | tracedVariables = strings.Split(*traceVar, ",") |
| 129 | } |
| 130 | |
Sasha Smundak | 3880279 | 2021-08-01 14:38:07 -0700 | [diff] [blame] | 131 | if *cpuProfile != "" { |
| 132 | f, err := os.Create(*cpuProfile) |
| 133 | if err != nil { |
| 134 | quit(err) |
| 135 | } |
| 136 | pprof.StartCPUProfile(f) |
| 137 | defer pprof.StopCPUProfile() |
| 138 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 139 | // Find out global variables |
| 140 | getConfigVariables() |
| 141 | getSoongVariables() |
| 142 | |
| 143 | if *printProductConfigMap { |
| 144 | productConfigMap := buildProductConfigMap() |
| 145 | var products []string |
| 146 | for p := range productConfigMap { |
| 147 | products = append(products, p) |
| 148 | } |
| 149 | sort.Strings(products) |
| 150 | for _, p := range products { |
| 151 | fmt.Println(p, productConfigMap[p]) |
| 152 | } |
| 153 | os.Exit(0) |
| 154 | } |
Sasha Smundak | b2ac859 | 2021-07-26 09:27:22 -0700 | [diff] [blame] | 155 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 156 | // Convert! |
Cole Faust | 07ea503 | 2021-09-30 16:11:16 -0700 | [diff] [blame] | 157 | files := flag.Args() |
Cole Faust | 07ea503 | 2021-09-30 16:11:16 -0700 | [diff] [blame] | 158 | if *allInSource { |
Cole Faust | ebf79bf | 2021-10-05 11:05:02 -0700 | [diff] [blame^] | 159 | productConfigMap := buildProductConfigMap() |
Cole Faust | 07ea503 | 2021-09-30 16:11:16 -0700 | [diff] [blame] | 160 | for _, path := range productConfigMap { |
| 161 | files = append(files, path) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 162 | } |
Cole Faust | 07ea503 | 2021-09-30 16:11:16 -0700 | [diff] [blame] | 163 | } |
Cole Faust | 07ea503 | 2021-09-30 16:11:16 -0700 | [diff] [blame] | 164 | ok := true |
| 165 | for _, mkFile := range files { |
| 166 | ok = convertOne(mkFile) && ok |
| 167 | } |
| 168 | |
| 169 | if *launcher != "" { |
| 170 | if len(files) != 1 { |
| 171 | quit(fmt.Errorf("a launcher can be generated only for a single product")) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 172 | } |
Sasha Smundak | d7d07ad | 2021-09-10 15:42:34 -0700 | [diff] [blame] | 173 | versionDefaults, err := generateVersionDefaults() |
| 174 | if err != nil { |
| 175 | quit(err) |
| 176 | } |
Sasha Smundak | d7d07ad | 2021-09-10 15:42:34 -0700 | [diff] [blame] | 177 | versionDefaultsPath := outputFilePath(versionDefaultsMk) |
| 178 | err = writeGenerated(versionDefaultsPath, versionDefaults) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 179 | if err != nil { |
Cole Faust | 07ea503 | 2021-09-30 16:11:16 -0700 | [diff] [blame] | 180 | fmt.Fprintf(os.Stderr, "%s:%s", files[0], err) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 181 | ok = false |
| 182 | } |
| 183 | |
Cole Faust | 07ea503 | 2021-09-30 16:11:16 -0700 | [diff] [blame] | 184 | err = writeGenerated(*launcher, mk2rbc.Launcher(outputFilePath(files[0]), versionDefaultsPath, |
| 185 | mk2rbc.MakePath2ModuleName(files[0]))) |
Sasha Smundak | d7d07ad | 2021-09-10 15:42:34 -0700 | [diff] [blame] | 186 | if err != nil { |
Cole Faust | 07ea503 | 2021-09-30 16:11:16 -0700 | [diff] [blame] | 187 | fmt.Fprintf(os.Stderr, "%s:%s", files[0], err) |
Sasha Smundak | d7d07ad | 2021-09-10 15:42:34 -0700 | [diff] [blame] | 188 | ok = false |
| 189 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 190 | } |
| 191 | |
| 192 | printStats() |
| 193 | if *errstat { |
| 194 | errorLogger.printStatistics() |
| 195 | } |
| 196 | if !ok { |
| 197 | os.Exit(1) |
| 198 | } |
| 199 | } |
| 200 | |
Sasha Smundak | d7d07ad | 2021-09-10 15:42:34 -0700 | [diff] [blame] | 201 | func generateVersionDefaults() (string, error) { |
| 202 | versionSettings, err := mk2rbc.ParseVersionDefaults(filepath.Join(*rootDir, versionDefaultsMk)) |
| 203 | if err != nil { |
| 204 | return "", err |
| 205 | } |
| 206 | return mk2rbc.VersionDefaults(versionSettings), nil |
| 207 | |
| 208 | } |
| 209 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 210 | func quit(s interface{}) { |
| 211 | fmt.Fprintln(os.Stderr, s) |
| 212 | os.Exit(2) |
| 213 | } |
| 214 | |
| 215 | func buildProductConfigMap() map[string]string { |
| 216 | const androidProductsMk = "AndroidProducts.mk" |
| 217 | // Build the list of AndroidProducts.mk files: it's |
Sasha Smundak | 70f1745 | 2021-09-01 19:14:24 -0700 | [diff] [blame] | 218 | // build/make/target/product/AndroidProducts.mk + device/**/AndroidProducts.mk plus + vendor/**/AndroidProducts.mk |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 219 | targetAndroidProductsFile := filepath.Join(*rootDir, "build", "make", "target", "product", androidProductsMk) |
| 220 | if _, err := os.Stat(targetAndroidProductsFile); err != nil { |
| 221 | fmt.Fprintf(os.Stderr, "%s: %s\n(hint: %s is not a source tree root)\n", |
| 222 | targetAndroidProductsFile, err, *rootDir) |
| 223 | } |
| 224 | productConfigMap := make(map[string]string) |
| 225 | if err := mk2rbc.UpdateProductConfigMap(productConfigMap, targetAndroidProductsFile); err != nil { |
| 226 | fmt.Fprintf(os.Stderr, "%s: %s\n", targetAndroidProductsFile, err) |
| 227 | } |
Sasha Smundak | 70f1745 | 2021-09-01 19:14:24 -0700 | [diff] [blame] | 228 | for _, t := range []string{"device", "vendor"} { |
| 229 | _ = filepath.WalkDir(filepath.Join(*rootDir, t), |
| 230 | func(path string, d os.DirEntry, err error) error { |
| 231 | if err != nil || d.IsDir() || filepath.Base(path) != androidProductsMk { |
| 232 | return nil |
| 233 | } |
| 234 | if err2 := mk2rbc.UpdateProductConfigMap(productConfigMap, path); err2 != nil { |
| 235 | fmt.Fprintf(os.Stderr, "%s: %s\n", path, err) |
| 236 | // Keep going, we want to find all such errors in a single run |
| 237 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 238 | return nil |
Sasha Smundak | 70f1745 | 2021-09-01 19:14:24 -0700 | [diff] [blame] | 239 | }) |
| 240 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 241 | return productConfigMap |
| 242 | } |
| 243 | |
| 244 | func getConfigVariables() { |
| 245 | path := filepath.Join(*rootDir, "build", "make", "core", "product.mk") |
| 246 | if err := mk2rbc.FindConfigVariables(path, mk2rbc.KnownVariables); err != nil { |
| 247 | quit(fmt.Errorf("%s\n(check --root[=%s], it should point to the source root)", |
| 248 | err, *rootDir)) |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | // Implements mkparser.Scope, to be used by mkparser.Value.Value() |
| 253 | type fileNameScope struct { |
| 254 | mk2rbc.ScopeBase |
| 255 | } |
| 256 | |
| 257 | func (s fileNameScope) Get(name string) string { |
| 258 | if name != "BUILD_SYSTEM" { |
| 259 | return fmt.Sprintf("$(%s)", name) |
| 260 | } |
| 261 | return filepath.Join(*rootDir, "build", "make", "core") |
| 262 | } |
| 263 | |
| 264 | func getSoongVariables() { |
| 265 | path := filepath.Join(*rootDir, "build", "make", "core", "soong_config.mk") |
| 266 | err := mk2rbc.FindSoongVariables(path, fileNameScope{}, mk2rbc.KnownVariables) |
| 267 | if err != nil { |
| 268 | quit(err) |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | var converted = make(map[string]*mk2rbc.StarlarkScript) |
| 273 | |
| 274 | //goland:noinspection RegExpRepeatedSpace |
| 275 | var cpNormalizer = regexp.MustCompile( |
| 276 | "# Copyright \\(C\\) 20.. The Android Open Source Project") |
| 277 | |
| 278 | const cpNormalizedCopyright = "# Copyright (C) 20xx The Android Open Source Project" |
| 279 | const copyright = `# |
| 280 | # Copyright (C) 20xx The Android Open Source Project |
| 281 | # |
| 282 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 283 | # you may not use this file except in compliance with the License. |
| 284 | # You may obtain a copy of the License at |
| 285 | # |
| 286 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 287 | # |
| 288 | # Unless required by applicable law or agreed to in writing, software |
| 289 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 290 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 291 | # See the License for the specific language governing permissions and |
| 292 | # limitations under the License. |
| 293 | # |
| 294 | ` |
| 295 | |
| 296 | // Convert a single file. |
| 297 | // Write the result either to the same directory, to the same place in |
| 298 | // the output hierarchy, or to the stdout. |
| 299 | // Optionally, recursively convert the files this one includes by |
| 300 | // $(call inherit-product) or an include statement. |
| 301 | func convertOne(mkFile string) (ok bool) { |
| 302 | if v, ok := converted[mkFile]; ok { |
| 303 | return v != nil |
| 304 | } |
| 305 | converted[mkFile] = nil |
| 306 | defer func() { |
| 307 | if r := recover(); r != nil { |
| 308 | ok = false |
| 309 | fmt.Fprintf(os.Stderr, "%s: panic while converting: %s\n%s\n", mkFile, r, debug.Stack()) |
| 310 | } |
| 311 | }() |
| 312 | |
| 313 | mk2starRequest := mk2rbc.Request{ |
| 314 | MkFile: mkFile, |
| 315 | Reader: nil, |
| 316 | RootDir: *rootDir, |
| 317 | OutputDir: *outputTop, |
| 318 | OutputSuffix: *suffix, |
| 319 | TracedVariables: tracedVariables, |
| 320 | TraceCalls: *traceCalls, |
| 321 | WarnPartialSuccess: *warn, |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 322 | SourceFS: os.DirFS(*rootDir), |
| 323 | MakefileFinder: makefileFinder, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 324 | } |
| 325 | if *errstat { |
| 326 | mk2starRequest.ErrorLogger = errorLogger |
| 327 | } |
| 328 | ss, err := mk2rbc.Convert(mk2starRequest) |
| 329 | if err != nil { |
| 330 | fmt.Fprintln(os.Stderr, mkFile, ": ", err) |
| 331 | return false |
| 332 | } |
| 333 | script := ss.String() |
| 334 | outputPath := outputFilePath(mkFile) |
| 335 | |
| 336 | if *dryRun { |
| 337 | fmt.Printf("==== %s ====\n", outputPath) |
| 338 | // Print generated script after removing the copyright header |
| 339 | outText := cpNormalizer.ReplaceAllString(script, cpNormalizedCopyright) |
| 340 | fmt.Println(strings.TrimPrefix(outText, copyright)) |
| 341 | } else { |
| 342 | if err := maybeBackup(outputPath); err != nil { |
| 343 | fmt.Fprintln(os.Stderr, err) |
| 344 | return false |
| 345 | } |
| 346 | if err := writeGenerated(outputPath, script); err != nil { |
| 347 | fmt.Fprintln(os.Stderr, err) |
| 348 | return false |
| 349 | } |
| 350 | } |
| 351 | ok = true |
| 352 | if *recurse { |
| 353 | for _, sub := range ss.SubConfigFiles() { |
| 354 | // File may be absent if it is a conditional load |
| 355 | if _, err := os.Stat(sub); os.IsNotExist(err) { |
| 356 | continue |
| 357 | } |
| 358 | ok = convertOne(sub) && ok |
| 359 | } |
| 360 | } |
| 361 | converted[mkFile] = ss |
| 362 | return ok |
| 363 | } |
| 364 | |
| 365 | // Optionally saves the previous version of the generated file |
| 366 | func maybeBackup(filename string) error { |
| 367 | stat, err := os.Stat(filename) |
| 368 | if os.IsNotExist(err) { |
| 369 | return nil |
| 370 | } |
| 371 | if !stat.Mode().IsRegular() { |
| 372 | return fmt.Errorf("%s exists and is not a regular file", filename) |
| 373 | } |
| 374 | switch *mode { |
| 375 | case "backup": |
| 376 | return os.Rename(filename, filename+backupSuffix) |
| 377 | case "write": |
| 378 | return os.Remove(filename) |
| 379 | default: |
| 380 | return fmt.Errorf("%s already exists, use --mode option", filename) |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | func outputFilePath(mkFile string) string { |
| 385 | path := strings.TrimSuffix(mkFile, filepath.Ext(mkFile)) + *suffix |
| 386 | if *outputTop != "" { |
| 387 | path = filepath.Join(*outputTop, path) |
| 388 | } |
| 389 | return path |
| 390 | } |
| 391 | |
| 392 | func writeGenerated(path string, contents string) error { |
| 393 | if err := os.MkdirAll(filepath.Dir(path), os.ModeDir|os.ModePerm); err != nil { |
| 394 | return err |
| 395 | } |
| 396 | if err := ioutil.WriteFile(path, []byte(contents), 0644); err != nil { |
| 397 | return err |
| 398 | } |
| 399 | return nil |
| 400 | } |
| 401 | |
| 402 | func printStats() { |
| 403 | var sortedFiles []string |
| 404 | if !*warn && !*verbose { |
| 405 | return |
| 406 | } |
| 407 | for p := range converted { |
| 408 | sortedFiles = append(sortedFiles, p) |
| 409 | } |
| 410 | sort.Strings(sortedFiles) |
| 411 | |
| 412 | nOk, nPartial, nFailed := 0, 0, 0 |
| 413 | for _, f := range sortedFiles { |
| 414 | if converted[f] == nil { |
| 415 | nFailed++ |
| 416 | } else if converted[f].HasErrors() { |
| 417 | nPartial++ |
| 418 | } else { |
| 419 | nOk++ |
| 420 | } |
| 421 | } |
| 422 | if *warn { |
| 423 | if nPartial > 0 { |
| 424 | fmt.Fprintf(os.Stderr, "Conversion was partially successful for:\n") |
| 425 | for _, f := range sortedFiles { |
| 426 | if ss := converted[f]; ss != nil && ss.HasErrors() { |
| 427 | fmt.Fprintln(os.Stderr, " ", f) |
| 428 | } |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | if nFailed > 0 { |
| 433 | fmt.Fprintf(os.Stderr, "Conversion failed for files:\n") |
| 434 | for _, f := range sortedFiles { |
| 435 | if converted[f] == nil { |
| 436 | fmt.Fprintln(os.Stderr, " ", f) |
| 437 | } |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | if *verbose { |
| 442 | fmt.Fprintf(os.Stderr, "%-16s%5d\n", "Succeeded:", nOk) |
| 443 | fmt.Fprintf(os.Stderr, "%-16s%5d\n", "Partial:", nPartial) |
| 444 | fmt.Fprintf(os.Stderr, "%-16s%5d\n", "Failed:", nFailed) |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | type datum struct { |
| 449 | count int |
| 450 | formattingArgs []string |
| 451 | } |
| 452 | |
| 453 | type errorsByType struct { |
| 454 | data map[string]datum |
| 455 | } |
| 456 | |
| 457 | func (ebt errorsByType) NewError(message string, node parser.Node, args ...interface{}) { |
| 458 | v, exists := ebt.data[message] |
| 459 | if exists { |
| 460 | v.count++ |
| 461 | } else { |
| 462 | v = datum{1, nil} |
| 463 | } |
| 464 | if strings.Contains(message, "%s") { |
| 465 | var newArg1 string |
| 466 | if len(args) == 0 { |
| 467 | panic(fmt.Errorf(`%s has %%s but args are missing`, message)) |
| 468 | } |
| 469 | newArg1 = fmt.Sprint(args[0]) |
| 470 | if message == "unsupported line" { |
| 471 | newArg1 = node.Dump() |
| 472 | } else if message == "unsupported directive %s" { |
| 473 | if newArg1 == "include" || newArg1 == "-include" { |
| 474 | newArg1 = node.Dump() |
| 475 | } |
| 476 | } |
| 477 | v.formattingArgs = append(v.formattingArgs, newArg1) |
| 478 | } |
| 479 | ebt.data[message] = v |
| 480 | } |
| 481 | |
| 482 | func (ebt errorsByType) printStatistics() { |
| 483 | if len(ebt.data) > 0 { |
| 484 | fmt.Fprintln(os.Stderr, "Error counts:") |
| 485 | } |
| 486 | for message, data := range ebt.data { |
| 487 | if len(data.formattingArgs) == 0 { |
| 488 | fmt.Fprintf(os.Stderr, "%4d %s\n", data.count, message) |
| 489 | continue |
| 490 | } |
| 491 | itemsByFreq, count := stringsWithFreq(data.formattingArgs, 30) |
| 492 | fmt.Fprintf(os.Stderr, "%4d %s [%d unique items]:\n", data.count, message, count) |
| 493 | fmt.Fprintln(os.Stderr, " ", itemsByFreq) |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | func stringsWithFreq(items []string, topN int) (string, int) { |
| 498 | freq := make(map[string]int) |
| 499 | for _, item := range items { |
| 500 | freq[strings.TrimPrefix(strings.TrimSuffix(item, "]"), "[")]++ |
| 501 | } |
| 502 | var sorted []string |
| 503 | for item := range freq { |
| 504 | sorted = append(sorted, item) |
| 505 | } |
| 506 | sort.Slice(sorted, func(i int, j int) bool { |
| 507 | return freq[sorted[i]] > freq[sorted[j]] |
| 508 | }) |
| 509 | sep := "" |
| 510 | res := "" |
| 511 | for i, item := range sorted { |
| 512 | if i >= topN { |
| 513 | res += " ..." |
| 514 | break |
| 515 | } |
| 516 | count := freq[item] |
| 517 | if count > 1 { |
| 518 | res += fmt.Sprintf("%s%s(%d)", sep, item, count) |
| 519 | } else { |
| 520 | res += fmt.Sprintf("%s%s", sep, item) |
| 521 | } |
| 522 | sep = ", " |
| 523 | } |
| 524 | return res, len(sorted) |
| 525 | } |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 526 | |
| 527 | type LinuxMakefileFinder struct { |
| 528 | cachedRoot string |
| 529 | cachedMakefiles []string |
| 530 | } |
| 531 | |
| 532 | func (l *LinuxMakefileFinder) Find(root string) []string { |
| 533 | if l.cachedMakefiles != nil && l.cachedRoot == root { |
| 534 | return l.cachedMakefiles |
| 535 | } |
| 536 | l.cachedRoot = root |
| 537 | l.cachedMakefiles = make([]string, 0) |
| 538 | |
| 539 | // Return all *.mk files but not in hidden directories. |
| 540 | |
| 541 | // NOTE(asmundak): as it turns out, even the WalkDir (which is an _optimized_ directory tree walker) |
| 542 | // is about twice slower than running `find` command (14s vs 6s on the internal Android source tree). |
| 543 | common_args := []string{"!", "-type", "d", "-name", "*.mk", "!", "-path", "*/.*/*"} |
| 544 | if root != "" { |
| 545 | common_args = append([]string{root}, common_args...) |
| 546 | } |
| 547 | cmd := exec.Command("/usr/bin/find", common_args...) |
| 548 | stdout, err := cmd.StdoutPipe() |
| 549 | if err == nil { |
| 550 | err = cmd.Start() |
| 551 | } |
| 552 | if err != nil { |
| 553 | panic(fmt.Errorf("cannot get the output from %s: %s", cmd, err)) |
| 554 | } |
| 555 | scanner := bufio.NewScanner(stdout) |
| 556 | for scanner.Scan() { |
| 557 | l.cachedMakefiles = append(l.cachedMakefiles, strings.TrimPrefix(scanner.Text(), "./")) |
| 558 | } |
| 559 | stdout.Close() |
| 560 | return l.cachedMakefiles |
| 561 | } |