blob: 8e4c0f4768346696e8eeaf5f9f3b260bc1a03375 [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// SortedIntKeys returns the keys of the given integer-keyed map in the ascending order
69// TODO(asmundak): once Go has generics, combine this with SortedStringKeys below.
Ulya Trafimovichb8063c62020-08-20 11:33:12 +010070func SortedIntKeys(m interface{}) []int {
71 v := reflect.ValueOf(m)
72 if v.Kind() != reflect.Map {
73 panic(fmt.Sprintf("%#v is not a map", m))
74 }
75 keys := v.MapKeys()
76 s := make([]int, 0, len(keys))
77 for _, key := range keys {
78 s = append(s, int(key.Int()))
79 }
80 sort.Ints(s)
81 return s
82}
83
Sasha Smundak1e533922020-11-19 16:48:18 -080084// SorterStringKeys returns the keys of the given string-keyed map in the ascending order
Inseob Kim1a365c62019-06-08 15:47:51 +090085func SortedStringKeys(m interface{}) []string {
86 v := reflect.ValueOf(m)
87 if v.Kind() != reflect.Map {
88 panic(fmt.Sprintf("%#v is not a map", m))
89 }
90 keys := v.MapKeys()
91 s := make([]string, 0, len(keys))
92 for _, key := range keys {
93 s = append(s, key.String())
Colin Cross1f8c52b2015-06-16 16:38:17 -070094 }
95 sort.Strings(s)
96 return s
97}
Dan Willemsenb1957a52016-06-23 23:44:54 -070098
Sasha Smundak1e533922020-11-19 16:48:18 -080099// SortedStringMapValues returns the values of the string-values map in the ascending order
Jooyung Han0302a842019-10-30 18:43:49 +0900100func SortedStringMapValues(m interface{}) []string {
101 v := reflect.ValueOf(m)
102 if v.Kind() != reflect.Map {
103 panic(fmt.Sprintf("%#v is not a map", m))
104 }
105 keys := v.MapKeys()
106 s := make([]string, 0, len(keys))
107 for _, key := range keys {
108 s = append(s, v.MapIndex(key).String())
109 }
110 sort.Strings(s)
111 return s
112}
113
Sasha Smundak1e533922020-11-19 16:48:18 -0800114// IndexList returns the index of the first occurrence of the given string in the list or -1
Colin Crossb4330e22017-12-22 15:47:09 -0800115func IndexList(s string, list []string) int {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700116 for i, l := range list {
117 if l == s {
118 return i
119 }
120 }
121
122 return -1
123}
124
Sasha Smundak1e533922020-11-19 16:48:18 -0800125// InList checks if the string belongs to the list
Colin Crossb4330e22017-12-22 15:47:09 -0800126func InList(s string, list []string) bool {
127 return IndexList(s, list) != -1
Dan Willemsenb1957a52016-06-23 23:44:54 -0700128}
129
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800130// Returns true if the given string s is prefixed with any string in the given prefix list.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800131func HasAnyPrefix(s string, prefixList []string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800132 for _, prefix := range prefixList {
133 if strings.HasPrefix(s, prefix) {
134 return true
135 }
136 }
137 return false
138}
139
140// Returns true if any string in the given list has the given prefix.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800141func PrefixInList(list []string, prefix string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800142 for _, s := range list {
Ivan Lozano5f595532017-07-13 14:46:05 -0700143 if strings.HasPrefix(s, prefix) {
144 return true
145 }
146 }
147 return false
148}
149
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400150// Returns true if any string in the given list has the given suffix.
151func SuffixInList(list []string, suffix string) bool {
152 for _, s := range list {
153 if strings.HasSuffix(s, suffix) {
154 return true
155 }
156 }
157 return false
158}
159
Jooyung Han12df5fb2019-07-11 16:18:47 +0900160// IndexListPred returns the index of the element which in the given `list` satisfying the predicate, or -1 if there is no such element.
161func IndexListPred(pred func(s string) bool, list []string) int {
162 for i, l := range list {
163 if pred(l) {
164 return i
165 }
166 }
167
168 return -1
169}
170
Sasha Smundak1e533922020-11-19 16:48:18 -0800171// FilterList divides the string list into two lists: one with the strings belonging
172// to the given filter list, and the other with the remaining ones
Colin Crossb4330e22017-12-22 15:47:09 -0800173func FilterList(list []string, filter []string) (remainder []string, filtered []string) {
Sasha Smundak1e533922020-11-19 16:48:18 -0800174 // InList is O(n). May be worth using more efficient lookup for longer lists.
Colin Crossb4330e22017-12-22 15:47:09 -0800175 for _, l := range list {
176 if InList(l, filter) {
177 filtered = append(filtered, l)
178 } else {
179 remainder = append(remainder, l)
180 }
181 }
182
183 return
184}
185
Sasha Smundak1e533922020-11-19 16:48:18 -0800186// RemoveListFromList removes the strings belonging to the filter list from the
187// given list and returns the result
Colin Crossb4330e22017-12-22 15:47:09 -0800188func RemoveListFromList(list []string, filter_out []string) (result []string) {
189 result = make([]string, 0, len(list))
190 for _, l := range list {
191 if !InList(l, filter_out) {
192 result = append(result, l)
193 }
194 }
195 return
196}
197
Sasha Smundak1e533922020-11-19 16:48:18 -0800198// RemoveFromList removes given string from the string list.
Colin Crossb4330e22017-12-22 15:47:09 -0800199func RemoveFromList(s string, list []string) (bool, []string) {
Sasha Smundak1e533922020-11-19 16:48:18 -0800200 result := make([]string, 0, len(list))
201 var removed bool
202 for _, item := range list {
203 if item != s {
204 result = append(result, item)
205 } else {
206 removed = true
Logan Chien7922ab82018-03-06 18:29:27 +0800207 }
208 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800209 return removed, result
Colin Crossb4330e22017-12-22 15:47:09 -0800210}
211
Colin Crossb6715442017-10-24 11:13:31 -0700212// FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of
213// each. It modifies the slice contents in place, and returns a subslice of the original slice.
214func FirstUniqueStrings(list []string) []string {
Colin Cross27027c72020-02-28 15:34:17 -0800215 // 128 was chosen based on BenchmarkFirstUniqueStrings results.
216 if len(list) > 128 {
217 return firstUniqueStringsMap(list)
218 }
219 return firstUniqueStringsList(list)
220}
221
222func firstUniqueStringsList(list []string) []string {
Colin Crossb6715442017-10-24 11:13:31 -0700223 k := 0
224outer:
225 for i := 0; i < len(list); i++ {
226 for j := 0; j < k; j++ {
227 if list[i] == list[j] {
228 continue outer
229 }
230 }
231 list[k] = list[i]
232 k++
233 }
234 return list[:k]
235}
236
Colin Cross27027c72020-02-28 15:34:17 -0800237func firstUniqueStringsMap(list []string) []string {
238 k := 0
239 seen := make(map[string]bool, len(list))
240 for i := 0; i < len(list); i++ {
241 if seen[list[i]] {
242 continue
243 }
244 seen[list[i]] = true
245 list[k] = list[i]
246 k++
247 }
248 return list[:k]
249}
250
Colin Crossb6715442017-10-24 11:13:31 -0700251// LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of
252// each. It modifies the slice contents in place, and returns a subslice of the original slice.
253func LastUniqueStrings(list []string) []string {
254 totalSkip := 0
255 for i := len(list) - 1; i >= totalSkip; i-- {
256 skip := 0
257 for j := i - 1; j >= totalSkip; j-- {
258 if list[i] == list[j] {
259 skip++
260 } else {
261 list[j+skip] = list[j]
262 }
263 }
264 totalSkip += skip
265 }
266 return list[totalSkip:]
267}
268
Jooyung Hane1633032019-08-01 17:41:43 +0900269// SortedUniqueStrings returns what the name says
270func SortedUniqueStrings(list []string) []string {
271 unique := FirstUniqueStrings(list)
272 sort.Strings(unique)
273 return unique
274}
275
Dan Willemsenb1957a52016-06-23 23:44:54 -0700276// checkCalledFromInit panics if a Go package's init function is not on the
277// call stack.
278func checkCalledFromInit() {
279 for skip := 3; ; skip++ {
280 _, funcName, ok := callerName(skip)
281 if !ok {
282 panic("not called from an init func")
283 }
284
Colin Cross3020fee2019-03-19 15:05:17 -0700285 if funcName == "init" || strings.HasPrefix(funcName, "init·") ||
286 strings.HasPrefix(funcName, "init.") {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700287 return
288 }
289 }
290}
291
Colin Cross3020fee2019-03-19 15:05:17 -0700292// A regex to find a package path within a function name. It finds the shortest string that is
293// followed by '.' and doesn't have any '/'s left.
294var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`)
295
Dan Willemsenb1957a52016-06-23 23:44:54 -0700296// callerName returns the package path and function name of the calling
297// function. The skip argument has the same meaning as the skip argument of
298// runtime.Callers.
299func callerName(skip int) (pkgPath, funcName string, ok bool) {
300 var pc [1]uintptr
301 n := runtime.Callers(skip+1, pc[:])
302 if n != 1 {
303 return "", "", false
304 }
305
Colin Cross3020fee2019-03-19 15:05:17 -0700306 f := runtime.FuncForPC(pc[0]).Name()
307 s := pkgPathRe.FindStringSubmatch(f)
308 if len(s) < 3 {
309 panic(fmt.Errorf("failed to extract package path and function name from %q", f))
Dan Willemsenb1957a52016-06-23 23:44:54 -0700310 }
311
Colin Cross3020fee2019-03-19 15:05:17 -0700312 return s[1], s[2], true
Dan Willemsenb1957a52016-06-23 23:44:54 -0700313}
Sundong Ahn0926fae2017-10-17 16:34:51 +0900314
Sasha Smundak1e533922020-11-19 16:48:18 -0800315// GetNumericSdkVersion removes the first occurrence of system_ in a string,
316// which is assumed to be something like "system_1.2.3"
Sundong Ahn0926fae2017-10-17 16:34:51 +0900317func GetNumericSdkVersion(v string) string {
Sasha Smundak1e533922020-11-19 16:48:18 -0800318 return strings.Replace(v, "system_", "", 1)
Sundong Ahn0926fae2017-10-17 16:34:51 +0900319}
Jiyong Park7f67f482019-01-05 12:57:48 +0900320
321// copied from build/kati/strutil.go
322func substPattern(pat, repl, str string) string {
323 ps := strings.SplitN(pat, "%", 2)
324 if len(ps) != 2 {
325 if str == pat {
326 return repl
327 }
328 return str
329 }
330 in := str
Sasha Smundak1e533922020-11-19 16:48:18 -0800331 trimmed := str
Jiyong Park7f67f482019-01-05 12:57:48 +0900332 if ps[0] != "" {
Sasha Smundak1e533922020-11-19 16:48:18 -0800333 trimmed = strings.TrimPrefix(in, ps[0])
334 if trimmed == in {
Jiyong Park7f67f482019-01-05 12:57:48 +0900335 return str
336 }
337 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800338 in = trimmed
Jiyong Park7f67f482019-01-05 12:57:48 +0900339 if ps[1] != "" {
Sasha Smundak1e533922020-11-19 16:48:18 -0800340 trimmed = strings.TrimSuffix(in, ps[1])
341 if trimmed == in {
Jiyong Park7f67f482019-01-05 12:57:48 +0900342 return str
343 }
344 }
345
346 rs := strings.SplitN(repl, "%", 2)
347 if len(rs) != 2 {
348 return repl
349 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800350 return rs[0] + trimmed + rs[1]
Jiyong Park7f67f482019-01-05 12:57:48 +0900351}
352
353// copied from build/kati/strutil.go
354func matchPattern(pat, str string) bool {
355 i := strings.IndexByte(pat, '%')
356 if i < 0 {
357 return pat == str
358 }
359 return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:])
360}
Ivan Lozano022a73b2019-09-09 20:29:31 -0700361
362var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+")
363
364// splitFileExt splits a file name into root, suffix and ext. root stands for the file name without
365// the file extension and the version number (e.g. "libexample"). suffix stands for the
366// concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the
367// file extension after the version numbers are trimmed (e.g. ".so").
368func SplitFileExt(name string) (string, string, string) {
369 // Extract and trim the shared lib version number if the file name ends with dot digits.
370 suffix := ""
371 matches := shlibVersionPattern.FindAllStringIndex(name, -1)
372 if len(matches) > 0 {
373 lastMatch := matches[len(matches)-1]
374 if lastMatch[1] == len(name) {
375 suffix = name[lastMatch[0]:lastMatch[1]]
376 name = name[0:lastMatch[0]]
377 }
378 }
379
380 // Extract the file name root and the file extension.
381 ext := filepath.Ext(name)
382 root := strings.TrimSuffix(name, ext)
383 suffix = ext + suffix
384
385 return root, suffix, ext
386}
Colin Cross0a2f7192019-09-23 14:33:09 -0700387
388// ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths.
389func ShardPaths(paths Paths, shardSize int) []Paths {
390 if len(paths) == 0 {
391 return nil
392 }
393 ret := make([]Paths, 0, (len(paths)+shardSize-1)/shardSize)
394 for len(paths) > shardSize {
395 ret = append(ret, paths[0:shardSize])
396 paths = paths[shardSize:]
397 }
398 if len(paths) > 0 {
399 ret = append(ret, paths)
400 }
401 return ret
402}
403
404// ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize
405// elements.
406func ShardStrings(s []string, shardSize int) [][]string {
407 if len(s) == 0 {
408 return nil
409 }
410 ret := make([][]string, 0, (len(s)+shardSize-1)/shardSize)
411 for len(s) > shardSize {
412 ret = append(ret, s[0:shardSize])
413 s = s[shardSize:]
414 }
415 if len(s) > 0 {
416 ret = append(ret, s)
417 }
418 return ret
419}
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700420
Sasha Smundak1e533922020-11-19 16:48:18 -0800421// CheckDuplicate checks if there are duplicates in given string list.
422// If there are, it returns first such duplicate and true.
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700423func CheckDuplicate(values []string) (duplicate string, found bool) {
424 seen := make(map[string]string)
425 for _, v := range values {
426 if duplicate, found = seen[v]; found {
Sasha Smundak1e533922020-11-19 16:48:18 -0800427 return duplicate, true
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700428 }
429 seen[v] = v
430 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800431 return "", false
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700432}