diff --git a/cmd/auth.go b/cmd/auth.go new file mode 100644 index 0000000..ed1d2c5 --- /dev/null +++ b/cmd/auth.go @@ -0,0 +1,147 @@ +package cmd + +import ( + "os" + "path/filepath" + + "github.com/spf13/cobra" + "gopkg.in/yaml.v3" +) + +const ( + goCdCacheDirName = ".gocd" + goCdAuthConfigFileName = "auth_config.yaml" +) + +func registerAuthConfigCommand() *cobra.Command { + registerAuthConfigCmd := &cobra.Command{ + Use: "auth-config", + Short: "Command to set/remove the authorization configuration to be used by the cli", + Long: `Using the auth config commands, one can cache the authorization configuration onto a file so it can be used by further calls made using this utility. +Also, the cached authentication configurations can be erased using the same`, + RunE: func(cmd *cobra.Command, args []string) error { + if err := cmd.Usage(); err != nil { + return err + } + + return nil + }, + } + + registerAuthConfigCmd.SetUsageTemplate(getUsageTemplate()) + + registerAuthConfigCmd.AddCommand(getAuthStoreCommand()) + registerAuthConfigCmd.AddCommand(getAuthEraseCommand()) + + for _, command := range registerAuthConfigCmd.Commands() { + command.SilenceUsage = true + } + + return registerAuthConfigCmd +} + +func getAuthStoreCommand() *cobra.Command { + authStoreCmd := &cobra.Command{ + Use: "store", + Short: "Command to cache the GoCD authorization configuration to be used by the cli", + Args: cobra.NoArgs, + PreRunE: setCLIClient, + RunE: func(cmd *cobra.Command, args []string) error { + cliLogger.Debug("saving authorisation config to cache, so that it can be reused next") + home, err := os.UserHomeDir() + if err != nil { + cliLogger.Errorf("fetching user's home directory errored with '%v'", err) + + return err + } + + authConfigDir := filepath.Join(home, goCdCacheDirName) + const filePermission = 0o644 + if err = os.Mkdir(authConfigDir, filePermission); os.IsNotExist(err) { + cliLogger.Errorf("creating directory '%s' errored with '%v'", authConfigDir, err) + + return err + } + + authFile := filepath.Join(authConfigDir, goCdAuthConfigFileName) + authConfigFile, err := os.Create(authFile) + if err != nil { + cliLogger.Errorf("creating authfile '%s' errored with '%v'", authFile, err) + + return err + } + + cliLogger.Infof("authorisation config would be saved under %s", authConfigFile.Name()) + + cfgYAML, err := yaml.Marshal(cliCfg) + if err != nil { + cliLogger.Errorf("serializing auth config data to yaml errored with '%s'", err) + + return err + } + + if _, err = authConfigFile.WriteString(string(cfgYAML)); err != nil { + cliLogger.Errorf("writing auth config data to file '%s' errored with '%s'", authConfigFile.Name(), err) + + return err + } + + cliLogger.Infof("authorisation config was successfully saved under %s", authConfigFile.Name()) + + return nil + }, + } + + return authStoreCmd +} + +func getAuthEraseCommand() *cobra.Command { + authEraseCmd := &cobra.Command{ + Use: "remove", + Short: "Command to remove the cached GoCD authorization configuration that is used by the cli.", + Args: cobra.NoArgs, + PreRunE: setCLIClient, + RunE: func(cmd *cobra.Command, args []string) error { + home, err := os.UserHomeDir() + if err != nil { + cliLogger.Errorf("fetching user's home directory errored with '%v'", err) + + return err + } + + authConfigFile := filepath.Join(home, goCdCacheDirName, goCdAuthConfigFileName) + + cliLogger.Infof("authorisation config saved in '%s' would be cleaned", authConfigFile) + + if err = os.RemoveAll(authConfigFile); err != nil { + cliLogger.Errorf("cleaning authorisation config saved in '%s' errored with '%v'", authConfigFile, err) + + return err + } + + cliLogger.Infof("authorisation config saved in '%s' was cleaned successfully", authConfigFile) + + return nil + }, + } + + return authEraseCmd +} + +func checkForConfig() (bool, string, error) { + cliLogger.Debug("searching for authorisation configuration in cache") + home, err := os.UserHomeDir() + if err != nil { + return false, "", err + } + + configPath := filepath.Join(home, goCdCacheDirName, goCdAuthConfigFileName) + + if _, err = os.Stat(configPath); os.IsNotExist(err) { + cliLogger.Debug("no authorisation configuration found in cache") + + return false, "", nil + } + + return true, configPath, nil +} diff --git a/cmd/client.go b/cmd/client.go index b438bbf..8786fd2 100644 --- a/cmd/client.go +++ b/cmd/client.go @@ -51,13 +51,6 @@ func setCLIClient(cmd *cobra.Command, args []string) error { } } - if cliCfg.saveConfig { - cliLogger.Debug("--save-config is enabled, hence saving authorisation configuration") - if err = cliCfg.saveAuthConfig(); err != nil { - return err - } - } - goCDClient := gocd.NewClient( cliCfg.URL, cliCfg.Auth, @@ -81,54 +74,3 @@ func setCLIClient(cmd *cobra.Command, args []string) error { return nil } - -func (cfg *Config) saveAuthConfig() error { - cliLogger.Debug("saving authorisation config to cache, so that it can be reused next") - home, err := os.UserHomeDir() - if err != nil { - return err - } - - authConfigDir := filepath.Join(home, ".gocd") - const filePermission = 0o644 - if err = os.Mkdir(authConfigDir, filePermission); os.IsNotExist(err) { - return err - } - - authConfigFile, err := os.Create(filepath.Join(authConfigDir, "auth_config.yaml")) - if err != nil { - return err - } - - cliLogger.Debugf("authorisation config would be saved under %s", authConfigFile.Name()) - - cfgYAML, err := yaml.Marshal(cliCfg) - if err != nil { - return err - } - - if _, err = authConfigFile.WriteString(string(cfgYAML)); err != nil { - return err - } - - return nil -} - -func checkForConfig() (bool, string, error) { - cliLogger.Debug("searching for authorisation configuration in cache") - home, err := os.UserHomeDir() - if err != nil { - return false, "", err - } - - authConfigDir := filepath.Join(home, ".gocd") - configPath := filepath.Join(authConfigDir, "auth_config.yaml") - - if _, err = os.Stat(configPath); os.IsNotExist(err) { - cliLogger.Debug("no authorisation configuration found in cache") - - return false, "", nil - } - - return true, configPath, nil -} diff --git a/cmd/commands.go b/cmd/commands.go index b3005dd..87c3dc5 100644 --- a/cmd/commands.go +++ b/cmd/commands.go @@ -20,7 +20,6 @@ type Config struct { LogLevel string `yaml:"-"` FromFile string `yaml:"-"` ToFile string `yaml:"-"` - saveConfig bool skipCacheConfig bool } @@ -47,6 +46,7 @@ func getGoCDCliCommands() *cobra.Command { command.commands = append(command.commands, registerMaintenanceCommand()) command.commands = append(command.commands, registerJobsCommand()) command.commands = append(command.commands, registerArtifactCommand()) + command.commands = append(command.commands, registerAuthConfigCommand()) return command.prepareCommands() } diff --git a/cmd/flags.go b/cmd/flags.go index c1a96ec..8f3a372 100644 --- a/cmd/flags.go +++ b/cmd/flags.go @@ -30,17 +30,12 @@ func registerGlobalFlags(cmd *cobra.Command) { "enable this to Render output in YAML format") cmd.PersistentFlags().BoolVarP(&cliCfg.YAML, "no-color", "", false, "enable this to Render output in YAML format") - cmd.PersistentFlags().BoolVarP(&cliCfg.saveConfig, "save-config", "", false, - "enable this to locally save auth configs used to connect GoCD server (path: $HOME/.gocd/auth_config.yaml)") cmd.PersistentFlags().BoolVarP(&cliCfg.skipCacheConfig, "skip-cache-config", "", false, "if enabled locally save auth configs would not be used to authenticate GoCD server (path: $HOME/.gocd/auth_config.yaml)") cmd.PersistentFlags().StringVarP(&cliCfg.FromFile, "from-file", "", "", "file containing configurations of objects that needs to be created in GoCD, config-repo/pipeline-group/environment and etc.") cmd.PersistentFlags().StringVarP(&cliCfg.ToFile, "to-file", "", "", "file to which the output needs to be written to (this works only if --yaml or --json is enabled)") - // cmd.PersistentFlags().StringSliceVarP(&queries, "query", "q", nil, - // `query to filter the results, ex: '.material.attributes.url'. this uses library gojsonq beneath - // more queries can be found here https://github.com/thedevsaddam/gojsonq/wiki/Queries`) cmd.PersistentFlags().StringVarP(&jsonQuery, "query", "q", "", `query to filter the results, ex: '.material.attributes.type | id eq git'. this uses library gojsonq beneath more queries can be found here https://github.com/thedevsaddam/gojsonq/wiki/Queries`) diff --git a/cmd/version.go b/cmd/version.go index 80113a0..089eade 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -81,7 +81,7 @@ func AppVersion(cmd *cobra.Command, args []string) error { } } - cliVersionInfo := strings.Join([]string{"cli version", string(buildInfo), "\n"}, ": ") + cliVersionInfo := strings.Join([]string{"client version", string(buildInfo), "\n"}, ": ") _, err = writer.Write([]byte(cliVersionInfo)) if err != nil { log.Fatalln(err)