Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: address go linting #389

Merged
merged 1 commit into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM golang:1.21-alpine as build
FROM golang:1.21-alpine AS build

WORKDIR /go/src/github.com/uselagoon/lagoon-cli/
COPY . .
Expand Down
12 changes: 5 additions & 7 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func parseLagoonConfig(flags pflag.FlagSet) LagoonConfigFlags {
})
jsonStr, _ := json.Marshal(configMap)
parsedFlags := LagoonConfigFlags{}
json.Unmarshal(jsonStr, &parsedFlags)
_ = json.Unmarshal(jsonStr, &parsedFlags)
return parsedFlags
}

Expand All @@ -55,12 +55,10 @@ var configDefaultCmd = &cobra.Command{
Use: "default",
Aliases: []string{"d"},
Short: "Set the default Lagoon to use",
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
lagoonConfig := parseLagoonConfig(*cmd.Flags())
if lagoonConfig.Lagoon == "" {
fmt.Println("Not enough arguments")
cmd.Help()
os.Exit(1)
return fmt.Errorf("not enough arguments")
}
lagoonCLIConfig.Default = strings.TrimSpace(string(lagoonConfig.Lagoon))
contextExists := false
Expand All @@ -70,8 +68,7 @@ var configDefaultCmd = &cobra.Command{
}
}
if !contextExists {
fmt.Println(fmt.Printf("Chosen context '%s' doesn't exist in config file", lagoonCLIConfig.Current))
os.Exit(1)
return fmt.Errorf("chosen context '%s' doesn't exist in config file", lagoonCLIConfig.Current)
}
err := writeLagoonConfig(&lagoonCLIConfig, filepath.Join(configFilePath, configName+configExtension))
handleError(err)
Expand All @@ -84,6 +81,7 @@ var configDefaultCmd = &cobra.Command{
}
r := output.RenderResult(resultData, outputOptions)
fmt.Fprintf(cmd.OutOrStdout(), "%s", r)
return nil
},
}

Expand Down
6 changes: 5 additions & 1 deletion cmd/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,11 @@ func Test_flagStringNullValueOrNil(t *testing.T) {
for k, v := range tt.args.flags {
flags.StringP(k, "", "", "")
if v != nil {
flags.Set(k, v.(string))
err := flags.Set(k, v.(string))
if (err != nil) != tt.wantErr {
t.Errorf("flagStringNullValueOrNil() error setting flags = %v, wantErr %v", err, tt.wantErr)
return
}
}
}
got, err := flagStringNullValueOrNil(flags, tt.args.flag)
Expand Down
6 changes: 3 additions & 3 deletions cmd/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -1081,7 +1081,7 @@ var listOrganizationDeployTargetsCmd = &cobra.Command{
},
}

