package cmd import ( "fmt" "os" "github.com/pterm/pterm" "github.com/spf13/cobra" "github.com/spf13/viper" "gitlab.sweetwater.com/it/devops/tools/gitlab-project-manager/internal/config" "gopkg.in/yaml.v3" ) var configGenerateCmd = &cobra.Command{ Use: "generate", Short: "Generate a default configuration", Aliases: []string{"gen", "new", "default"}, Long: configGenCmdLong, Run: runConfigGenerateCmd, } func runConfigGenerateCmd(cmd *cobra.Command, args []string) { var configFile string if viper.ConfigFileUsed() != "" { configFile = viper.ConfigFileUsed() } else { configFile = defConfigPath } plog.Debug("Using config file " + configFile) configFile, _ = resolvePath(configFile) newConf := promptConfigSettings(&conf) if write, _ := cmd.Flags().GetBool("write"); write { write, _ := pterm.DefaultInteractiveContinue. WithDefaultText("Really write config file?"). WithOptions([]string{"yes", "no"}). Show() if write != "yes" { plog.Fatal("Aborting config file write") } writeConfigFile(newConf, configFile) plog.Info("Wrote config to file", plog.Args("file", configFile)) } else { c, _ := yaml.Marshal(newConf) plog.Info("Suggest running with --write or redirect (> " + configFile + ")") fmt.Print(string(c)) } } func writeConfigFile(c *config.Config, path string) { file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0640) if err != nil { plog.Error("Failed to prepare config for writing", plog.Args("error", err)) } enc := yaml.NewEncoder(file) if err := enc.Encode(c); err != nil { plog.Fatal("Failed writing config file", plog.Args("file", path)) } } func promptConfigSettings(c *config.Config) *config.Config { if host, err := pterm.DefaultInteractiveTextInput. WithDefaultValue(c.GitlabHost). WithDefaultText("Enter gitlab URL"). Show(); err == nil { c.GitlabHost = host } if pPath, err := pterm.DefaultInteractiveTextInput. WithDefaultValue(c.ProjectPath). WithDefaultText("Enter path for projects and cache"). Show(); err == nil { c.ProjectPath = pPath } if ownerOnly, err := pterm.DefaultInteractiveConfirm. WithDefaultText("Only cache projects you are owner of?"). Show(); err == nil { if ownerOnly { c.Cache.Load.OwnerOnly = true } else { c.Cache.Load.OwnerOnly = false } } if token, err := pterm.DefaultInteractiveTextInput. WithMask("*"). WithDefaultValue(c.GitlabToken). WithDefaultText("Enter gitlab Token"). Show(); err == nil { c.GitlabToken = token } return c } func init() { configCmd.AddCommand(configGenerateCmd) configGenerateCmd.PersistentFlags().Bool("prompt", false, "Prompt for settings") configGenerateCmd.PersistentFlags().Bool("write", false, "Write config to file") }