Skip to content

Commit

Permalink
refactor: optimize the code to comply with golangci-lint warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
windvalley committed Jan 3, 2024
1 parent b96b055 commit 346f956
Show file tree
Hide file tree
Showing 11 changed files with 96 additions and 92 deletions.
3 changes: 0 additions & 3 deletions .golangci.yaml
Expand Up @@ -67,7 +67,6 @@ linters:
disable-all: true
enable:
- bodyclose
- deadcode
- dogsled
- dupl
- errcheck
Expand All @@ -91,13 +90,11 @@ linters:
- nolintlint
- rowserrcheck
- staticcheck
- structcheck
- stylecheck
- typecheck
- unconvert
- unparam
- unused
- varcheck
- whitespace

# don't enable:
Expand Down
7 changes: 4 additions & 3 deletions internal/cmd/vault/decrypt_file.go
Expand Up @@ -24,7 +24,7 @@ package vault

import (
"fmt"
"io/ioutil"
"os"

"github.com/spf13/cobra"

Expand All @@ -34,8 +34,9 @@ import (

var deOutputFile string

//nolint:dupl
// decryptFileCmd represents the vault decrypt-file command
//
//nolint:dupl
var decryptFileCmd = &cobra.Command{
Use: "decrypt-file FILENAME",
Short: "Decrypt vault encrypted file",
Expand Down Expand Up @@ -93,7 +94,7 @@ func init() {
}

func decryptFile(file, vaultPass string) (string, error) {
p, err := ioutil.ReadFile(file)
p, err := os.ReadFile(file)
if err != nil {
return "", err
}
Expand Down
6 changes: 3 additions & 3 deletions internal/cmd/vault/encrypt_file.go
Expand Up @@ -25,7 +25,6 @@ package vault
import (
"bytes"
"fmt"
"io/ioutil"
"os"

"github.com/spf13/cobra"
Expand All @@ -36,8 +35,9 @@ import (

var outputFile string

//nolint:dupl
// encryptFileCmd represents the vault encrypt-file command
//
//nolint:dupl
var encryptFileCmd = &cobra.Command{
Use: "encrypt-file FILENAME",
Short: "Encrypt a file",
Expand Down Expand Up @@ -110,7 +110,7 @@ func handleOutput(content, originalFile, newFile string) {
}

func encryptFile(file, vaultPass string) (string, error) {
p, err := ioutil.ReadFile(file)
p, err := os.ReadFile(file)
if err != nil {
return "", err
}
Expand Down
3 changes: 1 addition & 2 deletions internal/cmd/vault/vault.go
Expand Up @@ -25,7 +25,6 @@ package vault
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
Expand Down Expand Up @@ -166,7 +165,7 @@ func getVaultPasswordFromFile() string {
return vaultPass
}

passwordContent, err := ioutil.ReadFile(vaultPassFile)
passwordContent, err := os.ReadFile(vaultPassFile)
if err != nil {
err = fmt.Errorf("read vault password file '%s' failed: %w", vaultPassFile, err)
}
Expand Down
30 changes: 16 additions & 14 deletions internal/pkg/sshtask/sshtask.go
Expand Up @@ -492,8 +492,8 @@ func (t *Task) getAllHosts() ([]*batchssh.Host, error) {

if len(v.Keys) != 0 {
keys := parseItentityFiles(v.Keys)
assignRealPass(&v.Passphrase, v.Alias, "passphrase")
sshSigners := getSigners(keys, v.Passphrase, "Individual")
passphrase := getRealPass(v.Passphrase, v.Alias, "passphrase")
sshSigners := getSigners(keys, passphrase, "Individual")
if len(sshSigners) == 0 {
log.Debugf("Individual Auth: no valid individual identity files for '%s'", v.Alias)
} else {
Expand All @@ -502,11 +502,11 @@ func (t *Task) getAllHosts() ([]*batchssh.Host, error) {
}
}

realPassword := ""
if v.Password == "" {
v.Password = *t.defaultPass
assignRealPass(&v.Password, v.Alias, "password")
realPassword = getRealPass(*t.defaultPass, v.Alias, "password")
} else {
assignRealPass(&v.Password, v.Alias, "password")
realPassword = getRealPass(v.Password, v.Alias, "password")
hostSSHAuths = append(hostSSHAuths, ssh.Password(v.Password))
log.Debugf("Individual Auth: add individual password for '%s'", v.Alias)
}
Expand All @@ -518,7 +518,7 @@ func (t *Task) getAllHosts() ([]*batchssh.Host, error) {
Host: v.Host,
Port: v.Port,
User: v.User,
Password: v.Password,
Password: realPassword,
Keys: v.Keys,
SSHAuths: hostSSHAuths,
})
Expand Down Expand Up @@ -725,14 +725,14 @@ func getDefaultPassword(auth *configflags.Auth) string {
log.Debugf("Default Auth: received password of user '%s' from commandline flag or configuration file", auth.User)
}

assignRealPass(&password, "default", "password")
realPassword := getRealPass(password, "default", "password")

if auth.AskPass {
log.Debugf("Default Auth: ask for password of user '%s' by flag '-k/--auth.ask-pass'", auth.User)
password = getPasswordFromPrompt(auth.User)
realPassword = getPasswordFromPrompt(auth.User)
}

return password
return realPassword
}

func parseItentityFiles(identityFiles []string) (keyFiles []string) {
Expand Down Expand Up @@ -812,20 +812,22 @@ func getPasswordFromPrompt(loginUser string) string {
return password
}

func assignRealPass(pass *string, host, objectType string) {
var err error

if aes.IsAES256CipherText(*pass) {
func getRealPass(pass string, host, objectType string) string {
if aes.IsAES256CipherText(pass) {
vaultPass := vault.GetVaultPassword()

*pass, err = aes.AES256Decode(*pass, vaultPass)
realPass, err := aes.AES256Decode(pass, vaultPass)
if err != nil {
log.Debugf("Vault: decrypt %s for '%s' failed: %s", objectType, host, err)
util.CheckErr(err)
}

log.Debugf("Vault: decrypt %s for '%s' success", objectType, host)

return realPass
}

return pass
}

func deDuplicate(hosts []string) []string {
Expand Down
7 changes: 4 additions & 3 deletions pkg/aes/aes.go
Expand Up @@ -33,9 +33,10 @@ import (

// Encode plain text.
// Param keyLen available values: 16, 24, 32.
// AES-128 uses a 128 bit key (16 bytes),
// AES-192 uses a 192 bit key (24 bytes),
// AES-256 uses a 256 bit key (32 bytes).
//
// AES-128 uses a 128 bit key (16 bytes),
// AES-192 uses a 192 bit key (24 bytes),
// AES-256 uses a 256 bit key (32 bytes).
func Encode(plainText, key []byte, keyLen int) ([]byte, error) {
if keyLen != 16 && keyLen != 24 && keyLen != 32 {
return nil, errors.New("invalid key length, available length: 16, 24, 32")
Expand Down
2 changes: 1 addition & 1 deletion pkg/batchssh/fetch_zip.go
Expand Up @@ -66,7 +66,7 @@ fi`,

log.Debugf("%s: zip '%s' cost %s", host.Host, srcFile, time.Since(timeStart))

if err := fetchZipFile(ftpC, zippedFileFullpath, dstDir); err != nil {
if err = fetchZipFile(ftpC, zippedFileFullpath, dstDir); err != nil {
log.Errorf("%s: fetch zip file '%s' failed: %s", host.Host, zippedFileFullpath, err)
return err
}
Expand Down
74 changes: 37 additions & 37 deletions pkg/errors/errors.go
Expand Up @@ -2,89 +2,89 @@
//
// The traditional error handling idiom in Go is roughly akin to
//
// if err != nil {
// return err
// }
// if err != nil {
// return err
// }
//
// which when applied recursively up the call stack results in error reports
// without context or debugging information. The errors package allows
// programmers to add context to the failure path in their code in a way
// that does not destroy the original value of the error.
//
// Adding context to an error
// # Adding context to an error
//
// The errors.Wrap function returns a new error that adds context to the
// original error by recording a stack trace at the point Wrap is called,
// together with the supplied message. For example
//
// _, err := ioutil.ReadAll(r)
// if err != nil {
// return errors.Wrap(err, "read failed")
// }
// _, err := ioutil.ReadAll(r)
// if err != nil {
// return errors.Wrap(err, "read failed")
// }
//
// If additional control is required, the errors.WithStack and
// errors.WithMessage functions destructure errors.Wrap into its component
// operations: annotating an error with a stack trace and with a message,
// respectively.
//
// Retrieving the cause of an error
// # Retrieving the cause of an error
//
// Using errors.Wrap constructs a stack of errors, adding context to the
// preceding error. Depending on the nature of the error it may be necessary
// to reverse the operation of errors.Wrap to retrieve the original error
// for inspection. Any error value which implements this interface
//
// type causer interface {
// Cause() error
// }
// type causer interface {
// Cause() error
// }
//
// can be inspected by errors.Cause. errors.Cause will recursively retrieve
// the topmost error that does not implement causer, which is assumed to be
// the original cause. For example:
//
// switch err := errors.Cause(err).(type) {
// case *MyError:
// // handle specifically
// default:
// // unknown error
// }
// switch err := errors.Cause(err).(type) {
// case *MyError:
// // handle specifically
// default:
// // unknown error
// }
//
// Although the causer interface is not exported by this package, it is
// considered a part of its stable public interface.
//
// Formatted printing of errors
// # Formatted printing of errors
//
// All error values returned from this package implement fmt.Formatter and can
// be formatted by the fmt package. The following verbs are supported:
//
// %s print the error. If the error has a Cause it will be
// printed recursively.
// %v see %s
// %+v extended format. Each Frame of the error's StackTrace will
// be printed in detail.
// %s print the error. If the error has a Cause it will be
// printed recursively.
// %v see %s
// %+v extended format. Each Frame of the error's StackTrace will
// be printed in detail.
//
// Retrieving the stack trace of an error or wrapper
// # Retrieving the stack trace of an error or wrapper
//
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
// invoked. This information can be retrieved with the following interface:
//
// type stackTracer interface {
// StackTrace() errors.StackTrace
// }
// type stackTracer interface {
// StackTrace() errors.StackTrace
// }
//
// The returned errors.StackTrace type is defined as
//
// type StackTrace []Frame
// type StackTrace []Frame
//
// The Frame type represents a call site in the stack trace. Frame supports
// the fmt.Formatter interface that can be used for printing information about
// the stack trace of this error. For example:
//
// if err, ok := err.(stackTracer); ok {
// for _, f := range err.StackTrace() {
// fmt.Printf("%+s:%d\n", f, f)
// }
// }
// if err, ok := err.(stackTracer); ok {
// for _, f := range err.StackTrace() {
// fmt.Printf("%+s:%d\n", f, f)
// }
// }
//
// Although the stackTracer interface is not exported by this package, it is
// considered a part of its stable public interface.
Expand Down Expand Up @@ -356,9 +356,9 @@ func (w *withCode) Unwrap() error { return w.cause }
// An error value has a cause if it implements the following
// interface:
//
// type causer interface {
// Cause() error
// }
// type causer interface {
// Cause() error
// }
//
// If the error does not implement Cause, the original error will
// be returned. If the error is nil, nil will be returned without further
Expand Down
32 changes: 18 additions & 14 deletions pkg/errors/format.go
Expand Up @@ -16,27 +16,31 @@ type formatInfo struct {
stack *stack
}

//nolint:lll
// Format implements fmt.Formatter. https://golang.org/pkg/fmt/#hdr-Printing
//
// Verbs:
// %s - Returns the user-safe error string mapped to the error code or
// ┊ the error message if none is specified.
// %v Alias for %s
//
// %s - Returns the user-safe error string mapped to the error code or
// ┊ the error message if none is specified.
// %v Alias for %s
//
// Flags:
// # JSON formatted output, useful for logging
// - Output caller details, useful for troubleshooting
// + Output full error stack details, useful for debugging
//
// # JSON formatted output, useful for logging
// - Output caller details, useful for troubleshooting
// + Output full error stack details, useful for debugging
//
// Examples:
// %s: error for internal read B
// %v: error for internal read B
// %-v: error for internal read B - #0 [/gobackend/main.go:12 (main.main)] (#100102) Internal Server Error
// %+v: error for internal read B - #0 [/gobackend/main.go:12 (main.main)] (#100102) Internal Server Error; error for internal read A - #1 [/go-web-demo/main.go:35 (main.newErrorB)] (#100104) Validation failed
// %#v: [{"error":"error for internal read B"}]
// %#-v: [{"caller":"#0 /gobackend/main.go:12 (main.main)","error":"error for internal read B","message":"(#100102) Internal Server Error"}]
// %#+v: [{"caller":"#0 /gobackend/main.go:12 (main.main)","error":"error for internal read B","message":"(#100102) Internal Server Error"},{"caller":"#1 /go-web-demo/main.go:35 (main.newErrorB)","error":"error for internal read A","message":"(#100104) Validation failed"}]
//
// %s: error for internal read B
// %v: error for internal read B
// %-v: error for internal read B - #0 [/gobackend/main.go:12 (main.main)] (#100102) Internal Server Error
// %+v: error for internal read B - #0 [/gobackend/main.go:12 (main.main)] (#100102) Internal Server Error; error for internal read A - #1 [/go-web-demo/main.go:35 (main.newErrorB)] (#100104) Validation failed
// %#v: [{"error":"error for internal read B"}]
// %#-v: [{"caller":"#0 /gobackend/main.go:12 (main.main)","error":"error for internal read B","message":"(#100102) Internal Server Error"}]
// %#+v: [{"caller":"#0 /gobackend/main.go:12 (main.main)","error":"error for internal read B","message":"(#100102) Internal Server Error"},{"caller":"#1 /go-web-demo/main.go:35 (main.newErrorB)","error":"error for internal read A","message":"(#100104) Validation failed"}]
//
//nolint:lll
func (w *withCode) Format(state fmt.State, verb rune) {
switch verb {
case 'v':
Expand Down

0 comments on commit 346f956

Please sign in to comment.