Skip to content

Commit

Permalink
set context command
Browse files Browse the repository at this point in the history
  • Loading branch information
slntopp committed Jan 26, 2024
1 parent a4a683a commit f0ecaed
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
31 changes: 31 additions & 0 deletions cmd/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"gopkg.in/yaml.v2"

pb "github.com/infinimesh/proto/node"
accpb "github.com/infinimesh/proto/node/accounts"
Expand All @@ -43,6 +44,10 @@ func getVersion() string {
return VERSION
}

type ContextConf struct {
Selected string `yaml:"selected"`
}

// contextCmd represents the context command
var contextCmd = &cobra.Command{
Use: "context",
Expand Down Expand Up @@ -80,6 +85,31 @@ var contextCmd = &cobra.Command{
},
}

var setContextCmd = &cobra.Command{
Use: "set-context <context>",
Short: "Set infinimesh CLI Context",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
home, err := os.UserHomeDir()
cobra.CheckErr(err)

profilesCfg := fmt.Sprintf("%s/.infinimesh.contexts", home)

if _, err := os.Stat(profilesCfg); os.IsNotExist(err) {
if _, err := os.Create(profilesCfg); err != nil { // perm 0666
fmt.Fprintln(os.Stderr, "Can't create default contexts config file")
panic(err)
}
}

contexts := ContextConf{
Selected: args[0],
}
r, _ := yaml.Marshal(contexts)
return os.WriteFile(profilesCfg, r, 0640)
},
}

var loginCmd = &cobra.Command{
Use: "login <host:port> <login>",
Aliases: []string{"l", "auth", "a"},
Expand Down Expand Up @@ -304,6 +334,7 @@ func init() {
loginCmd.Flags().Bool("ldap", false, "Use Credentials Type LDAP")

rootCmd.AddCommand(contextCmd)
rootCmd.AddCommand(setContextCmd)
rootCmd.AddCommand(loginCmd)
rootCmd.AddCommand(versionCmd)

Expand Down
12 changes: 5 additions & 7 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func initConfig() {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
loadProfile()
loadContext()
}

viper.AutomaticEnv() // read in environment variables that match
Expand All @@ -76,8 +76,8 @@ func initConfig() {
}
}

func loadProfile() {
checkProfile()
func loadContext() {
checkContext()

home, err := os.UserHomeDir()
cobra.CheckErr(err)
Expand All @@ -100,7 +100,7 @@ func loadProfile() {
}
}

func checkProfile() {
func checkContext() {
if infContext != "" {
return
}
Expand All @@ -118,9 +118,7 @@ func checkProfile() {
}
}

contexts := struct {
Selected string `yaml:"selected"`
}{
contexts := ContextConf{
Selected: "default",
}
profilesBytes, err := os.ReadFile(profilesCfg)
Expand Down

0 comments on commit f0ecaed

Please sign in to comment.