blob: 0ee253e594b53da8286c1c0f9fcba28d85fe466e [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
Sasha Smundak1e533922020-11-19 16:48:18 -080032// JoinWithPrefix prepends the prefix to each string in the list and
33// returns them joined together with " " as separator.
Colin Crossc0b06f12015-04-08 13:03:43 -070034func JoinWithPrefix(strs []string, prefix string) string {
35 if len(strs) == 0 {
36 return ""
37 }
38
Sasha Smundak1e533922020-11-19 16:48:18 -080039 var buf strings.Builder
40 buf.WriteString(prefix)
41 buf.WriteString(strs[0])
42 for i := 1; i < len(strs); i++ {
43 buf.WriteString(" ")
44 buf.WriteString(prefix)
45 buf.WriteString(strs[i])
Colin Crossc0b06f12015-04-08 13:03:43 -070046 }
Sasha Smundak1e533922020-11-19 16:48:18 -080047 return buf.String()
Colin Crossc0b06f12015-04-08 13:03:43 -070048}
Colin Cross9b6826f2015-04-10 15:47:33 -070049
Sasha Smundak1e533922020-11-19 16:48:18 -080050// JoinWithSuffix appends the suffix to each string in the list and
51// returns them joined together with given separator.
Inseob Kim1f086e22019-05-09 13:29:15 +090052func JoinWithSuffix(strs []string, suffix string, separator string) string {
53 if len(strs) == 0 {
54 return ""
55 }
56
Sasha Smundak1e533922020-11-19 16:48:18 -080057 var buf strings.Builder
58 buf.WriteString(strs[0])
59 buf.WriteString(suffix)
60 for i := 1; i < len(strs); i++ {
61 buf.WriteString(separator)
62 buf.WriteString(strs[i])
63 buf.WriteString(suffix)
Inseob Kim1f086e22019-05-09 13:29:15 +090064 }
Sasha Smundak1e533922020-11-19 16:48:18 -080065 return buf.String()
Inseob Kim1f086e22019-05-09 13:29:15 +090066}
67
Sasha Smundak1e533922020-11-19 16:48:18 -080068// SorterStringKeys returns the keys of the given string-keyed map in the ascending order
Inseob Kim1a365c62019-06-08 15:47:51 +090069func SortedStringKeys(m interface{}) []string {
70 v := reflect.ValueOf(m)
71 if v.Kind() != reflect.Map {
72 panic(fmt.Sprintf("%#v is not a map", m))
73 }
74 keys := v.MapKeys()
75 s := make([]string, 0, len(keys))
76 for _, key := range keys {
77 s = append(s, key.String())
Colin Cross1f8c52b2015-06-16 16:38:17 -070078 }
79 sort.Strings(s)
80 return s
81}
Dan Willemsenb1957a52016-06-23 23:44:54 -070082
Sasha Smundak1e533922020-11-19 16:48:18 -080083// IndexList returns the index of the first occurrence of the given string in the list or -1
Colin Crossb4330e22017-12-22 15:47:09 -080084func IndexList(s string, list []string) int {
Dan Willemsenb1957a52016-06-23 23:44:54 -070085 for i, l := range list {
86 if l == s {
87 return i
88 }
89 }
90
91 return -1
92}
93
Sasha Smundak1e533922020-11-19 16:48:18 -080094// InList checks if the string belongs to the list
Colin Crossb4330e22017-12-22 15:47:09 -080095func InList(s string, list []string) bool {
96 return IndexList(s, list) != -1
Dan Willemsenb1957a52016-06-23 23:44:54 -070097}
98
Jaewoong Jung6431ca72020-01-15 14:15:10 -080099// Returns true if the given string s is prefixed with any string in the given prefix list.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800100func HasAnyPrefix(s string, prefixList []string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800101 for _, prefix := range prefixList {
102 if strings.HasPrefix(s, prefix) {
103 return true
104 }
105 }
106 return false
107}
108
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -0800109// Returns true if any string in the given list has the given substring.
110func SubstringInList(list []string, substr string) bool {
111 for _, s := range list {
112 if strings.Contains(s, substr) {
113 return true
114 }
115 }
116 return false
117}
118
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800119// Returns true if any string in the given list has the given prefix.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800120func PrefixInList(list []string, prefix string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800121 for _, s := range list {
Ivan Lozano5f595532017-07-13 14:46:05 -0700122 if strings.HasPrefix(s, prefix) {
123 return true
124 }
125 }
126 return false
127}
128
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400129// Returns true if any string in the given list has the given suffix.
130func SuffixInList(list []string, suffix string) bool {
131 for _, s := range list {
132 if strings.HasSuffix(s, suffix) {
133 return true
134 }
135 }
136 return false
137}
138
Jooyung Han12df5fb2019-07-11 16:18:47 +0900139// IndexListPred returns the index of the element which in the given `list` satisfying the predicate, or -1 if there is no such element.
140func IndexListPred(pred func(s string) bool, list []string) int {
141 for i, l := range list {
142 if pred(l) {
143 return i
144 }
145 }
146
147 return -1
148}
149
Sasha Smundak1e533922020-11-19 16:48:18 -0800150// FilterList divides the string list into two lists: one with the strings belonging
151// to the given filter list, and the other with the remaining ones
Colin Crossb4330e22017-12-22 15:47:09 -0800152func FilterList(list []string, filter []string) (remainder []string, filtered []string) {
Sasha Smundak1e533922020-11-19 16:48:18 -0800153 // InList is O(n). May be worth using more efficient lookup for longer lists.
Colin Crossb4330e22017-12-22 15:47:09 -0800154 for _, l := range list {
155 if InList(l, filter) {
156 filtered = append(filtered, l)
157 } else {
158 remainder = append(remainder, l)
159 }
160 }
161
162 return
163}
164
Martin Stjernholm1461c4d2021-03-27 19:04:05 +0000165// FilterListPred returns the elements of the given list for which the predicate
166// returns true. Order is kept.
167func FilterListPred(list []string, pred func(s string) bool) (filtered []string) {
168 for _, l := range list {
169 if pred(l) {
170 filtered = append(filtered, l)
171 }
172 }
173 return
174}
175
Sasha Smundak1e533922020-11-19 16:48:18 -0800176// RemoveListFromList removes the strings belonging to the filter list from the
177// given list and returns the result
Colin Crossb4330e22017-12-22 15:47:09 -0800178func RemoveListFromList(list []string, filter_out []string) (result []string) {
179 result = make([]string, 0, len(list))
180 for _, l := range list {
181 if !InList(l, filter_out) {
182 result = append(result, l)
183 }
184 }
185 return
186}
187
Sasha Smundak1e533922020-11-19 16:48:18 -0800188// RemoveFromList removes given string from the string list.
Colin Crossb4330e22017-12-22 15:47:09 -0800189func RemoveFromList(s string, list []string) (bool, []string) {
Sasha Smundak1e533922020-11-19 16:48:18 -0800190 result := make([]string, 0, len(list))
191 var removed bool
192 for _, item := range list {
193 if item != s {
194 result = append(result, item)
195 } else {
196 removed = true
Logan Chien7922ab82018-03-06 18:29:27 +0800197 }
198 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800199 return removed, result
Colin Crossb4330e22017-12-22 15:47:09 -0800200}
201
Colin Crossb6715442017-10-24 11:13:31 -0700202// FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of
203// each. It modifies the slice contents in place, and returns a subslice of the original slice.
204func FirstUniqueStrings(list []string) []string {
Colin Cross27027c72020-02-28 15:34:17 -0800205 // 128 was chosen based on BenchmarkFirstUniqueStrings results.
206 if len(list) > 128 {
207 return firstUniqueStringsMap(list)
208 }
209 return firstUniqueStringsList(list)
210}
211
212func firstUniqueStringsList(list []string) []string {
Colin Crossb6715442017-10-24 11:13:31 -0700213 k := 0
214outer:
215 for i := 0; i < len(list); i++ {
216 for j := 0; j < k; j++ {
217 if list[i] == list[j] {
218 continue outer
219 }
220 }
221 list[k] = list[i]
222 k++
223 }
224 return list[:k]
225}
226
Colin Cross27027c72020-02-28 15:34:17 -0800227func firstUniqueStringsMap(list []string) []string {
228 k := 0
229 seen := make(map[string]bool, len(list))
230 for i := 0; i < len(list); i++ {
231 if seen[list[i]] {
232 continue
233 }
234 seen[list[i]] = true
235 list[k] = list[i]
236 k++
237 }
238 return list[:k]
239}
240
Colin Crossb6715442017-10-24 11:13:31 -0700241// LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of
242// each. It modifies the slice contents in place, and returns a subslice of the original slice.
243func LastUniqueStrings(list []string) []string {
244 totalSkip := 0
245 for i := len(list) - 1; i >= totalSkip; i-- {
246 skip := 0
247 for j := i - 1; j >= totalSkip; j-- {
248 if list[i] == list[j] {
249 skip++
250 } else {
251 list[j+skip] = list[j]
252 }
253 }
254 totalSkip += skip
255 }
256 return list[totalSkip:]
257}
258
Jooyung Hane1633032019-08-01 17:41:43 +0900259// SortedUniqueStrings returns what the name says
260func SortedUniqueStrings(list []string) []string {
261 unique := FirstUniqueStrings(list)
262 sort.Strings(unique)
263 return unique
264}
265
Dan Willemsenb1957a52016-06-23 23:44:54 -0700266// checkCalledFromInit panics if a Go package's init function is not on the
267// call stack.
268func checkCalledFromInit() {
269 for skip := 3; ; skip++ {
270 _, funcName, ok := callerName(skip)
271 if !ok {
272 panic("not called from an init func")
273 }
274
Colin Cross3020fee2019-03-19 15:05:17 -0700275 if funcName == "init" || strings.HasPrefix(funcName, "init·") ||
276 strings.HasPrefix(funcName, "init.") {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700277 return
278 }
279 }
280}
281
Colin Cross3020fee2019-03-19 15:05:17 -0700282// A regex to find a package path within a function name. It finds the shortest string that is
283// followed by '.' and doesn't have any '/'s left.
284var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`)
285
Dan Willemsenb1957a52016-06-23 23:44:54 -0700286// callerName returns the package path and function name of the calling
287// function. The skip argument has the same meaning as the skip argument of
288// runtime.Callers.
289func callerName(skip int) (pkgPath, funcName string, ok bool) {
290 var pc [1]uintptr
291 n := runtime.Callers(skip+1, pc[:])
292 if n != 1 {
293 return "", "", false
294 }
295
Colin Cross3020fee2019-03-19 15:05:17 -0700296 f := runtime.FuncForPC(pc[0]).Name()
297 s := pkgPathRe.FindStringSubmatch(f)
298 if len(s) < 3 {
299 panic(fmt.Errorf("failed to extract package path and function name from %q", f))
Dan Willemsenb1957a52016-06-23 23:44:54 -0700300 }
301
Colin Cross3020fee2019-03-19 15:05:17 -0700302 return s[1], s[2], true
Dan Willemsenb1957a52016-06-23 23:44:54 -0700303}
Sundong Ahn0926fae2017-10-17 16:34:51 +0900304
Sasha Smundak1e533922020-11-19 16:48:18 -0800305// GetNumericSdkVersion removes the first occurrence of system_ in a string,
306// which is assumed to be something like "system_1.2.3"
Sundong Ahn0926fae2017-10-17 16:34:51 +0900307func GetNumericSdkVersion(v string) string {
Sasha Smundak1e533922020-11-19 16:48:18 -0800308 return strings.Replace(v, "system_", "", 1)
Sundong Ahn0926fae2017-10-17 16:34:51 +0900309}
Jiyong Park7f67f482019-01-05 12:57:48 +0900310
311// copied from build/kati/strutil.go
312func substPattern(pat, repl, str string) string {
313 ps := strings.SplitN(pat, "%", 2)
314 if len(ps) != 2 {
315 if str == pat {
316 return repl
317 }
318 return str
319 }
320 in := str
Sasha Smundak1e533922020-11-19 16:48:18 -0800321 trimmed := str
Jiyong Park7f67f482019-01-05 12:57:48 +0900322 if ps[0] != "" {
Sasha Smundak1e533922020-11-19 16:48:18 -0800323 trimmed = strings.TrimPrefix(in, ps[0])
324 if trimmed == in {
Jiyong Park7f67f482019-01-05 12:57:48 +0900325 return str
326 }
327 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800328 in = trimmed
Jiyong Park7f67f482019-01-05 12:57:48 +0900329 if ps[1] != "" {
Sasha Smundak1e533922020-11-19 16:48:18 -0800330 trimmed = strings.TrimSuffix(in, ps[1])
331 if trimmed == in {
Jiyong Park7f67f482019-01-05 12:57:48 +0900332 return str
333 }
334 }
335
336 rs := strings.SplitN(repl, "%", 2)
337 if len(rs) != 2 {
338 return repl
339 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800340 return rs[0] + trimmed + rs[1]
Jiyong Park7f67f482019-01-05 12:57:48 +0900341}
342
343// copied from build/kati/strutil.go
344func matchPattern(pat, str string) bool {
345 i := strings.IndexByte(pat, '%')
346 if i < 0 {
347 return pat == str
348 }
349 return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:])
350}
Ivan Lozano022a73b2019-09-09 20:29:31 -0700351
352var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+")
353
354// splitFileExt splits a file name into root, suffix and ext. root stands for the file name without
355// the file extension and the version number (e.g. "libexample"). suffix stands for the
356// concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the
357// file extension after the version numbers are trimmed (e.g. ".so").
358func SplitFileExt(name string) (string, string, string) {
359 // Extract and trim the shared lib version number if the file name ends with dot digits.
360 suffix := ""
361 matches := shlibVersionPattern.FindAllStringIndex(name, -1)
362 if len(matches) > 0 {
363 lastMatch := matches[len(matches)-1]
364 if lastMatch[1] == len(name) {
365 suffix = name[lastMatch[0]:lastMatch[1]]
366 name = name[0:lastMatch[0]]
367 }
368 }
369
370 // Extract the file name root and the file extension.
371 ext := filepath.Ext(name)
372 root := strings.TrimSuffix(name, ext)
373 suffix = ext + suffix
374
375 return root, suffix, ext
376}
Colin Cross0a2f7192019-09-23 14:33:09 -0700377
378// ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths.
379func ShardPaths(paths Paths, shardSize int) []Paths {
380 if len(paths) == 0 {
381 return nil
382 }
383 ret := make([]Paths, 0, (len(paths)+shardSize-1)/shardSize)
384 for len(paths) > shardSize {
385 ret = append(ret, paths[0:shardSize])
386 paths = paths[shardSize:]
387 }
388 if len(paths) > 0 {
389 ret = append(ret, paths)
390 }
391 return ret
392}
393
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100394// ShardString takes a string and returns a slice of strings where the length of each one is
395// at most shardSize.
396func ShardString(s string, shardSize int) []string {
397 if len(s) == 0 {
398 return nil
399 }
400 ret := make([]string, 0, (len(s)+shardSize-1)/shardSize)
401 for len(s) > shardSize {
402 ret = append(ret, s[0:shardSize])
403 s = s[shardSize:]
404 }
405 if len(s) > 0 {
406 ret = append(ret, s)
407 }
408 return ret
409}
410
Colin Cross0a2f7192019-09-23 14:33:09 -0700411// ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize
412// elements.
413func ShardStrings(s []string, shardSize int) [][]string {
414 if len(s) == 0 {
415 return nil
416 }
417 ret := make([][]string, 0, (len(s)+shardSize-1)/shardSize)
418 for len(s) > shardSize {
419 ret = append(ret, s[0:shardSize])
420 s = s[shardSize:]
421 }
422 if len(s) > 0 {
423 ret = append(ret, s)
424 }
425 return ret
426}
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700427
Sasha Smundak1e533922020-11-19 16:48:18 -0800428// CheckDuplicate checks if there are duplicates in given string list.
429// If there are, it returns first such duplicate and true.
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700430func CheckDuplicate(values []string) (duplicate string, found bool) {
431 seen := make(map[string]string)
432 for _, v := range values {
433 if duplicate, found = seen[v]; found {
Sasha Smundak1e533922020-11-19 16:48:18 -0800434 return duplicate, true
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700435 }
436 seen[v] = v
437 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800438 return "", false
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700439}