-
Notifications
You must be signed in to change notification settings - Fork 474
/
util.go
95 lines (84 loc) · 2.52 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
// Shared helpers across commands.
package cmd
import (
"flag"
"fmt"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"github.com/kiali/kiali/log"
)
var (
// Adapted from: https://stackoverflow.com/a/38644571
_, b, _, _ = runtime.Caller(0)
basepath = filepath.Dir(b)
// This works so long as the current dir structure stays the same.
// This should be the base of the project e.g. '/home/user1/kiali'.
// If the location of this file changes, this needs to be updated as well.
KialiProjectRoot = path.Dir(path.Dir(basepath))
)
// GetKubeConfig constructs a kube config from either the user's local kube config
// or the KUBECONFIG env var.
func GetKubeConfig() (*rest.Config, error) {
kubeconfig := os.Getenv("KUBECONFIG")
if len(kubeconfig) == 0 {
home, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("Unable to find user home dir. Err: %w", err)
}
kubeconfig = fmt.Sprintf("%s/.kube/config", home)
}
restConfig, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
return nil, fmt.Errorf("Unable to build config from flags: %w", err)
}
return restConfig, nil
}
func ConfigureKialiLogger() {
// Kiali logger is configured through env vars and the default format is json which isn't very nice for cmdline.
if err := os.Setenv("LOG_FORMAT", "text"); err != nil {
log.Errorf("Unable to configure logger. Err: %s", err)
} else {
log.InitializeLogger()
}
}
// Usage creates a custom usage function that allows you to specify position
// arguments and prints flags with two dashes instead of one e.g. '--url'
// instead of '-url'.
//
// You can assign this to flag.Usage directly or any other FlagSet.Usage
// e.g. 'flag.Usage = Usage(requiredFlag1)'.
//
// The resulting Usage will look like:
// Usage: cmd <pos-arg1> <pos-arg2> ... [Options]
//
// Options:
// --opt1 string
// opt description (default "")
// ...
func Usage(cmd string, posArgs ...string) func() {
return func() {
var b strings.Builder
fmt.Fprintf(&b, "Usage: %s ", cmd)
for _, arg := range posArgs {
b.WriteString(arg + " ")
}
b.WriteString("[Options]\n\n")
b.WriteString("Options:\n")
flag.VisitAll(func(f *flag.Flag) {
fType, _ := flag.UnquoteUsage(f)
fmt.Fprintf(&b, " --%s %s\n", f.Name, fType)
b.WriteString("\t" + f.Usage)
if f.DefValue == "" {
fmt.Fprintf(&b, " (default %q)\n", f.DefValue)
} else {
fmt.Fprintf(&b, " (default %s)\n", f.DefValue)
}
})
fmt.Fprint(flag.CommandLine.Output(), b.String())
}
}