blob: 8f4c17daa817728ee87330fa7a056ec6320a36d9 [file] [log] [blame]
Colin Crossc0b06f12015-04-08 13:03:43 -07001// 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
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Crossc0b06f12015-04-08 13:03:43 -070016
Dan Willemsenb1957a52016-06-23 23:44:54 -070017import (
Colin Cross3020fee2019-03-19 15:05:17 -070018 "fmt"
Ivan Lozano022a73b2019-09-09 20:29:31 -070019 "path/filepath"
Inseob Kim1a365c62019-06-08 15:47:51 +090020 "reflect"
Colin Cross3020fee2019-03-19 15:05:17 -070021 "regexp"
Dan Willemsenb1957a52016-06-23 23:44:54 -070022 "runtime"
23 "sort"
24 "strings"
25)
Colin Cross1f8c52b2015-06-16 16:38:17 -070026
Colin Cross454c0872019-02-15 23:03:34 -080027// CopyOf returns a new slice that has the same contents as s.
28func CopyOf(s []string) []string {
29 return append([]string(nil), s...)
30}
31
Jiakai Zhang8fe3a412023-02-23 17:37:16 +000032// Concat returns a new slice concatenated from the two input slices. It does not change the input
33// slices.
34func Concat[T any](s1, s2 []T) []T {
35 res := make([]T, 0, len(s1)+len(s2))
36 res = append(res, s1...)
37 res = append(res, s2...)
38 return res
39}
40
Sasha Smundak1e533922020-11-19 16:48:18 -080041// JoinWithPrefix prepends the prefix to each string in the list and
42// returns them joined together with " " as separator.
Colin Crossc0b06f12015-04-08 13:03:43 -070043func JoinWithPrefix(strs []string, prefix string) string {
Yu Liu8d82ac52022-05-17 15:13:28 -070044 return JoinWithPrefixAndSeparator(strs, prefix, " ")
45}
46
47// JoinWithPrefixAndSeparator prepends the prefix to each string in the list and
48// returns them joined together with the given separator.
49func JoinWithPrefixAndSeparator(strs []string, prefix string, sep string) string {
Colin Crossc0b06f12015-04-08 13:03:43 -070050 if len(strs) == 0 {
51 return ""
52 }
53
Sasha Smundak1e533922020-11-19 16:48:18 -080054 var buf strings.Builder
55 buf.WriteString(prefix)
56 buf.WriteString(strs[0])
57 for i := 1; i < len(strs); i++ {
Yu Liu8d82ac52022-05-17 15:13:28 -070058 buf.WriteString(sep)
Sasha Smundak1e533922020-11-19 16:48:18 -080059 buf.WriteString(prefix)
60 buf.WriteString(strs[i])
Colin Crossc0b06f12015-04-08 13:03:43 -070061 }
Sasha Smundak1e533922020-11-19 16:48:18 -080062 return buf.String()
Colin Crossc0b06f12015-04-08 13:03:43 -070063}
Colin Cross9b6826f2015-04-10 15:47:33 -070064
Sasha Smundak1e533922020-11-19 16:48:18 -080065// JoinWithSuffix appends the suffix to each string in the list and
66// returns them joined together with given separator.
Inseob Kim1f086e22019-05-09 13:29:15 +090067func JoinWithSuffix(strs []string, suffix string, separator string) string {
68 if len(strs) == 0 {
69 return ""
70 }
71
Sasha Smundak1e533922020-11-19 16:48:18 -080072 var buf strings.Builder
73 buf.WriteString(strs[0])
74 buf.WriteString(suffix)
75 for i := 1; i < len(strs); i++ {
76 buf.WriteString(separator)
77 buf.WriteString(strs[i])
78 buf.WriteString(suffix)
Inseob Kim1f086e22019-05-09 13:29:15 +090079 }
Sasha Smundak1e533922020-11-19 16:48:18 -080080 return buf.String()
Inseob Kim1f086e22019-05-09 13:29:15 +090081}
82
Colin Cross9eb853b2022-02-17 11:13:37 -080083// SorterStringKeys returns the keys of the given string-keyed map in the ascending order.
Inseob Kim1a365c62019-06-08 15:47:51 +090084func SortedStringKeys(m interface{}) []string {
85 v := reflect.ValueOf(m)
86 if v.Kind() != reflect.Map {
87 panic(fmt.Sprintf("%#v is not a map", m))
88 }
Colin Cross9eb853b2022-02-17 11:13:37 -080089 if v.Len() == 0 {
90 return nil
91 }
92 iter := v.MapRange()
93 s := make([]string, 0, v.Len())
94 for iter.Next() {
95 s = append(s, iter.Key().String())
Colin Cross1f8c52b2015-06-16 16:38:17 -070096 }
97 sort.Strings(s)
98 return s
99}
Dan Willemsenb1957a52016-06-23 23:44:54 -0700100
Colin Cross9eb853b2022-02-17 11:13:37 -0800101// stringValues returns the values of the given string-valued map in randomized map order.
102func stringValues(m interface{}) []string {
103 v := reflect.ValueOf(m)
104 if v.Kind() != reflect.Map {
105 panic(fmt.Sprintf("%#v is not a map", m))
106 }
107 if v.Len() == 0 {
108 return nil
109 }
110 iter := v.MapRange()
111 s := make([]string, 0, v.Len())
112 for iter.Next() {
113 s = append(s, iter.Value().String())
114 }
115 return s
116}
117
118// SortedStringValues returns the values of the given string-valued map in the ascending order.
119func SortedStringValues(m interface{}) []string {
120 s := stringValues(m)
121 sort.Strings(s)
122 return s
123}
124
125// SortedUniqueStringValues returns the values of the given string-valued map in the ascending order
126// with duplicates removed.
127func SortedUniqueStringValues(m interface{}) []string {
128 s := stringValues(m)
129 return SortedUniqueStrings(s)
130}
131
Sasha Smundak1e533922020-11-19 16:48:18 -0800132// IndexList returns the index of the first occurrence of the given string in the list or -1
Colin Crossb4330e22017-12-22 15:47:09 -0800133func IndexList(s string, list []string) int {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700134 for i, l := range list {
135 if l == s {
136 return i
137 }
138 }
139
140 return -1
141}
142
Sasha Smundak1e533922020-11-19 16:48:18 -0800143// InList checks if the string belongs to the list
Colin Crossb4330e22017-12-22 15:47:09 -0800144func InList(s string, list []string) bool {
145 return IndexList(s, list) != -1
Dan Willemsenb1957a52016-06-23 23:44:54 -0700146}
147
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500148func setFromList[T comparable](l []T) map[T]bool {
149 m := make(map[T]bool, len(l))
150 for _, t := range l {
151 m[t] = true
152 }
153 return m
154}
155
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500156// ListSetDifference checks if the two lists contain the same elements. It returns
157// a boolean which is true if there is a difference, and then returns lists of elements
158// that are in l1 but not l2, and l2 but not l1.
159func ListSetDifference[T comparable](l1, l2 []T) (bool, []T, []T) {
160 listsDiffer := false
161 diff1 := []T{}
162 diff2 := []T{}
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500163 m1 := setFromList(l1)
164 m2 := setFromList(l2)
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500165 for t := range m1 {
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500166 if _, ok := m2[t]; !ok {
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500167 diff1 = append(diff1, t)
168 listsDiffer = true
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500169 }
170 }
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500171 for t := range m2 {
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500172 if _, ok := m1[t]; !ok {
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500173 diff2 = append(diff2, t)
174 listsDiffer = true
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500175 }
176 }
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500177 return listsDiffer, diff1, diff2
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500178}
179
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800180// Returns true if the given string s is prefixed with any string in the given prefix list.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800181func HasAnyPrefix(s string, prefixList []string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800182 for _, prefix := range prefixList {
183 if strings.HasPrefix(s, prefix) {
184 return true
185 }
186 }
187 return false
188}
189
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -0800190// Returns true if any string in the given list has the given substring.
191func SubstringInList(list []string, substr string) bool {
192 for _, s := range list {
193 if strings.Contains(s, substr) {
194 return true
195 }
196 }
197 return false
198}
199
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800200// Returns true if any string in the given list has the given prefix.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800201func PrefixInList(list []string, prefix string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800202 for _, s := range list {
Ivan Lozano5f595532017-07-13 14:46:05 -0700203 if strings.HasPrefix(s, prefix) {
204 return true
205 }
206 }
207 return false
208}
209
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400210// Returns true if any string in the given list has the given suffix.
211func SuffixInList(list []string, suffix string) bool {
212 for _, s := range list {
213 if strings.HasSuffix(s, suffix) {
214 return true
215 }
216 }
217 return false
218}
219
Jooyung Han12df5fb2019-07-11 16:18:47 +0900220// IndexListPred returns the index of the element which in the given `list` satisfying the predicate, or -1 if there is no such element.
221func IndexListPred(pred func(s string) bool, list []string) int {
222 for i, l := range list {
223 if pred(l) {
224 return i
225 }
226 }
227
228 return -1
229}
230
Sasha Smundak1e533922020-11-19 16:48:18 -0800231// FilterList divides the string list into two lists: one with the strings belonging
232// to the given filter list, and the other with the remaining ones
Colin Crossb4330e22017-12-22 15:47:09 -0800233func FilterList(list []string, filter []string) (remainder []string, filtered []string) {
Sasha Smundak1e533922020-11-19 16:48:18 -0800234 // InList is O(n). May be worth using more efficient lookup for longer lists.
Colin Crossb4330e22017-12-22 15:47:09 -0800235 for _, l := range list {
236 if InList(l, filter) {
237 filtered = append(filtered, l)
238 } else {
239 remainder = append(remainder, l)
240 }
241 }
242
243 return
244}
245
Martin Stjernholm1461c4d2021-03-27 19:04:05 +0000246// FilterListPred returns the elements of the given list for which the predicate
247// returns true. Order is kept.
248func FilterListPred(list []string, pred func(s string) bool) (filtered []string) {
249 for _, l := range list {
250 if pred(l) {
251 filtered = append(filtered, l)
252 }
253 }
254 return
255}
256
Sasha Smundak1e533922020-11-19 16:48:18 -0800257// RemoveListFromList removes the strings belonging to the filter list from the
258// given list and returns the result
Colin Crossb4330e22017-12-22 15:47:09 -0800259func RemoveListFromList(list []string, filter_out []string) (result []string) {
260 result = make([]string, 0, len(list))
261 for _, l := range list {
262 if !InList(l, filter_out) {
263 result = append(result, l)
264 }
265 }
266 return
267}
268
Sasha Smundak1e533922020-11-19 16:48:18 -0800269// RemoveFromList removes given string from the string list.
Colin Crossb4330e22017-12-22 15:47:09 -0800270func RemoveFromList(s string, list []string) (bool, []string) {
Sasha Smundak1e533922020-11-19 16:48:18 -0800271 result := make([]string, 0, len(list))
272 var removed bool
273 for _, item := range list {
274 if item != s {
275 result = append(result, item)
276 } else {
277 removed = true
Logan Chien7922ab82018-03-06 18:29:27 +0800278 }
279 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800280 return removed, result
Colin Crossb4330e22017-12-22 15:47:09 -0800281}
282
Colin Crossb6715442017-10-24 11:13:31 -0700283// FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of
284// each. It modifies the slice contents in place, and returns a subslice of the original slice.
285func FirstUniqueStrings(list []string) []string {
Colin Cross27027c72020-02-28 15:34:17 -0800286 // 128 was chosen based on BenchmarkFirstUniqueStrings results.
287 if len(list) > 128 {
288 return firstUniqueStringsMap(list)
289 }
290 return firstUniqueStringsList(list)
291}
292
293func firstUniqueStringsList(list []string) []string {
Colin Crossb6715442017-10-24 11:13:31 -0700294 k := 0
295outer:
296 for i := 0; i < len(list); i++ {
297 for j := 0; j < k; j++ {
298 if list[i] == list[j] {
299 continue outer
300 }
301 }
302 list[k] = list[i]
303 k++
304 }
305 return list[:k]
306}
307
Colin Cross27027c72020-02-28 15:34:17 -0800308func firstUniqueStringsMap(list []string) []string {
309 k := 0
310 seen := make(map[string]bool, len(list))
311 for i := 0; i < len(list); i++ {
312 if seen[list[i]] {
313 continue
314 }
315 seen[list[i]] = true
316 list[k] = list[i]
317 k++
318 }
319 return list[:k]
320}
321
Colin Crossb6715442017-10-24 11:13:31 -0700322// LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of
323// each. It modifies the slice contents in place, and returns a subslice of the original slice.
324func LastUniqueStrings(list []string) []string {
325 totalSkip := 0
326 for i := len(list) - 1; i >= totalSkip; i-- {
327 skip := 0
328 for j := i - 1; j >= totalSkip; j-- {
329 if list[i] == list[j] {
330 skip++
331 } else {
332 list[j+skip] = list[j]
333 }
334 }
335 totalSkip += skip
336 }
337 return list[totalSkip:]
338}
339
Jooyung Hane1633032019-08-01 17:41:43 +0900340// SortedUniqueStrings returns what the name says
341func SortedUniqueStrings(list []string) []string {
342 unique := FirstUniqueStrings(list)
343 sort.Strings(unique)
344 return unique
345}
346
Dan Willemsenb1957a52016-06-23 23:44:54 -0700347// checkCalledFromInit panics if a Go package's init function is not on the
348// call stack.
349func checkCalledFromInit() {
350 for skip := 3; ; skip++ {
351 _, funcName, ok := callerName(skip)
352 if !ok {
353 panic("not called from an init func")
354 }
355
Colin Cross3020fee2019-03-19 15:05:17 -0700356 if funcName == "init" || strings.HasPrefix(funcName, "init·") ||
357 strings.HasPrefix(funcName, "init.") {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700358 return
359 }
360 }
361}
362
Colin Cross3020fee2019-03-19 15:05:17 -0700363// A regex to find a package path within a function name. It finds the shortest string that is
364// followed by '.' and doesn't have any '/'s left.
365var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`)
366
Dan Willemsenb1957a52016-06-23 23:44:54 -0700367// callerName returns the package path and function name of the calling
368// function. The skip argument has the same meaning as the skip argument of
369// runtime.Callers.
370func callerName(skip int) (pkgPath, funcName string, ok bool) {
371 var pc [1]uintptr
372 n := runtime.Callers(skip+1, pc[:])
373 if n != 1 {
374 return "", "", false
375 }
376
Colin Cross3020fee2019-03-19 15:05:17 -0700377 f := runtime.FuncForPC(pc[0]).Name()
378 s := pkgPathRe.FindStringSubmatch(f)
379 if len(s) < 3 {
380 panic(fmt.Errorf("failed to extract package path and function name from %q", f))
Dan Willemsenb1957a52016-06-23 23:44:54 -0700381 }
382
Colin Cross3020fee2019-03-19 15:05:17 -0700383 return s[1], s[2], true
Dan Willemsenb1957a52016-06-23 23:44:54 -0700384}
Sundong Ahn0926fae2017-10-17 16:34:51 +0900385
Sasha Smundak1e533922020-11-19 16:48:18 -0800386// GetNumericSdkVersion removes the first occurrence of system_ in a string,
387// which is assumed to be something like "system_1.2.3"
Sundong Ahn0926fae2017-10-17 16:34:51 +0900388func GetNumericSdkVersion(v string) string {
Sasha Smundak1e533922020-11-19 16:48:18 -0800389 return strings.Replace(v, "system_", "", 1)
Sundong Ahn0926fae2017-10-17 16:34:51 +0900390}
Jiyong Park7f67f482019-01-05 12:57:48 +0900391
392// copied from build/kati/strutil.go
393func substPattern(pat, repl, str string) string {
394 ps := strings.SplitN(pat, "%", 2)
395 if len(ps) != 2 {
396 if str == pat {
397 return repl
398 }
399 return str
400 }
401 in := str
Sasha Smundak1e533922020-11-19 16:48:18 -0800402 trimmed := str
Jiyong Park7f67f482019-01-05 12:57:48 +0900403 if ps[0] != "" {
Sasha Smundak1e533922020-11-19 16:48:18 -0800404 trimmed = strings.TrimPrefix(in, ps[0])
405 if trimmed == in {
Jiyong Park7f67f482019-01-05 12:57:48 +0900406 return str
407 }
408 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800409 in = trimmed
Jiyong Park7f67f482019-01-05 12:57:48 +0900410 if ps[1] != "" {
Sasha Smundak1e533922020-11-19 16:48:18 -0800411 trimmed = strings.TrimSuffix(in, ps[1])
412 if trimmed == in {
Jiyong Park7f67f482019-01-05 12:57:48 +0900413 return str
414 }
415 }
416
417 rs := strings.SplitN(repl, "%", 2)
418 if len(rs) != 2 {
419 return repl
420 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800421 return rs[0] + trimmed + rs[1]
Jiyong Park7f67f482019-01-05 12:57:48 +0900422}
423
424// copied from build/kati/strutil.go
425func matchPattern(pat, str string) bool {
426 i := strings.IndexByte(pat, '%')
427 if i < 0 {
428 return pat == str
429 }
430 return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:])
431}
Ivan Lozano022a73b2019-09-09 20:29:31 -0700432
433var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+")
434
435// splitFileExt splits a file name into root, suffix and ext. root stands for the file name without
436// the file extension and the version number (e.g. "libexample"). suffix stands for the
437// concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the
438// file extension after the version numbers are trimmed (e.g. ".so").
439func SplitFileExt(name string) (string, string, string) {
440 // Extract and trim the shared lib version number if the file name ends with dot digits.
441 suffix := ""
442 matches := shlibVersionPattern.FindAllStringIndex(name, -1)
443 if len(matches) > 0 {
444 lastMatch := matches[len(matches)-1]
445 if lastMatch[1] == len(name) {
446 suffix = name[lastMatch[0]:lastMatch[1]]
447 name = name[0:lastMatch[0]]
448 }
449 }
450
451 // Extract the file name root and the file extension.
452 ext := filepath.Ext(name)
453 root := strings.TrimSuffix(name, ext)
454 suffix = ext + suffix
455
456 return root, suffix, ext
457}
Colin Cross0a2f7192019-09-23 14:33:09 -0700458
459// ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths.
460func ShardPaths(paths Paths, shardSize int) []Paths {
461 if len(paths) == 0 {
462 return nil
463 }
464 ret := make([]Paths, 0, (len(paths)+shardSize-1)/shardSize)
465 for len(paths) > shardSize {
466 ret = append(ret, paths[0:shardSize])
467 paths = paths[shardSize:]
468 }
469 if len(paths) > 0 {
470 ret = append(ret, paths)
471 }
472 return ret
473}
474
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100475// ShardString takes a string and returns a slice of strings where the length of each one is
476// at most shardSize.
477func ShardString(s string, shardSize int) []string {
478 if len(s) == 0 {
479 return nil
480 }
481 ret := make([]string, 0, (len(s)+shardSize-1)/shardSize)
482 for len(s) > shardSize {
483 ret = append(ret, s[0:shardSize])
484 s = s[shardSize:]
485 }
486 if len(s) > 0 {
487 ret = append(ret, s)
488 }
489 return ret
490}
491
Colin Cross0a2f7192019-09-23 14:33:09 -0700492// ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize
493// elements.
494func ShardStrings(s []string, shardSize int) [][]string {
495 if len(s) == 0 {
496 return nil
497 }
498 ret := make([][]string, 0, (len(s)+shardSize-1)/shardSize)
499 for len(s) > shardSize {
500 ret = append(ret, s[0:shardSize])
501 s = s[shardSize:]
502 }
503 if len(s) > 0 {
504 ret = append(ret, s)
505 }
506 return ret
507}
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700508
Sasha Smundak1e533922020-11-19 16:48:18 -0800509// CheckDuplicate checks if there are duplicates in given string list.
510// If there are, it returns first such duplicate and true.
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700511func CheckDuplicate(values []string) (duplicate string, found bool) {
512 seen := make(map[string]string)
513 for _, v := range values {
514 if duplicate, found = seen[v]; found {
Sasha Smundak1e533922020-11-19 16:48:18 -0800515 return duplicate, true
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700516 }
517 seen[v] = v
518 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800519 return "", false
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700520}