Skip to content

Commit

Permalink
Merge pull request #9 from infinimesh/profiles
Browse files Browse the repository at this point in the history
Contexts
  • Loading branch information
slntopp authored Jan 26, 2024
2 parents 12ccf24 + f0ecaed commit b4893ca
Show file tree
Hide file tree
Showing 3 changed files with 121 additions and 39 deletions.
44 changes: 43 additions & 1 deletion 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 All @@ -63,6 +68,10 @@ var contextCmd = &cobra.Command{
data["insecure"] = insec
}

if viper.GetString("context") != "" {
data["context"] = viper.GetString("context")
}

if printJson, _ := cmd.Flags().GetBool("json"); printJson {
return printJsonResponse(data)
}
Expand All @@ -76,9 +85,35 @@ 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",
Use: "login <host:port> <login>",
Aliases: []string{"l", "auth", "a"},
Args: cobra.ExactArgs(2),
Short: "Authorize in infinimesh and store credentials",
RunE: func(cmd *cobra.Command, args []string) error {
creds := credentials.NewTLS(&tls.Config{InsecureSkipVerify: true})
Expand Down Expand Up @@ -139,9 +174,15 @@ var loginCmd = &cobra.Command{
fmt.Println(token)
}

infContext := "default"
if ctx, _ := cmd.Flags().GetString("context"); ctx != "" {
infContext = ctx
}

viper.Set("infinimesh", args[0])
viper.Set("token", token)
viper.Set("insecure", insec)
viper.Set("context", infContext)

err = viper.WriteConfig()
return err
Expand Down Expand Up @@ -293,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
28 changes: 11 additions & 17 deletions cmd/dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"net/url"
"strings"

"github.com/Pallinder/go-randomdata"
Expand Down Expand Up @@ -56,6 +55,16 @@ var genUIPluginUrlCmd = &cobra.Command{
}

api, _ := cmd.Flags().GetString("api")
if api == "" {
if g := viper.GetString("infinimesh"); g != "" {
api = strings.Split(g, ":")[0]
if !viper.GetBool("insecure") {
api = "https://" + api
} else {
api = "http://" + api
}
}
}
params["api"] = api

token, _ := cmd.Flags().GetString("token")
Expand Down Expand Up @@ -120,26 +129,11 @@ var genUIPluginUrlCmd = &cobra.Command{

func init() {

initConfig()

api := &url.URL{
Scheme: "http",
Host: "api.infinimesh.local",
}

if g := viper.GetString("infinimesh"); g != "" {
if !viper.GetBool("insecure") {
api.Scheme = "https"
}

api.Host = strings.Split(g, ":")[0]
}

genUIPluginUrlCmd.Flags().String("token", "", "Token to encode into URL (defaults to CLI stored auth)")
genUIPluginUrlCmd.Flags().String("title", randomdata.SillyName(), "User Title to encode (defaults to random)")
genUIPluginUrlCmd.Flags().String("namespace", "infinimesh", "Namespace to encode")
genUIPluginUrlCmd.Flags().Bool("light", false, "Wether to encode Light theme (Dark is used by default)")
genUIPluginUrlCmd.Flags().String("api", api.String(), "infinimesh REST API Base URL to use")
genUIPluginUrlCmd.Flags().String("api", "", "infinimesh REST API Base URL to use (default: hostname from infinimesh context)")
genUIPluginUrlCmd.Flags().Bool("url-only", false, "Print resulting URL only")

devCmd.AddCommand(genUIPluginUrlCmd)
Expand Down
88 changes: 67 additions & 21 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,13 @@ import (
"os"

"github.com/spf13/cobra"
"gopkg.in/yaml.v2"

"github.com/spf13/viper"
)

var cfgFile string
var initialized = false
var infContext string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Expand All @@ -47,49 +48,94 @@ func Execute() {
}

func init() {
cobra.OnInitialize(initConfig)

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.default.infinimesh.yaml)")
rootCmd.PersistentFlags().StringVar(&infContext, "context", "", "Use a specific config context (default is default)")
rootCmd.PersistentFlags().Bool("json", false, "Print output as json")
rootCmd.PersistentFlags().Bool("verbose", false, "Print additional info related to the CLI itself")

cobra.OnInitialize(initConfig)
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if initialized {
return
}
initialized = true
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := os.UserHomeDir()
cobra.CheckErr(err)
loadContext()
}

// Search config in home directory with name ".inf" (without extension).
viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigName(".default.infinimesh")
viper.AutomaticEnv() // read in environment variables that match

cfgFile = fmt.Sprintf("%s/.default.infinimesh.yaml", home)
verbose, _ := rootCmd.Flags().GetBool("verbose")
// If a config file is found, read it in.
err := viper.ReadInConfig()
if err == nil && verbose {
fmt.Println("Using context: ", infContext)
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}

viper.AutomaticEnv() // read in environment variables that match
func loadContext() {
checkContext()

home, err := os.UserHomeDir()
cobra.CheckErr(err)

// Search config in home directory with name ".inf" (without extension).
viper.AddConfigPath(home)
viper.SetConfigType("yaml")

config_name := fmt.Sprintf(".%s.infinimesh", infContext)

viper.SetConfigName(config_name)

cfgFile = fmt.Sprintf("%s/%s.yaml", home, config_name)

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

verbose, _ := rootCmd.Flags().GetBool("verbose")
// If a config file is found, read it in.
err := viper.ReadInConfig()
if err == nil && verbose {
fmt.Println("Using config file:", viper.ConfigFileUsed())
func checkContext() {
if infContext != "" {
return
}

home, err := os.UserHomeDir()
cobra.CheckErr(err)

faulty_conf := false
profilesCfg := fmt.Sprintf("%s/.infinimesh.contexts", home)
if _, err := os.Stat(profilesCfg); os.IsNotExist(err) {
faulty_conf = true
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: "default",
}
profilesBytes, err := os.ReadFile(profilesCfg)
if err != nil || len(profilesBytes) == 0 {
faulty_conf = true
}
if err == nil {
if yaml.Unmarshal(profilesBytes, &contexts) != nil {
faulty_conf = true
}
}

infContext = contexts.Selected

if faulty_conf {
r, _ := yaml.Marshal(contexts)
os.WriteFile(profilesCfg, r, 0640)
}
}

Expand Down

0 comments on commit b4893ca

Please sign in to comment.