blob: 65c5f1b282da04d373a744ca41f7376706cdb26e [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
Colin Crossc0b06f12015-04-08 13:03:43 -070032func JoinWithPrefix(strs []string, prefix string) string {
33 if len(strs) == 0 {
34 return ""
35 }
36
37 if len(strs) == 1 {
38 return prefix + strs[0]
39 }
40
41 n := len(" ") * (len(strs) - 1)
42 for _, s := range strs {
43 n += len(prefix) + len(s)
44 }
45
46 ret := make([]byte, 0, n)
47 for i, s := range strs {
48 if i != 0 {
49 ret = append(ret, ' ')
50 }
51 ret = append(ret, prefix...)
52 ret = append(ret, s...)
53 }
54 return string(ret)
55}
Colin Cross9b6826f2015-04-10 15:47:33 -070056
Inseob Kim1f086e22019-05-09 13:29:15 +090057func JoinWithSuffix(strs []string, suffix string, separator string) string {
58 if len(strs) == 0 {
59 return ""
60 }
61
62 if len(strs) == 1 {
63 return strs[0] + suffix
64 }
65
66 n := len(" ") * (len(strs) - 1)
67 for _, s := range strs {
68 n += len(suffix) + len(s)
69 }
70
71 ret := make([]byte, 0, n)
72 for i, s := range strs {
73 if i != 0 {
74 ret = append(ret, separator...)
75 }
76 ret = append(ret, s...)
77 ret = append(ret, suffix...)
78 }
79 return string(ret)
80}
81
Ulya Trafimovichb8063c62020-08-20 11:33:12 +010082func SortedIntKeys(m interface{}) []int {
83 v := reflect.ValueOf(m)
84 if v.Kind() != reflect.Map {
85 panic(fmt.Sprintf("%#v is not a map", m))
86 }
87 keys := v.MapKeys()
88 s := make([]int, 0, len(keys))
89 for _, key := range keys {
90 s = append(s, int(key.Int()))
91 }
92 sort.Ints(s)
93 return s
94}
95
Inseob Kim1a365c62019-06-08 15:47:51 +090096func SortedStringKeys(m interface{}) []string {
97 v := reflect.ValueOf(m)
98 if v.Kind() != reflect.Map {
99 panic(fmt.Sprintf("%#v is not a map", m))
100 }
101 keys := v.MapKeys()
102 s := make([]string, 0, len(keys))
103 for _, key := range keys {
104 s = append(s, key.String())
Colin Cross1f8c52b2015-06-16 16:38:17 -0700105 }
106 sort.Strings(s)
107 return s
108}
Dan Willemsenb1957a52016-06-23 23:44:54 -0700109
Jooyung Han0302a842019-10-30 18:43:49 +0900110func SortedStringMapValues(m interface{}) []string {
111 v := reflect.ValueOf(m)
112 if v.Kind() != reflect.Map {
113 panic(fmt.Sprintf("%#v is not a map", m))
114 }
115 keys := v.MapKeys()
116 s := make([]string, 0, len(keys))
117 for _, key := range keys {
118 s = append(s, v.MapIndex(key).String())
119 }
120 sort.Strings(s)
121 return s
122}
123
Colin Crossb4330e22017-12-22 15:47:09 -0800124func IndexList(s string, list []string) int {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700125 for i, l := range list {
126 if l == s {
127 return i
128 }
129 }
130
131 return -1
132}
133
Colin Crossb4330e22017-12-22 15:47:09 -0800134func InList(s string, list []string) bool {
135 return IndexList(s, list) != -1
Dan Willemsenb1957a52016-06-23 23:44:54 -0700136}
137
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800138// Returns true if the given string s is prefixed with any string in the given prefix list.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800139func HasAnyPrefix(s string, prefixList []string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800140 for _, prefix := range prefixList {
141 if strings.HasPrefix(s, prefix) {
142 return true
143 }
144 }
145 return false
146}
147
148// Returns true if any string in the given list has the given prefix.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800149func PrefixInList(list []string, prefix string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800150 for _, s := range list {
Ivan Lozano5f595532017-07-13 14:46:05 -0700151 if strings.HasPrefix(s, prefix) {
152 return true
153 }
154 }
155 return false
156}
157
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400158// Returns true if any string in the given list has the given suffix.
159func SuffixInList(list []string, suffix string) bool {
160 for _, s := range list {
161 if strings.HasSuffix(s, suffix) {
162 return true
163 }
164 }
165 return false
166}
167
Jooyung Han12df5fb2019-07-11 16:18:47 +0900168// IndexListPred returns the index of the element which in the given `list` satisfying the predicate, or -1 if there is no such element.
169func IndexListPred(pred func(s string) bool, list []string) int {
170 for i, l := range list {
171 if pred(l) {
172 return i
173 }
174 }
175
176 return -1
177}
178
Colin Crossb4330e22017-12-22 15:47:09 -0800179func FilterList(list []string, filter []string) (remainder []string, filtered []string) {
180 for _, l := range list {
181 if InList(l, filter) {
182 filtered = append(filtered, l)
183 } else {
184 remainder = append(remainder, l)
185 }
186 }
187
188 return
189}
190
191func RemoveListFromList(list []string, filter_out []string) (result []string) {
192 result = make([]string, 0, len(list))
193 for _, l := range list {
194 if !InList(l, filter_out) {
195 result = append(result, l)
196 }
197 }
198 return
199}
200
201func RemoveFromList(s string, list []string) (bool, []string) {
202 i := IndexList(s, list)
Logan Chien7922ab82018-03-06 18:29:27 +0800203 if i == -1 {
Colin Crossb4330e22017-12-22 15:47:09 -0800204 return false, list
205 }
Logan Chien7922ab82018-03-06 18:29:27 +0800206
207 result := make([]string, 0, len(list)-1)
208 result = append(result, list[:i]...)
209 for _, l := range list[i+1:] {
210 if l != s {
211 result = append(result, l)
212 }
213 }
214 return true, result
Colin Crossb4330e22017-12-22 15:47:09 -0800215}
216
Colin Crossb6715442017-10-24 11:13:31 -0700217// FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of
218// each. It modifies the slice contents in place, and returns a subslice of the original slice.
219func FirstUniqueStrings(list []string) []string {
Colin Cross27027c72020-02-28 15:34:17 -0800220 // 128 was chosen based on BenchmarkFirstUniqueStrings results.
221 if len(list) > 128 {
222 return firstUniqueStringsMap(list)
223 }
224 return firstUniqueStringsList(list)
225}
226
227func firstUniqueStringsList(list []string) []string {
Colin Crossb6715442017-10-24 11:13:31 -0700228 k := 0
229outer:
230 for i := 0; i < len(list); i++ {
231 for j := 0; j < k; j++ {
232 if list[i] == list[j] {
233 continue outer
234 }
235 }
236 list[k] = list[i]
237 k++
238 }
239 return list[:k]
240}
241
Colin Cross27027c72020-02-28 15:34:17 -0800242func firstUniqueStringsMap(list []string) []string {
243 k := 0
244 seen := make(map[string]bool, len(list))
245 for i := 0; i < len(list); i++ {
246 if seen[list[i]] {
247 continue
248 }
249 seen[list[i]] = true
250 list[k] = list[i]
251 k++
252 }
253 return list[:k]
254}
255
Colin Crossb6715442017-10-24 11:13:31 -0700256// LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of
257// each. It modifies the slice contents in place, and returns a subslice of the original slice.
258func LastUniqueStrings(list []string) []string {
259 totalSkip := 0
260 for i := len(list) - 1; i >= totalSkip; i-- {
261 skip := 0
262 for j := i - 1; j >= totalSkip; j-- {
263 if list[i] == list[j] {
264 skip++
265 } else {
266 list[j+skip] = list[j]
267 }
268 }
269 totalSkip += skip
270 }
271 return list[totalSkip:]
272}
273
Jooyung Hane1633032019-08-01 17:41:43 +0900274// SortedUniqueStrings returns what the name says
275func SortedUniqueStrings(list []string) []string {
276 unique := FirstUniqueStrings(list)
277 sort.Strings(unique)
278 return unique
279}
280
Dan Willemsenb1957a52016-06-23 23:44:54 -0700281// checkCalledFromInit panics if a Go package's init function is not on the
282// call stack.
283func checkCalledFromInit() {
284 for skip := 3; ; skip++ {
285 _, funcName, ok := callerName(skip)
286 if !ok {
287 panic("not called from an init func")
288 }
289
Colin Cross3020fee2019-03-19 15:05:17 -0700290 if funcName == "init" || strings.HasPrefix(funcName, "init·") ||
291 strings.HasPrefix(funcName, "init.") {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700292 return
293 }
294 }
295}
296
Colin Cross3020fee2019-03-19 15:05:17 -0700297// A regex to find a package path within a function name. It finds the shortest string that is
298// followed by '.' and doesn't have any '/'s left.
299var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`)
300
Dan Willemsenb1957a52016-06-23 23:44:54 -0700301// callerName returns the package path and function name of the calling
302// function. The skip argument has the same meaning as the skip argument of
303// runtime.Callers.
304func callerName(skip int) (pkgPath, funcName string, ok bool) {
305 var pc [1]uintptr
306 n := runtime.Callers(skip+1, pc[:])
307 if n != 1 {
308 return "", "", false
309 }
310
Colin Cross3020fee2019-03-19 15:05:17 -0700311 f := runtime.FuncForPC(pc[0]).Name()
312 s := pkgPathRe.FindStringSubmatch(f)
313 if len(s) < 3 {
314 panic(fmt.Errorf("failed to extract package path and function name from %q", f))
Dan Willemsenb1957a52016-06-23 23:44:54 -0700315 }
316
Colin Cross3020fee2019-03-19 15:05:17 -0700317 return s[1], s[2], true
Dan Willemsenb1957a52016-06-23 23:44:54 -0700318}
Sundong Ahn0926fae2017-10-17 16:34:51 +0900319
320func GetNumericSdkVersion(v string) string {
321 if strings.Contains(v, "system_") {
322 return strings.Replace(v, "system_", "", 1)
323 }
324 return v
325}
Jiyong Park7f67f482019-01-05 12:57:48 +0900326
327// copied from build/kati/strutil.go
328func substPattern(pat, repl, str string) string {
329 ps := strings.SplitN(pat, "%", 2)
330 if len(ps) != 2 {
331 if str == pat {
332 return repl
333 }
334 return str
335 }
336 in := str
337 trimed := str
338 if ps[0] != "" {
339 trimed = strings.TrimPrefix(in, ps[0])
340 if trimed == in {
341 return str
342 }
343 }
344 in = trimed
345 if ps[1] != "" {
346 trimed = strings.TrimSuffix(in, ps[1])
347 if trimed == in {
348 return str
349 }
350 }
351
352 rs := strings.SplitN(repl, "%", 2)
353 if len(rs) != 2 {
354 return repl
355 }
356 return rs[0] + trimed + rs[1]
357}
358
359// copied from build/kati/strutil.go
360func matchPattern(pat, str string) bool {
361 i := strings.IndexByte(pat, '%')
362 if i < 0 {
363 return pat == str
364 }
365 return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:])
366}
Ivan Lozano022a73b2019-09-09 20:29:31 -0700367
368var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+")
369
370// splitFileExt splits a file name into root, suffix and ext. root stands for the file name without
371// the file extension and the version number (e.g. "libexample"). suffix stands for the
372// concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the
373// file extension after the version numbers are trimmed (e.g. ".so").
374func SplitFileExt(name string) (string, string, string) {
375 // Extract and trim the shared lib version number if the file name ends with dot digits.
376 suffix := ""
377 matches := shlibVersionPattern.FindAllStringIndex(name, -1)
378 if len(matches) > 0 {
379 lastMatch := matches[len(matches)-1]
380 if lastMatch[1] == len(name) {
381 suffix = name[lastMatch[0]:lastMatch[1]]
382 name = name[0:lastMatch[0]]
383 }
384 }
385
386 // Extract the file name root and the file extension.
387 ext := filepath.Ext(name)
388 root := strings.TrimSuffix(name, ext)
389 suffix = ext + suffix
390
391 return root, suffix, ext
392}
Colin Cross0a2f7192019-09-23 14:33:09 -0700393
394// ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths.
395func ShardPaths(paths Paths, shardSize int) []Paths {
396 if len(paths) == 0 {
397 return nil
398 }
399 ret := make([]Paths, 0, (len(paths)+shardSize-1)/shardSize)
400 for len(paths) > shardSize {
401 ret = append(ret, paths[0:shardSize])
402 paths = paths[shardSize:]
403 }
404 if len(paths) > 0 {
405 ret = append(ret, paths)
406 }
407 return ret
408}
409
410// ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize
411// elements.
412func ShardStrings(s []string, shardSize int) [][]string {
413 if len(s) == 0 {
414 return nil
415 }
416 ret := make([][]string, 0, (len(s)+shardSize-1)/shardSize)
417 for len(s) > shardSize {
418 ret = append(ret, s[0:shardSize])
419 s = s[shardSize:]
420 }
421 if len(s) > 0 {
422 ret = append(ret, s)
423 }
424 return ret
425}
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700426
427func CheckDuplicate(values []string) (duplicate string, found bool) {
428 seen := make(map[string]string)
429 for _, v := range values {
430 if duplicate, found = seen[v]; found {
431 return
432 }
433 seen[v] = v
434 }
435 return
436}