blob: ade851eff06f70360fe8ce1bd75d1a9e4da5fe43 [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
Inseob Kim1a365c62019-06-08 15:47:51 +090082func SortedStringKeys(m interface{}) []string {
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([]string, 0, len(keys))
89 for _, key := range keys {
90 s = append(s, key.String())
Colin Cross1f8c52b2015-06-16 16:38:17 -070091 }
92 sort.Strings(s)
93 return s
94}
Dan Willemsenb1957a52016-06-23 23:44:54 -070095
Jooyung Han0302a842019-10-30 18:43:49 +090096func SortedStringMapValues(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, v.MapIndex(key).String())
105 }
106 sort.Strings(s)
107 return s
108}
109
Colin Crossb4330e22017-12-22 15:47:09 -0800110func IndexList(s string, list []string) int {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700111 for i, l := range list {
112 if l == s {
113 return i
114 }
115 }
116
117 return -1
118}
119
Colin Crossb4330e22017-12-22 15:47:09 -0800120func InList(s string, list []string) bool {
121 return IndexList(s, list) != -1
Dan Willemsenb1957a52016-06-23 23:44:54 -0700122}
123
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800124// Returns true if the given string s is prefixed with any string in the given prefix list.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800125func HasAnyPrefix(s string, prefixList []string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800126 for _, prefix := range prefixList {
127 if strings.HasPrefix(s, prefix) {
128 return true
129 }
130 }
131 return false
132}
133
134// Returns true if any string in the given list has the given prefix.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800135func PrefixInList(list []string, prefix string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800136 for _, s := range list {
Ivan Lozano5f595532017-07-13 14:46:05 -0700137 if strings.HasPrefix(s, prefix) {
138 return true
139 }
140 }
141 return false
142}
143
Jooyung Han12df5fb2019-07-11 16:18:47 +0900144// IndexListPred returns the index of the element which in the given `list` satisfying the predicate, or -1 if there is no such element.
145func IndexListPred(pred func(s string) bool, list []string) int {
146 for i, l := range list {
147 if pred(l) {
148 return i
149 }
150 }
151
152 return -1
153}
154
Colin Crossb4330e22017-12-22 15:47:09 -0800155func FilterList(list []string, filter []string) (remainder []string, filtered []string) {
156 for _, l := range list {
157 if InList(l, filter) {
158 filtered = append(filtered, l)
159 } else {
160 remainder = append(remainder, l)
161 }
162 }
163
164 return
165}
166
167func RemoveListFromList(list []string, filter_out []string) (result []string) {
168 result = make([]string, 0, len(list))
169 for _, l := range list {
170 if !InList(l, filter_out) {
171 result = append(result, l)
172 }
173 }
174 return
175}
176
177func RemoveFromList(s string, list []string) (bool, []string) {
178 i := IndexList(s, list)
Logan Chien7922ab82018-03-06 18:29:27 +0800179 if i == -1 {
Colin Crossb4330e22017-12-22 15:47:09 -0800180 return false, list
181 }
Logan Chien7922ab82018-03-06 18:29:27 +0800182
183 result := make([]string, 0, len(list)-1)
184 result = append(result, list[:i]...)
185 for _, l := range list[i+1:] {
186 if l != s {
187 result = append(result, l)
188 }
189 }
190 return true, result
Colin Crossb4330e22017-12-22 15:47:09 -0800191}
192
Colin Crossb6715442017-10-24 11:13:31 -0700193// FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of
194// each. It modifies the slice contents in place, and returns a subslice of the original slice.
195func FirstUniqueStrings(list []string) []string {
196 k := 0
197outer:
198 for i := 0; i < len(list); i++ {
199 for j := 0; j < k; j++ {
200 if list[i] == list[j] {
201 continue outer
202 }
203 }
204 list[k] = list[i]
205 k++
206 }
207 return list[:k]
208}
209
210// LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of
211// each. It modifies the slice contents in place, and returns a subslice of the original slice.
212func LastUniqueStrings(list []string) []string {
213 totalSkip := 0
214 for i := len(list) - 1; i >= totalSkip; i-- {
215 skip := 0
216 for j := i - 1; j >= totalSkip; j-- {
217 if list[i] == list[j] {
218 skip++
219 } else {
220 list[j+skip] = list[j]
221 }
222 }
223 totalSkip += skip
224 }
225 return list[totalSkip:]
226}
227
Jooyung Hane1633032019-08-01 17:41:43 +0900228// SortedUniqueStrings returns what the name says
229func SortedUniqueStrings(list []string) []string {
230 unique := FirstUniqueStrings(list)
231 sort.Strings(unique)
232 return unique
233}
234
Dan Willemsenb1957a52016-06-23 23:44:54 -0700235// checkCalledFromInit panics if a Go package's init function is not on the
236// call stack.
237func checkCalledFromInit() {
238 for skip := 3; ; skip++ {
239 _, funcName, ok := callerName(skip)
240 if !ok {
241 panic("not called from an init func")
242 }
243
Colin Cross3020fee2019-03-19 15:05:17 -0700244 if funcName == "init" || strings.HasPrefix(funcName, "init·") ||
245 strings.HasPrefix(funcName, "init.") {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700246 return
247 }
248 }
249}
250
Colin Cross3020fee2019-03-19 15:05:17 -0700251// A regex to find a package path within a function name. It finds the shortest string that is
252// followed by '.' and doesn't have any '/'s left.
253var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`)
254
Dan Willemsenb1957a52016-06-23 23:44:54 -0700255// callerName returns the package path and function name of the calling
256// function. The skip argument has the same meaning as the skip argument of
257// runtime.Callers.
258func callerName(skip int) (pkgPath, funcName string, ok bool) {
259 var pc [1]uintptr
260 n := runtime.Callers(skip+1, pc[:])
261 if n != 1 {
262 return "", "", false
263 }
264
Colin Cross3020fee2019-03-19 15:05:17 -0700265 f := runtime.FuncForPC(pc[0]).Name()
266 s := pkgPathRe.FindStringSubmatch(f)
267 if len(s) < 3 {
268 panic(fmt.Errorf("failed to extract package path and function name from %q", f))
Dan Willemsenb1957a52016-06-23 23:44:54 -0700269 }
270
Colin Cross3020fee2019-03-19 15:05:17 -0700271 return s[1], s[2], true
Dan Willemsenb1957a52016-06-23 23:44:54 -0700272}
Sundong Ahn0926fae2017-10-17 16:34:51 +0900273
274func GetNumericSdkVersion(v string) string {
275 if strings.Contains(v, "system_") {
276 return strings.Replace(v, "system_", "", 1)
277 }
278 return v
279}
Jiyong Park7f67f482019-01-05 12:57:48 +0900280
281// copied from build/kati/strutil.go
282func substPattern(pat, repl, str string) string {
283 ps := strings.SplitN(pat, "%", 2)
284 if len(ps) != 2 {
285 if str == pat {
286 return repl
287 }
288 return str
289 }
290 in := str
291 trimed := str
292 if ps[0] != "" {
293 trimed = strings.TrimPrefix(in, ps[0])
294 if trimed == in {
295 return str
296 }
297 }
298 in = trimed
299 if ps[1] != "" {
300 trimed = strings.TrimSuffix(in, ps[1])
301 if trimed == in {
302 return str
303 }
304 }
305
306 rs := strings.SplitN(repl, "%", 2)
307 if len(rs) != 2 {
308 return repl
309 }
310 return rs[0] + trimed + rs[1]
311}
312
313// copied from build/kati/strutil.go
314func matchPattern(pat, str string) bool {
315 i := strings.IndexByte(pat, '%')
316 if i < 0 {
317 return pat == str
318 }
319 return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:])
320}
Ivan Lozano022a73b2019-09-09 20:29:31 -0700321
322var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+")
323
324// splitFileExt splits a file name into root, suffix and ext. root stands for the file name without
325// the file extension and the version number (e.g. "libexample"). suffix stands for the
326// concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the
327// file extension after the version numbers are trimmed (e.g. ".so").
328func SplitFileExt(name string) (string, string, string) {
329 // Extract and trim the shared lib version number if the file name ends with dot digits.
330 suffix := ""
331 matches := shlibVersionPattern.FindAllStringIndex(name, -1)
332 if len(matches) > 0 {
333 lastMatch := matches[len(matches)-1]
334 if lastMatch[1] == len(name) {
335 suffix = name[lastMatch[0]:lastMatch[1]]
336 name = name[0:lastMatch[0]]
337 }
338 }
339
340 // Extract the file name root and the file extension.
341 ext := filepath.Ext(name)
342 root := strings.TrimSuffix(name, ext)
343 suffix = ext + suffix
344
345 return root, suffix, ext
346}
Colin Cross0a2f7192019-09-23 14:33:09 -0700347
348// ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths.
349func ShardPaths(paths Paths, shardSize int) []Paths {
350 if len(paths) == 0 {
351 return nil
352 }
353 ret := make([]Paths, 0, (len(paths)+shardSize-1)/shardSize)
354 for len(paths) > shardSize {
355 ret = append(ret, paths[0:shardSize])
356 paths = paths[shardSize:]
357 }
358 if len(paths) > 0 {
359 ret = append(ret, paths)
360 }
361 return ret
362}
363
364// ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize
365// elements.
366func ShardStrings(s []string, shardSize int) [][]string {
367 if len(s) == 0 {
368 return nil
369 }
370 ret := make([][]string, 0, (len(s)+shardSize-1)/shardSize)
371 for len(s) > shardSize {
372 ret = append(ret, s[0:shardSize])
373 s = s[shardSize:]
374 }
375 if len(s) > 0 {
376 ret = append(ret, s)
377 }
378 return ret
379}
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700380
381func CheckDuplicate(values []string) (duplicate string, found bool) {
382 seen := make(map[string]string)
383 for _, v := range values {
384 if duplicate, found = seen[v]; found {
385 return
386 }
387 seen[v] = v
388 }
389 return
390}