54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package add
|
|
|
|
import (
|
|
"errors"
|
|
"git.denysoft.de/CubeBit/ssh-hub/util"
|
|
"github.com/jedib0t/go-pretty/v6/table"
|
|
"github.com/spf13/cobra"
|
|
"github.com/spf13/viper"
|
|
"os"
|
|
"regexp"
|
|
)
|
|
|
|
var addCmd = &cobra.Command{
|
|
Use: "add",
|
|
Short: "Add new command with alias",
|
|
Args: func(cmd *cobra.Command, args []string) error {
|
|
if err := cobra.ExactArgs(2)(cmd, args); err != nil {
|
|
return err
|
|
}
|
|
|
|
conf := viper.GetStringMapString("data")
|
|
if _, ok := conf[args[0]]; ok {
|
|
return errors.New("such alias already exists")
|
|
}
|
|
|
|
if matched, err := regexp.MatchString("/[a-zA-Z|1-9-]{1,}", args[0]); !matched {
|
|
cobra.CheckErr(err)
|
|
return errors.New("alias is in false format. Example of correct one: /work/dev. Regex: /[a-zA-Z|1-9-]{1,}")
|
|
}
|
|
|
|
return nil
|
|
},
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
cfg := viper.GetStringMapString("data")
|
|
cfg[args[0]] = args[1]
|
|
|
|
err := util.SaveConfig(&cfg)
|
|
cobra.CheckErr(err)
|
|
|
|
t := table.NewWriter()
|
|
t.SetOutputMirror(os.Stdout)
|
|
t.AppendHeader(table.Row{"Alias", "Command"})
|
|
|
|
for alias, command := range cfg {
|
|
t.AppendRow(table.Row{alias, command})
|
|
}
|
|
t.Render()
|
|
},
|
|
}
|
|
|
|
func Cmd() *cobra.Command {
|
|
return addCmd
|
|
}
|