build_release.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // Copyright (C) 2021 The Android Open Source Project
  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 sdk
  15. import (
  16. "fmt"
  17. "reflect"
  18. "strings"
  19. )
  20. // Supports customizing sdk snapshot output based on target build release.
  21. // buildRelease represents the version of a build system used to create a specific release.
  22. //
  23. // The name of the release, is the same as the code for the dessert release, e.g. S, Tiramisu, etc.
  24. type buildRelease struct {
  25. // The name of the release, e.g. S, Tiramisu, etc.
  26. name string
  27. // The index of this structure within the buildReleases list.
  28. ordinal int
  29. }
  30. func (br *buildRelease) EarlierThan(other *buildRelease) bool {
  31. return br.ordinal < other.ordinal
  32. }
  33. // String returns the name of the build release.
  34. func (br *buildRelease) String() string {
  35. return br.name
  36. }
  37. // buildReleaseSet represents a set of buildRelease objects.
  38. type buildReleaseSet struct {
  39. // Set of *buildRelease represented as a map from *buildRelease to struct{}.
  40. contents map[*buildRelease]struct{}
  41. }
  42. // addItem adds a build release to the set.
  43. func (s *buildReleaseSet) addItem(release *buildRelease) {
  44. s.contents[release] = struct{}{}
  45. }
  46. // addRange adds all the build releases from start (inclusive) to end (inclusive).
  47. func (s *buildReleaseSet) addRange(start *buildRelease, end *buildRelease) {
  48. for i := start.ordinal; i <= end.ordinal; i += 1 {
  49. s.addItem(buildReleases[i])
  50. }
  51. }
  52. // contains returns true if the set contains the specified build release.
  53. func (s *buildReleaseSet) contains(release *buildRelease) bool {
  54. _, ok := s.contents[release]
  55. return ok
  56. }
  57. // String returns a string representation of the set, sorted from earliest to latest release.
  58. func (s *buildReleaseSet) String() string {
  59. list := []string{}
  60. for _, release := range buildReleases {
  61. if _, ok := s.contents[release]; ok {
  62. list = append(list, release.name)
  63. }
  64. }
  65. return fmt.Sprintf("[%s]", strings.Join(list, ","))
  66. }
  67. var (
  68. // nameToBuildRelease contains a map from name to build release.
  69. nameToBuildRelease = map[string]*buildRelease{}
  70. // buildReleases lists all the available build releases.
  71. buildReleases = []*buildRelease{}
  72. // allBuildReleaseSet is the set of all build releases.
  73. allBuildReleaseSet = &buildReleaseSet{contents: map[*buildRelease]struct{}{}}
  74. // Add the build releases from oldest to newest.
  75. buildReleaseS = initBuildRelease("S")
  76. buildReleaseT = initBuildRelease("Tiramisu")
  77. )
  78. // initBuildRelease creates a new build release with the specified name.
  79. func initBuildRelease(name string) *buildRelease {
  80. ordinal := len(nameToBuildRelease)
  81. release := &buildRelease{name: name, ordinal: ordinal}
  82. nameToBuildRelease[name] = release
  83. buildReleases = append(buildReleases, release)
  84. allBuildReleaseSet.addItem(release)
  85. return release
  86. }
  87. // latestBuildRelease returns the latest build release, i.e. the last one added.
  88. func latestBuildRelease() *buildRelease {
  89. return buildReleases[len(buildReleases)-1]
  90. }
  91. // nameToRelease maps from build release name to the corresponding build release (if it exists) or
  92. // the error if it does not.
  93. func nameToRelease(name string) (*buildRelease, error) {
  94. if r, ok := nameToBuildRelease[name]; ok {
  95. return r, nil
  96. }
  97. return nil, fmt.Errorf("unknown release %q, expected one of %s", name, allBuildReleaseSet)
  98. }
  99. // parseBuildReleaseSet parses a build release set string specification into a build release set.
  100. //
  101. // The specification consists of one of the following:
  102. // * a single build release name, e.g. S, T, etc.
  103. // * a closed range (inclusive to inclusive), e.g. S-T
  104. // * an open range, e.g. T+.
  105. //
  106. // This returns the set if the specification was valid or an error.
  107. func parseBuildReleaseSet(specification string) (*buildReleaseSet, error) {
  108. set := &buildReleaseSet{contents: map[*buildRelease]struct{}{}}
  109. if strings.HasSuffix(specification, "+") {
  110. rangeStart := strings.TrimSuffix(specification, "+")
  111. start, err := nameToRelease(rangeStart)
  112. if err != nil {
  113. return nil, err
  114. }
  115. end := latestBuildRelease()
  116. set.addRange(start, end)
  117. } else if strings.Contains(specification, "-") {
  118. limits := strings.SplitN(specification, "-", 2)
  119. start, err := nameToRelease(limits[0])
  120. if err != nil {
  121. return nil, err
  122. }
  123. end, err := nameToRelease(limits[1])
  124. if err != nil {
  125. return nil, err
  126. }
  127. if start.ordinal > end.ordinal {
  128. return nil, fmt.Errorf("invalid closed range, start release %q is later than end release %q", start.name, end.name)
  129. }
  130. set.addRange(start, end)
  131. } else {
  132. release, err := nameToRelease(specification)
  133. if err != nil {
  134. return nil, err
  135. }
  136. set.addItem(release)
  137. }
  138. return set, nil
  139. }
  140. // Given a set of properties (struct value), set the value of a field within that struct (or one of
  141. // its embedded structs) to its zero value.
  142. type fieldPrunerFunc func(structValue reflect.Value)
  143. // A property that can be cleared by a propertyPruner.
  144. type prunerProperty struct {
  145. // The name of the field for this property. It is a "."-separated path for fields in non-anonymous
  146. // sub-structs.
  147. name string
  148. // Sets the associated field to its zero value.
  149. prunerFunc fieldPrunerFunc
  150. }
  151. // propertyPruner provides support for pruning (i.e. setting to their zero value) properties from
  152. // a properties structure.
  153. type propertyPruner struct {
  154. // The properties that the pruner will clear.
  155. properties []prunerProperty
  156. }
  157. // gatherFields recursively processes the supplied structure and a nested structures, selecting the
  158. // fields that require pruning and populates the propertyPruner.properties with the information
  159. // needed to prune those fields.
  160. //
  161. // containingStructAccessor is a func that if given an object will return a field whose value is
  162. // of the supplied structType. It is nil on initial entry to this method but when this method is
  163. // called recursively on a field that is a nested structure containingStructAccessor is set to a
  164. // func that provides access to the field's value.
  165. //
  166. // namePrefix is the prefix to the fields that are being visited. It is "" on initial entry to this
  167. // method but when this method is called recursively on a field that is a nested structure
  168. // namePrefix is the result of appending the field name (plus a ".") to the previous name prefix.
  169. // Unless the field is anonymous in which case it is passed through unchanged.
  170. //
  171. // selector is a func that will select whether the supplied field requires pruning or not. If it
  172. // returns true then the field will be added to those to be pruned, otherwise it will not.
  173. func (p *propertyPruner) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string, selector fieldSelectorFunc) {
  174. for f := 0; f < structType.NumField(); f++ {
  175. field := structType.Field(f)
  176. if field.PkgPath != "" {
  177. // Ignore unexported fields.
  178. continue
  179. }
  180. // Save a copy of the field index for use in the function.
  181. fieldIndex := f
  182. name := namePrefix + field.Name
  183. fieldGetter := func(container reflect.Value) reflect.Value {
  184. if containingStructAccessor != nil {
  185. // This is an embedded structure so first access the field for the embedded
  186. // structure.
  187. container = containingStructAccessor(container)
  188. }
  189. // Skip through interface and pointer values to find the structure.
  190. container = getStructValue(container)
  191. defer func() {
  192. if r := recover(); r != nil {
  193. panic(fmt.Errorf("%s for fieldIndex %d of field %s of container %#v", r, fieldIndex, name, container.Interface()))
  194. }
  195. }()
  196. // Return the field.
  197. return container.Field(fieldIndex)
  198. }
  199. fieldType := field.Type
  200. if selector(name, field) {
  201. zeroValue := reflect.Zero(fieldType)
  202. fieldPruner := func(container reflect.Value) {
  203. if containingStructAccessor != nil {
  204. // This is an embedded structure so first access the field for the embedded
  205. // structure.
  206. container = containingStructAccessor(container)
  207. }
  208. // Skip through interface and pointer values to find the structure.
  209. container = getStructValue(container)
  210. defer func() {
  211. if r := recover(); r != nil {
  212. panic(fmt.Errorf("%s\n\tfor field (index %d, name %s)", r, fieldIndex, name))
  213. }
  214. }()
  215. // Set the field.
  216. container.Field(fieldIndex).Set(zeroValue)
  217. }
  218. property := prunerProperty{
  219. name,
  220. fieldPruner,
  221. }
  222. p.properties = append(p.properties, property)
  223. } else {
  224. switch fieldType.Kind() {
  225. case reflect.Struct:
  226. // Gather fields from the nested or embedded structure.
  227. var subNamePrefix string
  228. if field.Anonymous {
  229. subNamePrefix = namePrefix
  230. } else {
  231. subNamePrefix = name + "."
  232. }
  233. p.gatherFields(fieldType, fieldGetter, subNamePrefix, selector)
  234. case reflect.Map:
  235. // Get the type of the values stored in the map.
  236. valueType := fieldType.Elem()
  237. // Skip over * types.
  238. if valueType.Kind() == reflect.Ptr {
  239. valueType = valueType.Elem()
  240. }
  241. if valueType.Kind() == reflect.Struct {
  242. // If this is not referenced by a pointer then it is an error as it is impossible to
  243. // modify a struct that is stored directly as a value in a map.
  244. if fieldType.Elem().Kind() != reflect.Ptr {
  245. panic(fmt.Errorf("Cannot prune struct %s stored by value in map %s, map values must"+
  246. " be pointers to structs",
  247. fieldType.Elem(), name))
  248. }
  249. // Create a new pruner for the values of the map.
  250. valuePruner := newPropertyPrunerForStructType(valueType, selector)
  251. // Create a new fieldPruner that will iterate over all the items in the map and call the
  252. // pruner on them.
  253. fieldPruner := func(container reflect.Value) {
  254. mapValue := fieldGetter(container)
  255. for _, keyValue := range mapValue.MapKeys() {
  256. itemValue := mapValue.MapIndex(keyValue)
  257. defer func() {
  258. if r := recover(); r != nil {
  259. panic(fmt.Errorf("%s\n\tfor key %q", r, keyValue))
  260. }
  261. }()
  262. valuePruner.pruneProperties(itemValue.Interface())
  263. }
  264. }
  265. // Add the map field pruner to the list of property pruners.
  266. property := prunerProperty{
  267. name + "[*]",
  268. fieldPruner,
  269. }
  270. p.properties = append(p.properties, property)
  271. }
  272. }
  273. }
  274. }
  275. }
  276. // pruneProperties will prune (set to zero value) any properties in the struct referenced by the
  277. // supplied struct pointer.
  278. //
  279. // The struct must be of the same type as was originally passed to newPropertyPruner to create this
  280. // propertyPruner.
  281. func (p *propertyPruner) pruneProperties(propertiesStruct interface{}) {
  282. defer func() {
  283. if r := recover(); r != nil {
  284. panic(fmt.Errorf("%s\n\tof container %#v", r, propertiesStruct))
  285. }
  286. }()
  287. structValue := reflect.ValueOf(propertiesStruct)
  288. for _, property := range p.properties {
  289. property.prunerFunc(structValue)
  290. }
  291. }
  292. // fieldSelectorFunc is called to select whether a specific field should be pruned or not.
  293. // name is the name of the field, including any prefixes from containing str
  294. type fieldSelectorFunc func(name string, field reflect.StructField) bool
  295. // newPropertyPruner creates a new property pruner for the structure type for the supplied
  296. // properties struct.
  297. //
  298. // The returned pruner can be used on any properties structure of the same type as the supplied set
  299. // of properties.
  300. func newPropertyPruner(propertiesStruct interface{}, selector fieldSelectorFunc) *propertyPruner {
  301. structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
  302. return newPropertyPrunerForStructType(structType, selector)
  303. }
  304. // newPropertyPruner creates a new property pruner for the supplied properties struct type.
  305. //
  306. // The returned pruner can be used on any properties structure of the supplied type.
  307. func newPropertyPrunerForStructType(structType reflect.Type, selector fieldSelectorFunc) *propertyPruner {
  308. pruner := &propertyPruner{}
  309. pruner.gatherFields(structType, nil, "", selector)
  310. return pruner
  311. }
  312. // newPropertyPrunerByBuildRelease creates a property pruner that will clear any properties in the
  313. // structure which are not supported by the specified target build release.
  314. //
  315. // A property is pruned if its field has a tag of the form:
  316. //
  317. // `supported_build_releases:"<build-release-set>"`
  318. //
  319. // and the resulting build release set does not contain the target build release. Properties that
  320. // have no such tag are assumed to be supported by all releases.
  321. func newPropertyPrunerByBuildRelease(propertiesStruct interface{}, targetBuildRelease *buildRelease) *propertyPruner {
  322. return newPropertyPruner(propertiesStruct, func(name string, field reflect.StructField) bool {
  323. if supportedBuildReleases, ok := field.Tag.Lookup("supported_build_releases"); ok {
  324. set, err := parseBuildReleaseSet(supportedBuildReleases)
  325. if err != nil {
  326. panic(fmt.Errorf("invalid `supported_build_releases` tag on %s of %T: %s", name, propertiesStruct, err))
  327. }
  328. // If the field does not support tha target release then prune it.
  329. return !set.contains(targetBuildRelease)
  330. } else {
  331. // Any untagged fields are assumed to be supported by all build releases so should never be
  332. // pruned.
  333. return false
  334. }
  335. })
  336. }