var ListOrganizationUsersCmd = &cobra.Command{
var listOrganizationUsersCmd = &cobra.Command{
Use: "organization-users",
Aliases: []string{"org-u"},
Short: "List users in an organization",
Expand Down Expand Up @@ -1264,7 +1264,7 @@ func init() {
listCmd.AddCommand(listAllUsersCmd)
listCmd.AddCommand(listUsersGroupsCmd)
listCmd.AddCommand(listOrganizationProjectsCmd)
listCmd.AddCommand(ListOrganizationUsersCmd)
listCmd.AddCommand(listOrganizationUsersCmd)
listCmd.AddCommand(listOrganizationAdminsCmd)
listCmd.AddCommand(listOrganizationGroupsCmd)
listCmd.AddCommand(listOrganizationDeployTargetsCmd)
Expand All @@ -1277,7 +1277,7 @@ func init() {
listGroupProjectsCmd.Flags().BoolP("all-projects", "", false, "All projects")
listVariablesCmd.Flags().BoolP("reveal", "", false, "Reveal the variable values")
listOrganizationProjectsCmd.Flags().StringP("organization-name", "O", "", "Name of the organization to list associated projects for")
ListOrganizationUsersCmd.Flags().StringP("organization-name", "O", "", "Name of the organization to list associated users for")
listOrganizationUsersCmd.Flags().StringP("organization-name", "O", "", "Name of the organization to list associated users for")
listOrganizationAdminsCmd.Flags().StringP("organization-name", "O", "", "Name of the organization to list associated users for")
listOrganizationGroupsCmd.Flags().StringP("organization-name", "O", "", "Name of the organization to list associated groups for")
listOrganizationDeployTargetsCmd.Flags().StringP("organization-name", "O", "", "Name of the organization to list associated deploy targets for")
Expand Down
7 changes: 6 additions & 1 deletion cmd/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,12 @@ func retrieveTokenViaSsh() (string, error) {
HostKeyCallback: hkcb,
HostKeyAlgorithms: hkalgo,
}
defer closeSSHAgent()
defer func() {
err = closeSSHAgent()
if err != nil {
fmt.Fprintf(os.Stderr, "error closing ssh agent:%v\n", err)
}
}()

conn, err := ssh.Dial("tcp", sshHost, config)
if err != nil {
Expand Down
7 changes: 6 additions & 1 deletion cmd/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,12 @@ var logsCmd = &cobra.Command{
if err != nil {
return fmt.Errorf("couldn't get SSH client config: %v", err)
}
defer closeSSHAgent()
defer func() {
err = closeSSHAgent()
if err != nil {
fmt.Fprintf(os.Stderr, "error closing ssh agent:%v\n", err)
}
}()
// start SSH log streaming session
err = lagoonssh.LogStream(sshConfig, sshHost, sshPort, argv)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ func init() {
rootCmd.Flags().BoolVarP(&versionFlag, "version", "", false, "Version information")
rootCmd.Flags().BoolVarP(&docsFlag, "docs", "", false, "Generate docs")

rootCmd.Flags().MarkHidden("docs")
_ = rootCmd.Flags().MarkHidden("docs")

rootCmd.SetUsageTemplate(`Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
Expand Down
30 changes: 15 additions & 15 deletions cmd/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,25 @@ func parseSSHKeyFile(sshPubKey string, keyName string, keyValue string, userEmai
var err error

// will fail if value is not right
if strings.EqualFold(string(splitKey[0]), "ssh-rsa") {
switch splitKey[0] {
case "ssh-rsa":
keyType = schema.SSHRsa
} else if strings.EqualFold(string(splitKey[0]), "ssh-ed25519") {
case "ssh-ed25519":
keyType = schema.SSHEd25519
} else if strings.EqualFold(string(splitKey[0]), "ecdsa-sha2-nistp256") {
case "ecdsa-sha2-nistp256":
keyType = schema.SSHECDSA256
} else if strings.EqualFold(string(splitKey[0]), "ecdsa-sha2-nistp384") {
case "ecdsa-sha2-nistp384":
keyType = schema.SSHECDSA384
} else if strings.EqualFold(string(splitKey[0]), "ecdsa-sha2-nistp521") {
case "ecdsa-sha2-nistp521":
keyType = schema.SSHECDSA521
} else {
// return error stating key type not supported
default:
keyType = schema.SSHRsa
err = fmt.Errorf(fmt.Sprintf("SSH key type %s not supported", splitKey[0]))
err = fmt.Errorf("SSH key type %s not supported", splitKey[0])
}

// if the sshkey has a comment/name in it, we can use that
if keyName == "" && len(splitKey) == 3 {
//strip new line
// strip new line
keyName = stripNewLines(splitKey[2])
} else if keyName == "" && len(splitKey) == 2 {
keyName = userEmail
Expand Down Expand Up @@ -373,7 +373,7 @@ var updateUserCmd = &cobra.Command{
}

var getUserKeysCmd = &cobra.Command{
//@TODO: once individual user interaction comes in, this will need to be adjusted
// @TODO: once individual user interaction comes in, this will need to be adjusted
Use: "user-sshkeys",
Aliases: []string{"us"},
Short: "Get a user's SSH keys",
Expand Down Expand Up @@ -434,7 +434,7 @@ var getUserKeysCmd = &cobra.Command{
}

var getAllUserKeysCmd = &cobra.Command{
//@TODO: once individual user interaction comes in, this will need to be adjusted
// @TODO: once individual user interaction comes in, this will need to be adjusted
Use: "all-user-sshkeys",
Aliases: []string{"aus"},
Short: "Get all user SSH keys",
Expand Down Expand Up @@ -479,10 +479,10 @@ var getAllUserKeysCmd = &cobra.Command{
var data []output.Data
for _, userData := range userGroups {
keyID := strconv.Itoa(int(userData.SSHKey.ID))
userEmail := returnNonEmptyString(strings.Replace(userData.UserEmail, " ", "_", -1))
keyName := returnNonEmptyString(strings.Replace(userData.SSHKey.Name, " ", "_", -1))
keyValue := returnNonEmptyString(strings.Replace(userData.SSHKey.KeyValue, " ", "_", -1))
keyType := returnNonEmptyString(strings.Replace(string(userData.SSHKey.KeyType), " ", "_", -1))
userEmail := returnNonEmptyString(strings.ReplaceAll(userData.UserEmail, " ", "_"))
keyName := returnNonEmptyString(strings.ReplaceAll(userData.SSHKey.Name, " ", "_"))
keyValue := returnNonEmptyString(strings.ReplaceAll(userData.SSHKey.KeyValue, " ", "_"))
keyType := returnNonEmptyString(strings.ReplaceAll(string(userData.SSHKey.KeyType), " ", "_"))
data = append(data, []string{
keyID,
userEmail,
Expand Down
6 changes: 3 additions & 3 deletions pkg/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func (project *LagoonProject) ReadConfig() error {
}
sourceCompose, _ := os.ReadFile(dockerComposeFilepath)
var dockerCompose LagoonDockerCompose
yaml.Unmarshal(sourceCompose, &dockerCompose)
_ = yaml.Unmarshal(sourceCompose, &dockerCompose)
// Reset the name based on the docker-compose.yml file.
project.Name = dockerCompose.LagoonProject

Expand Down Expand Up @@ -83,8 +83,8 @@ func getProjectFromPath(path string) (LagoonProject, error) {
}
app.Name = filepath.Base(appDir)
app.Dir = appDir
app.ReadConfig()
return app, nil
err = app.ReadConfig()
return app, err
}

func findLocalProjectRoot(path string) (string, error) {
Expand Down
25 changes: 17 additions & 8 deletions pkg/lagoon/ssh/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,12 @@ func InteractiveSSH(lagoon map[string]string, sshService string, sshContainer st
if err != nil {
return err
}
defer term.Restore(fileDescriptor, originalState)
defer func() {
err = term.Restore(fileDescriptor, originalState)
if err != nil {
fmt.Fprintf(os.Stderr, "error restoring ssh terminal:%v\n", err)
}
}()
termWidth, termHeight, err := term.GetSize(fileDescriptor)
if err != nil {
return err
Expand All @@ -85,23 +90,22 @@ func InteractiveSSH(lagoon map[string]string, sshService string, sshContainer st
}
err = session.Start(connString)
if err != nil {
return fmt.Errorf("Failed to start shell: " + err.Error())
return fmt.Errorf("failed to start shell: %s", err.Error())
}
session.Wait()
return nil
return session.Wait()
}

// RunSSHCommand .
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 fmt.Errorf("Failed to dial: " + err.Error() + "\nCheck that the project or environment you are trying to connect to exists")
return fmt.Errorf("failed to dial: %s\nCheck that the project or environment you are trying to connect to exists", err.Error())
}

// start the session
session, err := client.NewSession()
if err != nil {
return fmt.Errorf("Failed to create session: " + err.Error())
return fmt.Errorf("failed to create session: %s", err.Error())
}
defer session.Close()
session.Stdout = os.Stdout
Expand All @@ -118,7 +122,12 @@ func RunSSHCommand(lagoon map[string]string, sshService string, sshContainer str
if err != nil {
return err
}
defer term.Restore(fileDescriptor, originalState)
defer func() {
err = term.Restore(fileDescriptor, originalState)
if err != nil {
fmt.Fprintf(os.Stderr, "error restoring ssh terminal:%v\n", err)
}
}()
termWidth, termHeight, err := term.GetSize(fileDescriptor)
if err != nil {
return err
Expand Down Expand Up @@ -188,7 +197,7 @@ func InteractiveKnownHosts(userPath, host string, ignorehost, accept bool) (ssh.
f, ferr := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0600)
if ferr == nil {
defer f.Close()
response := "n"
var response string
if accept {
response = "y"
} else {
Expand Down
2 changes: 1 addition & 1 deletion pkg/output/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ func RenderOutput(data Table, opts Options) string {
for _, dataValues := range data.Data {
jsonData := make(map[string]interface{})
for indexID, dataValue := range dataValues {
dataHeader := strings.Replace(strings.ToLower(data.Header[indexID]), " ", "-", -1)
dataHeader := strings.ReplaceAll(strings.ToLower(data.Header[indexID]), " ", "-")
jsonData[dataHeader] = dataValue
}
rawData = append(rawData, jsonData)
Expand Down
6 changes: 3 additions & 3 deletions pkg/output/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func TestRenderError(t *testing.T) {
RenderError(testData, outputOptions)
w.Close()
var out bytes.Buffer
io.Copy(&out, r)
_, _ = io.Copy(&out, r)
if out.String() != testSuccess {
checkEqual(t, out.String(), testSuccess, " render error stdout processing failed")
}
Expand All @@ -87,7 +87,7 @@ func TestRenderInfo(t *testing.T) {
RenderInfo(testData, outputOptions)
w.Close()
var out bytes.Buffer
io.Copy(&out, r)
_, _ = io.Copy(&out, r)
if out.String() != testSuccess1 {
checkEqual(t, out.String(), testSuccess1, " render info stdout processing failed")
}
Expand All @@ -109,7 +109,7 @@ func TestRenderOutput(t *testing.T) {
}

var dataMain Table
json.Unmarshal([]byte(testData), &dataMain)
_ = json.Unmarshal([]byte(testData), &dataMain)

output := RenderOutput(dataMain, outputOptions)
if output != testSuccess1 {
Expand Down
7 changes: 1 addition & 6 deletions pkg/updatecheck/updatecheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,5 @@ func ResetUpdateTime(filepath string) error {
// isReleaseVersion does a (very naive) check on whether a version string consistutes a release version or a dev build.
func isReleaseVersion(version string) bool {
parts := strings.Split(version, "-")

if len(parts) > 1 {
return false
}

return true
return len(parts) <= 1
}
2 changes: 1 addition & 1 deletion pkg/updatecheck/updatecheck_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func CreateTmpDir(prefix string) string {
func CleanupDir(dir string) {
err := os.RemoveAll(dir)
if err != nil {
log.Println(fmt.Sprintf("Failed to remove directory %s, err: %v", dir, err))
log.Printf("Failed to remove directory %s, err: %v", dir, err)
}
}

Expand Down