blob: efe12de5fe43b948705760e5ba983e21c07edb1f [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
Colin Crossb4330e22017-12-22 15:47:09 -0800124func PrefixInList(s string, list []string) bool {
Ivan Lozano5f595532017-07-13 14:46:05 -0700125 for _, prefix := range list {
126 if strings.HasPrefix(s, prefix) {
127 return true
128 }
129 }
130 return false
131}
132
Jooyung Han12df5fb2019-07-11 16:18:47 +0900133// IndexListPred returns the index of the element which in the given `list` satisfying the predicate, or -1 if there is no such element.
134func IndexListPred(pred func(s string) bool, list []string) int {
135 for i, l := range list {
136 if pred(l) {
137 return i
138 }
139 }
140
141 return -1
142}
143
Colin Crossb4330e22017-12-22 15:47:09 -0800144func FilterList(list []string, filter []string) (remainder []string, filtered []string) {
145 for _, l := range list {
146 if InList(l, filter) {
147 filtered = append(filtered, l)
148 } else {
149 remainder = append(remainder, l)
150 }
151 }
152
153 return
154}
155
156func RemoveListFromList(list []string, filter_out []string) (result []string) {
157 result = make([]string, 0, len(list))
158 for _, l := range list {
159 if !InList(l, filter_out) {
160 result = append(result, l)
161 }
162 }
163 return
164}
165
166func RemoveFromList(s string, list []string) (bool, []string) {
167 i := IndexList(s, list)
Logan Chien7922ab82018-03-06 18:29:27 +0800168 if i == -1 {
Colin Crossb4330e22017-12-22 15:47:09 -0800169 return false, list
170 }
Logan Chien7922ab82018-03-06 18:29:27 +0800171
172 result := make([]string, 0, len(list)-1)
173 result = append(result, list[:i]...)
174 for _, l := range list[i+1:] {
175 if l != s {
176 result = append(result, l)
177 }
178 }
179 return true, result
Colin Crossb4330e22017-12-22 15:47:09 -0800180}
181
Colin Crossb6715442017-10-24 11:13:31 -0700182// FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of
183// each. It modifies the slice contents in place, and returns a subslice of the original slice.
184func FirstUniqueStrings(list []string) []string {
185 k := 0
186outer:
187 for i := 0; i < len(list); i++ {
188 for j := 0; j < k; j++ {
189 if list[i] == list[j] {
190 continue outer
191 }
192 }
193 list[k] = list[i]
194 k++
195 }
196 return list[:k]
197}
198
199// LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of
200// each. It modifies the slice contents in place, and returns a subslice of the original slice.
201func LastUniqueStrings(list []string) []string {
202 totalSkip := 0
203 for i := len(list) - 1; i >= totalSkip; i-- {
204 skip := 0
205 for j := i - 1; j >= totalSkip; j-- {
206 if list[i] == list[j] {
207 skip++
208 } else {
209 list[j+skip] = list[j]
210 }
211 }
212 totalSkip += skip
213 }
214 return list[totalSkip:]
215}
216
Jooyung Hane1633032019-08-01 17:41:43 +0900217// SortedUniqueStrings returns what the name says
218func SortedUniqueStrings(list []string) []string {
219 unique := FirstUniqueStrings(list)
220 sort.Strings(unique)
221 return unique
222}
223
Dan Willemsenb1957a52016-06-23 23:44:54 -0700224// checkCalledFromInit panics if a Go package's init function is not on the
225// call stack.
226func checkCalledFromInit() {
227 for skip := 3; ; skip++ {
228 _, funcName, ok := callerName(skip)
229 if !ok {
230 panic("not called from an init func")
231 }
232
Colin Cross3020fee2019-03-19 15:05:17 -0700233 if funcName == "init" || strings.HasPrefix(funcName, "init·") ||
234 strings.HasPrefix(funcName, "init.") {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700235 return
236 }
237 }
238}
239
Colin Cross3020fee2019-03-19 15:05:17 -0700240// A regex to find a package path within a function name. It finds the shortest string that is
241// followed by '.' and doesn't have any '/'s left.
242var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`)
243
Dan Willemsenb1957a52016-06-23 23:44:54 -0700244// callerName returns the package path and function name of the calling
245// function. The skip argument has the same meaning as the skip argument of
246// runtime.Callers.
247func callerName(skip int) (pkgPath, funcName string, ok bool) {
248 var pc [1]uintptr
249 n := runtime.Callers(skip+1, pc[:])
250 if n != 1 {
251 return "", "", false
252 }
253
Colin Cross3020fee2019-03-19 15:05:17 -0700254 f := runtime.FuncForPC(pc[0]).Name()
255 s := pkgPathRe.FindStringSubmatch(f)
256 if len(s) < 3 {
257 panic(fmt.Errorf("failed to extract package path and function name from %q", f))
Dan Willemsenb1957a52016-06-23 23:44:54 -0700258 }
259
Colin Cross3020fee2019-03-19 15:05:17 -0700260 return s[1], s[2], true
Dan Willemsenb1957a52016-06-23 23:44:54 -0700261}
Sundong Ahn0926fae2017-10-17 16:34:51 +0900262
263func GetNumericSdkVersion(v string) string {
264 if strings.Contains(v, "system_") {
265 return strings.Replace(v, "system_", "", 1)
266 }
267 return v
268}
Jiyong Park7f67f482019-01-05 12:57:48 +0900269
270// copied from build/kati/strutil.go
271func substPattern(pat, repl, str string) string {
272 ps := strings.SplitN(pat, "%", 2)
273 if len(ps) != 2 {
274 if str == pat {
275 return repl
276 }
277 return str
278 }
279 in := str
280 trimed := str
281 if ps[0] != "" {
282 trimed = strings.TrimPrefix(in, ps[0])
283 if trimed == in {
284 return str
285 }
286 }
287 in = trimed
288 if ps[1] != "" {
289 trimed = strings.TrimSuffix(in, ps[1])
290 if trimed == in {
291 return str
292 }
293 }
294
295 rs := strings.SplitN(repl, "%", 2)
296 if len(rs) != 2 {
297 return repl
298 }
299 return rs[0] + trimed + rs[1]
300}
301
302// copied from build/kati/strutil.go
303func matchPattern(pat, str string) bool {
304 i := strings.IndexByte(pat, '%')
305 if i < 0 {
306 return pat == str
307 }
308 return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:])
309}
Ivan Lozano022a73b2019-09-09 20:29:31 -0700310
311var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+")
312
313// splitFileExt splits a file name into root, suffix and ext. root stands for the file name without
314// the file extension and the version number (e.g. "libexample"). suffix stands for the
315// concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the
316// file extension after the version numbers are trimmed (e.g. ".so").
317func SplitFileExt(name string) (string, string, string) {
318 // Extract and trim the shared lib version number if the file name ends with dot digits.
319 suffix := ""
320 matches := shlibVersionPattern.FindAllStringIndex(name, -1)
321 if len(matches) > 0 {
322 lastMatch := matches[len(matches)-1]
323 if lastMatch[1] == len(name) {
324 suffix = name[lastMatch[0]:lastMatch[1]]
325 name = name[0:lastMatch[0]]
326 }
327 }
328
329 // Extract the file name root and the file extension.
330 ext := filepath.Ext(name)
331 root := strings.TrimSuffix(name, ext)
332 suffix = ext + suffix
333
334 return root, suffix, ext
335}
Colin Cross0a2f7192019-09-23 14:33:09 -0700336
337// ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths.
338func ShardPaths(paths Paths, shardSize int) []Paths {
339 if len(paths) == 0 {
340 return nil
341 }
342 ret := make([]Paths, 0, (len(paths)+shardSize-1)/shardSize)
343 for len(paths) > shardSize {
344 ret = append(ret, paths[0:shardSize])
345 paths = paths[shardSize:]
346 }
347 if len(paths) > 0 {
348 ret = append(ret, paths)
349 }
350 return ret
351}
352
353// ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize
354// elements.
355func ShardStrings(s []string, shardSize int) [][]string {
356 if len(s) == 0 {
357 return nil
358 }
359 ret := make([][]string, 0, (len(s)+shardSize-1)/shardSize)
360 for len(s) > shardSize {
361 ret = append(ret, s[0:shardSize])
362 s = s[shardSize:]
363 }
364 if len(s) > 0 {
365 ret = append(ret, s)
366 }
367 return ret
368}