-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
util.go
99 lines (91 loc) · 2.38 KB
/
util.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package util
import (
"fmt"
"log"
"strings"
"sigs.k8s.io/kustomize/api/ifc"
"sigs.k8s.io/kustomize/kyaml/filesys"
)
// GlobPatterns accepts a slice of glob strings and returns the set of
// matching file paths.
func GlobPatterns(fSys filesys.FileSystem, patterns []string) ([]string, error) {
var result []string
for _, pattern := range patterns {
files, err := fSys.Glob(pattern)
if err != nil {
return nil, err
}
if len(files) == 0 {
log.Printf("%s has no match", pattern)
continue
}
result = append(result, files...)
}
return result, nil
}
// GlobPatterns accepts a slice of glob strings and returns the set of
// matching file paths. If files are not found, will try load from remote.
func GlobPatternsWithLoader(fSys filesys.FileSystem, ldr ifc.Loader, patterns []string) ([]string, error) {
var result []string
for _, pattern := range patterns {
files, err := fSys.Glob(pattern)
if err != nil {
return nil, err
}
if len(files) == 0 {
loader, err := ldr.New(pattern)
if err != nil {
log.Printf("%s has no match", pattern)
} else {
result = append(result, pattern)
if loader != nil {
loader.Cleanup()
}
}
continue
}
result = append(result, files...)
}
return result, nil
}
// ConvertToMap converts a string in the form of `key:value,key:value,...` into a map.
func ConvertToMap(input string, kind string) (map[string]string, error) {
result := make(map[string]string)
if input == "" {
return result, nil
}
inputs := strings.Split(input, ",")
return ConvertSliceToMap(inputs, kind)
}
// ConvertSliceToMap converts a slice of strings in the form of
// `key:value` into a map.
func ConvertSliceToMap(inputs []string, kind string) (map[string]string, error) {
result := make(map[string]string)
for _, input := range inputs {
c := strings.Index(input, ":")
switch {
case c == 0:
// key is not passed
return nil, fmt.Errorf("invalid %s: '%s' (%s)", kind, input, "need k:v pair where v may be quoted")
case c < 0:
// only key passed
result[input] = ""
default:
// both key and value passed
key := input[:c]
value := trimQuotes(input[c+1:])
result[key] = value
}
}
return result, nil
}
func trimQuotes(s string) string {
if len(s) >= 2 {
if s[0] == '"' && s[len(s)-1] == '"' {
return s[1 : len(s)-1]
}
}
return s
}