Skip to content

Commit 5f8f2cd

Browse files
committed
kube-tmux: fix error handling
1 parent 261d81c commit 5f8f2cd

File tree

1 file changed

+29
-8
lines changed

1 file changed

+29
-8
lines changed

main.go

+29-8
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@ import (
1414
)
1515

1616
const (
17-
defaultSepalater = "/"
18-
defaultformat = "{{.Context}}" + defaultSepalater + "{{.Namespace}}"
17+
defaultSepalater = "/"
18+
defaultContextFormat = "{{.Context}}"
19+
defaultNamespaceFormat = "{{.Namespace}}"
20+
defaultformat = defaultContextFormat + defaultSepalater + defaultNamespaceFormat
1921
)
2022

2123
type kubeContext struct {
@@ -30,26 +32,45 @@ func main() {
3032

3133
config, err := kubeConfig.RawConfig()
3234
if err != nil {
33-
fmt.Fprintln(os.Stdout, "could not get kubeconfig")
35+
fmt.Fprintln(os.Stdout, "[ERROR] could not get kubeconfig")
36+
return
3437
}
3538
if len(config.Contexts) == 0 {
36-
fmt.Fprintln(os.Stdout, "kubeconfig is empty")
39+
fmt.Fprintln(os.Stdout, "[ERROR] kubeconfig is empty")
40+
return
3741
}
3842

3943
curCtx := config.CurrentContext
44+
if curCtx == "" {
45+
kctx := kubeContext{
46+
Context: "empty",
47+
}
48+
if err := printContext(kctx, defaultContextFormat); err != nil {
49+
fmt.Fprintln(os.Stdout, "[ERROR] could not print kube context")
50+
}
51+
return
52+
}
53+
54+
kctx := kubeContext{
55+
Context: curCtx,
56+
}
57+
4058
curNs := config.Contexts[curCtx].Namespace
4159
if curNs == "" {
4260
curNs = corev1.NamespaceDefault
4361
}
62+
kctx.Namespace = curNs
4463

4564
format := defaultformat
4665
if len(os.Args) > 1 {
4766
format = os.Args[1]
4867
}
4968

50-
kctx := kubeContext{
51-
Context: curCtx,
52-
Namespace: curNs,
69+
if err := printContext(kctx, format); err != nil {
70+
fmt.Fprintf(os.Stdout, "[ERROR] could not print kube context: %v\n", err)
5371
}
54-
template.Must(template.New("kube-tmux").Parse(format)).Execute(os.Stdout, kctx)
72+
}
73+
74+
func printContext(kctx kubeContext, format string) error {
75+
return template.Must(template.New("kube-tmux").Parse(format)).Execute(os.Stdout, kctx)
5576
}

0 commit comments

Comments
 (0)