-
Notifications
You must be signed in to change notification settings - Fork 17
/
utils.go
67 lines (60 loc) · 1.43 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and Open Component Model contributors.
//
// SPDX-License-Identifier: Apache-2.0
package cpi
import (
"strings"
"github.com/open-component-model/ocm/v2/pkg/contexts/oci/grammar"
)
type StringList []string
func (s *StringList) Add(n string) {
for _, e := range *s {
if n == e {
return
}
}
*s = append(*s, n)
}
func FilterByNamespacePrefix(prefix string, list []string) []string {
result := []string{}
sub := prefix
if prefix != "" && !strings.HasSuffix(prefix, grammar.RepositorySeparator) {
sub = prefix + grammar.RepositorySeparator
}
for _, k := range list {
if k == prefix || strings.HasPrefix(k, sub) {
result = append(result, k)
}
}
return result
}
func FilterChildren(closure bool, prefix string, list []string) []string {
if closure {
return FilterByNamespacePrefix(prefix, list)
}
sub := prefix
if prefix != "" && !strings.HasSuffix(prefix, grammar.RepositorySeparator) {
sub = prefix + grammar.RepositorySeparator
}
set := map[string]bool{}
for _, n := range list {
if n == prefix {
set[n] = true
} else if strings.HasPrefix(n, sub) {
rest := n[len(sub):]
i := strings.Index(rest, grammar.RepositorySeparator)
if i < 0 {
set[n] = true
} else {
set[n[:i+len(sub)]] = true
}
}
}
result := make([]string, 0, len(set))
for _, n := range list {
if set[n] {
result = append(result, n)
}
}
return result
}