-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
209 lines (172 loc) · 6.17 KB
/
main.go
File metadata and controls
209 lines (172 loc) · 6.17 KB
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
/*
Copyright © 2022 steffakasid
*/
package main
import (
"encoding/json"
"fmt"
"os"
"path"
"strings"
"github.com/fatih/color"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/steffakasid/eslog"
"github.com/steffakasid/kubectl-co/internal"
)
type cmdCfg struct {
Delete bool `mapstructure:"delete"`
Debug bool `mapstructure:"debug"`
Add bool `mapstructure:"add"`
Previous bool `mapstructure:"previous"`
Current bool `mapstructure:"current"`
}
var config *cmdCfg = &cmdCfg{}
var version = "0.1-development"
const (
viperKeyPrevious = "previous"
viperKeyCurrent = "current"
viperKeyDebug = "debug"
viperKeyDelete = "delete"
viperKeyAdd = "add"
viperKeyHelp = "help"
viperKeyVersion = "version"
)
func init() {
var err error
flag.BoolP(viperKeyDelete, "d", false, "Delete the config with the given name. Usage: kubectl co --delete [configname]")
flag.BoolP(viperKeyAdd, "a", false, "Add a new given config providing the path and the name. Usage: kubectl co --add [configpath] [configname]")
flag.BoolP(viperKeyPrevious, "p", false, "Switch to previous config")
flag.BoolP(viperKeyCurrent, "c", false, "Show the current config path")
flag.BoolP(viperKeyHelp, "h", false, "Show help")
flag.Bool(viperKeyDebug, false, "Turn on debug output")
flag.Usage = func() {
stdErr := os.Stderr
_, err := fmt.Fprintf(stdErr, "Usage of %s: \n", os.Args[0])
eslog.LogIfErrorf(err, eslog.Fatalf, "Error printing usage: %s")
_, err = fmt.Fprintln(stdErr, `
This tool can be used to work with multiple kube configs. It allows to
add, delete and switch config files.
NOTE: If you set the KUBECONFIG environment var this will always take precedence before the config file.
Preqrequisites:
kubectl should be installed (even if the application would also run for it own as 'kubectl-co')
Examples:
kubectl co --add new-config ~/.kube/config - adds your current kubeconfig to be used by co with the name 'new-config'
kubectl co --add completly-new - adds a plain new config file which must be inialised afterwards
kubectl co --previous - switch to previous config and set current config to previous
kubectl co --delete config-name - delete config with name 'new-config'
kubectl co --current - show the current config path
kubectl co new-config - switch to 'new-config' this will overwrite ~/.kube/config with a symbolic link
kubectl co - list all available configs
Enable Shell completion:
# ~/.bashrc
echo 'source <(kubectl-co completion bash)' >> ~/.bashrc
# ~/.zshrc
echo 'source <(kubectl-co completion zsh)' >> ~/.zshrc
Usage:
kubectl co [flags]
kubectl-co [flags]
kubectl-co completion bash|zsh
Flags:`)
eslog.LogIfErrorf(err, eslog.Fatalf, "Error printing usage: %s")
flag.PrintDefaults()
}
flag.Parse()
initHome()
viper.AddConfigPath(path.Join(home, ".config", "kubectl-co"))
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.SetEnvPrefix("KUBECTL_CO")
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
viper.AutomaticEnv()
err = viper.ReadInConfig()
eslog.LogIfErrorf(err, eslog.Errorf, "Error reading config: %s")
err = viper.BindPFlags(flag.CommandLine)
eslog.LogIfErrorf(err, eslog.Fatalf, "Error binding flags: %s")
err = viper.Unmarshal(config)
eslog.LogIfErrorf(err, eslog.Fatalf, "Error unmarshal config: %s")
if config.Debug {
err = eslog.Logger.SetLogLevel("debug")
eslog.LogIfErrorf(err, eslog.Fatalf, "Error SetLogLevel(debug): %s")
} else {
err = eslog.Logger.SetLogLevel("info")
eslog.LogIfErrorf(err, eslog.Fatalf, "Error SetLogLevel(info): %s")
}
if isCompletionInvocation() {
handleCompletion()
os.Exit(0)
}
}
func main() {
if viper.GetBool(viperKeyVersion) {
fmt.Printf("kubectl-co version: %s\n", version)
} else if viper.GetBool(viperKeyHelp) {
flag.Usage()
} else {
args := flag.Args()
if len(args) > 0 && args[0] == "completion" {
handleCompletionCommand(args[1:])
return
}
err := validateFlags(args)
eslog.LogIfErrorf(err, eslog.Fatalf, "Error validating flags: %s")
execute(args)
}
}
func validateFlags(args []string) error {
eslog.Debugf("config %s", toString(config))
if (config.Current && config.Previous) || (config.Delete && config.Previous) || (config.Delete && config.Current) || (config.Add && config.Previous) || (config.Add && config.Current) || (config.Add && config.Delete) {
return fmt.Errorf("%s, %s, %s and %s are exklusiv just use one at a time", viperKeyAdd, viperKeyDelete, viperKeyPrevious, viperKeyCurrent)
} else if config.Delete && len(args) != 1 {
return fmt.Errorf("when using %s you must only provide the name of the config to be deleted", viperKeyDelete)
} else if config.Add && (len(args) == 0 || len(args) > 2) {
return fmt.Errorf("when using %s you must provide the path as first argument and the name of the config as second argument", viperKeyAdd)
} else if config.Previous && len(args) != 0 {
return fmt.Errorf("%s doesn't take any arguments", viperKeyPrevious)
}
return nil
}
func execute(args []string) {
var err error
co, err := internal.NewCO(home)
eslog.LogIfErrorf(err, eslog.Fatalf, "Error initializing co: %s")
if len(args) > 0 {
co.ConfigName = args[0]
}
if config.Add {
copyConfigFrom := ""
if len(args) == 2 {
copyConfigFrom = args[1]
}
err = co.AddConfig(copyConfigFrom)
if err != nil {
err = co.LinkKubeConfig()
}
} else if config.Delete {
err = co.DeleteConfig()
} else if config.Previous || len(args) == 1 {
err = co.LinkKubeConfig()
} else {
err = co.ListConfigs()
if err == nil {
printConfigs(co)
}
}
eslog.LogIfErrorf(err, eslog.Fatalf, "Error on execute: %s")
}
func toString(obj any) string {
bt, err := json.Marshal(obj)
eslog.LogIfErrorf(err, eslog.Errorf, "error marshalling obj to json string: %s")
return string(bt)
}
func printConfigs(co *internal.CO) {
red := color.New(color.FgRed)
for _, config := range co.Configs {
if strings.HasSuffix(co.CurrentConfigPath, config) {
_, err := red.Println(config)
eslog.LogIfErrorf(err, eslog.Errorf, "Error printing config: %s")
} else {
fmt.Println(config)
}
}
}