-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.go
More file actions
103 lines (87 loc) · 1.97 KB
/
Copy pathcli.go
File metadata and controls
103 lines (87 loc) · 1.97 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
package main
import (
"fmt"
"os"
"strings"
"github.com/fatih/color"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "amctx",
Short: "amtool context manager",
Args: cobra.MaximumNArgs(1),
RunE: runRoot,
SilenceUsage: true,
}
const noConfigFileMsg = "no config file found, file created"
func Execute() {
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
func init() {
red := color.New(color.FgRed, color.Bold)
rootCmd.SetErrPrefix(red.Sprint("error:"))
rootCmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
fmt.Println(`USAGE:
amctx : list the aliases
amctx <ALIAS> : switch to context <ALIAS>
amctx <ALIAS>=<URL> : create or update context
amctx -h, --help : show this message`)
})
}
func runRoot(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return printAliases()
}
return parseAlias(args[0])
}
func printAliases() error {
aliases, created, err := ListAliases()
if err != nil {
return err
}
if created {
fmt.Println(noConfigFileMsg)
return nil
}
if len(aliases) == 0 {
fmt.Println("no aliases found")
return nil
}
for _, alias := range aliases {
fmt.Println(alias)
}
return nil
}
func addAlias(alias, url string) error {
if alias == "" || url == "" {
return fmt.Errorf("invalid argument format, expected <alias>=<url>")
}
created, err := CreateOrUpdateAlertmanagerAlias(alias, url)
if err != nil {
return err
}
if created {
fmt.Println(noConfigFileMsg)
}
fmt.Printf("alias '%s' set with url: %s\n", alias, url)
return nil
}
func switchContext(alias string) error {
created, err := SwitchContext(alias)
if err != nil {
return err
}
if created {
fmt.Println(noConfigFileMsg)
}
fmt.Printf("switched to context '%s'\n", alias)
return nil
}
func parseAlias(arg string) error {
if alias, url, ok := strings.Cut(arg, "="); ok {
return addAlias(alias, url)
}
return switchContext(arg)
}