1// Copyright 2017 Google Inc. All rights reserved. 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 15package android 16 17import ( 18 "bytes" 19 "fmt" 20 "path/filepath" 21 "regexp" 22 "sort" 23 "strings" 24 "sync" 25 "testing" 26 27 mkparser "android/soong/androidmk/parser" 28 29 "github.com/google/blueprint" 30 "github.com/google/blueprint/proptools" 31) 32 33func newTestContextForFixture(config Config) *TestContext { 34 ctx := &TestContext{ 35 Context: &Context{blueprint.NewContext(), config}, 36 } 37 38 ctx.postDeps = append(ctx.postDeps, registerPathDepsMutator) 39 40 ctx.SetFs(ctx.config.fs) 41 if ctx.config.mockBpList != "" { 42 ctx.SetModuleListFile(ctx.config.mockBpList) 43 } 44 45 return ctx 46} 47 48func NewTestContext(config Config) *TestContext { 49 ctx := newTestContextForFixture(config) 50 51 nameResolver := NewNameResolver(config) 52 ctx.NameResolver = nameResolver 53 ctx.SetNameInterface(nameResolver) 54 55 return ctx 56} 57 58var PrepareForTestWithArchMutator = GroupFixturePreparers( 59 // Configure architecture targets in the fixture config. 60 FixtureModifyConfig(modifyTestConfigToSupportArchMutator), 61 62 // Add the arch mutator to the context. 63 FixtureRegisterWithContext(func(ctx RegistrationContext) { 64 ctx.PreDepsMutators(registerArchMutator) 65 }), 66) 67 68var PrepareForTestWithDefaults = FixtureRegisterWithContext(func(ctx RegistrationContext) { 69 ctx.PreArchMutators(RegisterDefaultsPreArchMutators) 70}) 71 72var PrepareForTestWithComponentsMutator = FixtureRegisterWithContext(func(ctx RegistrationContext) { 73 ctx.PreArchMutators(RegisterComponentsMutator) 74}) 75 76var PrepareForTestWithPrebuilts = FixtureRegisterWithContext(RegisterPrebuiltMutators) 77 78var PrepareForTestWithOverrides = FixtureRegisterWithContext(func(ctx RegistrationContext) { 79 ctx.PostDepsMutators(RegisterOverridePostDepsMutators) 80}) 81 82var PrepareForTestWithLicenses = GroupFixturePreparers( 83 FixtureRegisterWithContext(RegisterLicenseKindBuildComponents), 84 FixtureRegisterWithContext(RegisterLicenseBuildComponents), 85 FixtureRegisterWithContext(registerLicenseMutators), 86) 87 88var PrepareForTestWithGenNotice = FixtureRegisterWithContext(RegisterGenNoticeBuildComponents) 89 90func registerLicenseMutators(ctx RegistrationContext) { 91 ctx.PreArchMutators(RegisterLicensesPackageMapper) 92 ctx.PreArchMutators(RegisterLicensesPropertyGatherer) 93 ctx.PostDepsMutators(RegisterLicensesDependencyChecker) 94} 95 96var PrepareForTestWithLicenseDefaultModules = GroupFixturePreparers( 97 FixtureAddTextFile("build/soong/licenses/Android.bp", ` 98 license { 99 name: "Android-Apache-2.0", 100 package_name: "Android", 101 license_kinds: ["SPDX-license-identifier-Apache-2.0"], 102 copyright_notice: "Copyright (C) The Android Open Source Project", 103 license_text: ["LICENSE"], 104 } 105 106 license_kind { 107 name: "SPDX-license-identifier-Apache-2.0", 108 conditions: ["notice"], 109 url: "https://spdx.org/licenses/Apache-2.0.html", 110 } 111 112 license_kind { 113 name: "legacy_unencumbered", 114 conditions: ["unencumbered"], 115 } 116 `), 117 FixtureAddFile("build/soong/licenses/LICENSE", nil), 118) 119 120var PrepareForTestWithNamespace = FixtureRegisterWithContext(func(ctx RegistrationContext) { 121 registerNamespaceBuildComponents(ctx) 122 ctx.PreArchMutators(RegisterNamespaceMutator) 123}) 124 125var PrepareForTestWithMakevars = FixtureRegisterWithContext(func(ctx RegistrationContext) { 126 ctx.RegisterSingletonType("makevars", makeVarsSingletonFunc) 127}) 128 129// Test fixture preparer that will register most java build components. 130// 131// Singletons and mutators should only be added here if they are needed for a majority of java 132// module types, otherwise they should be added under a separate preparer to allow them to be 133// selected only when needed to reduce test execution time. 134// 135// Module types do not have much of an overhead unless they are used so this should include as many 136// module types as possible. The exceptions are those module types that require mutators and/or 137// singletons in order to function in which case they should be kept together in a separate 138// preparer. 139// 140// The mutators in this group were chosen because they are needed by the vast majority of tests. 141var PrepareForTestWithAndroidBuildComponents = GroupFixturePreparers( 142 // Sorted alphabetically as the actual order does not matter as tests automatically enforce the 143 // correct order. 144 PrepareForTestWithArchMutator, 145 PrepareForTestWithComponentsMutator, 146 PrepareForTestWithDefaults, 147 PrepareForTestWithFilegroup, 148 PrepareForTestWithOverrides, 149 PrepareForTestWithPackageModule, 150 PrepareForTestWithPrebuilts, 151 PrepareForTestWithVisibility, 152) 153 154// Prepares an integration test with all build components from the android package. 155// 156// This should only be used by tests that want to run with as much of the build enabled as possible. 157var PrepareForIntegrationTestWithAndroid = GroupFixturePreparers( 158 PrepareForTestWithAndroidBuildComponents, 159) 160 161// Prepares a test that may be missing dependencies by setting allow_missing_dependencies to 162// true. 163var PrepareForTestWithAllowMissingDependencies = GroupFixturePreparers( 164 FixtureModifyProductVariables(func(variables FixtureProductVariables) { 165 variables.Allow_missing_dependencies = proptools.BoolPtr(true) 166 }), 167 FixtureModifyContext(func(ctx *TestContext) { 168 ctx.SetAllowMissingDependencies(true) 169 }), 170) 171 172// Prepares a test that disallows non-existent paths. 173var PrepareForTestDisallowNonExistentPaths = FixtureModifyConfig(func(config Config) { 174 config.TestAllowNonExistentPaths = false 175}) 176 177func NewTestArchContext(config Config) *TestContext { 178 ctx := NewTestContext(config) 179 ctx.preDeps = append(ctx.preDeps, registerArchMutator) 180 return ctx 181} 182 183type TestContext struct { 184 *Context 185 preArch, preDeps, postDeps, finalDeps []RegisterMutatorFunc 186 bp2buildPreArch, bp2buildMutators []RegisterMutatorFunc 187 NameResolver *NameResolver 188 189 // The list of pre-singletons and singletons registered for the test. 190 preSingletons, singletons sortableComponents 191 192 // The order in which the pre-singletons, mutators and singletons will be run in this test 193 // context; for debugging. 194 preSingletonOrder, mutatorOrder, singletonOrder []string 195} 196 197func (ctx *TestContext) PreArchMutators(f RegisterMutatorFunc) { 198 ctx.preArch = append(ctx.preArch, f) 199} 200 201func (ctx *TestContext) HardCodedPreArchMutators(f RegisterMutatorFunc) { 202 // Register mutator function as normal for testing. 203 ctx.PreArchMutators(f) 204} 205 206func (ctx *TestContext) ModuleProvider(m blueprint.Module, p blueprint.ProviderKey) interface{} { 207 return ctx.Context.ModuleProvider(m, p) 208} 209 210func (ctx *TestContext) PreDepsMutators(f RegisterMutatorFunc) { 211 ctx.preDeps = append(ctx.preDeps, f) 212} 213 214func (ctx *TestContext) PostDepsMutators(f RegisterMutatorFunc) { 215 ctx.postDeps = append(ctx.postDeps, f) 216} 217 218func (ctx *TestContext) FinalDepsMutators(f RegisterMutatorFunc) { 219 ctx.finalDeps = append(ctx.finalDeps, f) 220} 221 222func (ctx *TestContext) RegisterBp2BuildConfig(config Bp2BuildConversionAllowlist) { 223 ctx.config.Bp2buildPackageConfig = config 224} 225 226// PreArchBp2BuildMutators adds mutators to be register for converting Android Blueprint modules 227// into Bazel BUILD targets that should run prior to deps and conversion. 228func (ctx *TestContext) PreArchBp2BuildMutators(f RegisterMutatorFunc) { 229 ctx.bp2buildPreArch = append(ctx.bp2buildPreArch, f) 230} 231 232// registeredComponentOrder defines the order in which a sortableComponent type is registered at 233// runtime and provides support for reordering the components registered for a test in the same 234// way. 235type registeredComponentOrder struct { 236 // The name of the component type, used for error messages. 237 componentType string 238 239 // The names of the registered components in the order in which they were registered. 240 namesInOrder []string 241 242 // Maps from the component name to its position in the runtime ordering. 243 namesToIndex map[string]int 244 245 // A function that defines the order between two named components that can be used to sort a slice 246 // of component names into the same order as they appear in namesInOrder. 247 less func(string, string) bool 248} 249 250// registeredComponentOrderFromExistingOrder takes an existing slice of sortableComponents and 251// creates a registeredComponentOrder that contains a less function that can be used to sort a 252// subset of that list of names so it is in the same order as the original sortableComponents. 253func registeredComponentOrderFromExistingOrder(componentType string, existingOrder sortableComponents) registeredComponentOrder { 254 // Only the names from the existing order are needed for this so create a list of component names 255 // in the correct order. 256 namesInOrder := componentsToNames(existingOrder) 257 258 // Populate the map from name to position in the list. 259 nameToIndex := make(map[string]int) 260 for i, n := range namesInOrder { 261 nameToIndex[n] = i 262 } 263 264 // A function to use to map from a name to an index in the original order. 265 indexOf := func(name string) int { 266 index, ok := nameToIndex[name] 267 if !ok { 268 // Should never happen as tests that use components that are not known at runtime do not sort 269 // so should never use this function. 270 panic(fmt.Errorf("internal error: unknown %s %q should be one of %s", componentType, name, strings.Join(namesInOrder, ", "))) 271 } 272 return index 273 } 274 275 // The less function. 276 less := func(n1, n2 string) bool { 277 i1 := indexOf(n1) 278 i2 := indexOf(n2) 279 return i1 < i2 280 } 281 282 return registeredComponentOrder{ 283 componentType: componentType, 284 namesInOrder: namesInOrder, 285 namesToIndex: nameToIndex, 286 less: less, 287 } 288} 289 290// componentsToNames maps from the slice of components to a slice of their names. 291func componentsToNames(components sortableComponents) []string { 292 names := make([]string, len(components)) 293 for i, c := range components { 294 names[i] = c.componentName() 295 } 296 return names 297} 298 299// enforceOrdering enforces the supplied components are in the same order as is defined in this 300// object. 301// 302// If the supplied components contains any components that are not registered at runtime, i.e. test 303// specific components, then it is impossible to sort them into an order that both matches the 304// runtime and also preserves the implicit ordering defined in the test. In that case it will not 305// sort the components, instead it will just check that the components are in the correct order. 306// 307// Otherwise, this will sort the supplied components in place. 308func (o *registeredComponentOrder) enforceOrdering(components sortableComponents) { 309 // Check to see if the list of components contains any components that are 310 // not registered at runtime. 311 var unknownComponents []string 312 testOrder := componentsToNames(components) 313 for _, name := range testOrder { 314 if _, ok := o.namesToIndex[name]; !ok { 315 unknownComponents = append(unknownComponents, name) 316 break 317 } 318 } 319 320 // If the slice contains some unknown components then it is not possible to 321 // sort them into an order that matches the runtime while also preserving the 322 // order expected from the test, so in that case don't sort just check that 323 // the order of the known mutators does match. 324 if len(unknownComponents) > 0 { 325 // Check order. 326 o.checkTestOrder(testOrder, unknownComponents) 327 } else { 328 // Sort the components. 329 sort.Slice(components, func(i, j int) bool { 330 n1 := components[i].componentName() 331 n2 := components[j].componentName() 332 return o.less(n1, n2) 333 }) 334 } 335} 336 337// checkTestOrder checks that the supplied testOrder matches the one defined by this object, 338// panicking if it does not. 339func (o *registeredComponentOrder) checkTestOrder(testOrder []string, unknownComponents []string) { 340 lastMatchingTest := -1 341 matchCount := 0 342 // Take a copy of the runtime order as it is modified during the comparison. 343 runtimeOrder := append([]string(nil), o.namesInOrder...) 344 componentType := o.componentType 345 for i, j := 0, 0; i < len(testOrder) && j < len(runtimeOrder); { 346 test := testOrder[i] 347 runtime := runtimeOrder[j] 348 349 if test == runtime { 350 testOrder[i] = test + fmt.Sprintf(" <-- matched with runtime %s %d", componentType, j) 351 runtimeOrder[j] = runtime + fmt.Sprintf(" <-- matched with test %s %d", componentType, i) 352 lastMatchingTest = i 353 i += 1 354 j += 1 355 matchCount += 1 356 } else if _, ok := o.namesToIndex[test]; !ok { 357 // The test component is not registered globally so assume it is the correct place, treat it 358 // as having matched and skip it. 359 i += 1 360 matchCount += 1 361 } else { 362 // Assume that the test list is in the same order as the runtime list but the runtime list 363 // contains some components that are not present in the tests. So, skip the runtime component 364 // to try and find the next one that matches the current test component. 365 j += 1 366 } 367 } 368 369 // If every item in the test order was either test specific or matched one in the runtime then 370 // it is in the correct order. Otherwise, it was not so fail. 371 if matchCount != len(testOrder) { 372 // The test component names were not all matched with a runtime component name so there must 373 // either be a component present in the test that is not present in the runtime or they must be 374 // in the wrong order. 375 testOrder[lastMatchingTest+1] = testOrder[lastMatchingTest+1] + " <--- unmatched" 376 panic(fmt.Errorf("the tests uses test specific components %q and so cannot be automatically sorted."+ 377 " Unfortunately it uses %s components in the wrong order.\n"+ 378 "test order:\n %s\n"+ 379 "runtime order\n %s\n", 380 SortedUniqueStrings(unknownComponents), 381 componentType, 382 strings.Join(testOrder, "\n "), 383 strings.Join(runtimeOrder, "\n "))) 384 } 385} 386 387// registrationSorter encapsulates the information needed to ensure that the test mutators are 388// registered, and thereby executed, in the same order as they are at runtime. 389// 390// It MUST be populated lazily AFTER all package initialization has been done otherwise it will 391// only define the order for a subset of all the registered build components that are available for 392// the packages being tested. 393// 394// e.g if this is initialized during say the cc package initialization then any tests run in the 395// java package will not sort build components registered by the java package's init() functions. 396type registrationSorter struct { 397 // Used to ensure that this is only created once. 398 once sync.Once 399 400 // The order of pre-singletons 401 preSingletonOrder registeredComponentOrder 402 403 // The order of mutators 404 mutatorOrder registeredComponentOrder 405 406 // The order of singletons 407 singletonOrder registeredComponentOrder 408} 409 410// populate initializes this structure from globally registered build components. 411// 412// Only the first call has any effect. 413func (s *registrationSorter) populate() { 414 s.once.Do(func() { 415 // Create an ordering from the globally registered pre-singletons. 416 s.preSingletonOrder = registeredComponentOrderFromExistingOrder("pre-singleton", preSingletons) 417 418 // Created an ordering from the globally registered mutators. 419 globallyRegisteredMutators := collateGloballyRegisteredMutators() 420 s.mutatorOrder = registeredComponentOrderFromExistingOrder("mutator", globallyRegisteredMutators) 421 422 // Create an ordering from the globally registered singletons. 423 globallyRegisteredSingletons := collateGloballyRegisteredSingletons() 424 s.singletonOrder = registeredComponentOrderFromExistingOrder("singleton", globallyRegisteredSingletons) 425 }) 426} 427 428// Provides support for enforcing the same order in which build components are registered globally 429// to the order in which they are registered during tests. 430// 431// MUST only be accessed via the globallyRegisteredComponentsOrder func. 432var globalRegistrationSorter registrationSorter 433 434// globallyRegisteredComponentsOrder returns the globalRegistrationSorter after ensuring it is 435// correctly populated. 436func globallyRegisteredComponentsOrder() *registrationSorter { 437 globalRegistrationSorter.populate() 438 return &globalRegistrationSorter 439} 440 441func (ctx *TestContext) Register() { 442 globalOrder := globallyRegisteredComponentsOrder() 443 444 // Ensure that the pre-singletons used in the test are in the same order as they are used at 445 // runtime. 446 globalOrder.preSingletonOrder.enforceOrdering(ctx.preSingletons) 447 ctx.preSingletons.registerAll(ctx.Context) 448 449 mutators := collateRegisteredMutators(ctx.preArch, ctx.preDeps, ctx.postDeps, ctx.finalDeps) 450 // Ensure that the mutators used in the test are in the same order as they are used at runtime. 451 globalOrder.mutatorOrder.enforceOrdering(mutators) 452 mutators.registerAll(ctx.Context) 453 454 // Ensure that the singletons used in the test are in the same order as they are used at runtime. 455 globalOrder.singletonOrder.enforceOrdering(ctx.singletons) 456 ctx.singletons.registerAll(ctx.Context) 457 458 // Save the sorted components order away to make them easy to access while debugging. 459 ctx.preSingletonOrder = componentsToNames(preSingletons) 460 ctx.mutatorOrder = componentsToNames(mutators) 461 ctx.singletonOrder = componentsToNames(singletons) 462} 463 464// RegisterForBazelConversion prepares a test context for bp2build conversion. 465func (ctx *TestContext) RegisterForBazelConversion() { 466 ctx.config.BuildMode = Bp2build 467 RegisterMutatorsForBazelConversion(ctx.Context, ctx.bp2buildPreArch) 468} 469 470// RegisterForApiBazelConversion prepares a test context for API bp2build conversion. 471func (ctx *TestContext) RegisterForApiBazelConversion() { 472 ctx.config.BuildMode = ApiBp2build 473 RegisterMutatorsForApiBazelConversion(ctx.Context, ctx.bp2buildPreArch) 474} 475 476func (ctx *TestContext) ParseFileList(rootDir string, filePaths []string) (deps []string, errs []error) { 477 // This function adapts the old style ParseFileList calls that are spread throughout the tests 478 // to the new style that takes a config. 479 return ctx.Context.ParseFileList(rootDir, filePaths, ctx.config) 480} 481 482func (ctx *TestContext) ParseBlueprintsFiles(rootDir string) (deps []string, errs []error) { 483 // This function adapts the old style ParseBlueprintsFiles calls that are spread throughout the 484 // tests to the new style that takes a config. 485 return ctx.Context.ParseBlueprintsFiles(rootDir, ctx.config) 486} 487 488func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) { 489 ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory)) 490} 491 492func (ctx *TestContext) RegisterSingletonModuleType(name string, factory SingletonModuleFactory) { 493 s, m := SingletonModuleFactoryAdaptor(name, factory) 494 ctx.RegisterSingletonType(name, s) 495 ctx.RegisterModuleType(name, m) 496} 497 498func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) { 499 ctx.singletons = append(ctx.singletons, newSingleton(name, factory)) 500} 501 502func (ctx *TestContext) RegisterPreSingletonType(name string, factory SingletonFactory) { 503 ctx.preSingletons = append(ctx.preSingletons, newPreSingleton(name, factory)) 504} 505 506// ModuleVariantForTests selects a specific variant of the module with the given 507// name by matching the variations map against the variations of each module 508// variant. A module variant matches the map if every variation that exists in 509// both have the same value. Both the module and the map are allowed to have 510// extra variations that the other doesn't have. Panics if not exactly one 511// module variant matches. 512func (ctx *TestContext) ModuleVariantForTests(name string, matchVariations map[string]string) TestingModule { 513 modules := []Module{} 514 ctx.VisitAllModules(func(m blueprint.Module) { 515 if ctx.ModuleName(m) == name { 516 am := m.(Module) 517 amMut := am.base().commonProperties.DebugMutators 518 amVar := am.base().commonProperties.DebugVariations 519 matched := true 520 for i, mut := range amMut { 521 if wantedVar, found := matchVariations[mut]; found && amVar[i] != wantedVar { 522 matched = false 523 break 524 } 525 } 526 if matched { 527 modules = append(modules, am) 528 } 529 } 530 }) 531 532 if len(modules) == 0 { 533 // Show all the modules or module variants that do exist. 534 var allModuleNames []string 535 var allVariants []string 536 ctx.VisitAllModules(func(m blueprint.Module) { 537 allModuleNames = append(allModuleNames, ctx.ModuleName(m)) 538 if ctx.ModuleName(m) == name { 539 allVariants = append(allVariants, m.(Module).String()) 540 } 541 }) 542 543 if len(allVariants) == 0 { 544 panic(fmt.Errorf("failed to find module %q. All modules:\n %s", 545 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n "))) 546 } else { 547 sort.Strings(allVariants) 548 panic(fmt.Errorf("failed to find module %q matching %v. All variants:\n %s", 549 name, matchVariations, strings.Join(allVariants, "\n "))) 550 } 551 } 552 553 if len(modules) > 1 { 554 moduleStrings := []string{} 555 for _, m := range modules { 556 moduleStrings = append(moduleStrings, m.String()) 557 } 558 sort.Strings(moduleStrings) 559 panic(fmt.Errorf("module %q has more than one variant that match %v:\n %s", 560 name, matchVariations, strings.Join(moduleStrings, "\n "))) 561 } 562 563 return newTestingModule(ctx.config, modules[0]) 564} 565 566func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule { 567 var module Module 568 ctx.VisitAllModules(func(m blueprint.Module) { 569 if ctx.ModuleName(m) == name && ctx.ModuleSubDir(m) == variant { 570 module = m.(Module) 571 } 572 }) 573 574 if module == nil { 575 // find all the modules that do exist 576 var allModuleNames []string 577 var allVariants []string 578 ctx.VisitAllModules(func(m blueprint.Module) { 579 allModuleNames = append(allModuleNames, ctx.ModuleName(m)) 580 if ctx.ModuleName(m) == name { 581 allVariants = append(allVariants, ctx.ModuleSubDir(m)) 582 } 583 }) 584 sort.Strings(allVariants) 585 586 if len(allVariants) == 0 { 587 panic(fmt.Errorf("failed to find module %q. All modules:\n %s", 588 name, strings.Join(SortedUniqueStrings(allModuleNames), "\n "))) 589 } else { 590 panic(fmt.Errorf("failed to find module %q variant %q. All variants:\n %s", 591 name, variant, strings.Join(allVariants, "\n "))) 592 } 593 } 594 595 return newTestingModule(ctx.config, module) 596} 597 598func (ctx *TestContext) ModuleVariantsForTests(name string) []string { 599 var variants []string 600 ctx.VisitAllModules(func(m blueprint.Module) { 601 if ctx.ModuleName(m) == name { 602 variants = append(variants, ctx.ModuleSubDir(m)) 603 } 604 }) 605 return variants 606} 607 608// SingletonForTests returns a TestingSingleton for the singleton registered with the given name. 609func (ctx *TestContext) SingletonForTests(name string) TestingSingleton { 610 allSingletonNames := []string{} 611 for _, s := range ctx.Singletons() { 612 n := ctx.SingletonName(s) 613 if n == name { 614 return TestingSingleton{ 615 baseTestingComponent: newBaseTestingComponent(ctx.config, s.(testBuildProvider)), 616 singleton: s.(*singletonAdaptor).Singleton, 617 } 618 } 619 allSingletonNames = append(allSingletonNames, n) 620 } 621 622 panic(fmt.Errorf("failed to find singleton %q."+ 623 "\nall singletons: %v", name, allSingletonNames)) 624} 625 626type InstallMakeRule struct { 627 Target string 628 Deps []string 629 OrderOnlyDeps []string 630} 631 632func parseMkRules(t *testing.T, config Config, nodes []mkparser.Node) []InstallMakeRule { 633 var rules []InstallMakeRule 634 for _, node := range nodes { 635 if mkParserRule, ok := node.(*mkparser.Rule); ok { 636 var rule InstallMakeRule 637 638 if targets := mkParserRule.Target.Words(); len(targets) == 0 { 639 t.Fatalf("no targets for rule %s", mkParserRule.Dump()) 640 } else if len(targets) > 1 { 641 t.Fatalf("unsupported multiple targets for rule %s", mkParserRule.Dump()) 642 } else if !targets[0].Const() { 643 t.Fatalf("unsupported non-const target for rule %s", mkParserRule.Dump()) 644 } else { 645 rule.Target = normalizeStringRelativeToTop(config, targets[0].Value(nil)) 646 } 647 648 prereqList := &rule.Deps 649 for _, prereq := range mkParserRule.Prerequisites.Words() { 650 if !prereq.Const() { 651 t.Fatalf("unsupported non-const prerequisite for rule %s", mkParserRule.Dump()) 652 } 653 654 if prereq.Value(nil) == "|" { 655 prereqList = &rule.OrderOnlyDeps 656 continue 657 } 658 659 *prereqList = append(*prereqList, normalizeStringRelativeToTop(config, prereq.Value(nil))) 660 } 661 662 rules = append(rules, rule) 663 } 664 } 665 666 return rules 667} 668 669func (ctx *TestContext) InstallMakeRulesForTesting(t *testing.T) []InstallMakeRule { 670 installs := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).installsForTesting 671 buf := bytes.NewBuffer(append([]byte(nil), installs...)) 672 parser := mkparser.NewParser("makevars", buf) 673 674 nodes, errs := parser.Parse() 675 if len(errs) > 0 { 676 t.Fatalf("error parsing install rules: %s", errs[0]) 677 } 678 679 return parseMkRules(t, ctx.config, nodes) 680} 681 682// MakeVarVariable provides access to make vars that will be written by the makeVarsSingleton 683type MakeVarVariable interface { 684 // Name is the name of the variable. 685 Name() string 686 687 // Value is the value of the variable. 688 Value() string 689} 690 691func (v makeVarsVariable) Name() string { 692 return v.name 693} 694 695func (v makeVarsVariable) Value() string { 696 return v.value 697} 698 699// PrepareForTestAccessingMakeVars sets up the test so that MakeVarsForTesting will work. 700var PrepareForTestAccessingMakeVars = GroupFixturePreparers( 701 PrepareForTestWithAndroidMk, 702 PrepareForTestWithMakevars, 703) 704 705// MakeVarsForTesting returns a filtered list of MakeVarVariable objects that represent the 706// variables that will be written out. 707// 708// It is necessary to use PrepareForTestAccessingMakeVars in tests that want to call this function. 709// Along with any other preparers needed to add the make vars. 710func (ctx *TestContext) MakeVarsForTesting(filter func(variable MakeVarVariable) bool) []MakeVarVariable { 711 vars := ctx.SingletonForTests("makevars").Singleton().(*makeVarsSingleton).varsForTesting 712 result := make([]MakeVarVariable, 0, len(vars)) 713 for _, v := range vars { 714 if filter(v) { 715 result = append(result, v) 716 } 717 } 718 719 return result 720} 721 722func (ctx *TestContext) Config() Config { 723 return ctx.config 724} 725 726type testBuildProvider interface { 727 BuildParamsForTests() []BuildParams 728 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams 729} 730 731type TestingBuildParams struct { 732 BuildParams 733 RuleParams blueprint.RuleParams 734 735 config Config 736} 737 738// RelativeToTop creates a new instance of this which has had any usages of the current test's 739// temporary and test specific build directory replaced with a path relative to the notional top. 740// 741// The parts of this structure which are changed are: 742// * BuildParams 743// - Args 744// - All Path, Paths, WritablePath and WritablePaths fields. 745// 746// * RuleParams 747// - Command 748// - Depfile 749// - Rspfile 750// - RspfileContent 751// - SymlinkOutputs 752// - CommandDeps 753// - CommandOrderOnly 754// 755// See PathRelativeToTop for more details. 756// 757// deprecated: this is no longer needed as TestingBuildParams are created in this form. 758func (p TestingBuildParams) RelativeToTop() TestingBuildParams { 759 // If this is not a valid params then just return it back. That will make it easy to use with the 760 // Maybe...() methods. 761 if p.Rule == nil { 762 return p 763 } 764 if p.config.config == nil { 765 return p 766 } 767 // Take a copy of the build params and replace any args that contains test specific temporary 768 // paths with paths relative to the top. 769 bparams := p.BuildParams 770 bparams.Depfile = normalizeWritablePathRelativeToTop(bparams.Depfile) 771 bparams.Output = normalizeWritablePathRelativeToTop(bparams.Output) 772 bparams.Outputs = bparams.Outputs.RelativeToTop() 773 bparams.SymlinkOutput = normalizeWritablePathRelativeToTop(bparams.SymlinkOutput) 774 bparams.SymlinkOutputs = bparams.SymlinkOutputs.RelativeToTop() 775 bparams.ImplicitOutput = normalizeWritablePathRelativeToTop(bparams.ImplicitOutput) 776 bparams.ImplicitOutputs = bparams.ImplicitOutputs.RelativeToTop() 777 bparams.Input = normalizePathRelativeToTop(bparams.Input) 778 bparams.Inputs = bparams.Inputs.RelativeToTop() 779 bparams.Implicit = normalizePathRelativeToTop(bparams.Implicit) 780 bparams.Implicits = bparams.Implicits.RelativeToTop() 781 bparams.OrderOnly = bparams.OrderOnly.RelativeToTop() 782 bparams.Validation = normalizePathRelativeToTop(bparams.Validation) 783 bparams.Validations = bparams.Validations.RelativeToTop() 784 bparams.Args = normalizeStringMapRelativeToTop(p.config, bparams.Args) 785 786 // Ditto for any fields in the RuleParams. 787 rparams := p.RuleParams 788 rparams.Command = normalizeStringRelativeToTop(p.config, rparams.Command) 789 rparams.Depfile = normalizeStringRelativeToTop(p.config, rparams.Depfile) 790 rparams.Rspfile = normalizeStringRelativeToTop(p.config, rparams.Rspfile) 791 rparams.RspfileContent = normalizeStringRelativeToTop(p.config, rparams.RspfileContent) 792 rparams.SymlinkOutputs = normalizeStringArrayRelativeToTop(p.config, rparams.SymlinkOutputs) 793 rparams.CommandDeps = normalizeStringArrayRelativeToTop(p.config, rparams.CommandDeps) 794 rparams.CommandOrderOnly = normalizeStringArrayRelativeToTop(p.config, rparams.CommandOrderOnly) 795 796 return TestingBuildParams{ 797 BuildParams: bparams, 798 RuleParams: rparams, 799 } 800} 801 802func normalizeWritablePathRelativeToTop(path WritablePath) WritablePath { 803 if path == nil { 804 return nil 805 } 806 return path.RelativeToTop().(WritablePath) 807} 808 809func normalizePathRelativeToTop(path Path) Path { 810 if path == nil { 811 return nil 812 } 813 return path.RelativeToTop() 814} 815 816func allOutputs(p BuildParams) []string { 817 outputs := append(WritablePaths(nil), p.Outputs...) 818 outputs = append(outputs, p.ImplicitOutputs...) 819 if p.Output != nil { 820 outputs = append(outputs, p.Output) 821 } 822 return outputs.Strings() 823} 824 825// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms. 826func (p TestingBuildParams) AllOutputs() []string { 827 return allOutputs(p.BuildParams) 828} 829 830// baseTestingComponent provides functionality common to both TestingModule and TestingSingleton. 831type baseTestingComponent struct { 832 config Config 833 provider testBuildProvider 834} 835 836func newBaseTestingComponent(config Config, provider testBuildProvider) baseTestingComponent { 837 return baseTestingComponent{config, provider} 838} 839 840// A function that will normalize a string containing paths, e.g. ninja command, by replacing 841// any references to the test specific temporary build directory that changes with each run to a 842// fixed path relative to a notional top directory. 843// 844// This is similar to StringPathRelativeToTop except that assumes the string is a single path 845// containing at most one instance of the temporary build directory at the start of the path while 846// this assumes that there can be any number at any position. 847func normalizeStringRelativeToTop(config Config, s string) string { 848 // The soongOutDir usually looks something like: /tmp/testFoo2345/001 849 // 850 // Replace any usage of the soongOutDir with out/soong, e.g. replace "/tmp/testFoo2345/001" with 851 // "out/soong". 852 outSoongDir := filepath.Clean(config.soongOutDir) 853 re := regexp.MustCompile(`\Q` + outSoongDir + `\E\b`) 854 s = re.ReplaceAllString(s, "out/soong") 855 856 // Replace any usage of the soongOutDir/.. with out, e.g. replace "/tmp/testFoo2345" with 857 // "out". This must come after the previous replacement otherwise this would replace 858 // "/tmp/testFoo2345/001" with "out/001" instead of "out/soong". 859 outDir := filepath.Dir(outSoongDir) 860 re = regexp.MustCompile(`\Q` + outDir + `\E\b`) 861 s = re.ReplaceAllString(s, "out") 862 863 return s 864} 865 866// normalizeStringArrayRelativeToTop creates a new slice constructed by applying 867// normalizeStringRelativeToTop to each item in the slice. 868func normalizeStringArrayRelativeToTop(config Config, slice []string) []string { 869 newSlice := make([]string, len(slice)) 870 for i, s := range slice { 871 newSlice[i] = normalizeStringRelativeToTop(config, s) 872 } 873 return newSlice 874} 875 876// normalizeStringMapRelativeToTop creates a new map constructed by applying 877// normalizeStringRelativeToTop to each value in the map. 878func normalizeStringMapRelativeToTop(config Config, m map[string]string) map[string]string { 879 newMap := map[string]string{} 880 for k, v := range m { 881 newMap[k] = normalizeStringRelativeToTop(config, v) 882 } 883 return newMap 884} 885 886func (b baseTestingComponent) newTestingBuildParams(bparams BuildParams) TestingBuildParams { 887 return TestingBuildParams{ 888 config: b.config, 889 BuildParams: bparams, 890 RuleParams: b.provider.RuleParamsForTests()[bparams.Rule], 891 }.RelativeToTop() 892} 893 894func (b baseTestingComponent) maybeBuildParamsFromRule(rule string) (TestingBuildParams, []string) { 895 var searchedRules []string 896 buildParams := b.provider.BuildParamsForTests() 897 for _, p := range buildParams { 898 ruleAsString := p.Rule.String() 899 searchedRules = append(searchedRules, ruleAsString) 900 if strings.Contains(ruleAsString, rule) { 901 return b.newTestingBuildParams(p), searchedRules 902 } 903 } 904 return TestingBuildParams{}, searchedRules 905} 906 907func (b baseTestingComponent) buildParamsFromRule(rule string) TestingBuildParams { 908 p, searchRules := b.maybeBuildParamsFromRule(rule) 909 if p.Rule == nil { 910 panic(fmt.Errorf("couldn't find rule %q.\nall rules:\n%s", rule, strings.Join(searchRules, "\n"))) 911 } 912 return p 913} 914 915func (b baseTestingComponent) maybeBuildParamsFromDescription(desc string) (TestingBuildParams, []string) { 916 var searchedDescriptions []string 917 for _, p := range b.provider.BuildParamsForTests() { 918 searchedDescriptions = append(searchedDescriptions, p.Description) 919 if strings.Contains(p.Description, desc) { 920 return b.newTestingBuildParams(p), searchedDescriptions 921 } 922 } 923 return TestingBuildParams{}, searchedDescriptions 924} 925 926func (b baseTestingComponent) buildParamsFromDescription(desc string) TestingBuildParams { 927 p, searchedDescriptions := b.maybeBuildParamsFromDescription(desc) 928 if p.Rule == nil { 929 panic(fmt.Errorf("couldn't find description %q\nall descriptions:\n%s", desc, strings.Join(searchedDescriptions, "\n"))) 930 } 931 return p 932} 933 934func (b baseTestingComponent) maybeBuildParamsFromOutput(file string) (TestingBuildParams, []string) { 935 searchedOutputs := WritablePaths(nil) 936 for _, p := range b.provider.BuildParamsForTests() { 937 outputs := append(WritablePaths(nil), p.Outputs...) 938 outputs = append(outputs, p.ImplicitOutputs...) 939 if p.Output != nil { 940 outputs = append(outputs, p.Output) 941 } 942 for _, f := range outputs { 943 if f.String() == file || f.Rel() == file || PathRelativeToTop(f) == file { 944 return b.newTestingBuildParams(p), nil 945 } 946 searchedOutputs = append(searchedOutputs, f) 947 } 948 } 949 950 formattedOutputs := []string{} 951 for _, f := range searchedOutputs { 952 formattedOutputs = append(formattedOutputs, 953 fmt.Sprintf("%s (rel=%s)", PathRelativeToTop(f), f.Rel())) 954 } 955 956 return TestingBuildParams{}, formattedOutputs 957} 958 959func (b baseTestingComponent) buildParamsFromOutput(file string) TestingBuildParams { 960 p, searchedOutputs := b.maybeBuildParamsFromOutput(file) 961 if p.Rule == nil { 962 panic(fmt.Errorf("couldn't find output %q.\nall outputs:\n %s\n", 963 file, strings.Join(searchedOutputs, "\n "))) 964 } 965 return p 966} 967 968func (b baseTestingComponent) allOutputs() []string { 969 var outputFullPaths []string 970 for _, p := range b.provider.BuildParamsForTests() { 971 outputFullPaths = append(outputFullPaths, allOutputs(p)...) 972 } 973 return outputFullPaths 974} 975 976// MaybeRule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Returns an empty 977// BuildParams if no rule is found. 978func (b baseTestingComponent) MaybeRule(rule string) TestingBuildParams { 979 r, _ := b.maybeBuildParamsFromRule(rule) 980 return r 981} 982 983// Rule finds a call to ctx.Build with BuildParams.Rule set to a rule with the given name. Panics if no rule is found. 984func (b baseTestingComponent) Rule(rule string) TestingBuildParams { 985 return b.buildParamsFromRule(rule) 986} 987 988// MaybeDescription finds a call to ctx.Build with BuildParams.Description set to a the given string. Returns an empty 989// BuildParams if no rule is found. 990func (b baseTestingComponent) MaybeDescription(desc string) TestingBuildParams { 991 p, _ := b.maybeBuildParamsFromDescription(desc) 992 return p 993} 994 995// Description finds a call to ctx.Build with BuildParams.Description set to a the given string. Panics if no rule is 996// found. 997func (b baseTestingComponent) Description(desc string) TestingBuildParams { 998 return b.buildParamsFromDescription(desc) 999} 1000 1001// MaybeOutput finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel() 1002// value matches the provided string. Returns an empty BuildParams if no rule is found. 1003func (b baseTestingComponent) MaybeOutput(file string) TestingBuildParams { 1004 p, _ := b.maybeBuildParamsFromOutput(file) 1005 return p 1006} 1007 1008// Output finds a call to ctx.Build with a BuildParams.Output or BuildParams.Outputs whose String() or Rel() 1009// value matches the provided string. Panics if no rule is found. 1010func (b baseTestingComponent) Output(file string) TestingBuildParams { 1011 return b.buildParamsFromOutput(file) 1012} 1013 1014// AllOutputs returns all 'BuildParams.Output's and 'BuildParams.Outputs's in their full path string forms. 1015func (b baseTestingComponent) AllOutputs() []string { 1016 return b.allOutputs() 1017} 1018 1019// TestingModule is wrapper around an android.Module that provides methods to find information about individual 1020// ctx.Build parameters for verification in tests. 1021type TestingModule struct { 1022 baseTestingComponent 1023 module Module 1024} 1025 1026func newTestingModule(config Config, module Module) TestingModule { 1027 return TestingModule{ 1028 newBaseTestingComponent(config, module), 1029 module, 1030 } 1031} 1032 1033// Module returns the Module wrapped by the TestingModule. 1034func (m TestingModule) Module() Module { 1035 return m.module 1036} 1037 1038// VariablesForTestsRelativeToTop returns a copy of the Module.VariablesForTests() with every value 1039// having any temporary build dir usages replaced with paths relative to a notional top. 1040func (m TestingModule) VariablesForTestsRelativeToTop() map[string]string { 1041 return normalizeStringMapRelativeToTop(m.config, m.module.VariablesForTests()) 1042} 1043 1044// OutputFiles calls OutputFileProducer.OutputFiles on the encapsulated module, exits the test 1045// immediately if there is an error and otherwise returns the result of calling Paths.RelativeToTop 1046// on the returned Paths. 1047func (m TestingModule) OutputFiles(t *testing.T, tag string) Paths { 1048 producer, ok := m.module.(OutputFileProducer) 1049 if !ok { 1050 t.Fatalf("%q must implement OutputFileProducer\n", m.module.Name()) 1051 } 1052 paths, err := producer.OutputFiles(tag) 1053 if err != nil { 1054 t.Fatal(err) 1055 } 1056 1057 return paths.RelativeToTop() 1058} 1059 1060// TestingSingleton is wrapper around an android.Singleton that provides methods to find information about individual 1061// ctx.Build parameters for verification in tests. 1062type TestingSingleton struct { 1063 baseTestingComponent 1064 singleton Singleton 1065} 1066 1067// Singleton returns the Singleton wrapped by the TestingSingleton. 1068func (s TestingSingleton) Singleton() Singleton { 1069 return s.singleton 1070} 1071 1072func FailIfErrored(t *testing.T, errs []error) { 1073 t.Helper() 1074 if len(errs) > 0 { 1075 for _, err := range errs { 1076 t.Error(err) 1077 } 1078 t.FailNow() 1079 } 1080} 1081 1082// Fail if no errors that matched the regular expression were found. 1083// 1084// Returns true if a matching error was found, false otherwise. 1085func FailIfNoMatchingErrors(t *testing.T, pattern string, errs []error) bool { 1086 t.Helper() 1087 1088 matcher, err := regexp.Compile(pattern) 1089 if err != nil { 1090 t.Fatalf("failed to compile regular expression %q because %s", pattern, err) 1091 } 1092 1093 found := false 1094 for _, err := range errs { 1095 if matcher.FindStringIndex(err.Error()) != nil { 1096 found = true 1097 break 1098 } 1099 } 1100 if !found { 1101 t.Errorf("could not match the expected error regex %q (checked %d error(s))", pattern, len(errs)) 1102 for i, err := range errs { 1103 t.Errorf("errs[%d] = %q", i, err) 1104 } 1105 } 1106 1107 return found 1108} 1109 1110func CheckErrorsAgainstExpectations(t *testing.T, errs []error, expectedErrorPatterns []string) { 1111 t.Helper() 1112 1113 if expectedErrorPatterns == nil { 1114 FailIfErrored(t, errs) 1115 } else { 1116 for _, expectedError := range expectedErrorPatterns { 1117 FailIfNoMatchingErrors(t, expectedError, errs) 1118 } 1119 if len(errs) > len(expectedErrorPatterns) { 1120 t.Errorf("additional errors found, expected %d, found %d", 1121 len(expectedErrorPatterns), len(errs)) 1122 for i, expectedError := range expectedErrorPatterns { 1123 t.Errorf("expectedErrors[%d] = %s", i, expectedError) 1124 } 1125 for i, err := range errs { 1126 t.Errorf("errs[%d] = %s", i, err) 1127 } 1128 t.FailNow() 1129 } 1130 } 1131} 1132 1133func SetKatiEnabledForTests(config Config) { 1134 config.katiEnabled = true 1135} 1136 1137func SetTrimmedApexEnabledForTests(config Config) { 1138 config.productVariables.TrimmedApex = new(bool) 1139 *config.productVariables.TrimmedApex = true 1140} 1141 1142func AndroidMkEntriesForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) []AndroidMkEntries { 1143 t.Helper() 1144 var p AndroidMkEntriesProvider 1145 var ok bool 1146 if p, ok = mod.(AndroidMkEntriesProvider); !ok { 1147 t.Errorf("module does not implement AndroidMkEntriesProvider: " + mod.Name()) 1148 } 1149 1150 entriesList := p.AndroidMkEntries() 1151 for i, _ := range entriesList { 1152 entriesList[i].fillInEntries(ctx, mod) 1153 } 1154 return entriesList 1155} 1156 1157func AndroidMkDataForTest(t *testing.T, ctx *TestContext, mod blueprint.Module) AndroidMkData { 1158 t.Helper() 1159 var p AndroidMkDataProvider 1160 var ok bool 1161 if p, ok = mod.(AndroidMkDataProvider); !ok { 1162 t.Fatalf("module does not implement AndroidMkDataProvider: " + mod.Name()) 1163 } 1164 data := p.AndroidMk() 1165 data.fillInData(ctx, mod) 1166 return data 1167} 1168 1169// Normalize the path for testing. 1170// 1171// If the path is relative to the build directory then return the relative path 1172// to avoid tests having to deal with the dynamically generated build directory. 1173// 1174// Otherwise, return the supplied path as it is almost certainly a source path 1175// that is relative to the root of the source tree. 1176// 1177// The build and source paths should be distinguishable based on their contents. 1178// 1179// deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates 1180// between output and source properly. 1181func NormalizePathForTesting(path Path) string { 1182 if path == nil { 1183 return "<nil path>" 1184 } 1185 p := path.String() 1186 if w, ok := path.(WritablePath); ok { 1187 rel, err := filepath.Rel(w.getSoongOutDir(), p) 1188 if err != nil { 1189 panic(err) 1190 } 1191 return rel 1192 } 1193 return p 1194} 1195 1196// NormalizePathsForTesting creates a slice of strings where each string is the result of applying 1197// NormalizePathForTesting to the corresponding Path in the input slice. 1198// 1199// deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates 1200// between output and source properly. 1201func NormalizePathsForTesting(paths Paths) []string { 1202 var result []string 1203 for _, path := range paths { 1204 relative := NormalizePathForTesting(path) 1205 result = append(result, relative) 1206 } 1207 return result 1208} 1209 1210// PathRelativeToTop returns a string representation of the path relative to a notional top 1211// directory. 1212// 1213// It return "<nil path>" if the supplied path is nil, otherwise it returns the result of calling 1214// Path.RelativeToTop to obtain a relative Path and then calling Path.String on that to get the 1215// string representation. 1216func PathRelativeToTop(path Path) string { 1217 if path == nil { 1218 return "<nil path>" 1219 } 1220 return path.RelativeToTop().String() 1221} 1222 1223// PathsRelativeToTop creates a slice of strings where each string is the result of applying 1224// PathRelativeToTop to the corresponding Path in the input slice. 1225func PathsRelativeToTop(paths Paths) []string { 1226 var result []string 1227 for _, path := range paths { 1228 relative := PathRelativeToTop(path) 1229 result = append(result, relative) 1230 } 1231 return result 1232} 1233 1234// StringPathRelativeToTop returns a string representation of the path relative to a notional top 1235// directory. 1236// 1237// See Path.RelativeToTop for more details as to what `relative to top` means. 1238// 1239// This is provided for processing paths that have already been converted into a string, e.g. paths 1240// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against 1241// which it can try and relativize paths. PathRelativeToTop must be used for process Path objects. 1242func StringPathRelativeToTop(soongOutDir string, path string) string { 1243 ensureTestOnly() 1244 1245 // A relative path must be a source path so leave it as it is. 1246 if !filepath.IsAbs(path) { 1247 return path 1248 } 1249 1250 // Check to see if the path is relative to the soong out dir. 1251 rel, isRel, err := maybeRelErr(soongOutDir, path) 1252 if err != nil { 1253 panic(err) 1254 } 1255 1256 if isRel { 1257 // The path is in the soong out dir so indicate that in the relative path. 1258 return filepath.Join("out/soong", rel) 1259 } 1260 1261 // Check to see if the path is relative to the top level out dir. 1262 outDir := filepath.Dir(soongOutDir) 1263 rel, isRel, err = maybeRelErr(outDir, path) 1264 if err != nil { 1265 panic(err) 1266 } 1267 1268 if isRel { 1269 // The path is in the out dir so indicate that in the relative path. 1270 return filepath.Join("out", rel) 1271 } 1272 1273 // This should never happen. 1274 panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir)) 1275} 1276 1277// StringPathsRelativeToTop creates a slice of strings where each string is the result of applying 1278// StringPathRelativeToTop to the corresponding string path in the input slice. 1279// 1280// This is provided for processing paths that have already been converted into a string, e.g. paths 1281// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against 1282// which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects. 1283func StringPathsRelativeToTop(soongOutDir string, paths []string) []string { 1284 var result []string 1285 for _, path := range paths { 1286 relative := StringPathRelativeToTop(soongOutDir, path) 1287 result = append(result, relative) 1288 } 1289 return result 1290} 1291 1292// StringRelativeToTop will normalize a string containing paths, e.g. ninja command, by replacing 1293// any references to the test specific temporary build directory that changes with each run to a 1294// fixed path relative to a notional top directory. 1295// 1296// This is similar to StringPathRelativeToTop except that assumes the string is a single path 1297// containing at most one instance of the temporary build directory at the start of the path while 1298// this assumes that there can be any number at any position. 1299func StringRelativeToTop(config Config, command string) string { 1300 return normalizeStringRelativeToTop(config, command) 1301} 1302 1303// StringsRelativeToTop will return a new slice such that each item in the new slice is the result 1304// of calling StringRelativeToTop on the corresponding item in the input slice. 1305func StringsRelativeToTop(config Config, command []string) []string { 1306 return normalizeStringArrayRelativeToTop(config, command) 1307} 1308