From a296c4cbc889f4b15f3a8b47c5bc145fa6795a76 Mon Sep 17 00:00:00 2001 From: Marques Johansson Date: Wed, 15 Dec 2021 08:29:58 -0500 Subject: [PATCH 1/6] add golangci-lint checks Signed-off-by: Marques Johansson --- .github/workflows/golangci-lint.yaml | 27 +++++++++++++++++++++++++++ hack/resolve-modules.sh | 8 ++++++++ 2 files changed, 35 insertions(+) create mode 100644 .github/workflows/golangci-lint.yaml create mode 100755 hack/resolve-modules.sh diff --git a/.github/workflows/golangci-lint.yaml b/.github/workflows/golangci-lint.yaml new file mode 100644 index 0000000..73ebf11 --- /dev/null +++ b/.github/workflows/golangci-lint.yaml @@ -0,0 +1,27 @@ +# https://github.com/golangci/golangci-lint/issues/828#issuecomment-658207652 +name: golangci-lint +on: [push, pull_request] +jobs: + resolve-modules: + name: Resolve Modules + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.set-matrix.outputs.matrix }} + steps: + - name: Checkout Sources + uses: actions/checkout@v2 + - id: set-matrix + run: ./hack/resolve-modules.sh + golangci: + name: Linter + needs: resolve-modules + runs-on: ubuntu-latest + strategy: + matrix: ${{ fromJson(needs.resolve-modules.outputs.matrix) }} + steps: + - uses: actions/checkout@v2 + - name: golangci-lint + uses: golangci/golangci-lint-action@v2 + with: + version: v1.43 + working-directory: ${{ matrix.workdir }} diff --git a/hack/resolve-modules.sh b/hack/resolve-modules.sh new file mode 100755 index 0000000..d6f0768 --- /dev/null +++ b/hack/resolve-modules.sh @@ -0,0 +1,8 @@ +#!/bin/bash +# Recursively finds all directories with a go.mod file and creates +# a GitHub Actions JSON output option. This is used by the linter action. + +echo "Resolving modules in $(pwd)" + +PATHS=$(find . -mindepth 2 -not -path "*/vendor/*" -type f -name go.mod -printf '{"workdir":"%h"},') +echo "::set-output name=matrix::{\"include\":[${PATHS%?}]}" From 64cd6593a9985de2c77cf4f09d8fb1494b71a620 Mon Sep 17 00:00:00 2001 From: Marques Johansson Date: Wed, 15 Dec 2021 08:45:32 -0500 Subject: [PATCH 2/6] fix spelling errors in log messages Signed-off-by: Marques Johansson --- actions/archive2disk/v1/main.go | 2 +- actions/cexec/v1/main.go | 6 +++--- actions/writefile/v1/main.go | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/actions/archive2disk/v1/main.go b/actions/archive2disk/v1/main.go index 613db3b..7c156bd 100644 --- a/actions/archive2disk/v1/main.go +++ b/actions/archive2disk/v1/main.go @@ -22,7 +22,7 @@ func main() { archiveType := os.Getenv("ARCHIVE_TYPE") if blockDevice == "" { - log.Fatalf("No Block Device speified with Environment Variable [DEST_DISK]") + log.Fatalf("No Block Device specified with Environment Variable [DEST_DISK]") } // Create the /mountAction mountpoint (no folders exist previously in scratch container) diff --git a/actions/cexec/v1/main.go b/actions/cexec/v1/main.go index 92c2090..ceb18af 100644 --- a/actions/cexec/v1/main.go +++ b/actions/cexec/v1/main.go @@ -33,7 +33,7 @@ func main() { var exitChroot func() error if blockDevice == "" { - log.Fatalf("No Block Device speified with Environment Variable [BLOCK_DEVICE]") + log.Fatalf("No Block Device specified with Environment Variable [BLOCK_DEVICE]") } // Create the /mountAction mountpoint (no folders exist previously in scratch container) @@ -67,7 +67,7 @@ func main() { if len(di) == 0 { log.Fatalln("Error parsing [\"DEFAULT_INTERPETER\"] [%s]", defaultInterpreter) } - // Look for default shell intepreter + // Look for default shell interpreter _, err = os.Stat(di[0]) if os.IsNotExist(err) { log.Fatalf("Unable to find the [\"DEFAULT_INTERPETER\"] [%s], check chroot and interpreter path", defaultInterpreter) @@ -85,7 +85,7 @@ func main() { log.Fatalf("Error running [%s] [%v]", debugCMD, err) } } else { - // Format the cmdLine string into seperate execution tasks + // Format the cmdLine string into separate execution tasks commandLines := strings.Split(cmdLine, ";") for x := range commandLines { command := strings.Split(commandLines[x], " ") diff --git a/actions/writefile/v1/main.go b/actions/writefile/v1/main.go index e5ed3cf..0d6df3d 100644 --- a/actions/writefile/v1/main.go +++ b/actions/writefile/v1/main.go @@ -30,7 +30,7 @@ func main() { // Validate inputs if blockDevice == "" { - log.Fatalf("No Block Device speified with Environment Variable [DEST_DISK]") + log.Fatalf("No Block Device specified with Environment Variable [DEST_DISK]") } if !filepath.IsAbs(filePath) { @@ -163,7 +163,7 @@ func ensureDir(mountPath, path string, mode os.FileMode, uid, gid int) error { return fmt.Errorf("failed to set ownership of directory %s to %d:%d: %w", path, uid, gid, err) } - log.Infof("Successfully set ownernership of directory %s to %d:%d", path, uid, gid) + log.Infof("Successfully set ownership of directory %s to %d:%d", path, uid, gid) return nil } From 64b9ea7cca0233baa41f64820199674909286787 Mon Sep 17 00:00:00 2001 From: Marques Johansson Date: Wed, 15 Dec 2021 09:43:24 -0500 Subject: [PATCH 3/6] fix golangci-lint detected problems Errors were detected with: find . -name go.mod | sed s/go.mod// | xargs -I{} sh -c 'cd {}; GOOS=linux golangci-lint run --path-prefix {} --fix ./...' Initial problems captured at https://gist.github.com/displague/94aa6e20a2aba10adc6582222acd6ee5 Signed-off-by: Marques Johansson --- .../archive2disk/v1/pkg/archive/archive.go | 6 ++++-- actions/cexec/v1/main.go | 8 +------- actions/grub2disk/v1/main.go | 2 +- actions/kexec/v1/cmd/grub/grub.go | 18 ----------------- actions/kexec/v1/cmd/kexec.go | 5 ++++- actions/oci2disk/v1/pkg/image/image.go | 15 -------------- actions/oci2disk/v1/pkg/image/writer.go | 4 ++-- actions/qemuimg2disk/v1/partprobe.go | 9 +++++++-- actions/rootio/v1/cmd/rootio.go | 12 ++++++++--- actions/slurp/v1/pkg/image/image.go | 20 ++++--------------- actions/slurp/v1/server/main.go | 14 ++++++------- actions/syslinux/v1/main.go | 17 ++++++++++++---- cmd/hub/cmd/generate.go | 6 ++++-- cmd/hub/main.go | 10 +++++++++- pkg/git/action.go | 2 +- pkg/img/build.go | 1 - 16 files changed, 65 insertions(+), 84 deletions(-) diff --git a/actions/archive2disk/v1/pkg/archive/archive.go b/actions/archive2disk/v1/pkg/archive/archive.go index 300fc58..76f3140 100644 --- a/actions/archive2disk/v1/pkg/archive/archive.go +++ b/actions/archive2disk/v1/pkg/archive/archive.go @@ -40,7 +40,9 @@ func Write(archiveURL, archiveType, path string) error { var out *tar.Reader absPath, err := filepath.Abs(path) - + if err != nil { + return err + } switch archiveType { case "gz": // With compression run data through gzip writer @@ -58,7 +60,7 @@ func Write(archiveURL, archiveType, path string) error { // With compression run data through gzip writer zipOUT, err := gzip.NewReader(resp.Body) if err != nil { - log.Fatalf("[ERROR] New gzip reader:", err) + log.Fatal("[ERROR] New gzip reader:", err) } defer zipOUT.Close() out = tar.NewReader(zipOUT) diff --git a/actions/cexec/v1/main.go b/actions/cexec/v1/main.go index ceb18af..4c44fb4 100644 --- a/actions/cexec/v1/main.go +++ b/actions/cexec/v1/main.go @@ -11,12 +11,6 @@ import ( log "github.com/sirupsen/logrus" ) -// Release - this struct contains the release information populated when building kexec -var Release struct { - Version string - Build string -} - const mountAction = "/mountAction" func main() { @@ -65,7 +59,7 @@ func main() { // Split the interpreter by space, in the event that the default intprepretter has flags. di := strings.Split(defaultInterpreter, " ") if len(di) == 0 { - log.Fatalln("Error parsing [\"DEFAULT_INTERPETER\"] [%s]", defaultInterpreter) + log.Fatalf("Error parsing [\"DEFAULT_INTERPETER\"] [%s]", defaultInterpreter) } // Look for default shell interpreter _, err = os.Stat(di[0]) diff --git a/actions/grub2disk/v1/main.go b/actions/grub2disk/v1/main.go index ed45c5e..1c224d5 100644 --- a/actions/grub2disk/v1/main.go +++ b/actions/grub2disk/v1/main.go @@ -10,7 +10,7 @@ import ( ) func main() { - fmt.Println("GRUB2Disk - GRUB streamer\n------------------------\n") + fmt.Print("GRUB2Disk - GRUB streamer\n------------------------\n\n") grubInstallPath := os.Getenv("GRUB_INSTALL_PATH") grubBlockDevice := os.Getenv("GRUB_DISK") filesystemType := os.Getenv("FS_TYPE") diff --git a/actions/kexec/v1/cmd/grub/grub.go b/actions/kexec/v1/cmd/grub/grub.go index 2ee3ade..434879a 100644 --- a/actions/kexec/v1/cmd/grub/grub.go +++ b/actions/kexec/v1/cmd/grub/grub.go @@ -108,24 +108,6 @@ func ParseGrubCfg(grubcfg string) (configs []Config, defaultConfig int64) { return } -type grubVersion int - -var ( - grubV1 grubVersion = 1 - grubV2 grubVersion = 2 -) - -func unquote(ver grubVersion, text string) string { - if ver == grubV2 { - // if grub2, unquote the string, as directives could be quoted - // https://www.gnu.org/software/grub/manual/grub/grub.html#Quoting - // TODO unquote everything, not just \$ - return strings.Replace(text, `\$`, "$", -1) - } - // otherwise return the unmodified string - return text -} - func trimQuote(s string) string { if len(s) > 0 && s[0] == '"' { s = s[1:] diff --git a/actions/kexec/v1/cmd/kexec.go b/actions/kexec/v1/cmd/kexec.go index 9478e38..1da8bb5 100644 --- a/actions/kexec/v1/cmd/kexec.go +++ b/actions/kexec/v1/cmd/kexec.go @@ -95,7 +95,10 @@ var kexecCmd = &cobra.Command{ } log.Info("Rebooting system") // Call the unix reboot command with the kexec functionality - unix.Reboot(unix.LINUX_REBOOT_CMD_KEXEC) + err = unix.Reboot(unix.LINUX_REBOOT_CMD_KEXEC) + if err != nil { + log.Fatal(err) + } }, } diff --git a/actions/oci2disk/v1/pkg/image/image.go b/actions/oci2disk/v1/pkg/image/image.go index f507c74..7cee5cd 100644 --- a/actions/oci2disk/v1/pkg/image/image.go +++ b/actions/oci2disk/v1/pkg/image/image.go @@ -12,22 +12,17 @@ import ( "net/http" "os" "path/filepath" - "strings" - "time" "github.com/containerd/containerd/reference" "github.com/containerd/containerd/remotes/docker" "github.com/deislabs/oras/pkg/oras" - "github.com/dustin/go-humanize" "github.com/klauspost/compress/zstd" log "github.com/sirupsen/logrus" "github.com/ulikunitz/xz" "golang.org/x/sys/unix" ) -var tick chan time.Time - // WriteCounter counts the number of bytes written to it. It implements to the io.Writer interface // and we can pass this into io.TeeReader() which will report progress on each write cycle. type WriteCounter struct { @@ -40,16 +35,6 @@ func (wc *WriteCounter) Write(p []byte) (int, error) { return n, nil } -func tickerProgress(byteCounter uint64) { - // Clear the line by using a character return to go back to the start and remove - // the remaining characters by filling it with spaces - fmt.Printf("\r%s", strings.Repeat(" ", 35)) - - // Return again and print current status of download - // We use the humanize package to print the bytes in a meaningful way (e.g. 10 MB) - fmt.Printf("\rDownloading... %s complete", humanize.Bytes(byteCounter)) -} - // Write will pull an image and write it to local storage device // with compress set to true it will use gzip compression to expand the data before // writing to an underlying device diff --git a/actions/oci2disk/v1/pkg/image/writer.go b/actions/oci2disk/v1/pkg/image/writer.go index 99576b3..5efe082 100644 --- a/actions/oci2disk/v1/pkg/image/writer.go +++ b/actions/oci2disk/v1/pkg/image/writer.go @@ -133,7 +133,7 @@ func (d DiskImageStore) Writer(ctx context.Context, opts ...ctrcontent.WriterOpt var ( err error ) - b := make([]byte, wOpts.Blocksize, wOpts.Blocksize) + b := make([]byte, wOpts.Blocksize) _, err = io.CopyBuffer(w, r, b) done <- err } @@ -147,7 +147,7 @@ func (d DiskImageStore) Writer(ctx context.Context, opts ...ctrcontent.WriterOpt log.Fatalf(err.Error()) done <- err } else { - b := make([]byte, wOpts.Blocksize, wOpts.Blocksize) + b := make([]byte, wOpts.Blocksize) _, err = io.CopyBuffer(w, decompressReader, b) done <- err } diff --git a/actions/qemuimg2disk/v1/partprobe.go b/actions/qemuimg2disk/v1/partprobe.go index 420e68d..e443aeb 100644 --- a/actions/qemuimg2disk/v1/partprobe.go +++ b/actions/qemuimg2disk/v1/partprobe.go @@ -2,14 +2,19 @@ package main import ( "fmt" - "golang.org/x/sys/unix" "os" + + "golang.org/x/sys/unix" ) func main() { disk := os.Getenv("DEST_DISK") fileOut, err := os.OpenFile(disk, os.O_CREATE|os.O_WRONLY, 0644) - defer fileOut.Close() + defer func() { + if err := fileOut.Close(); err != nil { + fmt.Fprint(os.Stderr, "error closing file: ", err) + } + }() if err != nil { fmt.Printf("unable to open the target disk %s: %v\n", disk, err) return diff --git a/actions/rootio/v1/cmd/rootio.go b/actions/rootio/v1/cmd/rootio.go index b3908fe..fc898b3 100644 --- a/actions/rootio/v1/cmd/rootio.go +++ b/actions/rootio/v1/cmd/rootio.go @@ -140,7 +140,11 @@ func test() (*types.Metadata, error) { } fmt.Println("Successfully Opened test data") // defer the closing of our jsonFile so that we can parse it later on - defer jsonFile.Close() + defer func() { + if err := jsonFile.Close(); err != nil { + log.Error(err) + } + }() byteValue, _ := ioutil.ReadAll(jsonFile) @@ -149,7 +153,9 @@ func test() (*types.Metadata, error) { // we unmarshal our byteArray which contains our // jsonFile's content into 'users' which we defined above - json.Unmarshal(byteValue, &mdata) - + err = json.Unmarshal(byteValue, &mdata) + if err != nil { + return nil, err + } return &mdata, nil } diff --git a/actions/slurp/v1/pkg/image/image.go b/actions/slurp/v1/pkg/image/image.go index ef067ec..627ce95 100644 --- a/actions/slurp/v1/pkg/image/image.go +++ b/actions/slurp/v1/pkg/image/image.go @@ -10,14 +10,8 @@ import ( "net/http" "os" "path/filepath" - "strings" - "time" - - "github.com/dustin/go-humanize" ) -var tick chan time.Time - // WriteCounter counts the number of bytes written to it. It implements to the io.Writer interface // and we can pass this into io.TeeReader() which will report progress on each write cycle. type WriteCounter struct { @@ -30,16 +24,6 @@ func (wc *WriteCounter) Write(p []byte) (int, error) { return n, nil } -func tickerProgress(byteCounter uint64) { - // Clear the line by using a character return to go back to the start and remove - // the remaining characters by filling it with spaces - fmt.Printf("\r%s", strings.Repeat(" ", 35)) - - // Return again and print current status of download - // We use the humanize package to print the bytes in a meaningful way (e.g. 10 MB) - fmt.Printf("\rDownloading... %s complete", humanize.Bytes(byteCounter)) -} - // Read - will take a local disk and copy an image to a remote server func Read(sourceDevice, destinationAddress, name string, compressed bool) error { @@ -124,6 +108,10 @@ func UploadMultipartFile(client *http.Client, uri, key, path string, compressed } // Ensure we close our zipWriter (otherwise we will get "unexpected EOF") err = zipWriter.Close() + if err != nil { + errchan <- fmt.Errorf("[ERROR] Closing gzip writer: %s", err) + return + } } diff --git a/actions/slurp/v1/server/main.go b/actions/slurp/v1/server/main.go index ddfd2f7..c3e214a 100644 --- a/actions/slurp/v1/server/main.go +++ b/actions/slurp/v1/server/main.go @@ -19,8 +19,6 @@ type WriteCounter struct { Total uint64 } -var data []byte - func (wc *WriteCounter) Write(p []byte) (int, error) { n := len(p) wc.Total += uint64(n) @@ -44,16 +42,20 @@ func imageHandler(w http.ResponseWriter, r *http.Request) { imageName := fmt.Sprintf("%s.img", r.RemoteAddr) - r.ParseMultipartForm(32 << 20) + if err := r.ParseMultipartForm(32 << 20); err != nil { + http.Error(w, "Error parsing multipart form", http.StatusInternalServerError) + return + } file, _, err := r.FormFile("BootyImage") if err != nil { - fmt.Println(err) + http.Error(w, "Error retrieving the file", http.StatusInternalServerError) return } defer file.Close() out, err := os.OpenFile(imageName, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { + http.Error(w, "Error opening file", http.StatusInternalServerError) log.Fatalf("%v", err) } defer out.Close() @@ -69,10 +71,6 @@ func imageHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -func configHandler(w http.ResponseWriter, r *http.Request) { - w.Write(data) -} - func main() { // // Server port diff --git a/actions/syslinux/v1/main.go b/actions/syslinux/v1/main.go index 6214427..9f4ccf0 100644 --- a/actions/syslinux/v1/main.go +++ b/actions/syslinux/v1/main.go @@ -34,11 +34,20 @@ func syslinux386(disk, partition string) { if err != nil { log.Fatalln(err) } - ReReadPartitionTable(blockOut) - defer blockOut.Close() - + if err := ReReadPartitionTable(blockOut); err != nil { + log.Fatalln(err) + } + deferWithError := func(f func() error) { + if err := f(); err != nil { + log.Fatalln(err) + } + } + defer deferWithError(blockOut.Close) mbrIn, err := os.OpenFile("/mbr.bin.386", os.O_RDONLY, 0644) - defer mbrIn.Close() + if err != nil { + log.Fatalln(err) + } + defer deferWithError(mbrIn.Close) _, err = io.Copy(blockOut, mbrIn) if err != nil { diff --git a/cmd/hub/cmd/generate.go b/cmd/hub/cmd/generate.go index 799c52c..6e1f54e 100644 --- a/cmd/hub/cmd/generate.go +++ b/cmd/hub/cmd/generate.go @@ -38,7 +38,7 @@ func runGenerate(opts *generateOptions) error { if os.IsNotExist(err) { return errors.Wrap(err, "we expect an actions directory inside the repository.") } - if info.IsDir() == false { + if !info.IsDir() { return errors.New("the expected actions directory has to be a directory, not a file") } @@ -48,7 +48,9 @@ func runGenerate(opts *generateOptions) error { } if _, err := os.Stat(generateOpts.output); os.IsNotExist(err) { - os.Mkdir(generateOpts.output, 0700) + if err := os.Mkdir(generateOpts.output, 0700); err != nil { + return err + } } // This is the manifest with all the pre-populated information. Ideally diff --git a/cmd/hub/main.go b/cmd/hub/main.go index b7f11b6..adc2fba 100644 --- a/cmd/hub/main.go +++ b/cmd/hub/main.go @@ -1,12 +1,20 @@ package main import ( + "fmt" + "os" + "github.com/tinkerbell/actions/cmd/hub/cmd" "go.uber.org/zap" ) func main() { logger, _ := zap.NewProduction() - defer logger.Sync() // flushes buffer, if any + defer func() { + // flushes buffer, if any + if err := logger.Sync(); err != nil { + fmt.Fprint(os.Stderr, "error flushing logger: ", err) + } + }() cmd.Execute(logger) } diff --git a/pkg/git/action.go b/pkg/git/action.go index 1d550bb..b05d9c2 100644 --- a/pkg/git/action.go +++ b/pkg/git/action.go @@ -49,7 +49,7 @@ func ModifiedActions(modifiedActions *[]TinkerbellAction, actionsPath string, co action := NewTinkerbellAction(file) // Deduplicate entries by checking if a modification for this action was already detected. - if detected[action.String()] == false { + if !detected[action.String()] { detected[action.String()] = true *modifiedActions = append(*modifiedActions, action) } diff --git a/pkg/img/build.go b/pkg/img/build.go index 9672c25..d4de246 100644 --- a/pkg/img/build.go +++ b/pkg/img/build.go @@ -29,7 +29,6 @@ import ( const ( defaultBackend = "auto" - defaultDockerRegistry = "https://index.docker.io/v1/" defaultDockerfileName = "Dockerfile" ) From b84c199a3213a43c36a09787de6f99eb27b4319c Mon Sep 17 00:00:00 2001 From: Marques Johansson Date: Thu, 16 Dec 2021 23:13:08 -0500 Subject: [PATCH 4/6] use ,golangci.yml offered by lint-install Signed-off-by: Marques Johansson --- .golangci.yml | 207 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 207 insertions(+) create mode 100644 .golangci.yml diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..2711908 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,207 @@ +run: + # The default runtime timeout is 1m, which doesn't work well on Github Actions. + timeout: 4m + +# NOTE: This file is populated by the lint-install tool. Local adjustments may be overwritten. +linters-settings: + cyclop: + # NOTE: This is a very high transitional threshold + max-complexity: 37 + package-average: 34.0 + skip-tests: true + + gocognit: + # NOTE: This is a very high transitional threshold + min-complexity: 98 + + dupl: + threshold: 200 + + goconst: + min-len: 4 + min-occurrences: 5 + ignore-tests: true + + gosec: + excludes: + - G107 # Potential HTTP request made with variable url + - G204 # Subprocess launched with function call as argument or cmd arguments + - G404 # Use of weak random number generator (math/rand instead of crypto/rand + + errorlint: + # these are still common in Go: for instance, exit errors. + asserts: false + + exhaustive: + default-signifies-exhaustive: true + + nestif: + min-complexity: 8 + + nolintlint: + require-explanation: true + allow-unused: false + require-specific: true + + revive: + ignore-generated-header: true + severity: warning + rules: + - name: atomic + - name: blank-imports + - name: bool-literal-in-expr + - name: confusing-naming + - name: constant-logical-expr + - name: context-as-argument + - name: context-keys-type + - name: deep-exit + - name: defer + - name: range-val-in-closure + - name: range-val-address + - name: dot-imports + - name: error-naming + - name: error-return + - name: error-strings + - name: errorf + - name: exported + - name: identical-branches + - name: if-return + - name: import-shadowing + - name: increment-decrement + - name: indent-error-flow + - name: indent-error-flow + - name: package-comments + - name: range + - name: receiver-naming + - name: redefines-builtin-id + - name: superfluous-else + - name: struct-tag + - name: time-naming + - name: unexported-naming + - name: unexported-return + - name: unnecessary-stmt + - name: unreachable-code + - name: unused-parameter + - name: var-declaration + - name: var-naming + - name: unconditional-recursion + - name: waitgroup-by-value + + staticcheck: + go: "1.16" + + unused: + go: "1.16" + +output: + sort-results: true + +linters: + disable-all: true + enable: + - asciicheck + - bodyclose + - cyclop + - deadcode + - dogsled + - dupl + - durationcheck + - errcheck + - errname + - errorlint + - exhaustive + - exportloopref + - forcetypeassert + - gocognit + - goconst + - gocritic + - godot + - gofmt + - gofumpt + - gosec + - goheader + - goimports + - goprintffuncname + - gosimple + - govet + - ifshort + - importas + - ineffassign + - makezero + - misspell + - nakedret + - nestif + - nilerr + - noctx + - nolintlint + - predeclared + # disabling for the initial iteration of the linting tool + # - promlinter + - revive + - rowserrcheck + - sqlclosecheck + - staticcheck + - structcheck + - stylecheck + - thelper + - tparallel + - typecheck + - unconvert + - unparam + - unused + - varcheck + - wastedassign + - whitespace + + # Disabled linters, due to being misaligned with Go practices + # - exhaustivestruct + # - gochecknoglobals + # - gochecknoinits + # - goconst + # - godox + # - goerr113 + # - gomnd + # - lll + # - nlreturn + # - testpackage + # - wsl + # Disabled linters, due to not being relevant to our code base: + # - maligned + # - prealloc "For most programs usage of prealloc will be a premature optimization." + # Disabled linters due to bad error messages or bugs + # - tagliatelle + +issues: + # Excluding configuration per-path, per-linter, per-text and per-source + exclude-rules: + - path: _test\.go + linters: + - dupl + - errcheck + - forcetypeassert + - gocyclo + - gosec + - noctx + + - path: .*cmd.* + linters: + - noctx + + - path: main\.go + linters: + - noctx + + - path: .*cmd.* + text: "deep-exit" + + - path: main\.go + text: "deep-exit" + + # This check is of questionable value + - linters: + - tparallel + text: "call t.Parallel on the top level as well as its subtests" + + # Don't hide lint issues just because there are many of them + max-same-issues: 0 + max-issues-per-linter: 0 \ No newline at end of file From 8f41a6e77f72b343c7bfe130455453eeb41226e7 Mon Sep 17 00:00:00 2001 From: Marques Johansson Date: Thu, 16 Dec 2021 23:17:01 -0500 Subject: [PATCH 5/6] apply golangci-lint --fix fixes with latest .golangci.yml Signed-off-by: Marques Johansson --- cmd/hub/cmd/build.go | 2 -- cmd/hub/cmd/generate.go | 2 +- cmd/hub/cmd/root.go | 12 +++++++----- pkg/artifacthub/manifest.go | 19 +++++++++---------- pkg/git/action.go | 2 +- pkg/img/build.go | 1 - 6 files changed, 18 insertions(+), 20 deletions(-) diff --git a/cmd/hub/cmd/build.go b/cmd/hub/cmd/build.go index 0bf5d18..2fa2cdb 100644 --- a/cmd/hub/cmd/build.go +++ b/cmd/hub/cmd/build.go @@ -58,14 +58,12 @@ func runBuild(opts *buildOptions) error { log.Info(action.String()) } } else { - // TODO: Run binfmt_misc to enable building multi-arch images. // cat /proc/sys/fs/binfmt_misc/qemu-arm | grep flags == "flags: OCF\n" // I am not sure if we should run each action build in a go routine, // because buildkit is already massively parallelized. for _, action := range *modifiedActions { - actionContext := path.Join(actionsPath, action.Name, action.Version) readmeFile, err := os.Open(path.Join(actionContext, "README.md")) diff --git a/cmd/hub/cmd/generate.go b/cmd/hub/cmd/generate.go index 6e1f54e..01ee559 100644 --- a/cmd/hub/cmd/generate.go +++ b/cmd/hub/cmd/generate.go @@ -48,7 +48,7 @@ func runGenerate(opts *generateOptions) error { } if _, err := os.Stat(generateOpts.output); os.IsNotExist(err) { - if err := os.Mkdir(generateOpts.output, 0700); err != nil { + if err := os.Mkdir(generateOpts.output, 0o700); err != nil { return err } } diff --git a/cmd/hub/cmd/root.go b/cmd/hub/cmd/root.go index 96b8529..afd2f41 100644 --- a/cmd/hub/cmd/root.go +++ b/cmd/hub/cmd/root.go @@ -5,11 +5,13 @@ import ( "go.uber.org/zap" ) -var log *zap.Logger -var rootCmd = &cobra.Command{ - Use: "hub", - Long: ``, -} +var ( + log *zap.Logger + rootCmd = &cobra.Command{ + Use: "hub", + Long: ``, + } +) // Execute starts the command line interface. func Execute(zap *zap.Logger) { diff --git a/pkg/artifacthub/manifest.go b/pkg/artifacthub/manifest.go index 13a17be..cfab93f 100644 --- a/pkg/artifacthub/manifest.go +++ b/pkg/artifacthub/manifest.go @@ -35,12 +35,12 @@ type Manifest struct { ContainersImages []struct { Name string `yaml:"name,omitempty"` Image string `yaml:"image,omitempty"` - //Whitelisted string `yaml:"whitelisted,omitempty"` + // Whitelisted string `yaml:"whitelisted,omitempty"` } `yaml:"containersImages,omitempty"` - //ContainsSecurityUpdates string `yaml:"containsSecurityUpdates,omitempty"` - //Operator string `yaml:"operator,omitempty"` - //Deprecated string `yaml:"deprecated,omitempty"` - //Prerelease string `yaml:"prerelease,omitempty"` + // ContainsSecurityUpdates string `yaml:"containsSecurityUpdates,omitempty"` + // Operator string `yaml:"operator,omitempty"` + // Deprecated string `yaml:"deprecated,omitempty"` + // Prerelease string `yaml:"prerelease,omitempty"` Keywords []string `yaml:"keywords,omitempty"` Links []struct { Name string `yaml:"name"` @@ -56,7 +56,7 @@ type Manifest struct { Provider struct { Name string `yaml:"name"` } `yaml:"provider"` - //Ignore []string `yaml:"ignore"` + // Ignore []string `yaml:"ignore"` } func PopulateFromActionMarkdown(file io.Reader, m *Manifest) error { @@ -83,7 +83,6 @@ func PopulateFromActionMarkdown(file io.Reader, m *Manifest) error { readmeBack := bytes.NewBuffer([]byte{}) if err := godown.Convert(readmeBack, &buf, nil); err != nil { return errors.Wrap(err, "error converting the readme back from html to markdown") - } m.Name = metaData["slug"].(string) @@ -97,7 +96,7 @@ func PopulateFromActionMarkdown(file io.Reader, m *Manifest) error { m.ContainersImages = []struct { Name string `yaml:"name,omitempty"` Image string `yaml:"image,omitempty"` - //Whitelisted string `yaml:"whitelisted,omitempty"` + // Whitelisted string `yaml:"whitelisted,omitempty"` }{ { Name: m.Name, @@ -121,13 +120,13 @@ func WriteToFile(manifest *Manifest, dst string) error { if err != nil { return errors.Wrap(err, "error marshalling manifest to yaml") } - if err := os.MkdirAll(path.Join(dst, manifest.Name, manifest.Version), 0700); err != nil { + if err := os.MkdirAll(path.Join(dst, manifest.Name, manifest.Version), 0o700); err != nil { return errors.Wrap(err, "error creating directory") } dstFile, err := os.OpenFile( path.Join(dst, manifest.Name, manifest.Version, "artifacthub-pkg.yml"), os.O_CREATE|os.O_WRONLY, - 0644) + 0o644) if err != nil { return errors.Wrap(err, "error creating manifest file") } diff --git a/pkg/git/action.go b/pkg/git/action.go index b05d9c2..543f005 100644 --- a/pkg/git/action.go +++ b/pkg/git/action.go @@ -26,7 +26,7 @@ func NewTinkerbellAction(file string) TinkerbellAction { } } -// ModifiedActions analyses the Git commit history and determines which actions have been modified +// ModifiedActions analyses the Git commit history and determines which actions have been modified. func ModifiedActions(modifiedActions *[]TinkerbellAction, actionsPath string, context string, gitRef string) error { // Check if Git is available in PATH. if out, err := exec.Command("git", "version").Output(); err != nil || strings.HasPrefix("git version", string(out)) { diff --git a/pkg/img/build.go b/pkg/img/build.go index d4de246..bb7dec2 100644 --- a/pkg/img/build.go +++ b/pkg/img/build.go @@ -3,7 +3,6 @@ package img import ( "context" "encoding/json" - "os" "path/filepath" "strings" From 3bf1c80f8cf2d0fc66575db493bc82bf1a8e9d62 Mon Sep 17 00:00:00 2001 From: Marques Johansson Date: Thu, 16 Dec 2021 23:18:42 -0500 Subject: [PATCH 6/6] run gofumpt -l -w . Signed-off-by: Marques Johansson --- actions/archive2disk/v1/pkg/archive/archive.go | 7 +++---- actions/cexec/v1/main.go | 5 ++--- actions/grub2disk/v1/pkg/grub/grub.go | 2 +- actions/image2disk/v1/main.go | 1 - actions/image2disk/v1/pkg/image/image.go | 5 ++--- actions/image2disk/v1/pkg/image/image_test.go | 1 - actions/kexec/v1/cmd/kexec.go | 4 +--- actions/kexec/v1/main.go | 2 -- actions/oci2disk/v1/main.go | 1 - actions/oci2disk/v1/pkg/image/image.go | 5 ++--- actions/oci2disk/v1/pkg/image/image_test.go | 1 - actions/oci2disk/v1/pkg/image/writer.go | 14 ++++---------- actions/qemuimg2disk/v1/partprobe.go | 2 +- actions/rootio/v1/cmd/rootio.go | 5 ----- actions/rootio/v1/main.go | 2 -- actions/rootio/v1/pkg/storage/mount.go | 5 ++--- actions/rootio/v1/pkg/storage/partition.go | 4 +--- actions/rootio/v1/pkg/types.go/metadata.go | 8 ++++---- actions/slurp/v1/main.go | 1 - actions/slurp/v1/pkg/image/image.go | 5 +---- actions/slurp/v1/server/main.go | 7 ++----- actions/syslinux/v1/main.go | 7 ++----- 22 files changed, 28 insertions(+), 66 deletions(-) diff --git a/actions/archive2disk/v1/pkg/archive/archive.go b/actions/archive2disk/v1/pkg/archive/archive.go index 76f3140..0ae7c38 100644 --- a/actions/archive2disk/v1/pkg/archive/archive.go +++ b/actions/archive2disk/v1/pkg/archive/archive.go @@ -18,7 +18,6 @@ import ( // with compress set to true it will use gzip compression to expand the data before // writing to an underlying device func Write(archiveURL, archiveType, path string) error { - req, err := http.NewRequest("GET", archiveURL, nil) if err != nil { return err @@ -55,7 +54,7 @@ func Write(archiveURL, archiveType, path string) error { case "tar": // With compression run data through gzip writer out = tar.NewReader(resp.Body) - //out = tarOUT + // out = tarOUT case "targz": // With compression run data through gzip writer zipOUT, err := gzip.NewReader(resp.Body) @@ -64,7 +63,7 @@ func Write(archiveURL, archiveType, path string) error { } defer zipOUT.Close() out = tar.NewReader(zipOUT) - //out = tarOUT + // out = tarOUT default: } @@ -83,7 +82,7 @@ func Write(archiveURL, archiveType, path string) error { absFileName := filepath.Join(absPath, fileName) // if a dir, create it, then go to next segment if finfo.Mode().IsDir() { - if err := os.MkdirAll(absFileName, 0755); err != nil { + if err := os.MkdirAll(absFileName, 0o755); err != nil { return err } continue diff --git a/actions/cexec/v1/main.go b/actions/cexec/v1/main.go index 4c44fb4..4eb6fb9 100644 --- a/actions/cexec/v1/main.go +++ b/actions/cexec/v1/main.go @@ -14,7 +14,6 @@ import ( const mountAction = "/mountAction" func main() { - fmt.Printf("CEXEC - Chroot Exec\n------------------------\n") // Parse the environment variables that are passed into the action @@ -69,7 +68,7 @@ func main() { di = append(di, cmdLine) cmd := exec.Command(di[0], di[1:]...) cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr - var debugCMD = fmt.Sprintf("%s %v", di[0], di[1:]) + debugCMD := fmt.Sprintf("%s %v", di[0], di[1:]) err = cmd.Start() if err != nil { log.Fatalf("Error starting [%s] [%v]", debugCMD, err) @@ -85,7 +84,7 @@ func main() { command := strings.Split(commandLines[x], " ") cmd := exec.Command(command[0], command[1:]...) cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr - var debugCMD = fmt.Sprintf("%s %v", command[0], command[1:]) + debugCMD := fmt.Sprintf("%s %v", command[0], command[1:]) err = cmd.Start() if err != nil { log.Fatalf("Error starting [%s] [%v]", debugCMD, err) diff --git a/actions/grub2disk/v1/pkg/grub/grub.go b/actions/grub2disk/v1/pkg/grub/grub.go index 95390b5..7bf6615 100644 --- a/actions/grub2disk/v1/pkg/grub/grub.go +++ b/actions/grub2disk/v1/pkg/grub/grub.go @@ -15,7 +15,7 @@ func makeDirAndMount(devicePath string, mountPoint string, filesystemType string return err } - //if err = syscall.Mount(devicePath, mountPoint, filesystemType, flag, ""); err != nil { + // if err = syscall.Mount(devicePath, mountPoint, filesystemType, flag, ""); err != nil { var params string if filesystemType != "" { params = "-t " + filesystemType diff --git a/actions/image2disk/v1/main.go b/actions/image2disk/v1/main.go index de10626..9ab8b0f 100644 --- a/actions/image2disk/v1/main.go +++ b/actions/image2disk/v1/main.go @@ -11,7 +11,6 @@ import ( ) func main() { - fmt.Printf("IMAGE2DISK - Cloud image streamer\n------------------------\n") disk := os.Getenv("DEST_DISK") img := os.Getenv("IMG_URL") diff --git a/actions/image2disk/v1/pkg/image/image.go b/actions/image2disk/v1/pkg/image/image.go index bf3e1ff..f83fb28 100644 --- a/actions/image2disk/v1/pkg/image/image.go +++ b/actions/image2disk/v1/pkg/image/image.go @@ -46,7 +46,6 @@ func tickerProgress(byteCounter uint64) { // with compress set to true it will use gzip compression to expand the data before // writing to an underlying device func Write(sourceImage, destinationDevice string, compressed bool) error { - req, err := http.NewRequest("GET", sourceImage, nil) if err != nil { return err @@ -68,7 +67,7 @@ func Write(sourceImage, destinationDevice string, compressed bool) error { var out io.Reader - fileOut, err := os.OpenFile(destinationDevice, os.O_CREATE|os.O_WRONLY, 0644) + fileOut, err := os.OpenFile(destinationDevice, os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { return err } @@ -144,7 +143,7 @@ func findDecompressor(imageURL string, r io.Reader) (out io.Reader, err error) { return } // The xz reader doesn't implement close() - //defer xzOUT.Close() + // defer xzOUT.Close() out = xzOUT case ".zs": zsOUT, zsErr := zstd.NewReader(r) diff --git a/actions/image2disk/v1/pkg/image/image_test.go b/actions/image2disk/v1/pkg/image/image_test.go index a419aef..c97ce5c 100644 --- a/actions/image2disk/v1/pkg/image/image_test.go +++ b/actions/image2disk/v1/pkg/image/image_test.go @@ -78,7 +78,6 @@ func Test_findDecompressor(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - _, err := findDecompressor(tt.args.imageURL, tt.args.r) if (err != nil) != tt.wantErr { t.Errorf("findDecompressor() error = %v, wantErr %v", err, tt.wantErr) diff --git a/actions/kexec/v1/cmd/kexec.go b/actions/kexec/v1/cmd/kexec.go index 1da8bb5..5e8df64 100644 --- a/actions/kexec/v1/cmd/kexec.go +++ b/actions/kexec/v1/cmd/kexec.go @@ -4,9 +4,8 @@ import ( "fmt" "io/ioutil" "os" - "syscall" - "path/filepath" + "syscall" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" @@ -26,7 +25,6 @@ var kexecCmd = &cobra.Command{ Use: "kexec", Short: "This is an action for performing a kexec into a new kernel/ramdisk", Run: func(cmd *cobra.Command, args []string) { - // Parse the environment variables that are passed into the action blockDevice := os.Getenv("BLOCK_DEVICE") filesystemType := os.Getenv("FS_TYPE") diff --git a/actions/kexec/v1/main.go b/actions/kexec/v1/main.go index 943cc0d..843a9d3 100644 --- a/actions/kexec/v1/main.go +++ b/actions/kexec/v1/main.go @@ -7,8 +7,6 @@ import ( ) func main() { - fmt.Printf("KEXEC - Kernel Exec\n------------------------\n") cmd.Execute() - } diff --git a/actions/oci2disk/v1/main.go b/actions/oci2disk/v1/main.go index e1eab49..dcb9adc 100644 --- a/actions/oci2disk/v1/main.go +++ b/actions/oci2disk/v1/main.go @@ -11,7 +11,6 @@ import ( ) func main() { - fmt.Printf("OCI2DISK - OCI Container Disk image streamer\n------------------------\n") disk := os.Getenv("DEST_DISK") img := os.Getenv("IMG_URL") diff --git a/actions/oci2disk/v1/pkg/image/image.go b/actions/oci2disk/v1/pkg/image/image.go index 7cee5cd..6b79027 100644 --- a/actions/oci2disk/v1/pkg/image/image.go +++ b/actions/oci2disk/v1/pkg/image/image.go @@ -39,7 +39,6 @@ func (wc *WriteCounter) Write(p []byte) (int, error) { // with compress set to true it will use gzip compression to expand the data before // writing to an underlying device func Write(sourceImage, destinationDevice string, compressed bool) error { - ctx := context.Background() client := http.DefaultClient opts := docker.ResolverOptions{} @@ -53,7 +52,7 @@ func Write(sourceImage, destinationDevice string, compressed bool) error { resolver := docker.NewResolver(opts) - fileOut, err := os.OpenFile(destinationDevice, os.O_CREATE|os.O_WRONLY, 0644) + fileOut, err := os.OpenFile(destinationDevice, os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { return err } @@ -110,7 +109,7 @@ func findDecompressor(imageURL string, r io.Reader) (out io.Reader, err error) { return } // The xz reader doesn't implement close() - //defer xzOUT.Close() + // defer xzOUT.Close() out = xzOUT case ".zs": zsOUT, zsErr := zstd.NewReader(r) diff --git a/actions/oci2disk/v1/pkg/image/image_test.go b/actions/oci2disk/v1/pkg/image/image_test.go index a419aef..c97ce5c 100644 --- a/actions/oci2disk/v1/pkg/image/image_test.go +++ b/actions/oci2disk/v1/pkg/image/image_test.go @@ -78,7 +78,6 @@ func Test_findDecompressor(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - _, err := findDecompressor(tt.args.imageURL, tt.args.r) if (err != nil) != tt.wantErr { t.Errorf("findDecompressor() error = %v, wantErr %v", err, tt.wantErr) diff --git a/actions/oci2disk/v1/pkg/image/writer.go b/actions/oci2disk/v1/pkg/image/writer.go index 5efe082..08af323 100644 --- a/actions/oci2disk/v1/pkg/image/writer.go +++ b/actions/oci2disk/v1/pkg/image/writer.go @@ -110,7 +110,7 @@ func (d DiskImageStore) Writer(ctx context.Context, opts ...ctrcontent.WriterOpt digester: digest.Canonical.Digester(), // we take the OutputHash, since the InputHash goes to the passthrough writer, // which then passes the processed output to us - //hash: wOpts.OutputHash, + // hash: wOpts.OutputHash, } // we have to reprocess the opts to find the desc @@ -125,23 +125,18 @@ func (d DiskImageStore) Writer(ctx context.Context, opts ...ctrcontent.WriterOpt fmt.Printf("%v\n", desc.Annotations["org.opencontainers.image.title"]) if desc.Annotations["org.opencontainers.image.title"] == "" { return content.NewIoContentWriter(ioutil.Discard, content.WithOutputHash(desc.Digest)), nil - } if !d.compressed { // Without compression send raw output f = func(r io.Reader, w io.Writer, done chan<- error) { - var ( - err error - ) + var err error b := make([]byte, wOpts.Blocksize) _, err = io.CopyBuffer(w, r, b) done <- err } } else { f = func(r io.Reader, w io.Writer, done chan<- error) { - var ( - err error - ) + var err error decompressReader, err := findDecompressor(d.sourceImage, r) if err != nil { log.Fatalf(err.Error()) @@ -152,11 +147,10 @@ func (d DiskImageStore) Writer(ctx context.Context, opts ...ctrcontent.WriterOpt done <- err } } - } writerOpts := []content.WriterOpt{} return content.NewPassthroughWriter(di, f, writerOpts...), nil - //return nil, err + // return nil, err } // DiskImage - diff --git a/actions/qemuimg2disk/v1/partprobe.go b/actions/qemuimg2disk/v1/partprobe.go index e443aeb..7759061 100644 --- a/actions/qemuimg2disk/v1/partprobe.go +++ b/actions/qemuimg2disk/v1/partprobe.go @@ -9,7 +9,7 @@ import ( func main() { disk := os.Getenv("DEST_DISK") - fileOut, err := os.OpenFile(disk, os.O_CREATE|os.O_WRONLY, 0644) + fileOut, err := os.OpenFile(disk, os.O_CREATE|os.O_WRONLY, 0o644) defer func() { if err := fileOut.Close(); err != nil { fmt.Fprint(os.Stderr, "error closing file: ", err) diff --git a/actions/rootio/v1/cmd/rootio.go b/actions/rootio/v1/cmd/rootio.go index fc898b3..66ca24c 100644 --- a/actions/rootio/v1/cmd/rootio.go +++ b/actions/rootio/v1/cmd/rootio.go @@ -26,7 +26,6 @@ var rootioCmd = &cobra.Command{ } func init() { - rootioCmd.AddCommand(rootioFormat) rootioCmd.AddCommand(rootioPartition) rootioCmd.AddCommand(rootioMount) @@ -47,7 +46,6 @@ func init() { } } fmt.Printf("Succesfully parsed the MetaData, Found [%d] Disks\n", len(metadata.Storage.Disks)) - } // Execute - starts the command parsing process @@ -62,7 +60,6 @@ var rootioFormat = &cobra.Command{ Use: "format", Short: "Use rootio to format disks based upon metadata", Run: func(cmd *cobra.Command, args []string) { - for fileSystem := range metadata.Storage.Filesystems { err := storage.FileSystemCreate(metadata.Storage.Filesystems[fileSystem]) if err != nil { @@ -76,7 +73,6 @@ var rootioMount = &cobra.Command{ Use: "mount", Short: "Use rootio to mount disks based upon metadata", Run: func(cmd *cobra.Command, args []string) { - for fileSystem := range metadata.Storage.Filesystems { err := storage.Mount(metadata.Storage.Filesystems[fileSystem]) if err != nil { @@ -90,7 +86,6 @@ var rootioPartition = &cobra.Command{ Use: "partition", Short: "Use rootio to partition disks based upon metadata", Run: func(cmd *cobra.Command, args []string) { - for disk := range metadata.Storage.Disks { err := storage.VerifyBlockDevice(metadata.Storage.Disks[disk].Device) if err != nil { diff --git a/actions/rootio/v1/main.go b/actions/rootio/v1/main.go index 6ad1ce0..78c1152 100644 --- a/actions/rootio/v1/main.go +++ b/actions/rootio/v1/main.go @@ -7,9 +7,7 @@ import ( ) func main() { - fmt.Printf("ROOTIO - Disk Manager\n------------------------\n") fmt.Println("Parsing MetaData") cmd.Execute() - } diff --git a/actions/rootio/v1/pkg/storage/mount.go b/actions/rootio/v1/pkg/storage/mount.go index a232bbb..a6188ec 100644 --- a/actions/rootio/v1/pkg/storage/mount.go +++ b/actions/rootio/v1/pkg/storage/mount.go @@ -10,14 +10,13 @@ import ( "github.com/tinkerbell/hub/actions/rootio/v1/pkg/types.go" ) -//Mount -= +// Mount -= func Mount(f types.Filesystem) error { - if f.Mount.Format == "swap" { // Format disk cmd := exec.Command("/sbin/swapon", f.Mount.Device) cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr - var debugCMD = fmt.Sprintf("%s %s", "/sbin/swapon", f.Mount.Device) + debugCMD := fmt.Sprintf("%s %s", "/sbin/swapon", f.Mount.Device) err := cmd.Start() if err != nil { return fmt.Errorf("Command [%s] Filesystem [%v]", debugCMD, err) diff --git a/actions/rootio/v1/pkg/storage/partition.go b/actions/rootio/v1/pkg/storage/partition.go index c011835..614efa8 100644 --- a/actions/rootio/v1/pkg/storage/partition.go +++ b/actions/rootio/v1/pkg/storage/partition.go @@ -65,7 +65,6 @@ func ExamineDisk(d types.Disk) error { // Partition will create the partitions and write them to the disk func Partition(d types.Disk) error { - table := &gpt.Table{ ProtectiveMBR: true, LogicalSectorSize: sectorSize, @@ -131,7 +130,6 @@ func Partition(d types.Disk) error { // MBRPartition will create the partitions and write them to the disk func MBRPartition(d types.Disk) error { - table := &mbr.Table{ LogicalSectorSize: sectorSize, PhysicalSectorSize: sectorSize, @@ -204,7 +202,7 @@ func MBRPartition(d types.Disk) error { // Wipe will clean the table from a disk func Wipe(d types.Disk) error { - disk, err := os.OpenFile(d.Device, os.O_CREATE|os.O_WRONLY, 0644) + disk, err := os.OpenFile(d.Device, os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { return err } diff --git a/actions/rootio/v1/pkg/types.go/metadata.go b/actions/rootio/v1/pkg/types.go/metadata.go index f548be3..96e5bfa 100644 --- a/actions/rootio/v1/pkg/types.go/metadata.go +++ b/actions/rootio/v1/pkg/types.go/metadata.go @@ -26,7 +26,7 @@ type Metadata struct { } `json:"storage"` } -//Filesystem defines the organisation of a filesystem +// Filesystem defines the organisation of a filesystem type Filesystem struct { Mount struct { Create struct { @@ -38,21 +38,21 @@ type Filesystem struct { } `json:"mount"` } -//Disk defines the configuration for a disk +// Disk defines the configuration for a disk type Disk struct { Device string `json:"device"` Partitions []Partitions `json:"partitions"` WipeTable bool `json:"wipe_table"` } -//Partitions details the architecture +// Partitions details the architecture type Partitions struct { Label string `json:"label"` Number int `json:"number"` Size uint64 `json:"size"` } -//RetreieveData - +// RetreieveData - func RetreieveData() (*Metadata, error) { metadataURL := os.Getenv("MIRROR_HOST") if metadataURL == "" { diff --git a/actions/slurp/v1/main.go b/actions/slurp/v1/main.go index cf28325..fdc7974 100644 --- a/actions/slurp/v1/main.go +++ b/actions/slurp/v1/main.go @@ -11,7 +11,6 @@ import ( ) func main() { - fmt.Printf("SLURP - Upload the contents of a block device\n------------------------\n") sourceDisk := os.Getenv("SOURCE_DISK") destinationURL := os.Getenv("DEST_URL") diff --git a/actions/slurp/v1/pkg/image/image.go b/actions/slurp/v1/pkg/image/image.go index 627ce95..35c07ac 100644 --- a/actions/slurp/v1/pkg/image/image.go +++ b/actions/slurp/v1/pkg/image/image.go @@ -26,7 +26,6 @@ func (wc *WriteCounter) Write(p []byte) (int, error) { // Read - will take a local disk and copy an image to a remote server func Read(sourceDevice, destinationAddress, name string, compressed bool) error { - var fileName string if !compressed { // raw image @@ -50,7 +49,7 @@ func Read(sourceDevice, destinationAddress, name string, compressed bool) error return nil } -//UploadMultipartFile - +// UploadMultipartFile - func UploadMultipartFile(client *http.Client, uri, key, path string, compressed bool) (*http.Response, error) { body, writer := io.Pipe() @@ -92,7 +91,6 @@ func UploadMultipartFile(client *http.Client, uri, key, path string, compressed errchan <- fmt.Errorf("error copying %s (%d bytes written): %v", path, written, err) return } - } else { // With compression run data through gzip writer zipWriter := gzip.NewWriter(w) @@ -119,7 +117,6 @@ func UploadMultipartFile(client *http.Client, uri, key, path string, compressed errchan <- err return } - }() resp, err := client.Do(req) diff --git a/actions/slurp/v1/server/main.go b/actions/slurp/v1/server/main.go index c3e214a..b58cdf2 100644 --- a/actions/slurp/v1/server/main.go +++ b/actions/slurp/v1/server/main.go @@ -26,7 +26,7 @@ func (wc *WriteCounter) Write(p []byte) (int, error) { return n, nil } -//PrintProgress - provides UX information about the writing of the image locally. +// PrintProgress - provides UX information about the writing of the image locally. func (wc WriteCounter) PrintProgress() { // Clear the line by using a character return to go back to the start and remove // the remaining characters by filling it with spaces @@ -39,7 +39,6 @@ func (wc WriteCounter) PrintProgress() { } func imageHandler(w http.ResponseWriter, r *http.Request) { - imageName := fmt.Sprintf("%s.img", r.RemoteAddr) if err := r.ParseMultipartForm(32 << 20); err != nil { @@ -53,7 +52,7 @@ func imageHandler(w http.ResponseWriter, r *http.Request) { } defer file.Close() - out, err := os.OpenFile(imageName, os.O_CREATE|os.O_WRONLY, 0644) + out, err := os.OpenFile(imageName, os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { http.Error(w, "Error opening file", http.StatusInternalServerError) log.Fatalf("%v", err) @@ -72,7 +71,6 @@ func imageHandler(w http.ResponseWriter, r *http.Request) { } func main() { - // // Server port port := flag.Int("port", 3000, "The port the server will listen on") @@ -84,5 +82,4 @@ func main() { if err != nil { log.Fatal(err) } - } diff --git a/actions/syslinux/v1/main.go b/actions/syslinux/v1/main.go index 9f4ccf0..0501821 100644 --- a/actions/syslinux/v1/main.go +++ b/actions/syslinux/v1/main.go @@ -11,7 +11,6 @@ import ( ) func main() { - fmt.Printf("SYSLINUX - Boot Loader Installation\n------------------------\n") disk := os.Getenv("DEST_DISK") partition := os.Getenv("DEST_PARTITION") @@ -24,13 +23,12 @@ func main() { default: log.Fatalf("Unknown syslinux version [%s]", ver) } - } func syslinux386(disk, partition string) { log.Infof("Writing mbr to [%s] and installing boot loader to [%s]", disk, partition) // Open the block device and write the Master boot record - blockOut, err := os.OpenFile(disk, os.O_CREATE|os.O_WRONLY, 0644) + blockOut, err := os.OpenFile(disk, os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { log.Fatalln(err) } @@ -43,7 +41,7 @@ func syslinux386(disk, partition string) { } } defer deferWithError(blockOut.Close) - mbrIn, err := os.OpenFile("/mbr.bin.386", os.O_RDONLY, 0644) + mbrIn, err := os.OpenFile("/mbr.bin.386", os.O_RDONLY, 0o644) if err != nil { log.Fatalln(err) } @@ -69,7 +67,6 @@ func syslinux386(disk, partition string) { if err != nil { log.Fatalf("Error running [%v]", err) } - } const (