diff --git a/cmd/config.go b/cmd/config.go index 975d3cae..aee6e242 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -1,11 +1,9 @@ package cmd import ( - "bufio" "context" "encoding/json" "fmt" - "io" "os" "path/filepath" "sort" @@ -146,7 +144,7 @@ var configAddCmd = &cobra.Command{ RunE: func(cmd *cobra.Command, args []string) error { lagoonConfig := parseLagoonConfig(*cmd.Flags()) if lagoonConfig.Lagoon == "" { - return fmt.Errorf("Missing arguments: Lagoon name is not defined") + return fmt.Errorf("missing arguments: Lagoon name is not defined") } if lagoonConfig.Hostname != "" && lagoonConfig.Port != "" && lagoonConfig.GraphQL != "" { @@ -193,7 +191,7 @@ var configAddCmd = &cobra.Command{ }, }, outputOptions) } else { - return fmt.Errorf("Must have Hostname, Port, and GraphQL endpoint") + return fmt.Errorf("must have Hostname, Port, and GraphQL endpoint") } return nil }, @@ -359,26 +357,6 @@ func readLagoonConfig(lc *lagoon.Config, file string) error { } -func analyze(file string) error { - handle, err := os.Open(file) - - if err != nil { - return err - } - defer handle.Close() - return doSomething(handle) -} - -func doSomething(handle io.Reader) error { - scanner := bufio.NewScanner(handle) - for scanner.Scan() { - // Do something with line - d := scanner.Text() - fmt.Println(d) - } - return nil -} - // functions to handle read/write of configuration file // writeLagoonConfig writes the lagoon config to specified file. diff --git a/cmd/deploy.go b/cmd/deploy.go index 0d723465..fdf1868d 100644 --- a/cmd/deploy.go +++ b/cmd/deploy.go @@ -44,7 +44,7 @@ use 'lagoon deploy latest' instead`, return err } if cmdProjectName == "" || branch == "" { - return fmt.Errorf("Missing arguments: Project name or branch name is not defined") + return fmt.Errorf("missing arguments: Project name or branch name is not defined") } buildVarStrings, err := cmd.Flags().GetStringArray("buildvar") @@ -109,7 +109,7 @@ var deployPromoteCmd = &cobra.Command{ return err } if cmdProjectName == "" || sourceEnvironment == "" || destinationEnvironment == "" { - return fmt.Errorf("Missing arguments: Project name, source environment, or destination environment is not defined") + return fmt.Errorf("missing arguments: Project name, source environment, or destination environment is not defined") } buildVarStrings, err := cmd.Flags().GetStringArray("buildvar") @@ -176,7 +176,7 @@ This environment should already exist in lagoon. It is analogous with the 'Deplo } if cmdProjectName == "" || cmdProjectEnvironment == "" { - return fmt.Errorf("Missing arguments: Project name or environment name is not defined") + return fmt.Errorf("missing arguments: Project name or environment name is not defined") } if yesNo(fmt.Sprintf("You are attempting to deploy the latest environment '%s' for project '%s', are you sure?", cmdProjectEnvironment, cmdProjectName)) { current := lagoonCLIConfig.Current @@ -246,7 +246,7 @@ This pullrequest may not already exist as an environment in lagoon.`, } if cmdProjectName == "" || prTitle == "" || prNumber == 0 || baseBranchName == "" || baseBranchRef == "" || headBranchName == "" || headBranchRef == "" { - return fmt.Errorf("Missing arguments: Project name, title, number, baseBranchName, baseBranchRef, headBranchName, or headBranchRef is not defined") + return fmt.Errorf("missing arguments: Project name, title, number, baseBranchName, baseBranchRef, headBranchName, or headBranchRef is not defined") } buildVarStrings, err := cmd.Flags().GetStringArray("buildvar") if err != nil { @@ -292,11 +292,6 @@ This pullrequest may not already exist as an environment in lagoon.`, }, } -var ( - promoteSourceEnv string - promoteDestEnv string -) - func init() { deployCmd.AddCommand(deployBranchCmd) deployCmd.AddCommand(deployPromoteCmd) diff --git a/cmd/deploytarget.go b/cmd/deploytarget.go index 4dfe254a..dc7fad9d 100644 --- a/cmd/deploytarget.go +++ b/cmd/deploytarget.go @@ -66,13 +66,13 @@ var addDeployTargetCmd = &cobra.Command{ } if name == "" { - return fmt.Errorf("Missing arguments: name is not defined") + return fmt.Errorf("missing arguments: name is not defined") } if token == "" { - return fmt.Errorf("Missing arguments: token is not defined") + return fmt.Errorf("missing arguments: token is not defined") } if consoleURL == "" { - return fmt.Errorf("Missing arguments: console-url is not defined") + return fmt.Errorf("missing arguments: console-url is not defined") } addDeployTarget := &schema.AddDeployTargetInput{ diff --git a/cmd/deploytargetconfig.go b/cmd/deploytargetconfig.go index 46fdb7ea..2287b60c 100644 --- a/cmd/deploytargetconfig.go +++ b/cmd/deploytargetconfig.go @@ -46,16 +46,16 @@ var addDeployTargetConfigCmd = &cobra.Command{ } if cmdProjectName == "" { - return fmt.Errorf("Missing arguments: project is a required flag") + return fmt.Errorf("missing arguments: project is a required flag") } if deploytarget == 0 { - return fmt.Errorf("Missing arguments: deploytarget id is a required flag") + return fmt.Errorf("missing arguments: deploytarget id is a required flag") } if pullrequests == "" { - return fmt.Errorf("Missing arguments: pullrequests is a required flag") + return fmt.Errorf("missing arguments: pullrequests is a required flag") } if branches == "" { - return fmt.Errorf("Missing arguments: branches is a required flag") + return fmt.Errorf("missing arguments: branches is a required flag") } current := lagoonCLIConfig.Current token := lagoonCLIConfig.Lagoons[current].Token @@ -150,7 +150,7 @@ var updateDeployTargetConfigCmd = &cobra.Command{ return err } if id == 0 { - return fmt.Errorf("Missing arguments: deploytarget config id is not defined") + return fmt.Errorf("missing arguments: deploytarget config id is not defined") } current := lagoonCLIConfig.Current lc := client.New( @@ -226,7 +226,7 @@ var deleteDeployTargetConfigCmd = &cobra.Command{ return err } if id == 0 { - return fmt.Errorf("Missing arguments: deploytarget config id is not defined") + return fmt.Errorf("missing arguments: deploytarget config id is not defined") } current := lagoonCLIConfig.Current lc := client.New( diff --git a/cmd/environment.go b/cmd/environment.go index d837aab1..1625380a 100644 --- a/cmd/environment.go +++ b/cmd/environment.go @@ -179,7 +179,7 @@ var listBackupsCmd = &cobra.Command{ return err } if cmdProjectEnvironment == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: Project name or environment name is not defined") + return fmt.Errorf("missing arguments: Project name or environment name is not defined") } current := lagoonCLIConfig.Current lc := client.New( @@ -246,7 +246,7 @@ This returns a direct URL to the backup, this is a signed download link with a l return err } if cmdProjectEnvironment == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: Project name or environment name is not defined") + return fmt.Errorf("missing arguments: Project name or environment name is not defined") } current := lagoonCLIConfig.Current lc := client.New( diff --git a/cmd/list.go b/cmd/list.go index 090dde61..bd729ec4 100644 --- a/cmd/list.go +++ b/cmd/list.go @@ -8,7 +8,6 @@ import ( "strconv" "github.com/spf13/cobra" - "github.com/spf13/pflag" "github.com/uselagoon/lagoon-cli/internal/lagoon" "github.com/uselagoon/lagoon-cli/internal/lagoon/client" "github.com/uselagoon/lagoon-cli/internal/schema" @@ -26,19 +25,6 @@ type ListFlags struct { Reveal bool `json:"reveal,omitempty"` } -func parseListFlags(flags pflag.FlagSet) ListFlags { - configMap := make(map[string]interface{}) - flags.VisitAll(func(f *pflag.Flag) { - if flags.Changed(f.Name) { - configMap[f.Name] = f.Value - } - }) - jsonStr, _ := json.Marshal(configMap) - parsedFlags := ListFlags{} - json.Unmarshal(jsonStr, &parsedFlags) - return parsedFlags -} - var listCmd = &cobra.Command{ Use: "list", Short: "List projects, environments, deployments, variables or notifications", @@ -408,10 +394,10 @@ Without a group name, this query may time out in large Lagoon installs.`, } for _, member := range groupMembers.Members { data = append(data, []string{ - returnNonEmptyString(fmt.Sprintf("%s", groupMembers.ID)), - returnNonEmptyString(fmt.Sprintf("%s", groupMembers.Name)), - returnNonEmptyString(fmt.Sprintf("%s", member.User.Email)), - returnNonEmptyString(fmt.Sprintf("%s", member.Role)), + returnNonEmptyString(groupMembers.ID.String()), + returnNonEmptyString(groupMembers.Name), + returnNonEmptyString(member.User.Email), + returnNonEmptyString(string(member.Role)), }) } } else { @@ -423,10 +409,10 @@ Without a group name, this query may time out in large Lagoon installs.`, for _, group := range *groupMembers { for _, member := range group.Members { data = append(data, []string{ - returnNonEmptyString(fmt.Sprintf("%s", group.ID)), - returnNonEmptyString(fmt.Sprintf("%s", group.Name)), - returnNonEmptyString(fmt.Sprintf("%s", member.User.Email)), - returnNonEmptyString(fmt.Sprintf("%s", member.Role)), + returnNonEmptyString(group.ID.String()), + returnNonEmptyString(group.Name), + returnNonEmptyString(member.User.Email), + returnNonEmptyString(string(member.Role)), }) } } @@ -475,11 +461,11 @@ This query can take a long time to run if there are a lot of users.`, data := []output.Data{} for _, user := range *allUsers { data = append(data, []string{ - returnNonEmptyString(fmt.Sprintf("%s", user.ID)), - returnNonEmptyString(fmt.Sprintf("%s", user.Email)), - returnNonEmptyString(fmt.Sprintf("%s", user.FirstName)), - returnNonEmptyString(fmt.Sprintf("%s", user.LastName)), - returnNonEmptyString(fmt.Sprintf("%s", user.Comment)), + returnNonEmptyString(user.ID.String()), + returnNonEmptyString(user.Email), + returnNonEmptyString(user.FirstName), + returnNonEmptyString(user.LastName), + returnNonEmptyString(user.Comment), }) } dataMain := output.Table{ @@ -509,7 +495,7 @@ var listUsersGroupsCmd = &cobra.Command{ return err } if emailAddress == "" { - return fmt.Errorf("Missing arguments: email address is not defined") + return fmt.Errorf("missing arguments: email address is not defined") } current := lagoonCLIConfig.Current token := lagoonCLIConfig.Lagoons[current].Token @@ -526,10 +512,10 @@ var listUsersGroupsCmd = &cobra.Command{ data := []output.Data{} for _, grouprole := range allUsers.GroupRoles { data = append(data, []string{ - returnNonEmptyString(fmt.Sprintf("%s", allUsers.ID)), - returnNonEmptyString(fmt.Sprintf("%s", allUsers.Email)), - returnNonEmptyString(fmt.Sprintf("%s", grouprole.Name)), - returnNonEmptyString(fmt.Sprintf("%s", grouprole.Role)), + returnNonEmptyString(allUsers.ID.String()), + returnNonEmptyString(allUsers.Email), + returnNonEmptyString(grouprole.Name), + returnNonEmptyString(grouprole.Role), }) } dataMain := output.Table{ @@ -681,8 +667,13 @@ var listOrganizationProjectsCmd = &cobra.Command{ debug) org, err := l.GetOrganizationByName(context.TODO(), organizationName, lc) + if err != nil { + return err + } orgProjects, err := l.ListProjectsByOrganizationID(context.TODO(), org.ID, lc) - handleError(err) + if err != nil { + return err + } if len(*orgProjects) == 0 { outputOptions.Error = fmt.Sprintf("No associated projects found for organization '%s'\n", organizationName) @@ -692,7 +683,7 @@ var listOrganizationProjectsCmd = &cobra.Command{ for _, project := range *orgProjects { data = append(data, []string{ returnNonEmptyString(fmt.Sprintf("%d", project.ID)), - returnNonEmptyString(fmt.Sprintf("%s", project.Name)), + returnNonEmptyString(project.Name), returnNonEmptyString(fmt.Sprintf("%d", project.GroupCount)), }) } @@ -735,9 +726,13 @@ var listOrganizationGroupsCmd = &cobra.Command{ debug) org, err := l.GetOrganizationByName(context.TODO(), organizationName, lc) + if err != nil { + return err + } orgGroups, err := l.ListGroupsByOrganizationID(context.TODO(), org.ID, lc) - handleError(err) - + if err != nil { + return err + } if len(*orgGroups) == 0 { outputOptions.Error = fmt.Sprintf("No associated groups found for organization '%s'\n", organizationName) } @@ -745,9 +740,9 @@ var listOrganizationGroupsCmd = &cobra.Command{ data := []output.Data{} for _, group := range *orgGroups { data = append(data, []string{ - returnNonEmptyString(fmt.Sprintf("%s", group.ID.String())), - returnNonEmptyString(fmt.Sprintf("%s", group.Name)), - returnNonEmptyString(fmt.Sprintf("%s", group.Type)), + returnNonEmptyString(group.ID.String()), + returnNonEmptyString(group.Name), + returnNonEmptyString(group.Type), returnNonEmptyString(fmt.Sprintf("%d", group.MemberCount)), }) } @@ -805,12 +800,12 @@ var listOrganizationDeployTargetsCmd = &cobra.Command{ for _, dt := range *deployTargets { data = append(data, []string{ returnNonEmptyString(fmt.Sprintf("%d", dt.ID)), - returnNonEmptyString(fmt.Sprintf("%s", dt.Name)), - returnNonEmptyString(fmt.Sprintf("%s", dt.RouterPattern)), - returnNonEmptyString(fmt.Sprintf("%s", dt.CloudRegion)), - returnNonEmptyString(fmt.Sprintf("%s", dt.CloudProvider)), - returnNonEmptyString(fmt.Sprintf("%s", dt.SSHHost)), - returnNonEmptyString(fmt.Sprintf("%s", dt.SSHPort)), + returnNonEmptyString(dt.Name), + returnNonEmptyString(dt.RouterPattern), + returnNonEmptyString(dt.CloudRegion), + returnNonEmptyString(dt.CloudProvider), + returnNonEmptyString(dt.SSHHost), + returnNonEmptyString(dt.SSHPort), }) } dataMain := output.Table{ @@ -858,11 +853,11 @@ var ListOrganizationUsersCmd = &cobra.Command{ data := []output.Data{} for _, user := range *users { data = append(data, []string{ - returnNonEmptyString(fmt.Sprintf("%s", user.ID)), - returnNonEmptyString(fmt.Sprintf("%s", user.Email)), - returnNonEmptyString(fmt.Sprintf("%s", user.FirstName)), - returnNonEmptyString(fmt.Sprintf("%s", user.LastName)), - returnNonEmptyString(fmt.Sprintf("%s", user.Comment)), + returnNonEmptyString(user.ID), + returnNonEmptyString(user.Email), + returnNonEmptyString(user.FirstName), + returnNonEmptyString(user.LastName), + returnNonEmptyString(user.Comment), returnNonEmptyString(fmt.Sprintf("%v", user.Owner)), }) } @@ -898,13 +893,16 @@ var listOrganizationsCmd = &cobra.Command{ debug) organizations, err := l.AllOrganizations(context.TODO(), lc) + if err != nil { + return err + } data := []output.Data{} for _, organization := range *organizations { data = append(data, []string{ returnNonEmptyString(fmt.Sprintf("%d", organization.ID)), - returnNonEmptyString(fmt.Sprintf("%s", organization.Name)), - returnNonEmptyString(fmt.Sprintf("%s", organization.Description)), + returnNonEmptyString(organization.Name), + returnNonEmptyString(organization.Description), returnNonEmptyString(fmt.Sprintf("%d", organization.QuotaProject)), returnNonEmptyString(fmt.Sprintf("%d", organization.QuotaGroup)), returnNonEmptyString(fmt.Sprintf("%d", organization.QuotaNotification)), diff --git a/cmd/login.go b/cmd/login.go index 30e5dd01..6d48ffc7 100644 --- a/cmd/login.go +++ b/cmd/login.go @@ -113,18 +113,18 @@ func retrieveTokenViaSsh() (string, error) { lagoonCLIConfig.Lagoons[lagoonCLIConfig.Current].Port) conn, err := ssh.Dial("tcp", sshHost, config) if err != nil { - return "", fmt.Errorf("couldn't connect to %s: %v", sshHost, err) + return "", fmt.Errorf("unable to authenticate or connect to host %s\nthere may be an issue determining which ssh-key to use, or there may be an issue establishing a connection to the host\nthe error returned was: %v", sshHost, err) } defer conn.Close() session, err := conn.NewSession() if err != nil { - return "", fmt.Errorf("couldn't open session: %v", err) + return "", fmt.Errorf("unable to establish ssh session, error from attempt is: %v", err) } out, err := session.CombinedOutput("token") if err != nil { - return "", fmt.Errorf("couldn't get token: %v", err) + return "", fmt.Errorf("unable to get token: %v", err) } return strings.TrimSpace(string(out)), err } diff --git a/cmd/notifications.go b/cmd/notifications.go index 77df6d7b..69da1b67 100644 --- a/cmd/notifications.go +++ b/cmd/notifications.go @@ -1,11 +1,5 @@ package cmd -import ( - "encoding/json" - - "github.com/spf13/pflag" -) - // NotificationFlags . type NotificationFlags struct { Project string `json:"project,omitempty"` @@ -16,19 +10,6 @@ type NotificationFlags struct { NotificationChannel string `json:"channel,omitempty"` } -func parseNotificationFlags(flags pflag.FlagSet) NotificationFlags { - configMap := make(map[string]interface{}) - flags.VisitAll(func(f *pflag.Flag) { - if flags.Changed(f.Name) { - configMap[f.Name] = f.Value - } - }) - jsonStr, _ := json.Marshal(configMap) - parsedFlags := NotificationFlags{} - json.Unmarshal(jsonStr, &parsedFlags) - return parsedFlags -} - func init() { addNotificationCmd.AddCommand(addProjectNotificationRocketChatCmd) addNotificationCmd.AddCommand(addProjectNotificationSlackCmd) diff --git a/cmd/notificationsemail.go b/cmd/notificationsemail.go index be1cff3e..ae4cb12b 100644 --- a/cmd/notificationsemail.go +++ b/cmd/notificationsemail.go @@ -45,7 +45,7 @@ It does not configure a project to send notifications to email though, you need return err } if name == "" || email == "" { - return fmt.Errorf("Missing arguments: name or email is not defined") + return fmt.Errorf("missing arguments: name or email is not defined") } if yesNo(fmt.Sprintf("You are attempting to create an email notification '%s' with email address '%s', are you sure?", name, email)) { current := lagoonCLIConfig.Current @@ -78,7 +78,7 @@ It does not configure a project to send notifications to email though, you need if err != nil { return err } - notificationData = append(notificationData, fmt.Sprintf("%s", organization.Name)) + notificationData = append(notificationData, organization.Name) } else { notificationData = append(notificationData, "-") } @@ -116,7 +116,7 @@ This command is used to add an existing email notification in Lagoon to a projec return err } if name == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: project name or notification name is not defined") + return fmt.Errorf("missing arguments: project name or notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to add email notification '%s' to project '%s', are you sure?", name, cmdProjectName)) { current := lagoonCLIConfig.Current @@ -264,7 +264,7 @@ var deleteProjectEmailNotificationCmd = &cobra.Command{ return err } if name == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: project name or notification name is not defined") + return fmt.Errorf("missing arguments: project name or notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to delete email notification '%s' from project '%s', are you sure?", name, cmdProjectName)) { current := lagoonCLIConfig.Current @@ -309,7 +309,7 @@ var deleteEmailNotificationCmd = &cobra.Command{ return err } if name == "" { - return fmt.Errorf("Missing arguments: notification name is not defined") + return fmt.Errorf("missing arguments: notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to delete email notification '%s', are you sure?", name)) { current := lagoonCLIConfig.Current @@ -357,7 +357,7 @@ var updateEmailNotificationCmd = &cobra.Command{ return err } if name == "" { - return fmt.Errorf("Missing arguments: notification name is not defined") + return fmt.Errorf("missing arguments: notification name is not defined") } patch := schema.AddNotificationEmailInput{ Name: newname, @@ -365,7 +365,7 @@ var updateEmailNotificationCmd = &cobra.Command{ } b1, _ := json.Marshal(patch) if bytes.Equal(b1, []byte("{}")) { - return fmt.Errorf("Missing arguments: either email or newname must be defined") + return fmt.Errorf("missing arguments: either email or newname must be defined") } if yesNo(fmt.Sprintf("You are attempting to update email notification '%s', are you sure?", name)) { diff --git a/cmd/notificationsrocketchat.go b/cmd/notificationsrocketchat.go index 5618fa4b..9e212ef5 100644 --- a/cmd/notificationsrocketchat.go +++ b/cmd/notificationsrocketchat.go @@ -50,7 +50,7 @@ It does not configure a project to send notifications to RocketChat though, you return err } if name == "" || channel == "" || webhook == "" { - return fmt.Errorf("Missing arguments: name, webhook, or email is not defined") + return fmt.Errorf("missing arguments: name, webhook, or email is not defined") } if yesNo(fmt.Sprintf("You are attempting to create an RocketChat notification '%s' with webhook '%s' channel '%s', are you sure?", name, webhook, channel)) { current := lagoonCLIConfig.Current @@ -85,7 +85,7 @@ It does not configure a project to send notifications to RocketChat though, you if err != nil { return err } - notificationData = append(notificationData, fmt.Sprintf("%s", organization.Name)) + notificationData = append(notificationData, organization.Name) } else { notificationData = append(notificationData, "-") } @@ -124,7 +124,7 @@ This command is used to add an existing RocketChat notification in Lagoon to a p return err } if name == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: project name or notification name is not defined") + return fmt.Errorf("missing arguments: project name or notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to add RocketChat notification '%s' to project '%s', are you sure?", name, cmdProjectName)) { current := lagoonCLIConfig.Current @@ -276,7 +276,7 @@ var deleteProjectRocketChatNotificationCmd = &cobra.Command{ return err } if name == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: project name or notification name is not defined") + return fmt.Errorf("missing arguments: project name or notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to delete RocketChat notification '%s' from project '%s', are you sure?", name, cmdProjectName)) { current := lagoonCLIConfig.Current @@ -321,7 +321,7 @@ var deleteRocketChatNotificationCmd = &cobra.Command{ return err } if name == "" { - return fmt.Errorf("Missing arguments: notification name is not defined") + return fmt.Errorf("missing arguments: notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to delete RocketChat notification '%s', are you sure?", name)) { current := lagoonCLIConfig.Current @@ -373,7 +373,7 @@ var updateRocketChatNotificationCmd = &cobra.Command{ return err } if name == "" { - return fmt.Errorf("Missing arguments: notification name is not defined") + return fmt.Errorf("missing arguments: notification name is not defined") } patch := schema.AddNotificationRocketChatInput{ Name: newname, @@ -382,7 +382,7 @@ var updateRocketChatNotificationCmd = &cobra.Command{ } b1, _ := json.Marshal(patch) if bytes.Equal(b1, []byte("{}")) { - return fmt.Errorf("Missing arguments: either channel, webhook, or newname must be defined") + return fmt.Errorf("missing arguments: either channel, webhook, or newname must be defined") } if yesNo(fmt.Sprintf("You are attempting to update RocketChat notification '%s', are you sure?", name)) { diff --git a/cmd/notificationsslack.go b/cmd/notificationsslack.go index 24ff8198..26c1c4f4 100644 --- a/cmd/notificationsslack.go +++ b/cmd/notificationsslack.go @@ -50,7 +50,7 @@ It does not configure a project to send notifications to Slack though, you need return err } if name == "" || channel == "" || webhook == "" { - return fmt.Errorf("Missing arguments: name, webhook, or email is not defined") + return fmt.Errorf("missing arguments: name, webhook, or email is not defined") } if yesNo(fmt.Sprintf("You are attempting to create an Slack notification '%s' with webhook '%s' channel '%s', are you sure?", name, webhook, channel)) { current := lagoonCLIConfig.Current @@ -85,7 +85,7 @@ It does not configure a project to send notifications to Slack though, you need if err != nil { return err } - notificationData = append(notificationData, fmt.Sprintf("%s", organization.Name)) + notificationData = append(notificationData, organization.Name) } else { notificationData = append(notificationData, "-") } @@ -124,7 +124,7 @@ This command is used to add an existing Slack notification in Lagoon to a projec return err } if name == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: project name or notification name is not defined") + return fmt.Errorf("missing arguments: project name or notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to add Slack notification '%s' to project '%s', are you sure?", name, cmdProjectName)) { current := lagoonCLIConfig.Current @@ -276,7 +276,7 @@ var deleteProjectSlackNotificationCmd = &cobra.Command{ return err } if name == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: project name or notification name is not defined") + return fmt.Errorf("missing arguments: project name or notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to delete Slack notification '%s' from project '%s', are you sure?", name, cmdProjectName)) { current := lagoonCLIConfig.Current @@ -321,7 +321,7 @@ var deleteSlackNotificationCmd = &cobra.Command{ return err } if name == "" { - return fmt.Errorf("Missing arguments: notification name is not defined") + return fmt.Errorf("missing arguments: notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to delete Slack notification '%s', are you sure?", name)) { current := lagoonCLIConfig.Current @@ -373,7 +373,7 @@ var updateSlackNotificationCmd = &cobra.Command{ return err } if name == "" { - return fmt.Errorf("Missing arguments: notification name is not defined") + return fmt.Errorf("missing arguments: notification name is not defined") } patch := schema.AddNotificationSlackInput{ Name: newname, @@ -382,7 +382,7 @@ var updateSlackNotificationCmd = &cobra.Command{ } b1, _ := json.Marshal(patch) if bytes.Equal(b1, []byte("{}")) { - return fmt.Errorf("Missing arguments: either channel, webhook, or newname must be defined") + return fmt.Errorf("missing arguments: either channel, webhook, or newname must be defined") } if yesNo(fmt.Sprintf("You are attempting to update Slack notification '%s', are you sure?", name)) { diff --git a/cmd/notificationsteams.go b/cmd/notificationsteams.go index 017bc09a..971b4720 100644 --- a/cmd/notificationsteams.go +++ b/cmd/notificationsteams.go @@ -46,7 +46,7 @@ It does not configure a project to send notifications to Microsoft Teams though, return err } if name == "" || webhook == "" { - return fmt.Errorf("Missing arguments: name or webhook is not defined") + return fmt.Errorf("missing arguments: name or webhook is not defined") } if yesNo(fmt.Sprintf("You are attempting to create a Microsoft Teams notification '%s' with webhook url '%s', are you sure?", name, webhook)) { current := lagoonCLIConfig.Current @@ -79,7 +79,7 @@ It does not configure a project to send notifications to Microsoft Teams though, if err != nil { return err } - notificationData = append(notificationData, fmt.Sprintf("%s", organization.Name)) + notificationData = append(notificationData, organization.Name) } else { notificationData = append(notificationData, "-") } @@ -117,7 +117,7 @@ This command is used to add an existing Microsoft Teams notification in Lagoon t return err } if name == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: project name or notification name is not defined") + return fmt.Errorf("missing arguments: project name or notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to add Microsoft Teams notification '%s' to project '%s', are you sure?", name, cmdProjectName)) { current := lagoonCLIConfig.Current @@ -265,7 +265,7 @@ var deleteProjectMicrosoftTeamsNotificationCmd = &cobra.Command{ return err } if name == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: project name or notification name is not defined") + return fmt.Errorf("missing arguments: project name or notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to delete Microsoft Teams notification '%s' from project '%s', are you sure?", name, cmdProjectName)) { current := lagoonCLIConfig.Current @@ -310,7 +310,7 @@ var deleteMicrosoftTeamsNotificationCmd = &cobra.Command{ return err } if name == "" { - return fmt.Errorf("Missing arguments: notification name is not defined") + return fmt.Errorf("missing arguments: notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to delete Microsoft Teams notification '%s', are you sure?", name)) { current := lagoonCLIConfig.Current @@ -358,7 +358,7 @@ var updateMicrosoftTeamsNotificationCmd = &cobra.Command{ return err } if name == "" { - return fmt.Errorf("Missing arguments: notification name is not defined") + return fmt.Errorf("missing arguments: notification name is not defined") } patch := schema.AddNotificationMicrosoftTeamsInput{ Name: newname, @@ -366,7 +366,7 @@ var updateMicrosoftTeamsNotificationCmd = &cobra.Command{ } b1, _ := json.Marshal(patch) if bytes.Equal(b1, []byte("{}")) { - return fmt.Errorf("Missing arguments: either webhook or newname must be defined") + return fmt.Errorf("missing arguments: either webhook or newname must be defined") } if yesNo(fmt.Sprintf("You are attempting to update Microsoft Teams notification '%s', are you sure?", name)) { diff --git a/cmd/notificationswebhook.go b/cmd/notificationswebhook.go index d621fd9b..22b3439b 100644 --- a/cmd/notificationswebhook.go +++ b/cmd/notificationswebhook.go @@ -46,7 +46,7 @@ It does not configure a project to send notifications to webhook though, you nee return err } if name == "" || webhook == "" { - return fmt.Errorf("Missing arguments: name or webhook is not defined") + return fmt.Errorf("missing arguments: name or webhook is not defined") } if yesNo(fmt.Sprintf("You are attempting to create a webhook notification '%s' with webhook url '%s', are you sure?", name, webhook)) { current := lagoonCLIConfig.Current @@ -79,7 +79,7 @@ It does not configure a project to send notifications to webhook though, you nee if err != nil { return err } - notificationData = append(notificationData, fmt.Sprintf("%s", organization.Name)) + notificationData = append(notificationData, organization.Name) } else { notificationData = append(notificationData, "-") } @@ -117,7 +117,7 @@ This command is used to add an existing webhook notification in Lagoon to a proj return err } if name == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: project name or notification name is not defined") + return fmt.Errorf("missing arguments: project name or notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to add webhook notification '%s' to project '%s', are you sure?", name, cmdProjectName)) { current := lagoonCLIConfig.Current @@ -265,7 +265,7 @@ var deleteProjectWebhookNotificationCmd = &cobra.Command{ return err } if name == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: project name or notification name is not defined") + return fmt.Errorf("missing arguments: project name or notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to delete webhook notification '%s' from project '%s', are you sure?", name, cmdProjectName)) { current := lagoonCLIConfig.Current @@ -310,7 +310,7 @@ var deleteWebhookNotificationCmd = &cobra.Command{ return err } if name == "" { - return fmt.Errorf("Missing arguments: notification name is not defined") + return fmt.Errorf("missing arguments: notification name is not defined") } if yesNo(fmt.Sprintf("You are attempting to delete webhook notification '%s', are you sure?", name)) { current := lagoonCLIConfig.Current @@ -358,7 +358,7 @@ var updateWebhookNotificationCmd = &cobra.Command{ return err } if name == "" { - return fmt.Errorf("Missing arguments: notification name is not defined") + return fmt.Errorf("missing arguments: notification name is not defined") } patch := schema.AddNotificationWebhookInput{ Name: newname, @@ -366,7 +366,7 @@ var updateWebhookNotificationCmd = &cobra.Command{ } b1, _ := json.Marshal(patch) if bytes.Equal(b1, []byte("{}")) { - return fmt.Errorf("Missing arguments: either webhook or newname must be defined") + return fmt.Errorf("missing arguments: either webhook or newname must be defined") } if yesNo(fmt.Sprintf("You are attempting to update webhook notification '%s', are you sure?", name)) { diff --git a/cmd/organization.go b/cmd/organization.go index 32c7270e..2956273a 100644 --- a/cmd/organization.go +++ b/cmd/organization.go @@ -197,6 +197,9 @@ var updateOrganizationCmd = &cobra.Command{ debug) organization, err := l.GetOrganizationByName(context.TODO(), organizationName, lc) + if err != nil { + return err + } organizationInput := s.UpdateOrganizationPatchInput{ Description: nullStrCheck(organizationDescription), FriendlyName: nullStrCheck(organizationFriendlyName), @@ -207,7 +210,9 @@ var updateOrganizationCmd = &cobra.Command{ QuotaRoute: nullIntCheck(organizationQuotaRoute), } result, err := l.UpdateOrganization(context.TODO(), organization.ID, organizationInput, lc) - handleError(err) + if err != nil { + return err + } resultData := output.Result{ Result: "success", diff --git a/cmd/project.go b/cmd/project.go index aa376462..2ff15bcb 100644 --- a/cmd/project.go +++ b/cmd/project.go @@ -157,7 +157,7 @@ var listProjectByMetadata = &cobra.Command{ return err } if key == "" { - return fmt.Errorf("Missing arguments: key is not defined") + return fmt.Errorf("missing arguments: key is not defined") } current := lagoonCLIConfig.Current token := lagoonCLIConfig.Lagoons[current].Token @@ -276,7 +276,7 @@ var updateProjectMetadata = &cobra.Command{ return err } if key == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: Project name or key is not defined") + return fmt.Errorf("missing arguments: Project name or key is not defined") } if yesNo(fmt.Sprintf("You are attempting to update key '%s' for project '%s' metadata, are you sure?", key, cmdProjectName)) { current := lagoonCLIConfig.Current @@ -332,7 +332,7 @@ var deleteProjectMetadataByKey = &cobra.Command{ return err } if key == "" || cmdProjectName == "" { - return fmt.Errorf("Missing arguments: Project name or key is not defined") + return fmt.Errorf("missing arguments: Project name or key is not defined") } if yesNo(fmt.Sprintf("You are attempting to delete key '%s' from project '%s' metadata, are you sure?", key, cmdProjectName)) { current := lagoonCLIConfig.Current diff --git a/cmd/retrieve.go b/cmd/retrieve.go index d39e1d89..40ef3498 100644 --- a/cmd/retrieve.go +++ b/cmd/retrieve.go @@ -40,7 +40,7 @@ You can check the status of the backup using the list backups or get backup comm return err } if backupID == "" { - return fmt.Errorf("Missing arguments: backup-id is not defined") + return fmt.Errorf("missing arguments: backup-id is not defined") } if yesNo(fmt.Sprintf("You are attempting to trigger a retrieval for backup ID '%s', are you sure?", backupID)) { current := lagoonCLIConfig.Current diff --git a/cmd/root.go b/cmd/root.go index 65ccb481..c729fbe8 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -13,7 +13,6 @@ import ( "github.com/manifoldco/promptui" "github.com/spf13/cobra" "github.com/spf13/cobra/doc" - "github.com/uselagoon/lagoon-cli/internal/lagoon" lagooncli "github.com/uselagoon/lagoon-cli/internal/lagoon" "github.com/uselagoon/lagoon-cli/internal/lagoon/client" "github.com/uselagoon/lagoon-cli/pkg/app" @@ -38,14 +37,13 @@ var configExtension = ".yml" var createConfig bool var userPath string var configFilePath string -var commandsFilePath = ".lagoon-cli/commands" var updateDocURL = "https://uselagoon.github.io/lagoon-cli" var skipUpdateCheck bool // global for the lagoon config that the cli uses // @TODO: when lagoon-cli rewrite happens, do this a bit better -var lagoonCLIConfig lagoon.Config +var lagoonCLIConfig lagooncli.Config // version/build information (populated at build time by make file) var ( @@ -60,10 +58,10 @@ var rootCmd = &cobra.Command{ Long: `Lagoon CLI. Manage your Lagoon hosted projects.`, DisableAutoGenTag: true, PersistentPreRun: func(cmd *cobra.Command, args []string) { - if lagoonCLIConfig.UpdateCheckDisable == true { + if lagoonCLIConfig.UpdateCheckDisable { skipUpdateCheck = true } - if skipUpdateCheck == false { + if !skipUpdateCheck { // Using code from https://github.com/drud/ddev/ updateFile := filepath.Join(userPath, ".lagoon.update") // Do periodic detection of whether an update is available for lagoon-cli users. @@ -209,8 +207,8 @@ var versionCmd = &cobra.Command{ } func displayVersionInfo() { - fmt.Println(fmt.Sprintf("lagoon %s (%s)", lagoonCLIVersion, lagoonCLIBuildGoVersion)) - fmt.Println(fmt.Sprintf("built %s", lagoonCLIBuild)) + fmt.Printf("lagoon %s (%s)\n", lagoonCLIVersion, lagoonCLIBuildGoVersion) + fmt.Printf("built %s\n", lagoonCLIBuild) } func initConfig() { @@ -245,7 +243,7 @@ func initConfig() { // we can use that inplaces where projects already exist so you don't have to type it out // and environments too // this option is opt-in now, so to use it you will need to `lagoon config feature --enable-local-dir-check=true` - if lagoonCLIConfig.EnvironmentFromDirectory == true { + if lagoonCLIConfig.EnvironmentFromDirectory { cmdProject, _ = app.GetLocalProject() } if cmdProject.Name != "" && cmdProjectName == "" { @@ -257,7 +255,7 @@ func initConfig() { } func yesNo(message string) bool { - if forceAction != true { + if !forceAction { prompt := promptui.Select{ Label: message + "; Select[Yes/No]", Items: []string{"No", "Yes"}, @@ -272,22 +270,6 @@ func yesNo(message string) bool { return true } -func selectList(listItems []string) string { - if forceAction != true { - prompt := promptui.Select{ - Label: "Select item", - Items: listItems, - } - _, result, err := prompt.Run() - if err != nil { - output.RenderError(err.Error(), outputOptions) - os.Exit(1) - } - return result - } - return "" -} - // GetInput reads input from an input buffer and returns the result as a string. func GetInput() string { inputScanner.Scan() @@ -296,7 +278,7 @@ func GetInput() string { // Prompt gets input with a prompt and returns the input func Prompt(prompt string) string { - fullPrompt := fmt.Sprintf("%s", prompt) + fullPrompt := prompt fmt.Print(fullPrompt + ": ") return GetInput() } @@ -323,10 +305,10 @@ func validateToken(lagoon string) { os.Exit(1) } valid := graphql.VerifyTokenExpiry(&lagoonCLIConfig, lagoon) - if valid == false { + if !valid { loginErr := loginToken() if loginErr != nil { - fmt.Println("Unable to refresh token, you may need to run `lagoon login` first, error was", loginErr.Error()) + fmt.Println("couldn't refresh token:", loginErr.Error()) os.Exit(1) } } @@ -362,7 +344,7 @@ func validateTokenE(lagoon string) error { return nil } if err = loginToken(); err != nil { - return fmt.Errorf("Couldn't refresh token, try `lagoon login`: %w", err) + return fmt.Errorf("couldn't refresh token: %w", err) } // set up the clients eClient, err = environments.New(&lagoonCLIConfig, debugEnable) @@ -412,7 +394,7 @@ func getLagoonConfigFile(configPath *string, configName *string, configExtension var configFilePath string configFilePath, err := cmd.Flags().GetString("config-file") if err != nil { - return fmt.Errorf("Error reading flag `config-file`: %v", err) + return fmt.Errorf("error reading flag `config-file`: %v", err) } if configFilePath == "" { if lagoonConfigEnvar, ok := os.LookupEnv("LAGOONCONFIG"); ok { @@ -437,12 +419,12 @@ func getLagoonConfigFile(configPath *string, configName *string, configExtension return nil } -func getLagoonContext(lagoonCLIConfig *lagoon.Config, lagoon *string, cmd *cobra.Command) error { +func getLagoonContext(lagoonCLIConfig *lagooncli.Config, lagoon *string, cmd *cobra.Command) error { // check if we have an envvar or flag to define our lagoon context var lagoonContext string lagoonContext, err := cmd.Flags().GetString("lagoon") if err != nil { - return fmt.Errorf("Error reading flag `lagoon`: %v", err) + return fmt.Errorf("error reading flag `lagoon`: %v", err) } if lagoonContext == "" { if lagoonContextEnvar, ok := os.LookupEnv("LAGOONCONTEXT"); ok { @@ -467,7 +449,7 @@ func getLagoonContext(lagoonCLIConfig *lagoon.Config, lagoon *string, cmd *cobra return nil } -func checkContextExists(lagoonCLIConfig *lagoon.Config) error { +func checkContextExists(lagoonCLIConfig *lagooncli.Config) error { contextExists := false for l := range lagoonCLIConfig.Lagoons { if l == lagoonCLIConfig.Current { @@ -475,7 +457,7 @@ func checkContextExists(lagoonCLIConfig *lagoon.Config) error { } } if !contextExists { - return fmt.Errorf("Chosen context '%s' doesn't exist in config file", lagoonCLIConfig.Current) + return fmt.Errorf("chosen context '%s' doesn't exist in config file", lagoonCLIConfig.Current) } return nil } diff --git a/cmd/shared.go b/cmd/shared.go index d67a2391..dcbba996 100644 --- a/cmd/shared.go +++ b/cmd/shared.go @@ -17,45 +17,24 @@ var lagoonUI string var lagoonKibana string var lagoonSSHKey string -// variable vars -var variableValue string -var variableName string -var variableScope string - // user vars var userFirstName string var userLastName string var userEmail string var pubKeyFile string -var nameInPubKeyFile bool var sshKeyName string -// openshift vars -var osName string -var osConsoleUrl string -var osToken string - // group vars var groupName string var jsonPatch string var revealValue bool var listAllProjects bool -var noHeader bool // These are available to all cmds and are set either by flags (-p and -e) or via `lagoon-cli/app` when entering a directory that has a valid lagoon project var cmdProjectName string var cmdProjectEnvironment string -var remoteID string - -var notificationName string -var notificationNewName string -var notificationWebhook string -var notificationChannel string - -var deployBranchName string - var outputOptions = output.Options{ Header: false, CSV: false, diff --git a/cmd/ssh.go b/cmd/ssh.go index 37b97350..f8740532 100644 --- a/cmd/ssh.go +++ b/cmd/ssh.go @@ -25,7 +25,7 @@ var sshEnvCmd = &cobra.Command{ validateToken(lagoonCLIConfig.Current) // get a new token if the current one is invalid if cmdProjectName == "" || cmdProjectEnvironment == "" { - return fmt.Errorf("Missing arguments: Project name or environment name are not defined") + return fmt.Errorf("missing arguments: Project name or environment name are not defined") } debug, err := cmd.Flags().GetBool("debug") if err != nil { @@ -128,7 +128,7 @@ func init() { // generateSSHConnectionString . func generateSSHConnectionString(lagoon map[string]string, service string, container string, isPortal bool) string { - connString := fmt.Sprintf("ssh -t") + connString := "ssh -t" if lagoon["sshKey"] != "" { connString = fmt.Sprintf("%s -i %s", connString, lagoon["sshKey"]) } diff --git a/cmd/tasks.go b/cmd/tasks.go index 7e31f65a..df7de11e 100644 --- a/cmd/tasks.go +++ b/cmd/tasks.go @@ -40,7 +40,7 @@ var getTaskByID = &cobra.Command{ return err } if taskID == 0 { - return fmt.Errorf("Missing arguments: ID is not defined") + return fmt.Errorf("missing arguments: ID is not defined") } current := lagoonCLIConfig.Current token := lagoonCLIConfig.Lagoons[current].Token @@ -99,7 +99,7 @@ If the task fails or fails to update, contact your Lagoon administrator for assi return err } if cmdProjectName == "" { - return fmt.Errorf("Missing arguments: Project name is not defined") + return fmt.Errorf("missing arguments: Project name is not defined") } if yesNo(fmt.Sprintf("You are attempting to run the active/standby switch for project '%s', are you sure?", cmdProjectName)) { current := lagoonCLIConfig.Current @@ -114,9 +114,9 @@ If the task fails or fails to update, contact your Lagoon administrator for assi if err != nil { return err } - fmt.Println(fmt.Sprintf(`Created a new task with ID %d + fmt.Printf(`Created a new task with ID %d You can use the following command to query the task status: -lagoon -l %s get task-by-id --id %d --logs`, result.ID, current, result.ID)) +lagoon -l %s get task-by-id --id %d --logs\n`, result.ID, current, result.ID) } return nil }, @@ -299,7 +299,7 @@ var uploadFilesToTask = &cobra.Command{ return err } if taskID == 0 { - return fmt.Errorf("Missing arguments: ID is not defined") + return fmt.Errorf("missing arguments: ID is not defined") } files, err := cmd.Flags().GetStringSlice("file") if err != nil { diff --git a/cmd/users.go b/cmd/users.go index 7033d544..343c8cf7 100644 --- a/cmd/users.go +++ b/cmd/users.go @@ -3,7 +3,6 @@ package cmd import ( "context" "encoding/json" - "errors" "fmt" "os" "strconv" @@ -59,7 +58,7 @@ func parseSSHKeyFile(sshPubKey string, keyName string, keyValue string, userEmai } else { // return error stating key type not supported keyType = api.SSHRsa - err = errors.New(fmt.Sprintf("SSH key type %s not supported", string(splitKey[0]))) + err = fmt.Errorf(fmt.Sprintf("SSH key type %s not supported", string(splitKey[0]))) } // if the sshkey has a comment/name in it, we can use that @@ -157,6 +156,9 @@ var deleteSSHKeyCmd = &cobra.Command{ }, RunE: func(cmd *cobra.Command, args []string) error { debug, err := cmd.Flags().GetBool("debug") + if err != nil { + return err + } sshKeyID, err := cmd.Flags().GetUint("id") if err != nil { return err diff --git a/cmd/web.go b/cmd/web.go index f5431c05..e052a5a0 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -31,7 +31,7 @@ var webCmd = &cobra.Command{ } url := urlBuilder.String() - fmt.Println(fmt.Sprintf("Opening %s", url)) + fmt.Printf("Opening %s\n", url) _ = browser.OpenURL(url) }, } @@ -49,7 +49,7 @@ var kibanaCmd = &cobra.Command{ } url := urlBuilder.String() - fmt.Println(fmt.Sprintf("Opening %s", url)) + fmt.Printf("Opening %s\n", url) _ = browser.OpenURL(url) }, } diff --git a/cmd/whoami.go b/cmd/whoami.go index 14d914a8..8e3e1cbb 100644 --- a/cmd/whoami.go +++ b/cmd/whoami.go @@ -42,7 +42,7 @@ This is useful if you have multiple keys or accounts in multiple lagoons and nee user, err := lagoon.GetMeInfo(context.TODO(), lc) if err != nil { if strings.Contains(err.Error(), "Cannot read property 'access_token' of null") { - return fmt.Errorf("Unable to get user information, you may be using an administration token") + return fmt.Errorf("unable to get user information, you may be using an administration token") } return err } @@ -74,7 +74,7 @@ This is useful if you have multiple keys or accounts in multiple lagoons and nee keyData = append(keyData, key.Created) } if opts["type"] { - keyData = append(keyData, fmt.Sprintf("%s", key.KeyType)) + keyData = append(keyData, string(key.KeyType)) } if opts["key"] { keyData = append(keyData, key.KeyValue) diff --git a/go.mod b/go.mod index 67c84d9f..85ff9405 100644 --- a/go.mod +++ b/go.mod @@ -21,6 +21,7 @@ require ( github.com/stretchr/testify v1.8.2 github.com/uselagoon/machinery v0.0.19 golang.org/x/crypto v0.21.0 + golang.org/x/term v0.18.0 gopkg.in/yaml.v3 v3.0.1 sigs.k8s.io/yaml v1.4.0 ) @@ -37,7 +38,6 @@ require ( github.com/rivo/uniseg v0.2.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect golang.org/x/sys v0.18.0 // indirect - golang.org/x/term v0.18.0 // indirect ) // replace github.com/uselagoon/machinery => ../machinery diff --git a/internal/lagoon/client/client.go b/internal/lagoon/client/client.go index 455c9278..50b16838 100644 --- a/internal/lagoon/client/client.go +++ b/internal/lagoon/client/client.go @@ -20,7 +20,6 @@ var lgraphql embed.FS // Client implements the lagoon package interfaces for the Lagoon GraphQL API. type Client struct { - userAgent string token string apiVersion string cliVersion string diff --git a/pkg/api/main.go b/pkg/api/main.go index 92a8bebf..e9a81770 100644 --- a/pkg/api/main.go +++ b/pkg/api/main.go @@ -75,9 +75,7 @@ type Client interface { // Interface struct type Interface struct { - tokenSigningKey string token string - jwtAudience string graphQLEndpoint string debug bool netClient *http.Client @@ -223,9 +221,9 @@ func debugRequest(req *graphql.Request) { data.Vars = append(data.Vars, DebugVar{Name: n, Value: v}) } jsonData, _ := json.Marshal(data) - fmt.Println(fmt.Sprintf("%s: %s", aurora.Yellow("Request"), strings.Replace(string(jsonData), "\\t", "", -1))) + fmt.Printf("%s: %s\n", aurora.Yellow("Request"), strings.Replace(string(jsonData), "\\t", "", -1)) } func debugResponse(resp []byte) { - fmt.Println(fmt.Sprintf("%s: %s", aurora.Yellow("Response"), string(resp))) + fmt.Printf("%s: %s\n", aurora.Yellow("Response"), string(resp)) } diff --git a/pkg/app/app.go b/pkg/app/app.go index 58966624..9f4b8505 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -39,7 +39,7 @@ func (project *LagoonProject) ReadConfig() error { dockerComposeFilepath := filepath.Join(project.Dir, project.DockerComposeYaml) if !fileExists(dockerComposeFilepath) { - return fmt.Errorf("Could not load docker-compose.yml at %s", dockerComposeFilepath) + return fmt.Errorf("could not load docker-compose.yml at %s", dockerComposeFilepath) } sourceCompose, _ := os.ReadFile(dockerComposeFilepath) var dockerCompose LagoonDockerCompose diff --git a/pkg/lagoon/environments/tasks.go b/pkg/lagoon/environments/tasks.go index 2ca2909d..00811349 100644 --- a/pkg/lagoon/environments/tasks.go +++ b/pkg/lagoon/environments/tasks.go @@ -413,7 +413,7 @@ func (e *Environments) InvokeAdvancedTaskDefinition(projectName string, environm } if taskId == 0 { - return nil, errors.New(fmt.Sprintf("Could not find a task `%v` for project/environment %v/%v", + return nil, fmt.Errorf(fmt.Sprintf("Could not find a task `%v` for project/environment %v/%v", advancedTaskName, projectName, environmentName)) } diff --git a/pkg/lagoon/environments/variables.go b/pkg/lagoon/environments/variables.go index a0ee9235..6d7fc846 100644 --- a/pkg/lagoon/environments/variables.go +++ b/pkg/lagoon/environments/variables.go @@ -153,6 +153,9 @@ func (e *Environments) ListEnvironmentVariables(projectName string, environmentN } var environmentInfo api.Environment err = json.Unmarshal([]byte(environmentByName), &environmentInfo) + if err != nil { + return []byte(""), err + } returnResult, err := processEnvironmentVariables(environmentInfo, projectName, revealValue) if err != nil { return []byte(""), err diff --git a/pkg/lagoon/projects/main.go b/pkg/lagoon/projects/main.go index 8b4db6c6..b6598638 100644 --- a/pkg/lagoon/projects/main.go +++ b/pkg/lagoon/projects/main.go @@ -43,8 +43,6 @@ func New(lc *lagoon.Config, debug bool) (Client, error) { } -var noDataError = "no data returned from the lagoon api" - // ListAllProjects will list all projects func (p *Projects) ListAllProjects() ([]byte, error) { allProjects, err := p.api.GetAllProjects(graphql.AllProjectsFragment) @@ -150,7 +148,7 @@ func processProjectExtra(project api.Project) []string { fmt.Sprintf("%v/%v", currentDevEnvironments, project.DevelopmentEnvironmentsLimit), fmt.Sprintf("%v", project.DevelopmentEnvironmentsLimit), fmt.Sprintf("%v", project.ProductionEnvironment), - fmt.Sprintf("%s", project.RouterPattern), + project.RouterPattern, fmt.Sprintf("%v", *project.AutoIdle), fmt.Sprintf("%v", *project.FactsUI), fmt.Sprintf("%v", *project.ProblemsUI), diff --git a/pkg/lagoon/ssh/main.go b/pkg/lagoon/ssh/main.go index ea297dd4..07f3a2f8 100644 --- a/pkg/lagoon/ssh/main.go +++ b/pkg/lagoon/ssh/main.go @@ -2,25 +2,24 @@ package ssh import ( "bytes" - "errors" "fmt" "os" "golang.org/x/crypto/ssh" - "golang.org/x/crypto/ssh/terminal" + "golang.org/x/term" ) // InteractiveSSH . func InteractiveSSH(lagoon map[string]string, sshService string, sshContainer string, config *ssh.ClientConfig) error { client, err := ssh.Dial("tcp", lagoon["hostname"]+":"+lagoon["port"], config) if err != nil { - return errors.New("Failed to dial: " + err.Error() + "\nCheck that the project or environment you are trying to connect to exists") + return fmt.Errorf("Failed to dial: " + err.Error() + "\nCheck that the project or environment you are trying to connect to exists") } // start the session session, err := client.NewSession() if err != nil { - return errors.New("Failed to create session: " + err.Error()) + return fmt.Errorf("Failed to create session: " + err.Error()) } defer session.Close() session.Stdout = os.Stdout @@ -32,13 +31,13 @@ func InteractiveSSH(lagoon map[string]string, sshService string, sshContainer st ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud } fileDescriptor := int(os.Stdin.Fd()) - if terminal.IsTerminal(fileDescriptor) { - originalState, err := terminal.MakeRaw(fileDescriptor) + if term.IsTerminal(fileDescriptor) { + originalState, err := term.MakeRaw(fileDescriptor) if err != nil { return err } - defer terminal.Restore(fileDescriptor, originalState) - termWidth, termHeight, err := terminal.GetSize(fileDescriptor) + defer term.Restore(fileDescriptor, originalState) + termWidth, termHeight, err := term.GetSize(fileDescriptor) if err != nil { return err } @@ -56,7 +55,7 @@ func InteractiveSSH(lagoon map[string]string, sshService string, sshContainer st } err = session.Start(connString) if err != nil { - return errors.New("Failed to start shell: " + err.Error()) + return fmt.Errorf("Failed to start shell: " + err.Error()) } session.Wait() return nil @@ -66,13 +65,13 @@ func InteractiveSSH(lagoon map[string]string, sshService string, sshContainer st func RunSSHCommand(lagoon map[string]string, sshService string, sshContainer string, command string, config *ssh.ClientConfig) error { client, err := ssh.Dial("tcp", lagoon["hostname"]+":"+lagoon["port"], config) if err != nil { - return errors.New("Failed to dial: " + err.Error() + "\nCheck that the project or environment you are trying to connect to exists") + return fmt.Errorf("Failed to dial: " + err.Error() + "\nCheck that the project or environment you are trying to connect to exists") } // start the session session, err := client.NewSession() if err != nil { - return errors.New("Failed to create session: " + err.Error()) + return fmt.Errorf("Failed to create session: " + err.Error()) } defer session.Close() session.Stdout = os.Stdout @@ -84,13 +83,13 @@ func RunSSHCommand(lagoon map[string]string, sshService string, sshContainer str ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud } fileDescriptor := int(os.Stdin.Fd()) - if terminal.IsTerminal(fileDescriptor) { - originalState, err := terminal.MakeRaw(fileDescriptor) + if term.IsTerminal(fileDescriptor) { + originalState, err := term.MakeRaw(fileDescriptor) if err != nil { return err } - defer terminal.Restore(fileDescriptor, originalState) - termWidth, termHeight, err := terminal.GetSize(fileDescriptor) + defer term.Restore(fileDescriptor, originalState) + termWidth, termHeight, err := term.GetSize(fileDescriptor) if err != nil { return err } diff --git a/pkg/lagoon/users/main.go b/pkg/lagoon/users/main.go index 39d40039..dcd6f719 100644 --- a/pkg/lagoon/users/main.go +++ b/pkg/lagoon/users/main.go @@ -1,6 +1,8 @@ package users import ( + "slices" + "github.com/uselagoon/lagoon-cli/internal/lagoon" "github.com/uselagoon/lagoon-cli/pkg/api" "github.com/uselagoon/lagoon-cli/pkg/graphql" @@ -105,19 +107,11 @@ func (ud *Data) AddItem(userData UserData) { func distinctObjects(objs []UserData) (distinctedObjs []UserData) { var output []UserData - for i := range objs { - if output == nil || len(output) == 0 { - output = append(output, objs[i]) - } else { - founded := false - for j := range output { - if output[j].ID == objs[i].ID { - founded = true - } - } - if !founded { - output = append(output, objs[i]) - } + ids := []string{} + for _, e := range objs { + if !slices.Contains(ids, e.ID) { + ids = append(ids, e.ID) + output = append(output, e) } } return output @@ -125,19 +119,11 @@ func distinctObjects(objs []UserData) (distinctedObjs []UserData) { func distinctKeys(objs []ExtendedSSHKey) (distinctedObjs []ExtendedSSHKey) { var output []ExtendedSSHKey - for i := range objs { - if output == nil || len(output) == 0 { - output = append(output, objs[i]) - } else { - founded := false - for j := range output { - if output[j].Email == objs[i].Email { - founded = true - } - } - if !founded { - output = append(output, objs[i]) - } + ids := []string{} + for _, e := range objs { + if !slices.Contains(ids, e.Email) { + ids = append(ids, e.Email) + output = append(output, e) } } return output diff --git a/pkg/output/main.go b/pkg/output/main.go index 36c47906..2465336d 100644 --- a/pkg/output/main.go +++ b/pkg/output/main.go @@ -87,17 +87,17 @@ func RenderResult(result Result, opts Options) { RenderJSON(result, opts) } else { if trimQuotes(result.Result) == "success" { - fmt.Println(fmt.Sprintf("Result: %s", aurora.Green(trimQuotes(result.Result)))) + fmt.Printf("Result: %s\n", aurora.Green(trimQuotes(result.Result))) if len(result.ResultData) != 0 { for k, v := range result.ResultData { - fmt.Println(fmt.Sprintf("%s: %v", k, v)) + fmt.Printf("%s: %v\n", k, v) } } } else { - fmt.Println(fmt.Sprintf("Result: %s", aurora.Yellow(trimQuotes(result.Result)))) + fmt.Printf("Result: %s\n", aurora.Yellow(trimQuotes(result.Result))) if len(result.ResultData) != 0 { for k, v := range result.ResultData { - fmt.Println(fmt.Sprintf("%s: %v", k, v)) + fmt.Printf("%s: %v\n", k, v) } } } @@ -108,7 +108,7 @@ func RenderResult(result Result, opts Options) { // RenderOutput . func RenderOutput(data Table, opts Options) { if opts.Debug { - fmt.Println(fmt.Sprintf("%s", aurora.Yellow("Final result:"))) + fmt.Printf("%s\n", aurora.Yellow("Final result:")) } if opts.JSON { // really basic tabledata to json implementation