Skip to content

Commit

Permalink
feat: Config flag error ignored during login #251 (#259)
Browse files Browse the repository at this point in the history
* Added configpath to loginview; Added configpath validator; Added configpath flag check to determine if given

Signed-off-by: qcserestipy <[email protected]>

* Added update credentials function

Signed-off-by: qcserestipy <[email protected]>

* Removed config file from login view; moved credential update or creation to runLogin function

Signed-off-by: qcserestipy <[email protected]>

* Added PersistentPreRun function to handle config init; Added data file logic that keeps track of the last active config; Made DataFile and ConfigFile Available through global pointer. Adjusted harbor client to retrieve credentials through config pointer; Added funtionality to login run to update credentials after login

Signed-off-by: qcserestipy <[email protected]>

* Enhanced logging for login subcommand

Signed-off-by: qcserestipy <[email protected]>

* Improved handling of initConfig function; introduced HARBOR_CLI_CONFIG flag

Signed-off-by: qcserestipy <[email protected]>

* Improved Data and Config Pointer error handling; Included Mutex functionality for Config and Data Pointer

Signed-off-by: qcserestipy <[email protected]>

* Added custom sync.Once to handle concurrent config environments in tests; added config tests; adapted login tests to work with new config management

Signed-off-by: Patrick Eschenbach <[email protected]>

* Added custom sync.Once to handle concurrent config environments in tests; added config tests; adapted login tests to work with new config management

Signed-off-by: Patrick Eschenbach <[email protected]>

---------

Signed-off-by: qcserestipy <[email protected]>
Signed-off-by: Patrick Eschenbach <[email protected]>
  • Loading branch information
qcserestipy authored Nov 26, 2024
1 parent 9b7fcc5 commit 0d1f474
Show file tree
Hide file tree
Showing 8 changed files with 617 additions and 120 deletions.
73 changes: 14 additions & 59 deletions cmd/harbor/root/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package root

import (
"fmt"
"log"
"os"

"github.com/goharbor/harbor-cli/cmd/harbor/root/artifact"
"github.com/goharbor/harbor-cli/cmd/harbor/root/project"
Expand All @@ -21,58 +19,7 @@ var (
verbose bool
)

func InitConfig() {
viper.SetConfigType("yaml")

// cfgFile = viper.GetStering("config")
viper.SetConfigFile(cfgFile)

if cfgFile != utils.DefaultConfigPath {
viper.SetConfigFile(cfgFile)
} else {
stat, err := os.Stat(utils.DefaultConfigPath)
if !os.IsNotExist(err) && stat.Size() == 0 {
log.Println("Config file is empty, creating a new one")
}

if os.IsNotExist(err) {
log.Printf("Config file not found at %s, creating a new one", cfgFile)
}

if os.IsNotExist(err) || (!os.IsNotExist(err) && stat.Size() == 0) {
if _, err := os.Stat(utils.HarborFolder); os.IsNotExist(err) {
// Create the parent directory if it doesn't exist

fmt.Println("Creating config file", utils.HarborFolder)
if err := os.MkdirAll(utils.HarborFolder, os.ModePerm); err != nil {
log.Fatal(err)
}
}
err = utils.CreateConfigFile()

if err != nil {
log.Fatal(err)
}

err = utils.AddCredentialsToConfigFile(utils.Credential{}, cfgFile)

if err != nil {
log.Fatal(err)
}

log.Printf("Config file created at %s", cfgFile)
}
}

if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Error reading config file: %s", err)
}

}

func RootCmd() *cobra.Command {
utils.SetLocation()

root := &cobra.Command{
Use: "harbor",
Short: "Official Harbor CLI",
Expand All @@ -85,22 +32,30 @@ harbor
// Display help about the command:
harbor help
`,
// RunE: func(cmd *cobra.Command, args []string) error {

// },
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// Determine if --config was explicitly set
userSpecifiedConfig := cmd.Flags().Changed("config")
// Initialize configuration
utils.InitConfig(cfgFile, userSpecifiedConfig)

return nil
},
}

cobra.OnInitialize(InitConfig)

root.PersistentFlags().StringVarP(&output, "output-format", "o", "", "Output format. One of: json|yaml")
root.PersistentFlags().StringVar(&cfgFile, "config", utils.DefaultConfigPath, "config file (default is $HOME/.harbor/config.yaml)")
root.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is $HOME/.config/harbor-cli/config.yaml)")
root.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output")

err := viper.BindPFlag("output-format", root.PersistentFlags().Lookup("output-format"))
if err != nil {
fmt.Println(err.Error())
}

err = viper.BindPFlag("config", root.PersistentFlags().Lookup("config"))
if err != nil {
fmt.Println(err.Error())
}

root.AddCommand(
versionCommand(),
LoginCommand(),
Expand Down
31 changes: 30 additions & 1 deletion cmd/harbor/root/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/goharbor/go-client/pkg/sdk/v2.0/client/user"
"github.com/goharbor/harbor-cli/pkg/utils"
"github.com/goharbor/harbor-cli/pkg/views/login"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/term"
)
Expand Down Expand Up @@ -115,9 +116,37 @@ func runLogin(opts login.LoginView) error {
Password: opts.Password,
ServerAddress: opts.Server,
}
harborData, err := utils.GetCurrentHarborData()
if err != nil {
return fmt.Errorf("failed to get current harbor data: %s", err)
}
configPath := harborData.ConfigPath
log.Debugf("Checking if credentials already exist in the config file...")
existingCred, err := utils.GetCredentials(opts.Name)
if err == nil {
if existingCred.Username == opts.Username && existingCred.ServerAddress == opts.Server {
if existingCred.Password == opts.Password {
log.Warn("Credentials already exist in the config file. They were not added again.")
return nil
} else {
log.Warn("Credentials already exist in the config file but the password is different. Updating the password.")
if err = utils.UpdateCredentialsInConfigFile(cred, configPath); err != nil {
log.Fatalf("failed to update the credential: %s", err)
}
return nil
}
} else {
log.Warn("Credentials already exist in the config file but more than one field was different. Updating the credentials.")
if err = utils.UpdateCredentialsInConfigFile(cred, configPath); err != nil {
log.Fatalf("failed to update the credential: %s", err)
}
return nil
}
}

if err = utils.AddCredentialsToConfigFile(cred, utils.DefaultConfigPath); err != nil {
if err = utils.AddCredentialsToConfigFile(cred, configPath); err != nil {
return fmt.Errorf("failed to store the credential: %s", err)
}
log.Debugf("Credentials successfully added to the config file.")
return nil
}
15 changes: 13 additions & 2 deletions pkg/utils/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/goharbor/go-client/pkg/harbor"
v2client "github.com/goharbor/go-client/pkg/sdk/v2.0/client"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)

var (
Expand All @@ -20,12 +19,24 @@ var (

func GetClient() (*v2client.HarborAPI, error) {
clientOnce.Do(func() {
credentialName := viper.GetString("current-credential-name")
config, err := GetCurrentHarborConfig()
if err != nil {
clientErr = fmt.Errorf("failed to get current credential name: %v", err)
return
}
credentialName := config.CurrentCredentialName
if credentialName == "" {
clientErr = fmt.Errorf("current-credential-name is not set in config file")
return
}

clientInstance = GetClientByCredentialName(credentialName)
if clientErr != nil {
log.Errorf("failed to initialize client: %v", clientErr)
return
}
})

return clientInstance, clientErr
}

Expand Down
Loading

0 comments on commit 0d1f474

Please sign in to comment.