-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathutil.go
184 lines (152 loc) · 3.81 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package util
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net/url"
"os"
"os/user"
"strings"
"text/template"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
const HOST_COLLECTORS_RUN_AS_ROOT_PROMPT = "Some host collectors need to be run as root.\nDo you want to exit and rerun the command using sudo?"
type Keyer interface {
UniqKey() string
}
func HomeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}
func IsURL(str string) bool {
parsed, err := url.ParseRequestURI(str)
if err != nil {
return false
}
return parsed.Scheme != ""
}
func AppName(name string) string {
words := strings.Split(cases.Title(language.English).String(strings.ReplaceAll(name, "-", " ")), " ")
casedWords := []string{}
for i, word := range words {
if strings.ToLower(word) == "ai" {
casedWords = append(casedWords, "AI")
} else if strings.ToLower(word) == "io" && i > 0 {
casedWords[i-1] += ".io"
} else {
casedWords = append(casedWords, word)
}
}
return strings.Join(casedWords, " ")
}
func SplitYAML(doc string) []string {
return strings.Split(doc, "\n---\n")
}
func EstimateNumberOfLines(text string) int {
n := strings.Count(text, "\n")
if len(text) > 0 && !strings.HasSuffix(text, "\n") {
n++
}
return n
}
// Append appends elements in src to target.
// We have this function because of how the
// builtin append() function works. It treats
// target nil slices the same as empty slices.
func Append[T any](target []T, src []T) []T {
// Do nothing only if src is nil
if src == nil {
return target
}
// In case target is nil, we need to initialize it
// since append() will not do it for us when len(src) == 0
if target == nil {
target = []T{}
}
return append(target, src...)
}
// IsInCluster returns true if the code is running within a process
// inside a kubernetes pod
func IsInCluster() bool {
// This is a best effort check, it's not guaranteed to be accurate
host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT")
if len(host) == 0 || len(port) == 0 {
return false
}
return true
}
// RenderTemplate renders a template and returns the result as a string
func RenderTemplate(tpl string, data interface{}) (string, error) {
// Create a new template and parse the letter into it
t, err := template.New("data").Parse(tpl)
if err != nil {
return "", err
}
// Create a new buffer
buf := new(bytes.Buffer)
// Execute the template and write the bytes to the buffer
err = t.Execute(buf, data)
if err != nil {
return "", err
}
// Return the string representation of the buffer
return buf.String(), nil
}
func IsRunningAsRoot() bool {
currentUser, err := user.Current()
if err != nil {
return false
}
// Check if the user ID is 0 (root's UID)
return currentUser.Uid == "0"
}
func PromptYesNo(question string) bool {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Printf("%s (yes/no): ", question)
response, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading response:", err)
continue
}
response = strings.TrimSpace(response)
response = strings.ToLower(response)
if response == "yes" || response == "y" {
return true
} else if response == "no" || response == "n" {
return false
} else {
fmt.Println("Please type 'yes' or 'no'.")
}
}
}
func Dedup[T any](objs []T) []T {
seen := make(map[string]bool)
out := []T{}
if len(objs) == 0 {
return objs
}
for _, o := range objs {
var key string
// Check if the object implements the Keyer interface
if k, ok := any(o).(Keyer); ok {
key = k.UniqKey()
} else {
data, err := json.Marshal(o)
if err != nil {
out = append(out, o)
continue
}
key = string(data)
}
if _, ok := seen[key]; !ok {
out = append(out, o)
seen[key] = true
}
}
return out
}