variable.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. // Copyright 2015 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. package android
  15. import (
  16. "fmt"
  17. "reflect"
  18. "runtime"
  19. "strings"
  20. "github.com/google/blueprint/proptools"
  21. )
  22. func init() {
  23. registerVariableBuildComponents(InitRegistrationContext)
  24. }
  25. func registerVariableBuildComponents(ctx RegistrationContext) {
  26. ctx.PreDepsMutators(func(ctx RegisterMutatorsContext) {
  27. ctx.BottomUp("variable", VariableMutator).Parallel()
  28. })
  29. }
  30. var PrepareForTestWithVariables = FixtureRegisterWithContext(registerVariableBuildComponents)
  31. type variableProperties struct {
  32. Product_variables struct {
  33. Platform_sdk_version struct {
  34. Asflags []string
  35. Cflags []string
  36. }
  37. // unbundled_build is a catch-all property to annotate modules that don't build in one or
  38. // more unbundled branches, usually due to dependencies missing from the manifest.
  39. Unbundled_build struct {
  40. Enabled *bool `android:"arch_variant"`
  41. } `android:"arch_variant"`
  42. Malloc_not_svelte struct {
  43. Cflags []string `android:"arch_variant"`
  44. Shared_libs []string `android:"arch_variant"`
  45. Whole_static_libs []string `android:"arch_variant"`
  46. Exclude_static_libs []string `android:"arch_variant"`
  47. } `android:"arch_variant"`
  48. Malloc_zero_contents struct {
  49. Cflags []string `android:"arch_variant"`
  50. } `android:"arch_variant"`
  51. Malloc_pattern_fill_contents struct {
  52. Cflags []string `android:"arch_variant"`
  53. } `android:"arch_variant"`
  54. Safestack struct {
  55. Cflags []string `android:"arch_variant"`
  56. } `android:"arch_variant"`
  57. Binder32bit struct {
  58. Cflags []string
  59. }
  60. Override_rs_driver struct {
  61. Cflags []string
  62. }
  63. // treble_linker_namespaces is true when the system/vendor linker namespace separation is
  64. // enabled.
  65. Treble_linker_namespaces struct {
  66. Cflags []string
  67. }
  68. // enforce_vintf_manifest is true when a device is required to have a vintf manifest.
  69. Enforce_vintf_manifest struct {
  70. Cflags []string
  71. }
  72. // debuggable is true for eng and userdebug builds, and can be used to turn on additional
  73. // debugging features that don't significantly impact runtime behavior. userdebug builds
  74. // are used for dogfooding and performance testing, and should be as similar to user builds
  75. // as possible.
  76. Debuggable struct {
  77. Cflags []string
  78. Cppflags []string
  79. Init_rc []string
  80. Required []string
  81. Host_required []string
  82. Target_required []string
  83. Strip struct {
  84. All *bool
  85. Keep_symbols *bool
  86. Keep_symbols_and_debug_frame *bool
  87. }
  88. }
  89. // eng is true for -eng builds, and can be used to turn on additionaly heavyweight debugging
  90. // features.
  91. Eng struct {
  92. Cflags []string
  93. Cppflags []string
  94. Lto struct {
  95. Never *bool
  96. }
  97. Sanitize struct {
  98. Address *bool
  99. }
  100. Optimize struct {
  101. Enabled *bool
  102. }
  103. }
  104. Pdk struct {
  105. Enabled *bool `android:"arch_variant"`
  106. } `android:"arch_variant"`
  107. Uml struct {
  108. Cppflags []string
  109. }
  110. Arc struct {
  111. Cflags []string `android:"arch_variant"`
  112. Exclude_srcs []string `android:"arch_variant"`
  113. Include_dirs []string `android:"arch_variant"`
  114. Shared_libs []string `android:"arch_variant"`
  115. Static_libs []string `android:"arch_variant"`
  116. Srcs []string `android:"arch_variant"`
  117. Whole_static_libs []string `android:"arch_variant"`
  118. } `android:"arch_variant"`
  119. Flatten_apex struct {
  120. Enabled *bool
  121. }
  122. Native_coverage struct {
  123. Src *string `android:"arch_variant"`
  124. Srcs []string `android:"arch_variant"`
  125. Exclude_srcs []string `android:"arch_variant"`
  126. } `android:"arch_variant"`
  127. } `android:"arch_variant"`
  128. }
  129. var defaultProductVariables interface{} = variableProperties{}
  130. type productVariables struct {
  131. // Suffix to add to generated Makefiles
  132. Make_suffix *string `json:",omitempty"`
  133. BuildId *string `json:",omitempty"`
  134. BuildNumberFile *string `json:",omitempty"`
  135. Platform_version_name *string `json:",omitempty"`
  136. Platform_sdk_version *int `json:",omitempty"`
  137. Platform_sdk_codename *string `json:",omitempty"`
  138. Platform_sdk_final *bool `json:",omitempty"`
  139. Platform_version_active_codenames []string `json:",omitempty"`
  140. Platform_vndk_version *string `json:",omitempty"`
  141. Platform_systemsdk_versions []string `json:",omitempty"`
  142. Platform_security_patch *string `json:",omitempty"`
  143. Platform_preview_sdk_version *string `json:",omitempty"`
  144. Platform_min_supported_target_sdk_version *string `json:",omitempty"`
  145. Platform_base_os *string `json:",omitempty"`
  146. DeviceName *string `json:",omitempty"`
  147. DeviceArch *string `json:",omitempty"`
  148. DeviceArchVariant *string `json:",omitempty"`
  149. DeviceCpuVariant *string `json:",omitempty"`
  150. DeviceAbi []string `json:",omitempty"`
  151. DeviceVndkVersion *string `json:",omitempty"`
  152. DeviceCurrentApiLevelForVendorModules *string `json:",omitempty"`
  153. DeviceSystemSdkVersions []string `json:",omitempty"`
  154. RecoverySnapshotVersion *string `json:",omitempty"`
  155. DeviceSecondaryArch *string `json:",omitempty"`
  156. DeviceSecondaryArchVariant *string `json:",omitempty"`
  157. DeviceSecondaryCpuVariant *string `json:",omitempty"`
  158. DeviceSecondaryAbi []string `json:",omitempty"`
  159. NativeBridgeArch *string `json:",omitempty"`
  160. NativeBridgeArchVariant *string `json:",omitempty"`
  161. NativeBridgeCpuVariant *string `json:",omitempty"`
  162. NativeBridgeAbi []string `json:",omitempty"`
  163. NativeBridgeRelativePath *string `json:",omitempty"`
  164. NativeBridgeSecondaryArch *string `json:",omitempty"`
  165. NativeBridgeSecondaryArchVariant *string `json:",omitempty"`
  166. NativeBridgeSecondaryCpuVariant *string `json:",omitempty"`
  167. NativeBridgeSecondaryAbi []string `json:",omitempty"`
  168. NativeBridgeSecondaryRelativePath *string `json:",omitempty"`
  169. HostArch *string `json:",omitempty"`
  170. HostSecondaryArch *string `json:",omitempty"`
  171. CrossHost *string `json:",omitempty"`
  172. CrossHostArch *string `json:",omitempty"`
  173. CrossHostSecondaryArch *string `json:",omitempty"`
  174. DeviceResourceOverlays []string `json:",omitempty"`
  175. ProductResourceOverlays []string `json:",omitempty"`
  176. EnforceRROTargets []string `json:",omitempty"`
  177. EnforceRROExcludedOverlays []string `json:",omitempty"`
  178. AAPTCharacteristics *string `json:",omitempty"`
  179. AAPTConfig []string `json:",omitempty"`
  180. AAPTPreferredConfig *string `json:",omitempty"`
  181. AAPTPrebuiltDPI []string `json:",omitempty"`
  182. DefaultAppCertificate *string `json:",omitempty"`
  183. AppsDefaultVersionName *string `json:",omitempty"`
  184. Allow_missing_dependencies *bool `json:",omitempty"`
  185. Unbundled_build *bool `json:",omitempty"`
  186. Unbundled_build_apps *bool `json:",omitempty"`
  187. Always_use_prebuilt_sdks *bool `json:",omitempty"`
  188. Skip_boot_jars_check *bool `json:",omitempty"`
  189. Malloc_not_svelte *bool `json:",omitempty"`
  190. Malloc_zero_contents *bool `json:",omitempty"`
  191. Malloc_pattern_fill_contents *bool `json:",omitempty"`
  192. Safestack *bool `json:",omitempty"`
  193. HostStaticBinaries *bool `json:",omitempty"`
  194. Binder32bit *bool `json:",omitempty"`
  195. UseGoma *bool `json:",omitempty"`
  196. UseRBE *bool `json:",omitempty"`
  197. UseRBEJAVAC *bool `json:",omitempty"`
  198. UseRBER8 *bool `json:",omitempty"`
  199. UseRBED8 *bool `json:",omitempty"`
  200. Debuggable *bool `json:",omitempty"`
  201. Eng *bool `json:",omitempty"`
  202. Treble_linker_namespaces *bool `json:",omitempty"`
  203. Enforce_vintf_manifest *bool `json:",omitempty"`
  204. Uml *bool `json:",omitempty"`
  205. Arc *bool `json:",omitempty"`
  206. MinimizeJavaDebugInfo *bool `json:",omitempty"`
  207. Check_elf_files *bool `json:",omitempty"`
  208. UncompressPrivAppDex *bool `json:",omitempty"`
  209. ModulesLoadedByPrivilegedModules []string `json:",omitempty"`
  210. BootJars ConfiguredJarList `json:",omitempty"`
  211. UpdatableBootJars ConfiguredJarList `json:",omitempty"`
  212. IntegerOverflowExcludePaths []string `json:",omitempty"`
  213. EnableCFI *bool `json:",omitempty"`
  214. CFIExcludePaths []string `json:",omitempty"`
  215. CFIIncludePaths []string `json:",omitempty"`
  216. DisableScudo *bool `json:",omitempty"`
  217. MemtagHeapExcludePaths []string `json:",omitempty"`
  218. MemtagHeapAsyncIncludePaths []string `json:",omitempty"`
  219. MemtagHeapSyncIncludePaths []string `json:",omitempty"`
  220. VendorPath *string `json:",omitempty"`
  221. OdmPath *string `json:",omitempty"`
  222. ProductPath *string `json:",omitempty"`
  223. SystemExtPath *string `json:",omitempty"`
  224. ClangTidy *bool `json:",omitempty"`
  225. TidyChecks *string `json:",omitempty"`
  226. SamplingPGO *bool `json:",omitempty"`
  227. JavaCoveragePaths []string `json:",omitempty"`
  228. JavaCoverageExcludePaths []string `json:",omitempty"`
  229. GcovCoverage *bool `json:",omitempty"`
  230. ClangCoverage *bool `json:",omitempty"`
  231. NativeCoveragePaths []string `json:",omitempty"`
  232. NativeCoverageExcludePaths []string `json:",omitempty"`
  233. // Set by NewConfig
  234. Native_coverage *bool
  235. SanitizeHost []string `json:",omitempty"`
  236. SanitizeDevice []string `json:",omitempty"`
  237. SanitizeDeviceDiag []string `json:",omitempty"`
  238. SanitizeDeviceArch []string `json:",omitempty"`
  239. ArtUseReadBarrier *bool `json:",omitempty"`
  240. BtConfigIncludeDir *string `json:",omitempty"`
  241. Override_rs_driver *string `json:",omitempty"`
  242. Fuchsia *bool `json:",omitempty"`
  243. DeviceKernelHeaders []string `json:",omitempty"`
  244. ExtraVndkVersions []string `json:",omitempty"`
  245. NamespacesToExport []string `json:",omitempty"`
  246. PgoAdditionalProfileDirs []string `json:",omitempty"`
  247. VndkUseCoreVariant *bool `json:",omitempty"`
  248. VndkSnapshotBuildArtifacts *bool `json:",omitempty"`
  249. DirectedVendorSnapshot bool `json:",omitempty"`
  250. VendorSnapshotModules map[string]bool `json:",omitempty"`
  251. DirectedRecoverySnapshot bool `json:",omitempty"`
  252. RecoverySnapshotModules map[string]bool `json:",omitempty"`
  253. VendorSnapshotDirsIncluded []string `json:",omitempty"`
  254. VendorSnapshotDirsExcluded []string `json:",omitempty"`
  255. RecoverySnapshotDirsExcluded []string `json:",omitempty"`
  256. RecoverySnapshotDirsIncluded []string `json:",omitempty"`
  257. BoardVendorSepolicyDirs []string `json:",omitempty"`
  258. BoardOdmSepolicyDirs []string `json:",omitempty"`
  259. BoardReqdMaskPolicy []string `json:",omitempty"`
  260. SystemExtPublicSepolicyDirs []string `json:",omitempty"`
  261. SystemExtPrivateSepolicyDirs []string `json:",omitempty"`
  262. BoardSepolicyM4Defs []string `json:",omitempty"`
  263. BoardSepolicyVers *string `json:",omitempty"`
  264. PlatformSepolicyVersion *string `json:",omitempty"`
  265. VendorVars map[string]map[string]string `json:",omitempty"`
  266. Ndk_abis *bool `json:",omitempty"`
  267. Exclude_draft_ndk_apis *bool `json:",omitempty"`
  268. Flatten_apex *bool `json:",omitempty"`
  269. ForceApexSymlinkOptimization *bool `json:",omitempty"`
  270. CompressedApex *bool `json:",omitempty"`
  271. Aml_abis *bool `json:",omitempty"`
  272. DexpreoptGlobalConfig *string `json:",omitempty"`
  273. ManifestPackageNameOverrides []string `json:",omitempty"`
  274. CertificateOverrides []string `json:",omitempty"`
  275. PackageNameOverrides []string `json:",omitempty"`
  276. EnforceSystemCertificate *bool `json:",omitempty"`
  277. EnforceSystemCertificateAllowList []string `json:",omitempty"`
  278. ProductHiddenAPIStubs []string `json:",omitempty"`
  279. ProductHiddenAPIStubsSystem []string `json:",omitempty"`
  280. ProductHiddenAPIStubsTest []string `json:",omitempty"`
  281. ProductPublicSepolicyDirs []string `json:",omitempty"`
  282. ProductPrivateSepolicyDirs []string `json:",omitempty"`
  283. ProductVndkVersion *string `json:",omitempty"`
  284. TargetFSConfigGen []string `json:",omitempty"`
  285. MissingUsesLibraries []string `json:",omitempty"`
  286. EnforceProductPartitionInterface *bool `json:",omitempty"`
  287. EnforceInterPartitionJavaSdkLibrary *bool `json:",omitempty"`
  288. InterPartitionJavaLibraryAllowList []string `json:",omitempty"`
  289. InstallExtraFlattenedApexes *bool `json:",omitempty"`
  290. BoardUsesRecoveryAsBoot *bool `json:",omitempty"`
  291. BoardKernelBinaries []string `json:",omitempty"`
  292. BoardKernelModuleInterfaceVersions []string `json:",omitempty"`
  293. BoardMoveRecoveryResourcesToVendorBoot *bool `json:",omitempty"`
  294. PrebuiltHiddenApiDir *string `json:",omitempty"`
  295. ShippingApiLevel *string `json:",omitempty"`
  296. BuildBrokenVendorPropertyNamespace bool `json:",omitempty"`
  297. }
  298. func boolPtr(v bool) *bool {
  299. return &v
  300. }
  301. func intPtr(v int) *int {
  302. return &v
  303. }
  304. func stringPtr(v string) *string {
  305. return &v
  306. }
  307. func (v *productVariables) SetDefaultConfig() {
  308. *v = productVariables{
  309. BuildNumberFile: stringPtr("build_number.txt"),
  310. Platform_version_name: stringPtr("S"),
  311. Platform_sdk_version: intPtr(30),
  312. Platform_sdk_codename: stringPtr("S"),
  313. Platform_sdk_final: boolPtr(false),
  314. Platform_version_active_codenames: []string{"S"},
  315. Platform_vndk_version: stringPtr("S"),
  316. HostArch: stringPtr("x86_64"),
  317. HostSecondaryArch: stringPtr("x86"),
  318. DeviceName: stringPtr("generic_arm64"),
  319. DeviceArch: stringPtr("arm64"),
  320. DeviceArchVariant: stringPtr("armv8-a"),
  321. DeviceCpuVariant: stringPtr("generic"),
  322. DeviceAbi: []string{"arm64-v8a"},
  323. DeviceSecondaryArch: stringPtr("arm"),
  324. DeviceSecondaryArchVariant: stringPtr("armv8-a"),
  325. DeviceSecondaryCpuVariant: stringPtr("generic"),
  326. DeviceSecondaryAbi: []string{"armeabi-v7a", "armeabi"},
  327. AAPTConfig: []string{"normal", "large", "xlarge", "hdpi", "xhdpi", "xxhdpi"},
  328. AAPTPreferredConfig: stringPtr("xhdpi"),
  329. AAPTCharacteristics: stringPtr("nosdcard"),
  330. AAPTPrebuiltDPI: []string{"xhdpi", "xxhdpi"},
  331. Malloc_not_svelte: boolPtr(true),
  332. Malloc_zero_contents: boolPtr(true),
  333. Malloc_pattern_fill_contents: boolPtr(false),
  334. Safestack: boolPtr(false),
  335. BootJars: ConfiguredJarList{apexes: []string{}, jars: []string{}},
  336. UpdatableBootJars: ConfiguredJarList{apexes: []string{}, jars: []string{}},
  337. }
  338. if runtime.GOOS == "linux" {
  339. v.CrossHost = stringPtr("windows")
  340. v.CrossHostArch = stringPtr("x86")
  341. v.CrossHostSecondaryArch = stringPtr("x86_64")
  342. }
  343. }
  344. func VariableMutator(mctx BottomUpMutatorContext) {
  345. var module Module
  346. var ok bool
  347. if module, ok = mctx.Module().(Module); !ok {
  348. return
  349. }
  350. // TODO: depend on config variable, create variants, propagate variants up tree
  351. a := module.base()
  352. if a.variableProperties == nil {
  353. return
  354. }
  355. variableValues := reflect.ValueOf(a.variableProperties).Elem().FieldByName("Product_variables")
  356. productVariables := reflect.ValueOf(mctx.Config().productVariables)
  357. for i := 0; i < variableValues.NumField(); i++ {
  358. variableValue := variableValues.Field(i)
  359. name := variableValues.Type().Field(i).Name
  360. property := "product_variables." + proptools.PropertyNameForField(name)
  361. // Check that the variable was set for the product
  362. val := productVariables.FieldByName(name)
  363. if !val.IsValid() || val.Kind() != reflect.Ptr || val.IsNil() {
  364. continue
  365. }
  366. val = val.Elem()
  367. // For bools, check that the value is true
  368. if val.Kind() == reflect.Bool && val.Bool() == false {
  369. continue
  370. }
  371. // Check if any properties were set for the module
  372. if variableValue.IsZero() {
  373. continue
  374. }
  375. a.setVariableProperties(mctx, property, variableValue, val.Interface())
  376. }
  377. }
  378. func (m *ModuleBase) setVariableProperties(ctx BottomUpMutatorContext,
  379. prefix string, productVariablePropertyValue reflect.Value, variableValue interface{}) {
  380. printfIntoProperties(ctx, prefix, productVariablePropertyValue, variableValue)
  381. err := proptools.AppendMatchingProperties(m.generalProperties,
  382. productVariablePropertyValue.Addr().Interface(), nil)
  383. if err != nil {
  384. if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok {
  385. ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error())
  386. } else {
  387. panic(err)
  388. }
  389. }
  390. }
  391. func printfIntoPropertiesError(ctx BottomUpMutatorContext, prefix string,
  392. productVariablePropertyValue reflect.Value, i int, err error) {
  393. field := productVariablePropertyValue.Type().Field(i).Name
  394. property := prefix + "." + proptools.PropertyNameForField(field)
  395. ctx.PropertyErrorf(property, "%s", err)
  396. }
  397. func printfIntoProperties(ctx BottomUpMutatorContext, prefix string,
  398. productVariablePropertyValue reflect.Value, variableValue interface{}) {
  399. for i := 0; i < productVariablePropertyValue.NumField(); i++ {
  400. propertyValue := productVariablePropertyValue.Field(i)
  401. kind := propertyValue.Kind()
  402. if kind == reflect.Ptr {
  403. if propertyValue.IsNil() {
  404. continue
  405. }
  406. propertyValue = propertyValue.Elem()
  407. }
  408. switch propertyValue.Kind() {
  409. case reflect.String:
  410. err := printfIntoProperty(propertyValue, variableValue)
  411. if err != nil {
  412. printfIntoPropertiesError(ctx, prefix, productVariablePropertyValue, i, err)
  413. }
  414. case reflect.Slice:
  415. for j := 0; j < propertyValue.Len(); j++ {
  416. err := printfIntoProperty(propertyValue.Index(j), variableValue)
  417. if err != nil {
  418. printfIntoPropertiesError(ctx, prefix, productVariablePropertyValue, i, err)
  419. }
  420. }
  421. case reflect.Bool:
  422. // Nothing
  423. case reflect.Struct:
  424. printfIntoProperties(ctx, prefix, propertyValue, variableValue)
  425. default:
  426. panic(fmt.Errorf("unsupported field kind %q", propertyValue.Kind()))
  427. }
  428. }
  429. }
  430. func printfIntoProperty(propertyValue reflect.Value, variableValue interface{}) error {
  431. s := propertyValue.String()
  432. count := strings.Count(s, "%")
  433. if count == 0 {
  434. return nil
  435. }
  436. if count > 1 {
  437. return fmt.Errorf("product variable properties only support a single '%%'")
  438. }
  439. if strings.Contains(s, "%d") {
  440. switch v := variableValue.(type) {
  441. case int:
  442. // Nothing
  443. case bool:
  444. if v {
  445. variableValue = 1
  446. } else {
  447. variableValue = 0
  448. }
  449. default:
  450. return fmt.Errorf("unsupported type %T for %%d", variableValue)
  451. }
  452. } else if strings.Contains(s, "%s") {
  453. switch variableValue.(type) {
  454. case string:
  455. // Nothing
  456. default:
  457. return fmt.Errorf("unsupported type %T for %%s", variableValue)
  458. }
  459. } else {
  460. return fmt.Errorf("unsupported %% in product variable property")
  461. }
  462. propertyValue.Set(reflect.ValueOf(fmt.Sprintf(s, variableValue)))
  463. return nil
  464. }
  465. var variablePropTypeMap OncePer
  466. // sliceToTypeArray takes a slice of property structs and returns a reflection created array containing the
  467. // reflect.Types of each property struct. The result can be used as a key in a map.
  468. func sliceToTypeArray(s []interface{}) interface{} {
  469. // Create an array using reflection whose length is the length of the input slice
  470. ret := reflect.New(reflect.ArrayOf(len(s), reflect.TypeOf(reflect.TypeOf(0)))).Elem()
  471. for i, e := range s {
  472. ret.Index(i).Set(reflect.ValueOf(reflect.TypeOf(e)))
  473. }
  474. return ret.Interface()
  475. }
  476. func initProductVariableModule(m Module) {
  477. base := m.base()
  478. // Allow tests to override the default product variables
  479. if base.variableProperties == nil {
  480. base.variableProperties = defaultProductVariables
  481. }
  482. // Filter the product variables properties to the ones that exist on this module
  483. base.variableProperties = createVariableProperties(m.GetProperties(), base.variableProperties)
  484. if base.variableProperties != nil {
  485. m.AddProperties(base.variableProperties)
  486. }
  487. }
  488. // createVariableProperties takes the list of property structs for a module and returns a property struct that
  489. // contains the product variable properties that exist in the property structs, or nil if there are none. It
  490. // caches the result.
  491. func createVariableProperties(moduleTypeProps []interface{}, productVariables interface{}) interface{} {
  492. // Convert the moduleTypeProps to an array of reflect.Types that can be used as a key in the OncePer.
  493. key := sliceToTypeArray(moduleTypeProps)
  494. // Use the variablePropTypeMap OncePer to cache the result for each set of property struct types.
  495. typ, _ := variablePropTypeMap.Once(NewCustomOnceKey(key), func() interface{} {
  496. // Compute the filtered property struct type.
  497. return createVariablePropertiesType(moduleTypeProps, productVariables)
  498. }).(reflect.Type)
  499. if typ == nil {
  500. return nil
  501. }
  502. // Create a new pointer to a filtered property struct.
  503. return reflect.New(typ).Interface()
  504. }
  505. // createVariablePropertiesType creates a new type that contains only the product variable properties that exist in
  506. // a list of property structs.
  507. func createVariablePropertiesType(moduleTypeProps []interface{}, productVariables interface{}) reflect.Type {
  508. typ, _ := proptools.FilterPropertyStruct(reflect.TypeOf(productVariables),
  509. func(field reflect.StructField, prefix string) (bool, reflect.StructField) {
  510. // Filter function, returns true if the field should be in the resulting struct
  511. if prefix == "" {
  512. // Keep the top level Product_variables field
  513. return true, field
  514. }
  515. _, rest := splitPrefix(prefix)
  516. if rest == "" {
  517. // Keep the 2nd level field (i.e. Product_variables.Eng)
  518. return true, field
  519. }
  520. // Strip off the first 2 levels of the prefix
  521. _, prefix = splitPrefix(rest)
  522. for _, p := range moduleTypeProps {
  523. if fieldExistsByNameRecursive(reflect.TypeOf(p).Elem(), prefix, field.Name) {
  524. // Keep any fields that exist in one of the property structs
  525. return true, field
  526. }
  527. }
  528. return false, field
  529. })
  530. return typ
  531. }
  532. func splitPrefix(prefix string) (first, rest string) {
  533. index := strings.IndexByte(prefix, '.')
  534. if index == -1 {
  535. return prefix, ""
  536. }
  537. return prefix[:index], prefix[index+1:]
  538. }
  539. func fieldExistsByNameRecursive(t reflect.Type, prefix, name string) bool {
  540. if t.Kind() != reflect.Struct {
  541. panic(fmt.Errorf("fieldExistsByNameRecursive can only be called on a reflect.Struct"))
  542. }
  543. if prefix != "" {
  544. split := strings.SplitN(prefix, ".", 2)
  545. firstPrefix := split[0]
  546. rest := ""
  547. if len(split) > 1 {
  548. rest = split[1]
  549. }
  550. f, exists := t.FieldByName(firstPrefix)
  551. if !exists {
  552. return false
  553. }
  554. ft := f.Type
  555. if ft.Kind() == reflect.Ptr {
  556. ft = ft.Elem()
  557. }
  558. if ft.Kind() != reflect.Struct {
  559. panic(fmt.Errorf("field %q in %q is not a struct", firstPrefix, t))
  560. }
  561. return fieldExistsByNameRecursive(ft, rest, name)
  562. } else {
  563. _, exists := t.FieldByName(name)
  564. return exists
  565. }
  566. }