From 7a129b6e8d3ec3e4aace63fd53ed1f46c0c9d6d0 Mon Sep 17 00:00:00 2001 From: Avi Deitcher Date: Wed, 9 Apr 2025 17:53:20 +0300 Subject: [PATCH] bump golangci-lint to v2.0.2 and update all lint issues (#4116) Signed-off-by: Avi Deitcher --- .github/workflows/ci.yml | 4 +- Makefile | 4 +- src/cmd/linuxkit/Makefile | 2 +- src/cmd/linuxkit/azure.go | 2 +- src/cmd/linuxkit/build.go | 6 +- src/cmd/linuxkit/cache/imagesource.go | 8 +- src/cmd/linuxkit/cache/indexsource.go | 7 +- src/cmd/linuxkit/cache/layout.go | 2 +- src/cmd/linuxkit/cache/write.go | 4 +- src/cmd/linuxkit/cache_clean.go | 2 +- src/cmd/linuxkit/cache_export.go | 10 +- src/cmd/linuxkit/cache_import.go | 4 +- src/cmd/linuxkit/docker/source.go | 6 +- src/cmd/linuxkit/gcp.go | 14 +-- src/cmd/linuxkit/metadata.go | 2 +- src/cmd/linuxkit/moby/build/build.go | 2 +- src/cmd/linuxkit/moby/build/image.go | 4 +- src/cmd/linuxkit/moby/build/linuxkit.go | 12 +-- src/cmd/linuxkit/moby/build/output.go | 98 +++++++++++-------- src/cmd/linuxkit/moby/config.go | 24 ++--- src/cmd/linuxkit/pkg_build.go | 4 +- src/cmd/linuxkit/pkg_builder.go | 4 +- src/cmd/linuxkit/pkglib/build.go | 57 ++++++----- src/cmd/linuxkit/pkglib/build_test.go | 52 +++++----- src/cmd/linuxkit/pkglib/depends.go | 4 +- src/cmd/linuxkit/pkglib/docker.go | 2 +- src/cmd/linuxkit/pkglib/git.go | 4 +- src/cmd/linuxkit/pkglib/pkglib.go | 10 +- src/cmd/linuxkit/pkglib/pkglib_test.go | 8 +- src/cmd/linuxkit/pkglib/utils.go | 20 ++-- src/cmd/linuxkit/push_aws.go | 20 ++-- src/cmd/linuxkit/push_equinixmetal.go | 18 ++-- src/cmd/linuxkit/push_gcp.go | 8 +- src/cmd/linuxkit/push_openstack.go | 6 +- src/cmd/linuxkit/push_scaleway.go | 18 ++-- src/cmd/linuxkit/push_vcenter.go | 2 +- src/cmd/linuxkit/run.go | 2 +- src/cmd/linuxkit/run_aws.go | 30 +++--- src/cmd/linuxkit/run_equinixmetal.go | 52 +++++----- src/cmd/linuxkit/run_gcp.go | 6 +- src/cmd/linuxkit/run_hyperkit.go | 74 +++++++------- src/cmd/linuxkit/run_hyperv.go | 24 ++--- src/cmd/linuxkit/run_openstack.go | 4 +- src/cmd/linuxkit/run_qemu.go | 28 +++--- src/cmd/linuxkit/run_vbox.go | 19 ++-- src/cmd/linuxkit/run_vcenter.go | 12 +-- ...tualizationframework_darwin_cgo_enabled.go | 42 ++++---- src/cmd/linuxkit/run_vmware.go | 16 +-- src/cmd/linuxkit/scaleway.go | 32 +++--- src/cmd/linuxkit/util.go | 20 ++-- tools/go-compile/Dockerfile | 2 +- tools/go-compile/compile.sh | 2 +- 52 files changed, 429 insertions(+), 390 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c2c0004d7..b74aa89cb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,9 +50,9 @@ jobs: GOPATH: ${{runner.workspace}} - name: golangci-lint CLI - uses: golangci/golangci-lint-action@v6 + uses: golangci/golangci-lint-action@v7 with: - version: v1.63.4 + version: v2.0.2 working-directory: src/cmd/linuxkit args: --verbose --timeout=10m - name: go vet CLI diff --git a/Makefile b/Makefile index 8487b0dfd..745ad6875 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ VERSION="v0.8+" TEST_SUITE ?= TEST_SHARD ?= -GO_COMPILE=linuxkit/go-compile:c97703655e8510b7257ffc57f25e40337b0f0813 +GO_COMPILE=linuxkit/go-compile:985a9db72a7e6941de5e1eb71c2b41b76bf0556f ifeq ($(OS),Windows_NT) LINUXKIT?=$(CURDIR)/bin/linuxkit.exe @@ -34,7 +34,7 @@ export VERSION GO_COMPILE GOOS GOARCH LOCAL_TARGET LINUXKIT default: linuxkit $(RTF) all: default -RTF_COMMIT=b74a4f7c78e5cddcf7e6d2e6be7be312b9f645fc +RTF_COMMIT=1118e08445438dc37ec62b4c1e216918b3d804d2 RTF_CMD=github.com/linuxkit/rtf/cmd RTF_VERSION=0.0 $(RTF): tmp_rtf_bin.tar | bin diff --git a/src/cmd/linuxkit/Makefile b/src/cmd/linuxkit/Makefile index 3b2694751..07d6d2783 100644 --- a/src/cmd/linuxkit/Makefile +++ b/src/cmd/linuxkit/Makefile @@ -19,7 +19,7 @@ report: @echo "GIT_TAG: $(GIT_TAG)" @echo "VERSION: $(VERSION)" -GO_COMPILE?=linuxkit/go-compile:c97703655e8510b7257ffc57f25e40337b0f0813 +GO_COMPILE?=linuxkit/go-compile:985a9db72a7e6941de5e1eb71c2b41b76bf0556f export GO_FLAGS=-mod=vendor ifeq ($(OS),Windows_NT) diff --git a/src/cmd/linuxkit/azure.go b/src/cmd/linuxkit/azure.go index f2a4d8117..54a41a46f 100644 --- a/src/cmd/linuxkit/azure.go +++ b/src/cmd/linuxkit/azure.go @@ -164,7 +164,7 @@ func uploadVMImage(resourceGroupName string, accountName string, imagePath strin if err != nil { log.Fatalf("Unable to create disk stream for VHD: %v", err) } - defer diskStream.Close() + defer func() { _ = diskStream.Close() }() simpleStorageClient, err = simpleStorage.NewBasicClient(accountName, *keys[0].Value) if err != nil { diff --git a/src/cmd/linuxkit/build.go b/src/cmd/linuxkit/build.go index a31f881b3..b4fb8d35f 100644 --- a/src/cmd/linuxkit/build.go +++ b/src/cmd/linuxkit/build.go @@ -141,7 +141,7 @@ The generated image can be in one of multiple formats which can be run on variou if err != nil { log.Fatalf("cannot open output file: %v", err) } - defer outfile.Close() + defer func() { _ = outfile.Close() }() } } @@ -168,7 +168,7 @@ The generated image can be in one of multiple formats which can be run on variou if err != nil { return fmt.Errorf("cannot fetch remote yaml file: %v", err) } - defer response.Body.Close() + defer func() { _ = response.Body.Close() }() _, err = io.Copy(buffer, response.Body) if err != nil { return fmt.Errorf("error reading http body: %v", err) @@ -216,7 +216,7 @@ The generated image can be in one of multiple formats which can be run on variou if tf, err = os.CreateTemp("", ""); err != nil { log.Fatalf("error creating tempfile: %v", err) } - defer os.Remove(tf.Name()) + defer func() { _ = os.Remove(tf.Name()) }() w = tf } if inputTar != "" && inputTar == outputFile { diff --git a/src/cmd/linuxkit/cache/imagesource.go b/src/cmd/linuxkit/cache/imagesource.go index 740df3012..8e00220e2 100644 --- a/src/cmd/linuxkit/cache/imagesource.go +++ b/src/cmd/linuxkit/cache/imagesource.go @@ -110,7 +110,7 @@ func (c ImageSource) V1TarReader(overrideName string) (io.ReadCloser, error) { // convert the writer to a reader r, w := io.Pipe() go func() { - defer w.Close() + defer func() { _ = w.Close() }() _ = tarball.Write(refName, image, w) }() return r, nil @@ -135,9 +135,9 @@ func (c ImageSource) OCITarReader(overrideName string) (io.ReadCloser, error) { // convert the writer to a reader r, w := io.Pipe() go func() { - defer w.Close() + defer func() { _ = w.Close() }() tw := tar.NewWriter(w) - defer tw.Close() + defer func() { _ = tw.Close() }() if err := writeLayoutHeader(tw); err != nil { _ = w.CloseWithError(err) return @@ -257,7 +257,7 @@ func (c ImageSource) SBoMs() ([]io.ReadCloser, error) { if _, err := io.Copy(&buf, layer); err != nil { return nil, err } - layer.Close() + _ = layer.Close() var stmt spdxStatement if err := json.Unmarshal(buf.Bytes(), &stmt); err != nil { return nil, err diff --git a/src/cmd/linuxkit/cache/indexsource.go b/src/cmd/linuxkit/cache/indexsource.go index 9c804ec9c..8632836d2 100644 --- a/src/cmd/linuxkit/cache/indexsource.go +++ b/src/cmd/linuxkit/cache/indexsource.go @@ -11,7 +11,6 @@ import ( v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/types" "github.com/linuxkit/linuxkit/src/cmd/linuxkit/spec" - lktspec "github.com/linuxkit/linuxkit/src/cmd/linuxkit/spec" imagespec "github.com/opencontainers/image-spec/specs-go/v1" ) @@ -26,7 +25,7 @@ type IndexSource struct { // NewIndexSource return an IndexSource for a specific ref in the given // cache directory. -func (p *Provider) NewIndexSource(ref *reference.Spec, descriptor *v1.Descriptor, platforms []imagespec.Platform) lktspec.IndexSource { +func (p *Provider) NewIndexSource(ref *reference.Spec, descriptor *v1.Descriptor, platforms []imagespec.Platform) spec.IndexSource { return IndexSource{ ref: ref, provider: p, @@ -74,9 +73,9 @@ func (c IndexSource) OCITarReader(overrideName string) (io.ReadCloser, error) { // convert the writer to a reader r, w := io.Pipe() go func() { - defer w.Close() + defer func() { _ = w.Close() }() tw := tar.NewWriter(w) - defer tw.Close() + defer func() { _ = tw.Close() }() if err := writeLayoutHeader(tw); err != nil { _ = w.CloseWithError(err) return diff --git a/src/cmd/linuxkit/cache/layout.go b/src/cmd/linuxkit/cache/layout.go index 147875e1e..111b42424 100644 --- a/src/cmd/linuxkit/cache/layout.go +++ b/src/cmd/linuxkit/cache/layout.go @@ -69,7 +69,7 @@ func writeLayoutImage(tw *tar.Writer, image v1.Image) error { if err != nil { return err } - defer blob.Close() + defer func() { _ = blob.Close() }() blobDigest, err := layer.Digest() if err != nil { return err diff --git a/src/cmd/linuxkit/cache/write.go b/src/cmd/linuxkit/cache/write.go index ddb3ac5b5..c1917fbbc 100644 --- a/src/cmd/linuxkit/cache/write.go +++ b/src/cmd/linuxkit/cache/write.go @@ -431,7 +431,7 @@ func (p *Provider) ImageInCache(ref *reference.Spec, trustedRef, architecture st if rc, err = p.cache.Blob(dig); err != nil { return false, fmt.Errorf("layer %s not found: %v", dig, err) } - rc.Close() + _ = rc.Close() } // check that the config exists config, err := img.ConfigName() @@ -442,7 +442,7 @@ func (p *Provider) ImageInCache(ref *reference.Spec, trustedRef, architecture st if rc, err = p.cache.Blob(config); err != nil { return false, fmt.Errorf("config %s not found: %v", config, err) } - rc.Close() + _ = rc.Close() return true, nil } diff --git a/src/cmd/linuxkit/cache_clean.go b/src/cmd/linuxkit/cache_clean.go index e5ccd28c1..3efc5c4d1 100644 --- a/src/cmd/linuxkit/cache_clean.go +++ b/src/cmd/linuxkit/cache_clean.go @@ -23,7 +23,7 @@ func cacheCleanCmd() *cobra.Command { // did we limit to published only? if !publishedOnly { if err := os.RemoveAll(cacheDir); err != nil { - return fmt.Errorf("Unable to clean cache %s: %v", cacheDir, err) + return fmt.Errorf("uUnable to clean cache %s: %v", cacheDir, err) } log.Infof("Cache emptied: %s", cacheDir) return nil diff --git a/src/cmd/linuxkit/cache_export.go b/src/cmd/linuxkit/cache_export.go index e2f6d3756..c83b5e9e8 100644 --- a/src/cmd/linuxkit/cache_export.go +++ b/src/cmd/linuxkit/cache_export.go @@ -77,21 +77,21 @@ func cacheExportCmd() *cobra.Command { if err != nil { log.Fatalf("error getting reader for image %s: %v", name, err) } - defer reader.Close() + defer func() { _ = reader.Close() }() // try to write the output file var w io.Writer - switch { - case outputFile == "": + switch outputFile { + case "": log.Fatal("'outfile' flag is required") - case outputFile == "-": + case "-": w = os.Stdout default: f, err := os.OpenFile(outputFile, os.O_CREATE|os.O_RDWR, 0644) if err != nil { log.Fatalf("unable to open %s: %v", outputFile, err) } - defer f.Close() + defer func() { _ = f.Close() }() w = f } diff --git a/src/cmd/linuxkit/cache_import.go b/src/cmd/linuxkit/cache_import.go index 29f811271..d31a777c9 100644 --- a/src/cmd/linuxkit/cache_import.go +++ b/src/cmd/linuxkit/cache_import.go @@ -43,10 +43,10 @@ func cacheImportCmd() *cobra.Command { if err != nil { log.Fatalf("unable to open %s: %v", infile, err) } - defer f.Close() + defer func() { _ = f.Close() }() reader = f } - defer reader.Close() + defer func() { _ = reader.Close() }() if _, err := p.ImageLoad(reader); err != nil { log.Fatalf("unable to load image: %v", err) diff --git a/src/cmd/linuxkit/docker/source.go b/src/cmd/linuxkit/docker/source.go index 962efe764..3669ee212 100644 --- a/src/cmd/linuxkit/docker/source.go +++ b/src/cmd/linuxkit/docker/source.go @@ -60,17 +60,17 @@ func (d ImageSource) Config() (imagespec.ImageConfig, error) { func (d ImageSource) TarReader() (io.ReadCloser, error) { container, err := Create(d.ref.String(), false) if err != nil { - return nil, fmt.Errorf("Failed to create docker image %s: %v", d.ref, err) + return nil, fmt.Errorf("failed to create docker image %s: %v", d.ref, err) } contents, err := Export(container) if err != nil { - return nil, fmt.Errorf("Failed to docker export container from container %s: %v", container, err) + return nil, fmt.Errorf("failed to docker export container from container %s: %v", container, err) } return readCloser{ r: contents, closer: func() error { - contents.Close() + _ = contents.Close() return Rm(container) }, diff --git a/src/cmd/linuxkit/gcp.go b/src/cmd/linuxkit/gcp.go index 1b38cd423..eaa97d026 100644 --- a/src/cmd/linuxkit/gcp.go +++ b/src/cmd/linuxkit/gcp.go @@ -113,7 +113,7 @@ func (g GCPClient) UploadFile(src, dst, bucketName string, public bool) error { if err != nil { return err } - defer f.Close() + defer func() { _ = f.Close() }() objectCall := g.storage.Objects.Insert(bucketName, &storage.Object{Name: dst}).Media(f) @@ -395,7 +395,7 @@ func (g GCPClient) ConnectToInstanceSerialPort(instance, zone string) error { if err != nil { return err } - defer resp.Body.Close() + defer func() { _ = resp.Body.Close() }() body, err := io.ReadAll(resp.Body) if err != nil { return err @@ -431,17 +431,17 @@ func (g GCPClient) ConnectToInstanceSerialPort(instance, zone string) error { if conn == nil { return err } - defer conn.Close() + defer func() { _ = conn.Close() }() session, err := conn.NewSession() if err != nil { return err } - defer session.Close() + defer func() { _ = session.Close() }() stdin, err := session.StdinPipe() if err != nil { - return fmt.Errorf("Unable to setup stdin for session: %v", err) + return fmt.Errorf("unable to setup stdin for session: %v", err) } go func() { _, _ = io.Copy(stdin, os.Stdin) @@ -449,7 +449,7 @@ func (g GCPClient) ConnectToInstanceSerialPort(instance, zone string) error { stdout, err := session.StdoutPipe() if err != nil { - return fmt.Errorf("Unable to setup stdout for session: %v", err) + return fmt.Errorf("unable to setup stdout for session: %v", err) } go func() { _, _ = io.Copy(os.Stdout, stdout) @@ -457,7 +457,7 @@ func (g GCPClient) ConnectToInstanceSerialPort(instance, zone string) error { stderr, err := session.StderrPipe() if err != nil { - return fmt.Errorf("Unable to setup stderr for session: %v", err) + return fmt.Errorf("unable to setup stderr for session: %v", err) } go func() { _, _ = io.Copy(os.Stderr, stderr) diff --git a/src/cmd/linuxkit/metadata.go b/src/cmd/linuxkit/metadata.go index 9f8686dad..9d314a4f1 100644 --- a/src/cmd/linuxkit/metadata.go +++ b/src/cmd/linuxkit/metadata.go @@ -13,7 +13,7 @@ func WriteMetadataISO(path string, content []byte) error { if err != nil { return err } - defer outfh.Close() + defer func() { _ = outfh.Close() }() return iso9660wrap.WriteBuffer(outfh, content, "config") } diff --git a/src/cmd/linuxkit/moby/build/build.go b/src/cmd/linuxkit/moby/build/build.go index 76d18c777..c3e01e850 100644 --- a/src/cmd/linuxkit/moby/build/build.go +++ b/src/cmd/linuxkit/moby/build/build.go @@ -160,7 +160,7 @@ func Build(m moby.Moby, w io.Writer, opts BuildOpts) error { if err != nil { return fmt.Errorf("failed to open input tar: %w", err) } - defer in.Close() + defer func() { _ = in.Close() }() if _, err := in.Seek(0, 0); err != nil { return fmt.Errorf("failed to seek to beginning of tmpfile: %w", err) } diff --git a/src/cmd/linuxkit/moby/build/image.go b/src/cmd/linuxkit/moby/build/image.go index e140e9a2e..2d0b3ead7 100644 --- a/src/cmd/linuxkit/moby/build/image.go +++ b/src/cmd/linuxkit/moby/build/image.go @@ -210,7 +210,7 @@ func ImageTar(location string, ref *reference.Spec, prefix string, tw tarWriter, return fmt.Errorf("could not unpack image %s: %v", ref, err) } - defer contents.Close() + defer func() { _ = contents.Close() }() // all of the files in `touch` must exist in the output, so keep track if // we found them, and, if not, create them @@ -392,7 +392,7 @@ func ImageOCITar(location string, ref *reference.Spec, prefix string, tw tarWrit return fmt.Errorf("could not unpack image %s: %v", ref, err) } - defer contents.Close() + defer func() { _ = contents.Close() }() tr := tar.NewReader(contents) diff --git a/src/cmd/linuxkit/moby/build/linuxkit.go b/src/cmd/linuxkit/moby/build/linuxkit.go index 9fcf5991e..eeb1aff8c 100644 --- a/src/cmd/linuxkit/moby/build/linuxkit.go +++ b/src/cmd/linuxkit/moby/build/linuxkit.go @@ -56,7 +56,7 @@ func ensureLinuxkitImage(name, cache string) error { if err != nil { return err } - defer os.Remove(tf.Name()) + defer func() { _ = os.Remove(tf.Name()) }() if err := Build(m, tf, BuildOpts{Pull: false, BuilderType: "", DecompressKernel: false, CacheDir: cache, DockerCache: true, Arch: arch}); err != nil { return err } @@ -68,10 +68,10 @@ func ensureLinuxkitImage(name, cache string) error { if err != nil { return err } - defer image.Close() + defer func() { _ = image.Close() }() kernel, initrd, cmdline, _, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } return writeKernelInitrd(filename, kernel, initrd, cmdline) } @@ -95,7 +95,7 @@ func outputLinuxKit(format string, filename string, kernel []byte, initrd []byte if err != nil { return err } - defer os.RemoveAll(tmp) + defer func() { _ = os.RemoveAll(tmp) }() buf, err := tarInitrdKernel(kernel, initrd, cmdline) if err != nil { @@ -120,11 +120,11 @@ func outputLinuxKit(format string, filename string, kernel []byte, initrd []byte _ = os.Remove(filename) _, err = os.Stat(filename) if err == nil || !os.IsNotExist(err) { - return fmt.Errorf("Cannot remove existing file [%s]", filename) + return fmt.Errorf("cannot remove existing file [%s]", filename) } linuxkit, err := exec.LookPath("linuxkit") if err != nil { - return fmt.Errorf("Cannot find linuxkit executable, needed to build %s output type: %v", format, err) + return fmt.Errorf("cannot find linuxkit executable, needed to build %s output type: %v", format, err) } commandLine := []string{ "-q", "run", "qemu", diff --git a/src/cmd/linuxkit/moby/build/output.go b/src/cmd/linuxkit/moby/build/output.go index fbacc8948..e32cc485d 100644 --- a/src/cmd/linuxkit/moby/build/output.go +++ b/src/cmd/linuxkit/moby/build/output.go @@ -28,84 +28,84 @@ var outFuns = map[string]func(base string, ir io.Reader, size int, arch string) "kernel+initrd": func(base string, image io.Reader, size int, arch string) error { kernel, initrd, cmdline, ucode, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } err = outputKernelInitrd(base, kernel, initrd, cmdline, ucode) if err != nil { - return fmt.Errorf("Error writing kernel+initrd output: %v", err) + return fmt.Errorf("error writing kernel+initrd output: %v", err) } return nil }, "tar-kernel-initrd": func(base string, image io.Reader, size int, arch string) error { kernel, initrd, cmdline, ucode, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } if err := outputKernelInitrdTarball(base, kernel, initrd, cmdline, ucode); err != nil { - return fmt.Errorf("Error writing kernel+initrd tarball output: %v", err) + return fmt.Errorf("error writing kernel+initrd tarball output: %v", err) } return nil }, "iso-bios": func(base string, image io.Reader, size int, arch string) error { err := outputIso(outputImages["iso-bios"], base+".iso", image, arch) if err != nil { - return fmt.Errorf("Error writing iso-bios output: %v", err) + return fmt.Errorf("error writing iso-bios output: %v", err) } return nil }, "iso-efi": func(base string, image io.Reader, size int, arch string) error { err := outputIso(outputImages["iso-efi"], base+"-efi.iso", image, arch) if err != nil { - return fmt.Errorf("Error writing iso-efi output: %v", err) + return fmt.Errorf("error writing iso-efi output: %v", err) } return nil }, "iso-efi-initrd": func(base string, image io.Reader, size int, arch string) error { kernel, initrd, cmdline, _, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } err = outputImg(outputImages["iso-efi-initrd"], base+"-efi-initrd.iso", kernel, initrd, cmdline, arch) if err != nil { - return fmt.Errorf("Error writing iso-efi-initrd output: %v", err) + return fmt.Errorf("error writing iso-efi-initrd output: %v", err) } return nil }, "raw-bios": func(base string, image io.Reader, size int, arch string) error { kernel, initrd, cmdline, _, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } // TODO: Handle ucode err = outputImg(outputImages["raw-bios"], base+"-bios.img", kernel, initrd, cmdline, arch) if err != nil { - return fmt.Errorf("Error writing raw-bios output: %v", err) + return fmt.Errorf("error writing raw-bios output: %v", err) } return nil }, "raw-efi": func(base string, image io.Reader, size int, arch string) error { kernel, initrd, cmdline, _, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } err = outputImg(outputImages["raw-efi"], base+"-efi.img", kernel, initrd, cmdline, arch) if err != nil { - return fmt.Errorf("Error writing raw-efi output: %v", err) + return fmt.Errorf("error writing raw-efi output: %v", err) } return nil }, "kernel+squashfs": func(base string, image io.Reader, size int, arch string) error { err := outputKernelSquashFS(outputImages["squashfs"], base, image, arch) if err != nil { - return fmt.Errorf("Error writing kernel+squashfs output: %v", err) + return fmt.Errorf("error writing kernel+squashfs output: %v", err) } return nil }, "kernel+iso": func(base string, image io.Reader, size int, arch string) error { err := outputKernelISO(outputImages["iso"], base, image, arch) if err != nil { - return fmt.Errorf("Error writing kernel+iso output: %v", err) + return fmt.Errorf("error writing kernel+iso output: %v", err) } return nil }, @@ -114,33 +114,33 @@ var outFuns = map[string]func(base string, ir io.Reader, size int, arch string) log.Infof(" %s", filename) kernel, initrd, cmdline, _, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } err = outputLinuxKit("raw", filename, kernel, initrd, cmdline, size) if err != nil { - return fmt.Errorf("Error writing raw output: %v", err) + return fmt.Errorf("error writing raw output: %v", err) } return nil }, "gcp": func(base string, image io.Reader, size int, arch string) error { kernel, initrd, cmdline, _, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } err = outputImg(outputImages["gcp"], base+".img.tar.gz", kernel, initrd, cmdline, arch) if err != nil { - return fmt.Errorf("Error writing gcp output: %v", err) + return fmt.Errorf("error writing gcp output: %v", err) } return nil }, "qcow2-efi": func(base string, image io.Reader, size int, arch string) error { kernel, initrd, cmdline, _, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } err = outputImg(outputImages["qcow2-efi"], base+"-efi.qcow2", kernel, initrd, cmdline, arch) if err != nil { - return fmt.Errorf("Error writing qcow2 EFI output: %v", err) + return fmt.Errorf("error writing qcow2 EFI output: %v", err) } return nil }, @@ -149,55 +149,55 @@ var outFuns = map[string]func(base string, ir io.Reader, size int, arch string) log.Infof(" %s", filename) kernel, initrd, cmdline, _, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } // TODO: Handle ucode err = outputLinuxKit("qcow2", filename, kernel, initrd, cmdline, size) if err != nil { - return fmt.Errorf("Error writing qcow2 output: %v", err) + return fmt.Errorf("error writing qcow2 output: %v", err) } return nil }, "vhd": func(base string, image io.Reader, size int, arch string) error { kernel, initrd, cmdline, _, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } err = outputImg(outputImages["vhd"], base+".vhd", kernel, initrd, cmdline, arch) if err != nil { - return fmt.Errorf("Error writing vhd output: %v", err) + return fmt.Errorf("error writing vhd output: %v", err) } return nil }, "dynamic-vhd": func(base string, image io.Reader, size int, arch string) error { kernel, initrd, cmdline, _, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } err = outputImg(outputImages["dynamic-vhd"], base+".vhd", kernel, initrd, cmdline, arch) if err != nil { - return fmt.Errorf("Error writing vhd output: %v", err) + return fmt.Errorf("error writing vhd output: %v", err) } return nil }, "vmdk": func(base string, image io.Reader, size int, arch string) error { kernel, initrd, cmdline, _, err := tarToInitrd(image) if err != nil { - return fmt.Errorf("Error converting to initrd: %v", err) + return fmt.Errorf("error converting to initrd: %v", err) } err = outputImg(outputImages["vmdk"], base+".vmdk", kernel, initrd, cmdline, arch) if err != nil { - return fmt.Errorf("Error writing vmdk output: %v", err) + return fmt.Errorf("error writing vmdk output: %v", err) } return nil }, "rpi3": func(base string, image io.Reader, size int, arch string) error { if runtime.GOARCH != "arm64" { - return fmt.Errorf("Raspberry Pi output currently only supported on arm64") + return fmt.Errorf("raspberry Pi output currently only supported on arm64") } err := outputRPi3(outputImages["rpi3"], base+".tar", image) if err != nil { - return fmt.Errorf("Error writing rpi3 output: %v", err) + return fmt.Errorf("error writing rpi3 output: %v", err) } return nil }, @@ -240,11 +240,11 @@ func ValidateFormats(formats []string, cache string) error { for _, o := range formats { f := outFuns[o] if f == nil { - return fmt.Errorf("Unknown format type %s", o) + return fmt.Errorf("unknown format type %s", o) } err := ensurePrereq(o, cache) if err != nil { - return fmt.Errorf("Failed to set up format type %s: %v", o, err) + return fmt.Errorf("failed to set up format type %s: %v", o, err) } } @@ -264,7 +264,9 @@ func Formats(base string, image string, formats []string, size int, arch, cache if err != nil { return err } - defer ir.Close() + defer func() { + _ = ir.Close() + }() f := outFuns[o] if err := f(base, ir, size, arch); err != nil { return err @@ -282,7 +284,7 @@ func tarToInitrd(r io.Reader) ([]byte, []byte, string, []byte, error) { if err != nil { return []byte{}, []byte{}, "", []byte{}, err } - iw.Close() + _ = iw.Close() return kernel, w.Bytes(), cmdline, ucode, nil } @@ -348,7 +350,9 @@ func outputImg(image, filename string, kernel []byte, initrd []byte, cmdline, ar if err != nil { return err } - defer output.Close() + defer func() { + _ = output.Close() + }() march, err := util.MArch(arch) if err != nil { return err @@ -363,7 +367,9 @@ func outputIso(image, filename string, filesystem io.Reader, arch string) error if err != nil { return err } - defer output.Close() + defer func() { + _ = output.Close() + }() march, err := util.MArch(arch) if err != nil { return err @@ -378,7 +384,9 @@ func outputRPi3(image, filename string, filesystem io.Reader) error { if err != nil { return err } - defer output.Close() + defer func() { + _ = output.Close() + }() return dockerRun(filesystem, output, image, nil) } @@ -395,7 +403,9 @@ func outputKernelInitrd(base string, kernel []byte, initrd []byte, cmdline strin if err != nil { return err } - defer f.Close() + defer func() { + _ = f.Close() + }() if _, err = f.Write(initrd); err != nil { return err } @@ -426,7 +436,9 @@ func outputKernelInitrdTarball(base string, kernel []byte, initrd []byte, cmdlin if err != nil { return err } - defer f.Close() + defer func() { + _ = f.Close() + }() tw := tar.NewWriter(f) if len(kernel) != 0 { hdr := &tar.Header{ @@ -535,13 +547,13 @@ func outputKernelSquashFS(image, base string, filesystem io.Reader, arch string) } } } - rootfs.Close() + _ = rootfs.Close() output, err := os.Create(base + "-squashfs.img") if err != nil { return err } - defer output.Close() + defer func() { _ = output.Close() }() march, err := util.MArch(arch) if err != nil { @@ -594,13 +606,13 @@ func outputKernelISO(image, base string, filesystem io.Reader, arch string) erro } } } - rootfs.Close() + _ = rootfs.Close() output, err := os.Create(base + ".iso") if err != nil { return err } - defer output.Close() + defer func() { _ = output.Close() }() march, err := util.MArch(arch) if err != nil { diff --git a/src/cmd/linuxkit/moby/config.go b/src/cmd/linuxkit/moby/config.go index 4f73e9fe7..0160f329f 100644 --- a/src/cmd/linuxkit/moby/config.go +++ b/src/cmd/linuxkit/moby/config.go @@ -806,9 +806,9 @@ func IDNumeric(v interface{}, idMap map[string]uint32) (uint32, error) { return v, nil } } - return 0, fmt.Errorf("Cannot find id: %s", id) + return 0, fmt.Errorf("cannot find id: %s", id) default: - return 0, fmt.Errorf("Bad type for uid or gid") + return 0, fmt.Errorf("bad type for uid or gid") } } @@ -866,7 +866,7 @@ func ConfigToOCI(yaml *Image, config imagespec.ImageConfig, idMap map[string]uin for _, t := range assignStrings(label.Tmpfs, yaml.Tmpfs) { parts := strings.Split(t, ":") if len(parts) > 2 { - return oci, runtime, fmt.Errorf("Cannot parse tmpfs, too many ':': %s", t) + return oci, runtime, fmt.Errorf("cannot parse tmpfs, too many ':': %s", t) } dest := parts[0] var opts []string @@ -878,10 +878,10 @@ func ConfigToOCI(yaml *Image, config imagespec.ImageConfig, idMap map[string]uin for _, b := range assignStrings(mergeStrings(label.Binds, yaml.BindsAdd), yaml.Binds) { parts := strings.Split(b, ":") if len(parts) < 2 { - return oci, runtime, fmt.Errorf("Cannot parse bind, missing ':': %s", b) + return oci, runtime, fmt.Errorf("cannot parse bind, missing ':': %s", b) } if len(parts) > 3 { - return oci, runtime, fmt.Errorf("Cannot parse bind, too many ':': %s", b) + return oci, runtime, fmt.Errorf("cannot parse bind, too many ':': %s", b) } src := parts[0] dest := parts[1] @@ -907,7 +907,7 @@ func ConfigToOCI(yaml *Image, config imagespec.ImageConfig, idMap map[string]uin tp = "tmpfs" } if tp == "" { - return oci, runtime, fmt.Errorf("Mount for destination %s is missing type", dest) + return oci, runtime, fmt.Errorf("mount for destination %s is missing type", dest) } if src == "" { // usually sane, eg proc, tmpfs etc @@ -917,7 +917,7 @@ func ConfigToOCI(yaml *Image, config imagespec.ImageConfig, idMap map[string]uin dest = defaultMountpoint(tp) } if dest == "" { - return oci, runtime, fmt.Errorf("Mount type %s is missing destination", tp) + return oci, runtime, fmt.Errorf("mount type %s is missing destination", tp) } mounts[dest] = specs.Mount{Destination: dest, Type: tp, Source: src, Options: opts} } @@ -1042,7 +1042,7 @@ func ConfigToOCI(yaml *Image, config imagespec.ImageConfig, idMap map[string]uin var err error soft, err = strconv.ParseUint(softString, 10, 64) if err != nil { - return oci, runtime, fmt.Errorf("Cannot parse %s as uint64: %v", softString, err) + return oci, runtime, fmt.Errorf("cannot parse %s as uint64: %v", softString, err) } } hardString := strings.TrimSpace(rs[2]) @@ -1052,7 +1052,7 @@ func ConfigToOCI(yaml *Image, config imagespec.ImageConfig, idMap map[string]uin var err error hard, err = strconv.ParseUint(hardString, 10, 64) if err != nil { - return oci, runtime, fmt.Errorf("Cannot parse %s as uint64: %v", hardString, err) + return oci, runtime, fmt.Errorf("cannot parse %s as uint64: %v", hardString, err) } } switch limit { @@ -1075,10 +1075,10 @@ func ConfigToOCI(yaml *Image, config imagespec.ImageConfig, idMap map[string]uin "RLIMIT_RTTIME": rlimits = append(rlimits, specs.POSIXRlimit{Type: limit, Soft: soft, Hard: hard}) default: - return oci, runtime, fmt.Errorf("Unknown limit: %s", origLimit) + return oci, runtime, fmt.Errorf("unknown limit: %s", origLimit) } default: - return oci, runtime, fmt.Errorf("Cannot parse rlimit: %s", rlimitsString) + return oci, runtime, fmt.Errorf("cannot parse rlimit: %s", rlimitsString) } } @@ -1156,7 +1156,7 @@ func ConfigToOCI(yaml *Image, config imagespec.ImageConfig, idMap map[string]uin } mode, err := strconv.ParseInt(device.Mode, 8, 32) if err != nil { - return oci, runtime, fmt.Errorf("Cannot parse device mode as octal value: %v", err) + return oci, runtime, fmt.Errorf("cannot parse device mode as octal value: %v", err) } fileMode := os.FileMode(mode) linuxDevice := specs.LinuxDevice{ diff --git a/src/cmd/linuxkit/pkg_build.go b/src/cmd/linuxkit/pkg_build.go index e6f87d391..7e5f0eb82 100644 --- a/src/cmd/linuxkit/pkg_build.go +++ b/src/cmd/linuxkit/pkg_build.go @@ -106,7 +106,7 @@ func addCmdRunPkgBuildPush(cmd *cobra.Command, withPush bool) *cobra.Command { if err != nil { return fmt.Errorf("error opening build args file %s: %w", filename, err) } - defer f.Close() + defer func() { _ = f.Close() }() scanner := bufio.NewScanner(f) for scanner.Scan() { buildArgs = append(buildArgs, scanner.Text()) @@ -123,7 +123,7 @@ func addCmdRunPkgBuildPush(cmd *cobra.Command, withPush bool) *cobra.Command { for _, platform := range strings.Split(skipPlatforms, ",") { parts := strings.SplitN(platform, "/", 2) if len(parts) != 2 || parts[0] == "" || parts[0] != "linux" || parts[1] == "" { - return fmt.Errorf("invalid target platform specification '%s'\n", platform) + return fmt.Errorf("invalid target platform specification '%s'", platform) } skipPlatformsMap[strings.Trim(parts[1], " ")] = true } diff --git a/src/cmd/linuxkit/pkg_builder.go b/src/cmd/linuxkit/pkg_builder.go index 5eb7f3f09..a37971585 100644 --- a/src/cmd/linuxkit/pkg_builder.go +++ b/src/cmd/linuxkit/pkg_builder.go @@ -41,11 +41,11 @@ func pkgBuilderCmd() *cobra.Command { switch command { case "du": if err := pkglib.DiskUsage(buildersMap, builderImage, platformsToClean, verbose); err != nil { - return fmt.Errorf("Unable to print disk usage of builder: %w", err) + return fmt.Errorf("unable to print disk usage of builder: %w", err) } case "prune": if err := pkglib.PruneBuilder(buildersMap, builderImage, platformsToClean, verbose); err != nil { - return fmt.Errorf("Unable to prune builder: %w", err) + return fmt.Errorf("unable to prune builder: %w", err) } default: return fmt.Errorf("unexpected command %s", command) diff --git a/src/cmd/linuxkit/pkglib/build.go b/src/cmd/linuxkit/pkglib/build.go index 1a623c2d4..dc1561eb9 100644 --- a/src/cmd/linuxkit/pkglib/build.go +++ b/src/cmd/linuxkit/pkglib/build.go @@ -16,7 +16,6 @@ import ( registry "github.com/google/go-containerregistry/pkg/v1" "github.com/linuxkit/linuxkit/src/cmd/linuxkit/cache" "github.com/linuxkit/linuxkit/src/cmd/linuxkit/spec" - lktspec "github.com/linuxkit/linuxkit/src/cmd/linuxkit/spec" "github.com/linuxkit/linuxkit/src/cmd/linuxkit/util" "github.com/linuxkit/linuxkit/src/cmd/linuxkit/version" imagespec "github.com/opencontainers/image-spec/specs-go/v1" @@ -34,7 +33,7 @@ type buildOpts struct { manifest bool targetDocker bool cacheDir string - cacheProvider lktspec.CacheProvider + cacheProvider spec.CacheProvider platforms []imagespec.Platform builders map[string]string runner dockerRunner @@ -142,7 +141,7 @@ func WithBuildDocker(runner dockerRunner) BuildOpt { } // WithBuildCacheProvider provides a cacheProvider to use. If nil, defaults to the one shipped with linuxkit -func WithBuildCacheProvider(c lktspec.CacheProvider) BuildOpt { +func WithBuildCacheProvider(c spec.CacheProvider) BuildOpt { return func(bo *buildOpts) error { bo.cacheProvider = c return nil @@ -316,37 +315,37 @@ func (p Pkg) Build(bos ...BuildOpt) error { platformsToBuild = nil default: // check local cache, fallback to check registry / pull image from registry, fallback to build - fmt.Fprintf(writer, "checking for %s in local cache...\n", ref) + _, _ = fmt.Fprintf(writer, "checking for %s in local cache...\n", ref) for _, platform := range bo.platforms { exists, err := c.ImageInCache(&ref, "", platform.Architecture) switch { case err == nil && exists: - fmt.Fprintf(writer, "found %s in local cache, skipping build\n", ref) + _, _ = fmt.Fprintf(writer, "found %s in local cache, skipping build\n", ref) imageInLocalCache = true continue case bo.pull: // need to pull the image from the registry, else build - fmt.Fprintf(writer, "%s %s not found in local cache, trying to pull\n", ref, platform.Architecture) + _, _ = fmt.Fprintf(writer, "%s %s not found in local cache, trying to pull\n", ref, platform.Architecture) if err := c.ImagePull(&ref, []imagespec.Platform{platform}, false); err == nil { - fmt.Fprintf(writer, "%s pulled\n", ref) + _, _ = fmt.Fprintf(writer, "%s pulled\n", ref) // successfully pulled, no need to build, continue with next platform continue } - fmt.Fprintf(writer, "%s not found, will build: %s\n", ref, err) + _, _ = fmt.Fprintf(writer, "%s not found, will build: %s\n", ref, err) platformsToBuild = append(platformsToBuild, platform) default: // do not pull, just check if it exists in a registry - fmt.Fprintf(writer, "%s %s not found in local cache, checking registry\n", ref, platform.Architecture) + _, _ = fmt.Fprintf(writer, "%s %s not found in local cache, checking registry\n", ref, platform.Architecture) exists, err := c.ImageInRegistry(&ref, "", platform.Architecture) if err != nil { return fmt.Errorf("error checking remote registry for %s: %v", ref, err) } if exists { - fmt.Fprintf(writer, "%s %s found on registry\n", ref, platform.Architecture) + _, _ = fmt.Fprintf(writer, "%s %s found on registry\n", ref, platform.Architecture) continue } - fmt.Fprintf(writer, "%s %s not found, will build\n", ref, platform.Architecture) + _, _ = fmt.Fprintf(writer, "%s %s not found, will build\n", ref, platform.Architecture) platformsToBuild = append(platformsToBuild, platform) } } @@ -357,7 +356,7 @@ func (p Pkg) Build(bos ...BuildOpt) error { for _, platform := range platformsToBuild { arches = append(arches, platform.Architecture) } - fmt.Fprintf(writer, "building %s for arches: %s\n", ref, strings.Join(arches, ",")) + _, _ = fmt.Fprintf(writer, "building %s for arches: %s\n", ref, strings.Join(arches, ",")) var ( imageBuildOpts = spec.ImageBuildOptions{ Labels: map[string]string{}, @@ -508,7 +507,7 @@ func (p Pkg) Build(bos ...BuildOpt) error { } if !bo.push { - fmt.Fprintf(writer, "Build complete, not pushing, all done.\n") + _, _ = fmt.Fprintf(writer, "Build complete, not pushing, all done.\n") return nil } @@ -533,7 +532,7 @@ func (p Pkg) Build(bos ...BuildOpt) error { } } if !imageInLocalCache { - fmt.Fprintf(writer, "No new platforms to push, skipping.\n") + _, _ = fmt.Fprintf(writer, "No new platforms to push, skipping.\n") return nil } } @@ -548,7 +547,7 @@ func (p Pkg) Build(bos ...BuildOpt) error { } if bo.release == "" { - fmt.Fprintf(writer, "Build and push complete, not releasing, all done.\n") + _, _ = fmt.Fprintf(writer, "Build and push complete, not releasing, all done.\n") return nil } @@ -585,7 +584,7 @@ func (p Pkg) Build(bos ...BuildOpt) error { } } - fmt.Fprintf(writer, "Build, push and release of %q complete, all done.\n", bo.release) + _, _ = fmt.Fprintf(writer, "Build, push and release of %q complete, all done.\n", bo.release) return nil } @@ -603,14 +602,14 @@ func (p Pkg) Build(bos ...BuildOpt) error { // C - manifest, saved in cache as is, referenced by the index (E), and returned as a descriptor // D - attestations (if any), saved in cache as is, referenced by the index (E), and returned as a descriptor // E - index, saved in cache as is, stored in cache as tag "image:tag-arch", *not* returned as a descriptor -func (p Pkg) buildArch(ctx context.Context, d dockerRunner, c lktspec.CacheProvider, builderImage, arch string, restart bool, writer io.Writer, bo buildOpts, imageBuildOpts spec.ImageBuildOptions) ([]registry.Descriptor, error) { +func (p Pkg) buildArch(ctx context.Context, d dockerRunner, c spec.CacheProvider, builderImage, arch string, restart bool, writer io.Writer, bo buildOpts, imageBuildOpts spec.ImageBuildOptions) ([]registry.Descriptor, error) { var ( tagArch string tag = p.FullTag() indexDesc []registry.Descriptor ) tagArch = tag + "-" + arch - fmt.Fprintf(writer, "Building for arch %s as %s\n", arch, tagArch) + _, _ = fmt.Fprintf(writer, "Building for arch %s as %s\n", arch, tagArch) if !bo.force { ref, err := reference.Parse(p.FullTag()) @@ -618,14 +617,14 @@ func (p Pkg) buildArch(ctx context.Context, d dockerRunner, c lktspec.CacheProvi return nil, fmt.Errorf("could not resolve references for image %s: %v", p.Tag(), err) } if err := c.ImagePull(&ref, []imagespec.Platform{{Architecture: arch, OS: "linux"}}, false); err == nil { - fmt.Fprintf(writer, "image already found %s for arch %s", ref, arch) + _, _ = fmt.Fprintf(writer, "image already found %s for arch %s", ref, arch) desc, err := c.FindDescriptor(&ref) if err != nil { return nil, fmt.Errorf("could not find root descriptor for %s: %v", ref, err) } return []registry.Descriptor{*desc}, nil } - fmt.Fprintf(writer, "No image pulled for arch %s, continuing with build\n", arch) + _, _ = fmt.Fprintf(writer, "No image pulled for arch %s, continuing with build\n", arch) } if err := p.dockerDepends.Do(d); err != nil { @@ -641,7 +640,7 @@ func (p Pkg) buildArch(ctx context.Context, d dockerRunner, c lktspec.CacheProvi eg errgroup.Group stdoutCloser = func() { if stdout != nil { - stdout.Close() + _ = stdout.Close() } } ) @@ -654,11 +653,11 @@ func (p Pkg) buildArch(ctx context.Context, d dockerRunner, c lktspec.CacheProvi d, err := c.ImageLoad(piper) // send the error down the channel if err != nil { - fmt.Fprintf(stdout, "cache.ImageLoad goroutine ended with error: %v\n", err) + _, _ = fmt.Fprintf(stdout, "cache.ImageLoad goroutine ended with error: %v\n", err) } else { indexDesc = d } - piper.Close() + _ = piper.Close() return err }) @@ -704,7 +703,9 @@ func (p Pkg) buildArch(ctx context.Context, d dockerRunner, c lktspec.CacheProvi if err != nil { return nil, fmt.Errorf("could not get content for index descriptor: %v", err) } - defer r.Close() + defer func() { + _ = r.Close() + }() dec := json.NewDecoder(r) var im registry.IndexManifest if err := dec.Decode(&im); err != nil { @@ -728,8 +729,8 @@ func (c *buildCtx) Reader() io.ReadCloser { go func() { defer func() { - tw.Close() - w.Close() + _ = tw.Close() + _ = w.Close() }() for _, s := range c.sources { log.Debugf("Adding to build context: %s -> %s", s.src, s.dst) @@ -769,7 +770,9 @@ func (c *buildCtx) Reader() io.ReadCloser { if err != nil { return fmt.Errorf("ctx: Open %s: %v", p, err) } - defer f.Close() + defer func() { + _ = f.Close() + }() _, err = io.Copy(tw, f) if err != nil { diff --git a/src/cmd/linuxkit/pkglib/build_test.go b/src/cmd/linuxkit/pkglib/build_test.go index 4cd439f6e..479b56771 100644 --- a/src/cmd/linuxkit/pkglib/build_test.go +++ b/src/cmd/linuxkit/pkglib/build_test.go @@ -16,11 +16,9 @@ import ( "github.com/containerd/containerd/v2/core/content" "github.com/containerd/containerd/v2/core/images" "github.com/containerd/containerd/v2/pkg/reference" - registry "github.com/google/go-containerregistry/pkg/v1" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/types" "github.com/linuxkit/linuxkit/src/cmd/linuxkit/spec" - lktspec "github.com/linuxkit/linuxkit/src/cmd/linuxkit/spec" buildkitClient "github.com/moby/buildkit/client" imagespec "github.com/opencontainers/image-spec/specs-go/v1" ) @@ -58,7 +56,7 @@ func (d *dockerMocker) contextSupportCheck() error { func (d *dockerMocker) builder(_ context.Context, _, _, _ string, _ bool) (*buildkitClient.Client, error) { return nil, fmt.Errorf("not implemented") } -func (d *dockerMocker) build(ctx context.Context, tag, pkg, dockerContext, builderImage, platform string, builderRestart bool, c lktspec.CacheProvider, r io.Reader, stdout io.Writer, sbomScan bool, sbomScannerImage, progress string, imageBuildOpts spec.ImageBuildOptions) error { +func (d *dockerMocker) build(ctx context.Context, tag, pkg, dockerContext, builderImage, platform string, builderRestart bool, c spec.CacheProvider, r io.Reader, stdout io.Writer, sbomScan bool, sbomScannerImage, progress string, imageBuildOpts spec.ImageBuildOptions) error { if !d.enableBuild { return errors.New("build disabled") } @@ -71,7 +69,9 @@ func (d *dockerMocker) build(ctx context.Context, tag, pkg, dockerContext, build // an index blob (points to the manifest) // index.json (points to the index) tw := tar.NewWriter(stdout) - defer tw.Close() + defer func() { + _ = tw.Close() + }() buf := make([]byte, 128) var ( @@ -230,7 +230,7 @@ func (d *dockerMocker) pull(img string) (bool, error) { return false, errors.New("failed to pull") } -var _ lktspec.CacheProvider = &cacheMocker{} +var _ spec.CacheProvider = &cacheMocker{} type cacheMocker struct { enablePush bool @@ -238,7 +238,7 @@ type cacheMocker struct { enableImagePull bool enableImageLoad bool enableIndexWrite bool - images map[string][]registry.Descriptor + images map[string][]v1.Descriptor hashes map[string][]byte } @@ -280,14 +280,14 @@ func (c *cacheMocker) ImageInRegistry(ref *reference.Spec, trustedRef, architect return false, nil } -func (c *cacheMocker) ImageLoad(r io.Reader) ([]registry.Descriptor, error) { +func (c *cacheMocker) ImageLoad(r io.Reader) ([]v1.Descriptor, error) { if !c.enableImageLoad { return nil, errors.New("ImageLoad disabled") } return c.imageWriteStream(r) } -func (c *cacheMocker) imageWriteStream(r io.Reader) ([]registry.Descriptor, error) { +func (c *cacheMocker) imageWriteStream(r io.Reader) ([]v1.Descriptor, error) { var ( image string size int64 @@ -352,7 +352,7 @@ func (c *cacheMocker) imageWriteStream(r io.Reader) ([]registry.Descriptor, erro } } - desc := registry.Descriptor{ + desc := v1.Descriptor{ MediaType: types.OCIManifestSchema1, Size: size, Digest: hash, @@ -361,15 +361,15 @@ func (c *cacheMocker) imageWriteStream(r io.Reader) ([]registry.Descriptor, erro }, } c.appendImage(image, desc) - return []registry.Descriptor{desc}, nil + return []v1.Descriptor{desc}, nil } -func (c *cacheMocker) IndexWrite(ref *reference.Spec, descriptors ...registry.Descriptor) error { +func (c *cacheMocker) IndexWrite(ref *reference.Spec, descriptors ...v1.Descriptor) error { if !c.enableIndexWrite { return errors.New("disabled") } image := ref.String() - im := registry.IndexManifest{ + im := v1.IndexManifest{ MediaType: types.OCIImageIndex, Manifests: descriptors, SchemaVersion: 2, @@ -380,12 +380,12 @@ func (c *cacheMocker) IndexWrite(ref *reference.Spec, descriptors ...registry.De if err != nil { return fmt.Errorf("unable to marshal new index to json: %v", err) } - hash, size, err := registry.SHA256(bytes.NewReader(b)) + hash, size, err := v1.SHA256(bytes.NewReader(b)) if err != nil { return fmt.Errorf("error calculating hash of index json: %v", err) } c.assignHash(hash.String(), b) - desc := registry.Descriptor{ + desc := v1.Descriptor{ MediaType: types.OCIImageIndex, Size: size, Digest: hash, @@ -407,15 +407,15 @@ func (c *cacheMocker) Push(name, remoteName string, withManifest, override bool) return nil } -func (c *cacheMocker) DescriptorWrite(ref *reference.Spec, desc registry.Descriptor) error { +func (c *cacheMocker) DescriptorWrite(ref *reference.Spec, desc v1.Descriptor) error { if !c.enabledDescriptorWrite { return errors.New("descriptor disabled") } var ( image = ref.String() - im = registry.IndexManifest{ + im = v1.IndexManifest{ MediaType: types.OCIImageIndex, - Manifests: []registry.Descriptor{desc}, + Manifests: []v1.Descriptor{desc}, SchemaVersion: 2, } ) @@ -424,12 +424,12 @@ func (c *cacheMocker) DescriptorWrite(ref *reference.Spec, desc registry.Descrip if err != nil { return fmt.Errorf("unable to marshal new index to json: %v", err) } - hash, size, err := registry.SHA256(bytes.NewReader(b)) + hash, size, err := v1.SHA256(bytes.NewReader(b)) if err != nil { return fmt.Errorf("error calculating hash of index json: %v", err) } c.assignHash(hash.String(), b) - root := registry.Descriptor{ + root := v1.Descriptor{ MediaType: types.OCIImageIndex, Size: size, Digest: hash, @@ -441,14 +441,14 @@ func (c *cacheMocker) DescriptorWrite(ref *reference.Spec, desc registry.Descrip return nil } -func (c *cacheMocker) FindDescriptor(ref *reference.Spec) (*registry.Descriptor, error) { +func (c *cacheMocker) FindDescriptor(ref *reference.Spec) (*v1.Descriptor, error) { name := ref.String() if desc, ok := c.images[name]; ok && len(desc) > 0 { return &desc[0], nil } return nil, fmt.Errorf("not found %s", name) } -func (c *cacheMocker) NewSource(ref *reference.Spec, platform *imagespec.Platform, descriptor *registry.Descriptor) lktspec.ImageSource { +func (c *cacheMocker) NewSource(ref *reference.Spec, platform *imagespec.Platform, descriptor *v1.Descriptor) spec.ImageSource { return cacheMockerSource{c, ref, platform, descriptor} } func (c *cacheMocker) assignHash(hash string, b []byte) { @@ -457,9 +457,9 @@ func (c *cacheMocker) assignHash(hash string, b []byte) { } c.hashes[hash] = b } -func (c *cacheMocker) appendImage(image string, root registry.Descriptor) { +func (c *cacheMocker) appendImage(image string, root v1.Descriptor) { if c.images == nil { - c.images = map[string][]registry.Descriptor{} + c.images = map[string][]v1.Descriptor{} } c.images[image] = append(c.images[image], root) } @@ -481,7 +481,7 @@ type cacheMockerSource struct { c *cacheMocker ref *reference.Spec platform *imagespec.Platform - descriptor *registry.Descriptor + descriptor *v1.Descriptor } func (c cacheMockerSource) Config() (imagespec.ImageConfig, error) { @@ -508,7 +508,7 @@ func (c cacheMockerSource) OCITarReader(overrideName string) (io.ReadCloser, err _, _ = rand.Read(b) return io.NopCloser(bytes.NewReader(b)), nil } -func (c cacheMockerSource) Descriptor() *registry.Descriptor { +func (c cacheMockerSource) Descriptor() *v1.Descriptor { return c.descriptor } func (c cacheMockerSource) SBoMs() ([]io.ReadCloser, error) { @@ -529,7 +529,7 @@ func TestBuild(t *testing.T) { err string }{ {"invalid tag", Pkg{image: "docker.io/foo/bar:abc:def:ghi"}, nil, nil, &dockerMocker{}, &cacheMocker{}, "could not resolve references"}, - {"not at head", Pkg{org: "foo", image: "bar", hash: "abc", arches: []string{"amd64"}, commitHash: "foo"}, nil, []string{"amd64"}, &dockerMocker{supportContexts: false}, &cacheMocker{}, "Cannot build from commit hash != HEAD"}, + {"not at head", Pkg{org: "foo", image: "bar", hash: "abc", arches: []string{"amd64"}, commitHash: "foo"}, nil, []string{"amd64"}, &dockerMocker{supportContexts: false}, &cacheMocker{}, "cannot build from commit hash != HEAD"}, {"no build cache", Pkg{org: "foo", image: "bar", hash: "abc", arches: []string{"amd64"}, commitHash: "HEAD"}, nil, []string{"amd64"}, &dockerMocker{supportContexts: false}, &cacheMocker{}, "must provide linuxkit build cache"}, {"unsupported contexts", Pkg{org: "foo", image: "bar", hash: "abc", arches: []string{"amd64"}, commitHash: "HEAD"}, []BuildOpt{WithBuildCacheDir(cacheDir)}, []string{"amd64"}, &dockerMocker{supportContexts: false}, &cacheMocker{}, "contexts not supported, check docker version"}, {"load docker without local platform", Pkg{org: "foo", image: "bar", hash: "abc", arches: []string{"amd64", "arm64"}, commitHash: "HEAD"}, []BuildOpt{WithBuildCacheDir(cacheDir), WithBuildTargetDockerCache()}, []string{"amd64", "arm64"}, &dockerMocker{supportContexts: true, enableBuild: true, images: map[string][]byte{}, enableTag: true}, &cacheMocker{enableImagePull: false, enableImageLoad: true, enableIndexWrite: true}, ""}, diff --git a/src/cmd/linuxkit/pkglib/depends.go b/src/cmd/linuxkit/pkglib/depends.go index 34fbaff77..18df11669 100644 --- a/src/cmd/linuxkit/pkglib/depends.go +++ b/src/cmd/linuxkit/pkglib/depends.go @@ -40,7 +40,9 @@ func newDockerDepends(pkgPath string, pi *pkgInfo) (dockerDepends, error) { if err != nil { return dockerDepends{}, err } - defer f.Close() + defer func() { + _ = f.Close() + }() s := bufio.NewScanner(f) for s.Scan() { diff --git a/src/cmd/linuxkit/pkglib/docker.go b/src/cmd/linuxkit/pkglib/docker.go index aaa8cff7e..c88e85fe3 100644 --- a/src/cmd/linuxkit/pkglib/docker.go +++ b/src/cmd/linuxkit/pkglib/docker.go @@ -508,7 +508,7 @@ func (dr *dockerRunnerImpl) build(ctx context.Context, tag, pkg, dockerContext, if err != nil { return fmt.Errorf("error opening dockerfile %s: %v", dockerfileRef, err) } - defer f.Close() + defer func() { _ = f.Close() }() ast, err := parser.Parse(f) if err != nil { return fmt.Errorf("error parsing dockerfile from bytes into AST %s: %v", dockerfileRef, err) diff --git a/src/cmd/linuxkit/pkglib/git.go b/src/cmd/linuxkit/pkglib/git.go index 007bd956d..8d65ef802 100644 --- a/src/cmd/linuxkit/pkglib/git.go +++ b/src/cmd/linuxkit/pkglib/git.go @@ -150,12 +150,12 @@ func (g git) treeHash(pkg, commit string) (string, error) { } if out == "" { - return "", fmt.Errorf("Package %s is not in git", pkg) + return "", fmt.Errorf("package %s is not in git", pkg) } matches := treeHashRe.FindStringSubmatch(out) if len(matches) != 2 { - return "", fmt.Errorf("Unable to parse ls-tree output: %q", out) + return "", fmt.Errorf("unable to parse ls-tree output: %q", out) } return matches[1], nil diff --git a/src/cmd/linuxkit/pkglib/pkglib.go b/src/cmd/linuxkit/pkglib/pkglib.go index ca751f077..c34924d92 100644 --- a/src/cmd/linuxkit/pkglib/pkglib.go +++ b/src/cmd/linuxkit/pkglib/pkglib.go @@ -197,7 +197,7 @@ func NewFromConfig(cfg PkglibConfig, args ...string) ([]Pkg, error) { for _, source := range pi.ExtraSources { tmp := strings.Split(source, ":") if len(tmp) != 2 { - return nil, fmt.Errorf("Bad source format in %s", source) + return nil, fmt.Errorf("bad source format in %s", source) } srcPath := filepath.Clean(tmp[0]) // Should work with windows paths dstPath := path.Clean(tmp[1]) // 'path' here because this should be a Unix path @@ -211,7 +211,7 @@ func NewFromConfig(cfg PkglibConfig, args ...string) ([]Pkg, error) { return nil, err } if g == nil { - return nil, fmt.Errorf("Source %s not in a git repository", srcPath) + return nil, fmt.Errorf("source %s not in a git repository", srcPath) } h, err := g.treeHash(srcPath, cfg.HashCommit) if err != nil { @@ -308,10 +308,10 @@ func (p Pkg) Hash() string { // ReleaseTag returns the tag to use for a particular release of the package func (p Pkg) ReleaseTag(release string) (string, error) { if release == "" { - return "", fmt.Errorf("A release tag is required") + return "", fmt.Errorf("a release tag is required") } if p.dirty { - return "", fmt.Errorf("Cannot release a dirty package") + return "", fmt.Errorf("cannot release a dirty package") } tag := p.org + "/" + p.image + ":" + release return tag, nil @@ -358,7 +358,7 @@ func (p Pkg) archSupported(want string) bool { func (p Pkg) cleanForBuild() error { if p.commitHash != "HEAD" { - return fmt.Errorf("Cannot build from commit hash != HEAD") + return fmt.Errorf("cannot build from commit hash != HEAD") } return nil } diff --git a/src/cmd/linuxkit/pkglib/pkglib_test.go b/src/cmd/linuxkit/pkglib/pkglib_test.go index 628b1992f..a338872f5 100644 --- a/src/cmd/linuxkit/pkglib/pkglib_test.go +++ b/src/cmd/linuxkit/pkglib/pkglib_test.go @@ -34,7 +34,9 @@ func testGetBoolPkg(t *testing.T, fileKey, cfgKey string, fileSetting, cfgSettin require.NoError(t, err) tmpDir, err := os.MkdirTemp(tmpdirBase, "pkglib_test") require.NoError(t, err) - defer os.RemoveAll(tmpdirBase) + defer func() { + _ = os.RemoveAll(tmpdirBase) + }() var value string if fileSetting != nil { value = fmt.Sprintf("%s: %v\n", fileKey, *fileSetting) @@ -110,7 +112,9 @@ func testBadBuildYML(t *testing.T, build, expect string) { tmpDir := filepath.Join(cwd, t.Name()) err = os.Mkdir(tmpDir, 0755) require.NoError(t, err) - defer os.RemoveAll(tmpDir) + defer func() { + _ = os.RemoveAll(tmpDir) + }() pkgDir := dummyPackage(t, tmpDir, build) _, err = NewFromConfig(PkglibConfig{ diff --git a/src/cmd/linuxkit/pkglib/utils.go b/src/cmd/linuxkit/pkglib/utils.go index 80f226388..29c447b6b 100644 --- a/src/cmd/linuxkit/pkglib/utils.go +++ b/src/cmd/linuxkit/pkglib/utils.go @@ -15,7 +15,7 @@ import ( ) func printTableHeader(tw *tabwriter.Writer) { - fmt.Fprintln(tw, "ID\tRECLAIMABLE\tSIZE\tLAST ACCESSED") + _, _ = fmt.Fprintln(tw, "ID\tRECLAIMABLE\tSIZE\tLAST ACCESSED") } func printTableRow(tw *tabwriter.Writer, di *buildkitClient.UsageInfo) { @@ -31,7 +31,7 @@ func printTableRow(tw *tabwriter.Writer, di *buildkitClient.UsageInfo) { if di.LastUsedAt != nil { lastAccessed = units.HumanDuration(time.Since(*di.LastUsedAt)) + " ago" } - fmt.Fprintf(tw, "%-40s\t%-5v\t%-10s\t%s\n", id, !di.InUse, size, lastAccessed) + _, _ = fmt.Fprintf(tw, "%-40s\t%-5v\t%-10s\t%s\n", id, !di.InUse, size, lastAccessed) } func printSummary(tw *tabwriter.Writer, du []*buildkitClient.UsageInfo) { @@ -52,17 +52,17 @@ func printSummary(tw *tabwriter.Writer, du []*buildkitClient.UsageInfo) { } if shared > 0 { - fmt.Fprintf(tw, "Shared:\t%s\n", units.HumanSize(float64(shared))) - fmt.Fprintf(tw, "Private:\t%s\n", units.HumanSize(float64(total-shared))) + _, _ = fmt.Fprintf(tw, "Shared:\t%s\n", units.HumanSize(float64(shared))) + _, _ = fmt.Fprintf(tw, "Private:\t%s\n", units.HumanSize(float64(total-shared))) } - fmt.Fprintf(tw, "Reclaimable:\t%s\n", units.HumanSize(float64(reclaimable))) - fmt.Fprintf(tw, "Total:\t%s\n", units.HumanSize(float64(total))) - tw.Flush() + _, _ = fmt.Fprintf(tw, "Reclaimable:\t%s\n", units.HumanSize(float64(reclaimable))) + _, _ = fmt.Fprintf(tw, "Total:\t%s\n", units.HumanSize(float64(total))) + _ = tw.Flush() } func printKV(w io.Writer, k string, v interface{}) { - fmt.Fprintf(w, "%s:\t%v\n", k, v) + _, _ = fmt.Fprintf(w, "%s:\t%v\n", k, v) } func printVerbose(tw *tabwriter.Writer, du []*buildkitClient.UsageInfo) { @@ -87,10 +87,10 @@ func printVerbose(tw *tabwriter.Writer, du []*buildkitClient.UsageInfo) { printKV(tw, "Type", di.RecordType) } - fmt.Fprintf(tw, "\n") + _, _ = fmt.Fprintf(tw, "\n") } - tw.Flush() + _ = tw.Flush() } func getClientForPlatform(ctx context.Context, buildersMap map[string]string, builderImage, platform string) (*buildkitClient.Client, error) { diff --git a/src/cmd/linuxkit/push_aws.go b/src/cmd/linuxkit/push_aws.go index 9eda3093f..71f18f98c 100644 --- a/src/cmd/linuxkit/push_aws.go +++ b/src/cmd/linuxkit/push_aws.go @@ -48,7 +48,7 @@ func pushAWSCmd() *cobra.Command { } if !uefi && tpm { - return fmt.Errorf("Cannot use tpm without uefi mode") + return fmt.Errorf("cannot use tpm without uefi mode") } sess := session.Must(session.NewSession()) @@ -58,14 +58,14 @@ func pushAWSCmd() *cobra.Command { defer cancelFn() if bucket == "" { - return fmt.Errorf("Please provide the bucket to use") + return fmt.Errorf("please provide the bucket to use") } f, err := os.Open(path) if err != nil { - return fmt.Errorf("Error opening file: %v", err) + return fmt.Errorf("error opening file: %v", err) } - defer f.Close() + defer func() { _ = f.Close() }() if name == "" { name = strings.TrimSuffix(path, filepath.Ext(path)) @@ -74,7 +74,7 @@ func pushAWSCmd() *cobra.Command { fi, err := f.Stat() if err != nil { - return fmt.Errorf("Error reading file information: %v", err) + return fmt.Errorf("error reading file information: %v", err) } dst := name + filepath.Ext(path) @@ -89,7 +89,7 @@ func pushAWSCmd() *cobra.Command { _, err = storage.PutObjectWithContext(ctx, putParams) if err != nil { - return fmt.Errorf("Error uploading to S3: %v", err) + return fmt.Errorf("error uploading to S3: %v", err) } compute := ec2.New(sess) @@ -109,7 +109,7 @@ func pushAWSCmd() *cobra.Command { resp, err := compute.ImportSnapshot(importParams) if err != nil { - return fmt.Errorf("Error importing snapshot: %v", err) + return fmt.Errorf("error importing snapshot: %v", err) } var snapshotID *string @@ -122,10 +122,10 @@ func pushAWSCmd() *cobra.Command { log.Debugf("DescribeImportSnapshotTask:\n%v", describeParams) status, err := compute.DescribeImportSnapshotTasks(describeParams) if err != nil { - return fmt.Errorf("Error getting import snapshot status: %v", err) + return fmt.Errorf("error getting import snapshot status: %v", err) } if len(status.ImportSnapshotTasks) == 0 { - return fmt.Errorf("Unable to get import snapshot task status") + return fmt.Errorf("unable to get import snapshot task status") } if *status.ImportSnapshotTasks[0].SnapshotTaskDetail.Status != "completed" { progress := "0" @@ -174,7 +174,7 @@ func pushAWSCmd() *cobra.Command { log.Debugf("RegisterImage:\n%v", regParams) regResp, err := compute.RegisterImage(regParams) if err != nil { - return fmt.Errorf("Error registering the image: %s; %v", name, err) + return fmt.Errorf("error registering the image: %s; %v", name, err) } log.Infof("Created AMI: %s", *regResp.ImageId) return nil diff --git a/src/cmd/linuxkit/push_equinixmetal.go b/src/cmd/linuxkit/push_equinixmetal.go index 1a367ffbf..0b17856fc 100644 --- a/src/cmd/linuxkit/push_equinixmetal.go +++ b/src/cmd/linuxkit/push_equinixmetal.go @@ -51,11 +51,11 @@ func pushEquinixMetalCmd() *cobra.Command { baseURL := getStringValue(equinixmetalBaseURL, baseURLFlag, "") if baseURL == "" { - return fmt.Errorf("Need to specify a value for --base-url from where the kernel, initrd and iPXE script will be loaded from.") + return fmt.Errorf("need to specify a value for --base-url from where the kernel, initrd and iPXE script will be loaded from") } if dst == "" { - return fmt.Errorf("Need to specify the destination where to push to.") + return fmt.Errorf("need to specify the destination where to push to") } name := getStringValue(equinixmetalNameVar, nameFlag, prefix) @@ -70,7 +70,7 @@ func pushEquinixMetalCmd() *cobra.Command { // Read kernel command line var cmdline string if c, err := os.ReadFile(prefix + "-cmdline"); err != nil { - return fmt.Errorf("Cannot open cmdline file: %v", err) + return fmt.Errorf("cannot open cmdline file: %v", err) } else { cmdline = string(c) } @@ -80,13 +80,13 @@ func pushEquinixMetalCmd() *cobra.Command { // Parse the destination dst, err := url.Parse(dst) if err != nil { - return fmt.Errorf("Cannot parse destination: %v", err) + return fmt.Errorf("cannot parse destination: %v", err) } switch dst.Scheme { case "", "file": equinixmetalPushFile(dst, decompress, name, cmdline, ipxeScript) default: - return fmt.Errorf("Unknown destination format: %s", dst.Scheme) + return fmt.Errorf("unknown destination format: %s", dst.Scheme) } return nil }, @@ -129,7 +129,9 @@ func equinixmetalCopy(dst, src string, decompress bool) error { if err != nil { return err } - defer in.Close() + defer func() { + _ = in.Close() + }() var r io.Reader = in if decompress { @@ -144,7 +146,9 @@ func equinixmetalCopy(dst, src string, decompress bool) error { if err != nil { return err } - defer out.Close() + defer func() { + _ = out.Close() + }() _, err = io.Copy(out, r) if err != nil { diff --git a/src/cmd/linuxkit/push_gcp.go b/src/cmd/linuxkit/push_gcp.go index 0579a0cf8..0e21ed781 100644 --- a/src/cmd/linuxkit/push_gcp.go +++ b/src/cmd/linuxkit/push_gcp.go @@ -45,20 +45,20 @@ func pushGCPCmd() *cobra.Command { client, err := NewGCPClient(keys, project) if err != nil { - return fmt.Errorf("Unable to connect to GCP: %v", err) + return fmt.Errorf("unable to connect to GCP: %v", err) } if bucket == "" { - return fmt.Errorf("Please specify the bucket to use") + return fmt.Errorf("please specify the bucket to use") } err = client.UploadFile(path, name+suffix, bucket, public) if err != nil { - return fmt.Errorf("Error copying to Google Storage: %v", err) + return fmt.Errorf("error copying to Google Storage: %v", err) } err = client.CreateImage(name, "https://storage.googleapis.com/"+bucket+"/"+name+suffix, family, nestedVirt, uefi, true) if err != nil { - return fmt.Errorf("Error creating Google Compute Image: %v", err) + return fmt.Errorf("error creating Google Compute Image: %v", err) } return nil diff --git a/src/cmd/linuxkit/push_openstack.go b/src/cmd/linuxkit/push_openstack.go index de4406ff5..43f362aa3 100644 --- a/src/cmd/linuxkit/push_openstack.go +++ b/src/cmd/linuxkit/push_openstack.go @@ -21,7 +21,7 @@ func createOpenStackImage(filePath string, imageName string, client *gophercloud formats := []string{"ami", "vhd", "vhdx", "vmdk", "raw", "qcow2", "iso"} // Find extension of the filename and remove the leading stop - fileExtension := strings.Replace(path.Ext(filePath), ".", "", -1) + fileExtension := strings.ReplaceAll(path.Ext(filePath), ".", "") fileName := strings.TrimSuffix(path.Base(filePath), filepath.Ext(filePath)) // Check for Supported extension var supportedExtension bool @@ -54,7 +54,7 @@ func createOpenStackImage(filePath string, imageName string, client *gophercloud if err != nil { log.Fatalf("Can't read image file: %s", err) } - defer f.Close() + defer func() { _ = f.Close() }() log.Infof("Uploading file %s with Image ID %s", filePath, image.ID) imagedata.Upload(client, image.ID, f) @@ -63,7 +63,7 @@ func createOpenStackImage(filePath string, imageName string, client *gophercloud // then there's been a problem validImage, _ := images.Get(client, image.ID).Extract() if validImage.Status != "active" { - log.Fatalf("Error uploading image, status is %s", validImage.Status) + log.Fatalf("error uploading image, status is %s", validImage.Status) } else { log.Infof("Image uploaded successfully!") fmt.Println(image.ID) diff --git a/src/cmd/linuxkit/push_scaleway.go b/src/cmd/linuxkit/push_scaleway.go index 10c1abbb2..3321c007b 100644 --- a/src/cmd/linuxkit/push_scaleway.go +++ b/src/cmd/linuxkit/push_scaleway.go @@ -54,7 +54,7 @@ func pushScalewayCmd() *cobra.Command { client, err := NewScalewayClient(accessKey, secretKey, zone, organizationID) if err != nil { - return fmt.Errorf("Unable to connect to Scaleway: %v", err) + return fmt.Errorf("unable to connect to Scaleway: %v", err) } // if volume size not set, try to calculate it from file size @@ -72,44 +72,44 @@ func pushScalewayCmd() *cobra.Command { if instanceID == "" { instanceID, err = client.CreateInstance(volumeSize) if err != nil { - return fmt.Errorf("Error creating a Scaleway instance: %v", err) + return fmt.Errorf("error creating a Scaleway instance: %v", err) } err = client.BootInstanceAndWait(instanceID) if err != nil { - return fmt.Errorf("Error booting instance: %v", err) + return fmt.Errorf("error booting instance: %v", err) } } volumeID, err := client.GetSecondVolumeID(instanceID) if err != nil { - return fmt.Errorf("Error retrieving second volume ID: %v", err) + return fmt.Errorf("error retrieving second volume ID: %v", err) } err = client.CopyImageToInstance(instanceID, path, sshKeyFile) if err != nil { - return fmt.Errorf("Error copying ISO file to Scaleway's instance: %v", err) + return fmt.Errorf("error copying ISO file to Scaleway's instance: %v", err) } err = client.WriteImageToVolume(instanceID, deviceName) if err != nil { - return fmt.Errorf("Error writing ISO file to additional volume: %v", err) + return fmt.Errorf("error writing ISO file to additional volume: %v", err) } err = client.TerminateInstance(instanceID) if err != nil { - return fmt.Errorf("Error terminating Scaleway's instance: %v", err) + return fmt.Errorf("error terminating Scaleway's instance: %v", err) } err = client.CreateScalewayImage(instanceID, volumeID, name) if err != nil { - return fmt.Errorf("Error creating Scaleway image: %v", err) + return fmt.Errorf("error creating Scaleway image: %v", err) } if !noCleanFlag { err = client.DeleteInstanceAndVolumes(instanceID) if err != nil { - return fmt.Errorf("Error deleting Scaleway instance and volumes: %v", err) + return fmt.Errorf("error deleting Scaleway instance and volumes: %v", err) } } return nil diff --git a/src/cmd/linuxkit/push_vcenter.go b/src/cmd/linuxkit/push_vcenter.go index 4452e8268..fc8e7a2e1 100644 --- a/src/cmd/linuxkit/push_vcenter.go +++ b/src/cmd/linuxkit/push_vcenter.go @@ -97,7 +97,7 @@ func uploadFile(c *govmomi.Client, newVM vmConfig, dss *object.Datastore) { p := soap.DefaultUpload ctx := context.Background() - if err := c.Client.UploadFile(ctx, *newVM.path, dsurl, &p); err != nil { + if err := c.UploadFile(ctx, *newVM.path, dsurl, &p); err != nil { log.Fatalf("Unable to upload file to vCenter Datastore\n%v", err) } } diff --git a/src/cmd/linuxkit/run.go b/src/cmd/linuxkit/run.go index 88c2315d7..55ef7a319 100644 --- a/src/cmd/linuxkit/run.go +++ b/src/cmd/linuxkit/run.go @@ -37,7 +37,7 @@ func runCmd() *cobra.Command { case "windows": target = "hyperv" default: - return fmt.Errorf("there currently is no default 'run' backend for your platform.") + return fmt.Errorf("there currently is no default 'run' backend for your platform") } children := cmd.Commands() for _, child := range children { diff --git a/src/cmd/linuxkit/run_aws.go b/src/cmd/linuxkit/run_aws.go index c33e5063e..cfc1e3a17 100644 --- a/src/cmd/linuxkit/run_aws.go +++ b/src/cmd/linuxkit/run_aws.go @@ -52,7 +52,7 @@ func runAWSCmd() *cobra.Command { if dataPath != "" { dataB, err := os.ReadFile(dataPath) if err != nil { - return fmt.Errorf("Unable to read metadata file: %v", err) + return fmt.Errorf("unable to read metadata file: %v", err) } data = string(dataB) } @@ -78,13 +78,13 @@ func runAWSCmd() *cobra.Command { } results, err := compute.DescribeImages(filter) if err != nil { - return fmt.Errorf("Unable to describe images: %s", err) + return fmt.Errorf("unable to describe images: %s", err) } if len(results.Images) < 1 { - return fmt.Errorf("Unable to find image with name %s", name) + return fmt.Errorf("unable to find image with name %s", name) } if len(results.Images) > 1 { - log.Warnf("Found multiple images with the same name, using the first one") + log.Warnf("found multiple images with the same name, using the first one") } imageID := results.Images[0].ImageId @@ -102,11 +102,11 @@ func runAWSCmd() *cobra.Command { } runResult, err := compute.RunInstances(params) if err != nil { - return fmt.Errorf("Unable to run instance: %s", err) + return fmt.Errorf("unable to run instance: %s", err) } instanceID := runResult.Instances[0].InstanceId - log.Infof("Created instance %s", *instanceID) + log.Infof("reated instance %s", *instanceID) instanceFilter := &ec2.DescribeInstancesInput{ Filters: []*ec2.Filter{ @@ -118,7 +118,7 @@ func runAWSCmd() *cobra.Command { } if err = compute.WaitUntilInstanceRunning(instanceFilter); err != nil { - return fmt.Errorf("Error waiting for instance to start: %s", err) + return fmt.Errorf("error waiting for instance to start: %s", err) } log.Infof("Instance %s is running", *instanceID) @@ -133,7 +133,7 @@ func runAWSCmd() *cobra.Command { volume, err := compute.CreateVolume(diskParams) if err != nil { - return fmt.Errorf("Error creating volume: %s", err) + return fmt.Errorf("error creating volume: %s", err) } waitVol := &ec2.DescribeVolumesInput{ @@ -148,7 +148,7 @@ func runAWSCmd() *cobra.Command { log.Infof("Waiting for volume %s to be available", *volume.VolumeId) if err := compute.WaitUntilVolumeAvailable(waitVol); err != nil { - return fmt.Errorf("Error waiting for volume to be available: %s", err) + return fmt.Errorf("error waiting for volume to be available: %s", err) } log.Infof("Attaching volume %s to instance %s", *volume.VolumeId, *instanceID) @@ -159,7 +159,7 @@ func runAWSCmd() *cobra.Command { } _, err = compute.AttachVolume(volParams) if err != nil { - return fmt.Errorf("Error attaching volume to instance: %s", err) + return fmt.Errorf("error attaching volume to instance: %s", err) } } @@ -167,7 +167,7 @@ func runAWSCmd() *cobra.Command { log.Warn("Waiting for instance to stop...") if err = compute.WaitUntilInstanceStopped(instanceFilter); err != nil { - return fmt.Errorf("Error waiting for instance to stop: %s", err) + return fmt.Errorf("error waiting for instance to stop: %s", err) } consoleParams := &ec2.GetConsoleOutputInput{ @@ -175,7 +175,7 @@ func runAWSCmd() *cobra.Command { } output, err := compute.GetConsoleOutput(consoleParams) if err != nil { - return fmt.Errorf("Error getting output from instance %s: %s", *instanceID, err) + return fmt.Errorf("error getting output from instance %s: %s", *instanceID, err) } if output.Output == nil { @@ -183,7 +183,7 @@ func runAWSCmd() *cobra.Command { } else { out, err := base64.StdEncoding.DecodeString(*output.Output) if err != nil { - return fmt.Errorf("Error decoding output: %s", err) + return fmt.Errorf("error decoding output: %s", err) } fmt.Printf("%s\n", string(out)) } @@ -192,10 +192,10 @@ func runAWSCmd() *cobra.Command { InstanceIds: []*string{instanceID}, } if _, err := compute.TerminateInstances(terminateParams); err != nil { - return fmt.Errorf("Error terminating instance %s", *instanceID) + return fmt.Errorf("error terminating instance %s", *instanceID) } if err = compute.WaitUntilInstanceTerminated(instanceFilter); err != nil { - return fmt.Errorf("Error waiting for instance to terminate: %s", err) + return fmt.Errorf("error waiting for instance to terminate: %s", err) } return nil diff --git a/src/cmd/linuxkit/run_equinixmetal.go b/src/cmd/linuxkit/run_equinixmetal.go index 519095e19..e377587d3 100644 --- a/src/cmd/linuxkit/run_equinixmetal.go +++ b/src/cmd/linuxkit/run_equinixmetal.go @@ -77,17 +77,17 @@ func runEquinixMetalCmd() *cobra.Command { } url := getStringValue(equinixmetalBaseURL, baseURLFlag, "") if url == "" { - return fmt.Errorf("Need to specify a value for --base-url where the images are hosted. This URL should contain /%s-kernel, /%s-initrd.img and /%s-equinixmetal.ipxe", prefix, prefix, prefix) + return fmt.Errorf("need to specify a value for --base-url where the images are hosted. This URL should contain /%s-kernel, /%s-initrd.img and /%s-equinixmetal.ipxe", prefix, prefix, prefix) } facility := getStringValue(equinixmetalZoneVar, zoneFlag, "") plan := getStringValue(equinixmetalMachineVar, machineFlag, defaultMachine) apiKey := getStringValue(equinixmetalAPIKeyVar, apiKeyFlag, "") if apiKey == "" { - return errors.New("Must specify an api.equinix.com API key with --api-key") + return errors.New("must specify an api.equinix.com API key with --api-key") } projectID := getStringValue(equinixmetalProjectIDVar, projectFlag, "") if projectID == "" { - return errors.New("Must specify an api.equinix.com Project ID with --project-id") + return errors.New("must specify an api.equinix.com Project ID with --project-id") } hostname := getStringValue(equinixmetalHostnameVar, hostNameFlag, "") name := getStringValue(equinixmetalNameVar, nameFlag, prefix) @@ -95,7 +95,7 @@ func runEquinixMetalCmd() *cobra.Command { billing := "hourly" if !keepFlag && !consoleFlag { - return fmt.Errorf("Combination of keep=%t and console=%t makes little sense", keepFlag, consoleFlag) + return fmt.Errorf("combination of keep=%t and console=%t makes little sense", keepFlag, consoleFlag) } ipxeScriptName := fmt.Sprintf("%s-equinixmetal.ipxe", name) @@ -106,7 +106,7 @@ func runEquinixMetalCmd() *cobra.Command { // Read kernel command line var cmdline string if c, err := os.ReadFile(prefix + "-cmdline"); err != nil { - return fmt.Errorf("Cannot open cmdline file: %v", err) + return fmt.Errorf("cannot open cmdline file: %v", err) } else { cmdline = string(c) } @@ -118,7 +118,7 @@ func runEquinixMetalCmd() *cobra.Command { mux := http.NewServeMux() mux.HandleFunc(fmt.Sprintf("/%s", ipxeScriptName), func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, ipxeScript) + _, _ = fmt.Fprint(w, ipxeScript) }) fs := serveFiles{[]string{fmt.Sprintf("%s-kernel", name), fmt.Sprintf("%s-initrd.img", name)}} mux.Handle("/", http.FileServer(fs)) @@ -137,15 +137,15 @@ func runEquinixMetalCmd() *cobra.Command { kernelURL := fmt.Sprintf("%s/%s-kernel", url, name) log.Infof("Validating URL: %s", ipxeURL) if err := validateHTTPURL(ipxeURL); err != nil { - return fmt.Errorf("Invalid iPXE URL %s: %v", ipxeURL, err) + return fmt.Errorf("invalid iPXE URL %s: %v", ipxeURL, err) } log.Infof("Validating URL: %s", kernelURL) if err := validateHTTPURL(kernelURL); err != nil { - return fmt.Errorf("Invalid kernel URL %s: %v", kernelURL, err) + return fmt.Errorf("invalid kernel URL %s: %v", kernelURL, err) } log.Infof("Validating URL: %s", initrdURL) if err := validateHTTPURL(initrdURL); err != nil { - return fmt.Errorf("Invalid initrd URL %s: %v", initrdURL, err) + return fmt.Errorf("invalid initrd URL %s: %v", initrdURL, err) } client := metalv1.NewAPIClient(&metalv1.Configuration{}) @@ -163,7 +163,7 @@ func runEquinixMetalCmd() *cobra.Command { if deviceFlag != "" { dev, _, err = client.DevicesApi.FindDeviceByIdExecute(client.DevicesApi.FindDeviceById(metalCtx, deviceFlag)) if err != nil { - return fmt.Errorf("Getting info for device %s failed: %v", deviceFlag, err) + return fmt.Errorf("getting info for device %s failed: %v", deviceFlag, err) } b, err := json.MarshalIndent(dev, "", " ") if err != nil { @@ -181,13 +181,13 @@ func runEquinixMetalCmd() *cobra.Command { }) dev, _, err = client.DevicesApi.UpdateDeviceExecute(updateReq) if err != nil { - return fmt.Errorf("Update device %s failed: %v", deviceFlag, err) + return fmt.Errorf("update device %s failed: %v", deviceFlag, err) } actionReq := client.DevicesApi.PerformAction(metalCtx, deviceFlag) actionReq.DeviceActionInput(metalv1.DeviceActionInput{Type: metalv1.DEVICEACTIONINPUTTYPE_REBOOT}) if _, err := client.DevicesApi.PerformActionExecute(actionReq); err != nil { - return fmt.Errorf("Rebooting device %s failed: %v", deviceFlag, err) + return fmt.Errorf("rebooting device %s failed: %v", deviceFlag, err) } } else { // Create a new device @@ -207,7 +207,7 @@ func runEquinixMetalCmd() *cobra.Command { }) dev, _, err = client.DevicesApi.CreateDeviceExecute(createReq) if err != nil { - return fmt.Errorf("Creating device failed: %w", err) + return fmt.Errorf("creating device failed: %w", err) } } b, err := json.MarshalIndent(dev, "", " ") @@ -252,7 +252,7 @@ func runEquinixMetalCmd() *cobra.Command { } else { deleteReq := client.DevicesApi.DeleteDevice(metalCtx, *dev.Id) if _, err := client.DevicesApi.DeleteDeviceExecute(deleteReq); err != nil { - return fmt.Errorf("Unable to delete device: %v", err) + return fmt.Errorf("unable to delete device: %v", err) } } return nil @@ -321,7 +321,7 @@ func validateHTTPURL(url string) error { return err } if resp.StatusCode >= 400 { - return fmt.Errorf("Got a non 200- or 300- HTTP response code: %s", resp.Status) + return fmt.Errorf("got a non 200- or 300- HTTP response code: %s", resp.Status) } return nil } @@ -331,7 +331,7 @@ func equinixmetalSOS(user, host string) error { hostKey, err := sshHostKey(host) if err != nil { - return fmt.Errorf("Host key not found. Maybe need to add it? %v", err) + return fmt.Errorf("host key not found. Maybe need to add it? %v", err) } sshConfig := &ssh.ClientConfig{ @@ -344,14 +344,16 @@ func equinixmetalSOS(user, host string) error { c, err := ssh.Dial("tcp", host+":22", sshConfig) if err != nil { - return fmt.Errorf("Failed to dial: %s", err) + return fmt.Errorf("failed to dial: %s", err) } s, err := c.NewSession() if err != nil { - return fmt.Errorf("Failed to create session: %v", err) + return fmt.Errorf("failed to create session: %v", err) } - defer s.Close() + defer func() { + _ = s.Close() + }() s.Stdout = os.Stdout s.Stderr = os.Stderr @@ -369,7 +371,7 @@ func equinixmetalSOS(user, host string) error { height = 40 } if err := s.RequestPty("vt100", width, height, modes); err != nil { - return fmt.Errorf("Request for PTY failed: %v", err) + return fmt.Errorf("request for PTY failed: %v", err) } oldState, err := term.MakeRaw(int(os.Stdin.Fd())) if err != nil { @@ -381,7 +383,7 @@ func equinixmetalSOS(user, host string) error { // Start remote shell if err := s.Shell(); err != nil { - return fmt.Errorf("Failed to start shell: %v", err) + return fmt.Errorf("failed to start shell: %v", err) } _ = s.Wait() @@ -402,7 +404,7 @@ func sshAgent() ssh.AuthMethod { func sshHostKey(host string) (ssh.PublicKey, error) { f, err := os.ReadFile(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts")) if err != nil { - return nil, fmt.Errorf("Can't read known_hosts file: %v", err) + return nil, fmt.Errorf("can't read known_hosts file: %v", err) } for { @@ -411,7 +413,7 @@ func sshHostKey(host string) (ssh.PublicKey, error) { break } if err != nil { - return nil, fmt.Errorf("Parse error in known_hosts: %v", err) + return nil, fmt.Errorf("parse error in known_hosts: %v", err) } if marker != "" { //ignore CA or revoked key @@ -426,7 +428,7 @@ func sshHostKey(host string) (ssh.PublicKey, error) { f = rest } - return nil, fmt.Errorf("No hostkey for %s", host) + return nil, fmt.Errorf("no hostkey for %s", host) } // This implements a http.FileSystem which only responds to specific files. @@ -458,5 +460,5 @@ func (fs serveFiles) Open(name string) (http.File, error) { return f, nil } } - return nil, fmt.Errorf("File %s not found", name) + return nil, fmt.Errorf("file %s not found", name) } diff --git a/src/cmd/linuxkit/run_gcp.go b/src/cmd/linuxkit/run_gcp.go index 4ec1d8ecf..67dcf2d1b 100644 --- a/src/cmd/linuxkit/run_gcp.go +++ b/src/cmd/linuxkit/run_gcp.go @@ -49,7 +49,7 @@ func runGCPCmd() *cobra.Command { image := args[0] if data != "" && dataPath != "" { - return errors.New("Cannot specify both -data and -data-file") + return errors.New("cannot specify both -data and -data-file") } if name == "" { @@ -59,7 +59,7 @@ func runGCPCmd() *cobra.Command { if dataPath != "" { dataB, err := os.ReadFile(dataPath) if err != nil { - return fmt.Errorf("Unable to read metadata file: %v", err) + return fmt.Errorf("unable to read metadata file: %v", err) } data = string(dataB) } @@ -71,7 +71,7 @@ func runGCPCmd() *cobra.Command { client, err := NewGCPClient(keys, project) if err != nil { - return fmt.Errorf("Unable to connect to GCP: %v", err) + return fmt.Errorf("unable to connect to GCP: %v", err) } if err = client.CreateInstance(name, image, zone, machine, disks, &data, nestedVirt, vTPM, true); err != nil { diff --git a/src/cmd/linuxkit/run_hyperkit.go b/src/cmd/linuxkit/run_hyperkit.go index 6790e7150..088477596 100644 --- a/src/cmd/linuxkit/run_hyperkit.go +++ b/src/cmd/linuxkit/run_hyperkit.go @@ -62,7 +62,7 @@ func runHyperkitCmd() *cobra.Command { path := args[0] if data != "" && dataPath != "" { - return errors.New("Cannot specify both -data and -data-file") + return errors.New("cannot specify both -data and -data-file") } prefix := path @@ -75,22 +75,22 @@ func runHyperkitCmd() *cobra.Command { switch { case squashFSBoot: if kernelBoot || isoBoot { - return fmt.Errorf("Please specify only one boot method") + return fmt.Errorf("please specify only one boot method") } if !statKernel { - return fmt.Errorf("Booting a SquashFS root filesystem requires a kernel at %s", path+"-kernel") + return fmt.Errorf("booting a SquashFS root filesystem requires a kernel at %s", path+"-kernel") } _, err = os.Stat(path + "-squashfs.img") statSquashFS := err == nil if !statSquashFS { - return fmt.Errorf("Cannot find SquashFS image (%s): %v", path+"-squashfs.img", err) + return fmt.Errorf("cannot find SquashFS image (%s): %v", path+"-squashfs.img", err) } case isoBoot: if kernelBoot { - return fmt.Errorf("Please specify only one boot method") + return fmt.Errorf("please specify only one boot method") } if !uefiBoot { - return fmt.Errorf("Hyperkit requires --uefi to be set to boot an ISO") + return fmt.Errorf("hyperkit requires --uefi to be set to boot an ISO") } // We used to auto-detect ISO boot. For backwards compat, append .iso if not present isoPath := path @@ -100,19 +100,19 @@ func runHyperkitCmd() *cobra.Command { _, err = os.Stat(isoPath) statISO := err == nil if !statISO { - return fmt.Errorf("Cannot find ISO image (%s): %v", isoPath, err) + return fmt.Errorf("cannot find ISO image (%s): %v", isoPath, err) } prefix = strings.TrimSuffix(path, ".iso") isoPaths = append(isoPaths, isoPath) default: // Default to kernel+initrd if !statKernel { - return fmt.Errorf("Cannot find kernel file: %s", path+"-kernel") + return fmt.Errorf("cannot find kernel file: %s", path+"-kernel") } _, err = os.Stat(path + "-initrd.img") statInitrd := err == nil if !statInitrd { - return fmt.Errorf("Cannot find initrd file (%s): %v", path+"-initrd.img", err) + return fmt.Errorf("cannot find initrd file (%s): %v", path+"-initrd.img", err) } kernelBoot = true } @@ -120,7 +120,7 @@ func runHyperkitCmd() *cobra.Command { if uefiBoot { _, err := os.Stat(fw) if err != nil { - return fmt.Errorf("Cannot open UEFI firmware file (%s): %v", fw, err) + return fmt.Errorf("cannot open UEFI firmware file (%s): %v", fw, err) } } @@ -128,7 +128,7 @@ func runHyperkitCmd() *cobra.Command { state = prefix + "-state" } if err := os.MkdirAll(state, 0755); err != nil { - return fmt.Errorf("Could not create state directory: %v", err) + return fmt.Errorf("could not create state directory: %v", err) } metadataPaths, err := CreateMetadataISO(state, data, dataPath) @@ -145,15 +145,15 @@ func runHyperkitCmd() *cobra.Command { if _, err := os.Stat(vpnkitUUIDFile); os.IsNotExist(err) { vpnkitUUID = uuid.New().String() if err := os.WriteFile(vpnkitUUIDFile, []byte(vpnkitUUID), 0600); err != nil { - return fmt.Errorf("Unable to write to %s: %v", vpnkitUUIDFile, err) + return fmt.Errorf("unable to write to %s: %v", vpnkitUUIDFile, err) } } else { uuidBytes, err := os.ReadFile(vpnkitUUIDFile) if err != nil { - return fmt.Errorf("Unable to read VPNKit UUID from %s: %v", vpnkitUUIDFile, err) + return fmt.Errorf("unable to read VPNKit UUID from %s: %v", vpnkitUUIDFile, err) } if tmp, err := uuid.ParseBytes(uuidBytes); err != nil { - return fmt.Errorf("Unable to parse VPNKit UUID from %s: %v", vpnkitUUIDFile, err) + return fmt.Errorf("unable to parse VPNKit UUID from %s: %v", vpnkitUUIDFile, err) } else { vpnkitUUID = tmp.String() } @@ -168,7 +168,7 @@ func runHyperkitCmd() *cobra.Command { if kernelBoot || squashFSBoot { cmdlineBytes, err := os.ReadFile(prefix + "-cmdline") if err != nil { - return fmt.Errorf("Cannot open cmdline file: %v", err) + return fmt.Errorf("cannot open cmdline file: %v", err) } cmdline = string(cmdlineBytes) } @@ -176,7 +176,7 @@ func runHyperkitCmd() *cobra.Command { // Create new HyperKit instance (w/o networking for now) h, err := hyperkit.New(hyperkitPath, "", state) if err != nil { - return fmt.Errorf("Error creating hyperkit: %w", err) + return fmt.Errorf("error creating hyperkit: %w", err) } if consoleToFile { @@ -224,7 +224,7 @@ func runHyperkitCmd() *cobra.Command { } if h.VSockPorts, err = stringToIntArray(vsockports, ","); err != nil { - return fmt.Errorf("Unable to parse vsock-ports: %w", err) + return fmt.Errorf("unable to parse vsock-ports: %w", err) } // Select network mode @@ -248,7 +248,7 @@ func runHyperkitCmd() *cobra.Command { } else { _, err = os.Stat(newEthSock) if err != nil { - return errors.New("Cannot find Docker for Mac network sockets. Install Docker or use a different network mode.") + return errors.New("cannot find Docker for Mac network sockets. Install Docker or use a different network mode") } h.VPNKitSock = newEthSock vpnkitPortSocket = newPortSock @@ -271,7 +271,7 @@ func runHyperkitCmd() *cobra.Command { vsockSocket := filepath.Join(state, "connect") vpnkitProcess, err = launchVPNKit(vpnkitPath, h.VPNKitSock, vsockSocket, vpnkitPortSocket) if err != nil { - return fmt.Errorf("Unable to start vpnkit: %w", err) + return fmt.Errorf("unable to start vpnkit: %w", err) } defer shutdownVPNKit(vpnkitProcess) log.RegisterExitHandler(func() { @@ -288,7 +288,7 @@ func runHyperkitCmd() *cobra.Command { case hyperkitNetworkingNone: h.VPNKitSock = "" default: - return fmt.Errorf("Invalid networking mode: %s", netMode[0]) + return fmt.Errorf("invalid networking mode: %s", netMode[0]) } h.VPNKitUUID = vpnkitUUID @@ -296,7 +296,7 @@ func runHyperkitCmd() *cobra.Command { if ip := net.ParseIP(ipStr); len(ip) > 0 && ip.To4() != nil { h.VPNKitPreferredIPv4 = ip.String() } else { - return fmt.Errorf("Unable to parse IPv4 address: %v", ipStr) + return fmt.Errorf("unable to parse IPv4 address: %v", ipStr) } } @@ -305,22 +305,22 @@ func runHyperkitCmd() *cobra.Command { switch netMode[0] { case hyperkitNetworkingDockerForMac, hyperkitNetworkingVPNKit: if vpnkitPortSocket == "" { - return fmt.Errorf("The VPNKit Port socket path is required to publish ports") + return fmt.Errorf("the VPNKit Port socket path is required to publish ports") } f, err := vpnkitPublishPorts(h, publishFlags, vpnkitPortSocket) if err != nil { - return fmt.Errorf("Publish ports failed with: %v", err) + return fmt.Errorf("publish ports failed with: %v", err) } defer f() log.RegisterExitHandler(f) default: - return fmt.Errorf("Port publishing requires %q or %q networking mode", hyperkitNetworkingDockerForMac, hyperkitNetworkingVPNKit) + return fmt.Errorf("port publishing requires %q or %q networking mode", hyperkitNetworkingDockerForMac, hyperkitNetworkingVPNKit) } } err = h.Run(cmdline) if err != nil { - return fmt.Errorf("Cannot run hyperkit: %v", err) + return fmt.Errorf("cannot run hyperkit: %v", err) } return nil }, @@ -366,7 +366,7 @@ func shutdownVPNKit(process *os.Process) { // createListenSocket creates a new unix domain socket and returns the open file func createListenSocket(path string) (*os.File, error) { - os.Remove(path) + _ = os.Remove(path) conn, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) if err != nil { return nil, fmt.Errorf("unable to create socket: %v", err) @@ -387,7 +387,7 @@ func launchVPNKit(vpnkitPath, etherSock, vsockSock, portSock string) (*os.Proces if vpnkitPath == "" { vpnkitPath, err = exec.LookPath("vpnkit") if err != nil { - return nil, fmt.Errorf("Unable to find vpnkit binary") + return nil, fmt.Errorf("unable to find vpnkit binary") } } @@ -436,20 +436,20 @@ func vpnkitPublishPorts(h *hyperkit.HyperKit, publishFlags multipleFlag, portSoc vpnkitUUID, err := uuid.Parse(h.VPNKitUUID) if err != nil { - return nil, fmt.Errorf("Failed to parse VPNKit UUID %s: %v", h.VPNKitUUID, err) + return nil, fmt.Errorf("failed to parse VPNKit UUID %s: %v", h.VPNKitUUID, err) } localhost := net.ParseIP("127.0.0.1") if localhost == nil { - return nil, fmt.Errorf("Failed to parse 127.0.0.1") + return nil, fmt.Errorf("failed to parse 127.0.0.1") } log.Debugf("Creating new VPNKit VMNet on %s", h.VPNKitSock) vmnetClient, err := vmnet.New(ctx, h.VPNKitSock) if err != nil { - return nil, fmt.Errorf("NewVmnet failed: %v", err) + return nil, fmt.Errorf("vmnet.New() failed: %v", err) } - defer vmnetClient.Close() + defer func() { _ = vmnetClient.Close() }() // Register with VPNKit var vif *vmnet.Vif @@ -457,17 +457,17 @@ func vpnkitPublishPorts(h *hyperkit.HyperKit, publishFlags multipleFlag, portSoc log.Debugf("Creating VPNKit VIF for %v", vpnkitUUID) vif, err = vmnetClient.ConnectVif(vpnkitUUID) if err != nil { - return nil, fmt.Errorf("Connection to Vif failed: %v", err) + return nil, fmt.Errorf("connection to Vif failed: %v", err) } } else { ip := net.ParseIP(h.VPNKitPreferredIPv4) if ip == nil { - return nil, fmt.Errorf("Failed to parse IP: %s", h.VPNKitPreferredIPv4) + return nil, fmt.Errorf("failed to parse IP: %s", h.VPNKitPreferredIPv4) } log.Debugf("Creating VPNKit VIF for %v ip=%v", vpnkitUUID, ip) vif, err = vmnetClient.ConnectVifIP(vpnkitUUID, ip) if err != nil { - return nil, fmt.Errorf("Connection to Vif with IP failed: %v", err) + return nil, fmt.Errorf("connection to Vif with IP failed: %v", err) } } log.Debugf("VPNKit UUID:%s IP: %v", vpnkitUUID, vif.IP) @@ -475,7 +475,7 @@ func vpnkitPublishPorts(h *hyperkit.HyperKit, publishFlags multipleFlag, portSoc log.Debugf("Connecting to VPNKit on %s", portSocket) c, err := vpnkit.NewClient(portSocket) if err != nil { - return nil, fmt.Errorf("Connection to VPNKit failed: %v", err) + return nil, fmt.Errorf("connection to VPNKit failed: %v", err) } // Publish ports @@ -483,7 +483,7 @@ func vpnkitPublishPorts(h *hyperkit.HyperKit, publishFlags multipleFlag, portSoc for _, publish := range publishFlags { p, err := NewPublishedPort(publish) if err != nil { - return nil, fmt.Errorf("Failed to parse port publish %s: %v", publish, err) + return nil, fmt.Errorf("failed to parse port publish %s: %v", publish, err) } log.Debugf("Publishing %s", publish) @@ -495,7 +495,7 @@ func vpnkitPublishPorts(h *hyperkit.HyperKit, publishFlags multipleFlag, portSoc InPort: p.Guest, } if err = c.Expose(context.Background(), vp); err != nil { - return nil, fmt.Errorf("Failed to expose port %s: %v", publish, err) + return nil, fmt.Errorf("failed to expose port %s: %v", publish, err) } ports = append(ports, vp) } diff --git a/src/cmd/linuxkit/run_hyperv.go b/src/cmd/linuxkit/run_hyperv.go index ae0057bd5..87deab14a 100644 --- a/src/cmd/linuxkit/run_hyperv.go +++ b/src/cmd/linuxkit/run_hyperv.go @@ -52,7 +52,7 @@ func runHyperVCmd() *cobra.Command { "-NoVHD", "-SwitchName", fmt.Sprintf("'%s'", vmSwitch)) if err != nil { - return fmt.Errorf("Failed to create new VM: %w\n%s", err, out) + return fmt.Errorf("failed to create new VM: %w\n%s", err, out) } log.Infof("Configure VM: %s", vmName) _, out, err = poshCmd("Set-VM", "-Name", fmt.Sprintf("'%s'", vmName), @@ -63,7 +63,7 @@ func runHyperVCmd() *cobra.Command { "-StaticMemory", "-ProcessorCount", fmt.Sprintf("%d", cpus)) if err != nil { - return fmt.Errorf("Failed to configure new VM: %w\n%s", err, out) + return fmt.Errorf("failed to configure new VM: %w\n%s", err, out) } for i, d := range disks { @@ -86,10 +86,10 @@ func runHyperVCmd() *cobra.Command { "-SizeBytes", fmt.Sprintf("%dMB", d.Size), "-Dynamic") if err != nil { - return fmt.Errorf("Failed to create VHD %s: %w\n%s", d.Path, err, out) + return fmt.Errorf("failed to create VHD %s: %w\n%s", d.Path, err, out) } } else { - return fmt.Errorf("Problem accessing disk %s. %w", d.Path, err) + return fmt.Errorf("problem accessing disk %s. %w", d.Path, err) } } else { log.Infof("Using existing disk %s", d.Path) @@ -99,7 +99,7 @@ func runHyperVCmd() *cobra.Command { "-VMName", fmt.Sprintf("'%s'", vmName), "-Path", fmt.Sprintf("'%s'", d.Path)) if err != nil { - return fmt.Errorf("Failed to add VHD %s: %w\n%s", d.Path, err, out) + return fmt.Errorf("failed to add VHD %s: %w\n%s", d.Path, err, out) } } @@ -108,7 +108,7 @@ func runHyperVCmd() *cobra.Command { "-VMName", fmt.Sprintf("'%s'", vmName), "-Path", fmt.Sprintf("'%s'", isoPath)) if err != nil { - return fmt.Errorf("Failed add DVD: %w\n%s", err, out) + return fmt.Errorf("failed add DVD: %w\n%s", err, out) } _, out, err = poshCmd( fmt.Sprintf("$cdrom = Get-VMDvdDrive -vmname '%s';", vmName), @@ -116,7 +116,7 @@ func runHyperVCmd() *cobra.Command { "-EnableSecureBoot", "Off", "-FirstBootDevice", "$cdrom") if err != nil { - return fmt.Errorf("Failed set DVD as boot device: %w\n%s", err, out) + return fmt.Errorf("failed set DVD as boot device: %w\n%s", err, out) } log.Info("Set up COM port") @@ -125,13 +125,13 @@ func runHyperVCmd() *cobra.Command { "-number", "1", "-Path", fmt.Sprintf(`\\.\pipe\%s-com1`, vmName)) if err != nil { - return fmt.Errorf("Failed set up COM port: %w\n%s", err, out) + return fmt.Errorf("failed set up COM port: %w\n%s", err, out) } log.Info("Start the VM") _, out, err = poshCmd("Start-VM", "-Name", fmt.Sprintf("'%s'", vmName)) if err != nil { - return fmt.Errorf("Failed start the VM: %w\n%s", err, out) + return fmt.Errorf("failed start the VM: %w\n%s", err, out) } err = hypervStartConsole(vmName) @@ -233,7 +233,7 @@ func hypervChecks() { func hypervGetSwitch(name string) (string, error) { if name != "" { if _, _, err := poshCmd("Get-VMSwitch", name); err != nil { - return "", fmt.Errorf("Could not find switch %s: %v", name, err) + return "", fmt.Errorf("could not find switch %s: %v", name, err) } return name, nil } @@ -247,7 +247,7 @@ func hypervGetSwitch(name string) (string, error) { out, _, err := poshCmd("Get-VMSwitch | Format-Table -Property Name, SwitchType -HideTableHeaders") if err != nil { - return "", fmt.Errorf("Could not get list of switches: %v", err) + return "", fmt.Errorf("could not get list of switches: %v", err) } switches := splitLines(out) for _, s := range switches { @@ -262,5 +262,5 @@ func hypervGetSwitch(name string) (string, error) { return strings.Join(t[:len(t)-1], " "), nil } } - return "", fmt.Errorf("Could not find an external switch") + return "", fmt.Errorf("could not find an external switch") } diff --git a/src/cmd/linuxkit/run_openstack.go b/src/cmd/linuxkit/run_openstack.go index 68c54aba5..eb9e0129a 100644 --- a/src/cmd/linuxkit/run_openstack.go +++ b/src/cmd/linuxkit/run_openstack.go @@ -41,7 +41,7 @@ func runOpenStackCmd() *cobra.Command { client, err := clientconfig.NewServiceClient("compute", nil) if err != nil { - return fmt.Errorf("Unable to create Compute client, %s", err) + return fmt.Errorf("unable to create Compute client, %s", err) } network := servers.Network{ @@ -68,7 +68,7 @@ func runOpenStackCmd() *cobra.Command { server, err := servers.Create(client, serverOpts).Extract() if err != nil { - return fmt.Errorf("Unable to create server: %w", err) + return fmt.Errorf("unable to create server: %w", err) } _ = servers.WaitForStatus(client, server.ID, "ACTIVE", 600) diff --git a/src/cmd/linuxkit/run_qemu.go b/src/cmd/linuxkit/run_qemu.go index 2474eec3b..ecf95ee67 100644 --- a/src/cmd/linuxkit/run_qemu.go +++ b/src/cmd/linuxkit/run_qemu.go @@ -160,7 +160,7 @@ func runQEMUCmd() *cobra.Command { path := args[0] if data != "" && dataPath != "" { - return errors.New("Cannot specify both -data and -data-file") + return errors.New("cannot specify both -data and -data-file") } // Generate UUID, so that /sys/class/dmi/id/product_uuid is populated @@ -202,7 +202,7 @@ func runQEMUCmd() *cobra.Command { } if err := os.MkdirAll(state, 0755); err != nil { - return fmt.Errorf("Could not create state directory: %w", err) + return fmt.Errorf("could not create state directory: %w", err) } var isoPaths []string @@ -261,27 +261,27 @@ func runQEMUCmd() *cobra.Command { netdevConfig = "user,id=t0" case qemuNetworkingTap: if len(netMode) != 2 { - return fmt.Errorf("Not enough arguments for %q networking mode", qemuNetworkingTap) + return fmt.Errorf("not enough arguments for %q networking mode", qemuNetworkingTap) } if len(publishFlags) != 0 { - return fmt.Errorf("Port publishing requires %q networking mode", qemuNetworkingUser) + return fmt.Errorf("port publishing requires %q networking mode", qemuNetworkingUser) } netdevConfig = fmt.Sprintf("tap,id=t0,ifname=%s,script=no,downscript=no", netMode[1]) case qemuNetworkingBridge: if len(netMode) != 2 { - return fmt.Errorf("Not enough arguments for %q networking mode", qemuNetworkingBridge) + return fmt.Errorf("not enough arguments for %q networking mode", qemuNetworkingBridge) } if len(publishFlags) != 0 { - return fmt.Errorf("Port publishing requires %q networking mode", qemuNetworkingUser) + return fmt.Errorf("port publishing requires %q networking mode", qemuNetworkingUser) } netdevConfig = fmt.Sprintf("bridge,id=t0,br=%s", netMode[1]) case qemuNetworkingNone: if len(publishFlags) != 0 { - return fmt.Errorf("Port publishing requires %q networking mode", qemuNetworkingUser) + return fmt.Errorf("port publishing requires %q networking mode", qemuNetworkingUser) } netdevConfig = "" default: - return fmt.Errorf("Invalid networking mode: %s", netMode[0]) + return fmt.Errorf("invalid networking mode: %s", netMode[0]) } config := QemuConfig{ @@ -385,7 +385,7 @@ func runQemuLocal(config QemuConfig) error { qemuImgCmd := exec.Command(config.QemuImgPath, "create", "-f", d.Format, d.Path, fmt.Sprintf("%dM", d.Size)) log.Debugf("%v\n", qemuImgCmd.Args) if err := qemuImgCmd.Run(); err != nil { - return fmt.Errorf("Error creating disk [%s] format %s: %s", d.Path, d.Format, err.Error()) + return fmt.Errorf("error creating disk [%s] format %s: %s", d.Path, d.Format, err.Error()) } } else { return err @@ -400,13 +400,13 @@ func runQemuLocal(config QemuConfig) error { if config.FWPath == "" { // there is no default on mac if runtime.GOOS == "darwin" { - return fmt.Errorf("To run qemu with UEFI firmware on macOS, you must specify the path to locally installed OVMF firmware as `--fw `. You can download OVMF from https://sourceforge.net/projects/edk2/files/OVMF/ ") + return fmt.Errorf("to run qemu with UEFI firmware on macOS, you must specify the path to locally installed OVMF firmware as `--fw `. You can download OVMF from https://sourceforge.net/projects/edk2/files/OVMF/ ") } config.FWPath = defaultFWPath } if _, err := os.Stat(config.FWPath); err != nil { if os.IsNotExist(err) { - return fmt.Errorf("File [%s] does not exist, please ensure OVMF is installed", config.FWPath) + return fmt.Errorf("file [%s] does not exist, please ensure OVMF is installed", config.FWPath) } return err } @@ -414,7 +414,7 @@ func runQemuLocal(config QemuConfig) error { // Detached mode is only supported in a container. if config.Detached { - return fmt.Errorf("Detached mode is only supported when running in a container, not locally") + return fmt.Errorf("detached mode is only supported when running in a container, not locally") } if len(config.VirtiofsShares) > 0 { @@ -640,12 +640,12 @@ func discoverQemu(config QemuConfig) (QemuConfig, error) { var err error config.QemuBinPath, err = exec.LookPath(qemuBinPath) if err != nil { - return config, fmt.Errorf("Unable to find %s within the $PATH", qemuBinPath) + return config, fmt.Errorf("unable to find %s within the $PATH", qemuBinPath) } config.QemuImgPath, err = exec.LookPath(qemuImgPath) if err != nil { - return config, fmt.Errorf("Unable to find %s within the $PATH", qemuImgPath) + return config, fmt.Errorf("unable to find %s within the $PATH", qemuImgPath) } return config, nil diff --git a/src/cmd/linuxkit/run_vbox.go b/src/cmd/linuxkit/run_vbox.go index c217d7d5a..461c93c28 100644 --- a/src/cmd/linuxkit/run_vbox.go +++ b/src/cmd/linuxkit/run_vbox.go @@ -50,7 +50,7 @@ func (l *VBNetworks) Set(value string) error { case "adapter", "bridgeadapter", "hostadapter": d.Adapter = c[1] default: - return fmt.Errorf("Unknown network config: %s", c[0]) + return fmt.Errorf("unknown network config: %s", c[0]) } } } @@ -90,7 +90,7 @@ func runVBoxCmd() *cobra.Command { vboxmanage, err := exec.LookPath(vboxmanageFlag) if err != nil { - return fmt.Errorf("Cannot find management binary %s: %v", vboxmanageFlag, err) + return fmt.Errorf("cannot find management binary %s: %v", vboxmanageFlag, err) } name := vmName @@ -103,7 +103,7 @@ func runVBoxCmd() *cobra.Command { state = prefix + "-state" } if err := os.MkdirAll(state, 0755); err != nil { - return fmt.Errorf("Could not create state directory: %v", err) + return fmt.Errorf("could not create state directory: %v", err) } // remove machine in case it already exists @@ -151,7 +151,7 @@ func runVBoxCmd() *cobra.Command { consolePath = filepath.Join(state, "console") consolePath, err = filepath.Abs(consolePath) if err != nil { - return fmt.Errorf("Bad path: %v", err) + return fmt.Errorf("bad path: %v", err) } } @@ -206,7 +206,7 @@ func runVBoxCmd() *cobra.Command { if d.Path == "" { d.Path = filepath.Join(state, "disk"+id+".img") if err := os.Truncate(d.Path, int64(d.Size)*int64(1048576)); err != nil { - return fmt.Errorf("Cannot create disk: %v", err) + return fmt.Errorf("cannot create disk: %v", err) } } _, out, err = manage(vboxmanage, "storageattach", name, "--storagectl", "SATA", "--port", "0", "--device", id, "--type", "hdd", "--medium", d.Path) @@ -226,12 +226,13 @@ func runVBoxCmd() *cobra.Command { if err != nil { return fmt.Errorf("modifyvm --nic error: %v\n%s", err, out) } - if d.Type == "hostonly" { + switch d.Type { + case "hostonly": _, out, err = manage(vboxmanage, "modifyvm", name, fmt.Sprintf("--hostonlyadapter%d", nic), d.Adapter) if err != nil { return fmt.Errorf("modifyvm --hostonlyadapter error: %v\n%s", err, out) } - } else if d.Type == "bridged" { + case "bridged": _, out, err = manage(vboxmanage, "modifyvm", name, fmt.Sprintf("--bridgeadapter%d", nic), d.Adapter) if err != nil { return fmt.Errorf("modifyvm --bridgeadapter error: %v\n%s", err, out) @@ -248,7 +249,7 @@ func runVBoxCmd() *cobra.Command { _ = os.Remove(consolePath) ln, err := net.Listen("unix", consolePath) if err != nil { - return fmt.Errorf("Cannot listen on console socket %s: %v", consolePath, err) + return fmt.Errorf("cannot listen on console socket %s: %v", consolePath, err) } var vmType string @@ -273,7 +274,7 @@ func runVBoxCmd() *cobra.Command { socket, err := ln.Accept() if err != nil { - return fmt.Errorf("Accept error: %v", err) + return fmt.Errorf("accept error: %v", err) } go func() { diff --git a/src/cmd/linuxkit/run_vcenter.go b/src/cmd/linuxkit/run_vcenter.go index c3f4d2e86..638eb48b7 100644 --- a/src/cmd/linuxkit/run_vcenter.go +++ b/src/cmd/linuxkit/run_vcenter.go @@ -61,7 +61,7 @@ func runVCenterCmd() *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { imagePath := args[0] if guestIP && !poweron { - return errors.New("The waitForIP flag can not be used without the powerOn flag") + return errors.New("the waitForIP flag can not be used without the powerOn flag") } // Ensure an iso has been passed to the vCenter run Command if strings.HasSuffix(vmPath, ".iso") { @@ -70,7 +70,7 @@ func runVCenterCmd() *cobra.Command { vmFolder = strings.TrimSuffix(path.Base(vmPath), ".iso") } } else { - return fmt.Errorf("Please pass an \".iso\" file as the path") + return fmt.Errorf("please pass an \".iso\" file as the path") } ctx, cancel := context.WithCancel(context.Background()) @@ -106,7 +106,7 @@ func runVCenterCmd() *cobra.Command { scsi, err := object.SCSIControllerTypes().CreateSCSIController("pvscsi") if err != nil { - return errors.New("Error creating pvscsi controller as part of new VM") + return errors.New("error creating pvscsi controller as part of new VM") } spec.DeviceChange = append(spec.DeviceChange, &types.VirtualDeviceConfigSpec{ @@ -116,12 +116,12 @@ func runVCenterCmd() *cobra.Command { task, err := folders.VmFolder.CreateVM(ctx, spec, rp, hs) if err != nil { - return errors.New("Creating new VM failed, more detail can be found in vCenter tasks") + return errors.New("creating new VM failed, more detail can be found in vCenter tasks") } info, err := task.WaitForResult(ctx, nil) if err != nil { - return fmt.Errorf("Creating new VM failed\n%w", err) + return fmt.Errorf("creating new VM failed\n%w", err) } // Retrieve the new VM @@ -132,7 +132,7 @@ func runVCenterCmd() *cobra.Command { if *newVM.persistent != "" { newVM.persistentSz, err = getDiskSizeMB(*newVM.persistent) if err != nil { - return fmt.Errorf("Couldn't parse disk-size %s: %v", *newVM.persistent, err) + return fmt.Errorf("couldn't parse disk-size %s: %v", *newVM.persistent, err) } addVMDK(ctx, vm, dss, newVM) } diff --git a/src/cmd/linuxkit/run_virtualizationframework_darwin_cgo_enabled.go b/src/cmd/linuxkit/run_virtualizationframework_darwin_cgo_enabled.go index 505673d70..ceef7242d 100644 --- a/src/cmd/linuxkit/run_virtualizationframework_darwin_cgo_enabled.go +++ b/src/cmd/linuxkit/run_virtualizationframework_darwin_cgo_enabled.go @@ -25,7 +25,7 @@ import ( // Process the run arguments and execute run func runVirtualizationFramework(cfg virtualizationFramwworkConfig, path string) error { if cfg.data != "" && cfg.dataPath != "" { - return errors.New("Cannot specify both -data and -data-file") + return errors.New("cannot specify both -data and -data-file") } prefix := path @@ -37,12 +37,12 @@ func runVirtualizationFramework(cfg virtualizationFramwworkConfig, path string) // Default to kernel+initrd if !statKernel { - return fmt.Errorf("Cannot find kernel file: %s", path+"-kernel") + return fmt.Errorf("cannot find kernel file: %s", path+"-kernel") } _, err = os.Stat(path + "-initrd.img") statInitrd := err == nil if !statInitrd { - return fmt.Errorf("Cannot find initrd file (%s): %w", path+"-initrd.img", err) + return fmt.Errorf("cannot find initrd file (%s): %w", path+"-initrd.img", err) } cfg.kernelBoot = true @@ -59,7 +59,7 @@ func runVirtualizationFramework(cfg virtualizationFramwworkConfig, path string) cmdlineBytes, err := os.ReadFile(prefix + "-cmdline") if err != nil { - return fmt.Errorf("Cannot open cmdline file: %v", err) + return fmt.Errorf("cannot open cmdline file: %v", err) } // must have hvc0 as console for vf kernelCommandLineArguments := strings.Split(string(cmdlineBytes), " ") @@ -88,18 +88,22 @@ func runVirtualizationFramework(cfg virtualizationFramwworkConfig, path string) if err != nil { return fmt.Errorf("unable to read kernel file %s: %v", vmlinuz, err) } - defer f.Close() + defer func() { _ = f.Close() }() r, err := gzip.NewReader(f) if err != nil { return fmt.Errorf("unable to read from file %s: %v", vmlinuz, err) } - defer r.Close() + defer func() { + _ = r.Close() + }() writer, err := os.Create(vmlinuzUncompressed) if err != nil { return fmt.Errorf("unable to create decompressed kernel file %s: %v", vmlinuzUncompressed, err) } - defer writer.Close() + defer func() { + _ = writer.Close() + }() if _, err = io.Copy(writer, r); err != nil { return fmt.Errorf("unable to decompress kernel file to %s: %v", vmlinuzUncompressed, err) @@ -151,29 +155,29 @@ func runVirtualizationFramework(cfg virtualizationFramwworkConfig, path string) case virtualizationNetworkingVMNet: natAttachment, err := vz.NewNATNetworkDeviceAttachment() if err != nil { - return fmt.Errorf("Could not create NAT network device attachment: %v", err) + return fmt.Errorf("could not create NAT network device attachment: %v", err) } networkConfig, err := vz.NewVirtioNetworkDeviceConfiguration(natAttachment) if err != nil { - return fmt.Errorf("Could not create virtio network device configuration: %v", err) + return fmt.Errorf("could not create virtio network device configuration: %v", err) } config.SetNetworkDevicesVirtualMachineConfiguration([]*vz.VirtioNetworkDeviceConfiguration{ networkConfig, }) macAddress, err := vz.NewRandomLocallyAdministeredMACAddress() if err != nil { - return fmt.Errorf("Could not create random MAC address: %v", err) + return fmt.Errorf("could not create random MAC address: %v", err) } networkConfig.SetMACAddress(macAddress) case virtualizationNetworkingNone: default: - return fmt.Errorf("Invalid networking mode: %s", netMode[0]) + return fmt.Errorf("invalid networking mode: %s", netMode[0]) } // entropy entropyConfig, err := vz.NewVirtioEntropyDeviceConfiguration() if err != nil { - return fmt.Errorf("Could not create virtio entropy device configuration: %v", err) + return fmt.Errorf("could not create virtio entropy device configuration: %v", err) } config.SetEntropyDevicesVirtualMachineConfiguration([]*vz.VirtioEntropyDeviceConfiguration{ @@ -216,7 +220,7 @@ func runVirtualizationFramework(cfg virtualizationFramwworkConfig, path string) } storageDeviceConfig, err := vz.NewVirtioBlockDeviceConfiguration(diskImageAttachment) if err != nil { - return fmt.Errorf("Could not create virtio block device configuration: %v", err) + return fmt.Errorf("could not create virtio block device configuration: %v", err) } storageDevices = append(storageDevices, storageDeviceConfig) } @@ -230,7 +234,7 @@ func runVirtualizationFramework(cfg virtualizationFramwworkConfig, path string) } storageDeviceConfig, err := vz.NewVirtioBlockDeviceConfiguration(diskImageAttachment) if err != nil { - return fmt.Errorf("Could not create virtio block device configuration: %v", err) + return fmt.Errorf("could not create virtio block device configuration: %v", err) } storageDevices = append(storageDevices, storageDeviceConfig) } @@ -240,7 +244,7 @@ func runVirtualizationFramework(cfg virtualizationFramwworkConfig, path string) // traditional memory balloon device which allows for managing guest memory. (optional) memoryBalloonDeviceConfiguration, err := vz.NewVirtioTraditionalMemoryBalloonDeviceConfiguration() if err != nil { - return fmt.Errorf("Could not create virtio traditional memory balloon device configuration: %v", err) + return fmt.Errorf("could not create virtio traditional memory balloon device configuration: %v", err) } config.SetMemoryBalloonDevicesVirtualMachineConfiguration([]vz.MemoryBalloonDeviceConfiguration{ memoryBalloonDeviceConfiguration, @@ -249,7 +253,7 @@ func runVirtualizationFramework(cfg virtualizationFramwworkConfig, path string) // socket device (optional) socketDeviceConfiguration, err := vz.NewVirtioSocketDeviceConfiguration() if err != nil { - return fmt.Errorf("Could not create virtio socket device configuration: %v", err) + return fmt.Errorf("could not create virtio socket device configuration: %v", err) } config.SetSocketDevicesVirtualMachineConfiguration([]vz.SocketDeviceConfiguration{ socketDeviceConfiguration, @@ -285,7 +289,7 @@ func runVirtualizationFramework(cfg virtualizationFramwworkConfig, path string) vm, err := vz.NewVirtualMachine(config) if err != nil { - return fmt.Errorf("Could not create virtual machine: %v", err) + return fmt.Errorf("could not create virtual machine: %v", err) } signalCh := make(chan os.Signal, 1) @@ -349,7 +353,9 @@ func checkFileType(infile string) (string, error) { if err != nil { return "", err } - defer file.Close() + defer func() { + _ = file.Close() + }() b := make([]byte, 512) diff --git a/src/cmd/linuxkit/run_vmware.go b/src/cmd/linuxkit/run_vmware.go index ac2bf721b..ef2b349b6 100644 --- a/src/cmd/linuxkit/run_vmware.go +++ b/src/cmd/linuxkit/run_vmware.go @@ -83,7 +83,7 @@ func runVMWareCmd() *cobra.Command { state = prefix + "-state" } if err := os.MkdirAll(state, 0755); err != nil { - return fmt.Errorf("Could not create state directory: %v", err) + return fmt.Errorf("could not create state directory: %v", err) } var vmrunPath, vmDiskManagerPath string @@ -104,7 +104,7 @@ func runVMWareCmd() *cobra.Command { fullVMrunPath, err := exec.LookPath(vmrunPath) if err != nil { // Kept as separate error as people may manually change their environment vars - return fmt.Errorf("Unable to find %s within the $PATH", vmrunPath) + return fmt.Errorf("unable to find %s within the $PATH", vmrunPath) } vmrunPath = fullVMrunPath vmrunArgs = []string{"-T", "ws", "start"} @@ -141,18 +141,18 @@ func runVMWareCmd() *cobra.Command { // If disk doesn't exist then create one, error if disk is unreadable if _, err := os.Stat(d.Path); err != nil { if os.IsPermission(err) { - return fmt.Errorf("Unable to read file [%s], please check permissions", d.Path) + return fmt.Errorf("unable to read file [%s], please check permissions", d.Path) } else if os.IsNotExist(err) { log.Infof("Creating new VMware disk [%s]", d.Path) vmDiskCmd := exec.Command(vmDiskManagerPath, "-c", "-s", fmt.Sprintf("%dMB", d.Size), "-a", "lsilogic", "-t", "0", d.Path) if err = vmDiskCmd.Run(); err != nil { - return fmt.Errorf("Error creating disk [%s]: %w", d.Path, err) + return fmt.Errorf("error creating disk [%s]: %w", d.Path, err) } } else { - return fmt.Errorf("Unable to read file [%s]: %w", d.Path, err) + return fmt.Errorf("unable to read file [%s]: %w", d.Path, err) } } else { - log.Infof("Using existing disk [%s]", d.Path) + log.Infof("using existing disk [%s]", d.Path) } } @@ -175,14 +175,14 @@ func runVMWareCmd() *cobra.Command { vmxPath := filepath.Join(state, "linuxkit.vmx") err := os.WriteFile(vmxPath, []byte(vmx), 0644) if err != nil { - return fmt.Errorf("Error writing .vmx file: %v", err) + return fmt.Errorf("error writing .vmx file: %v", err) } vmrunArgs = append(vmrunArgs, vmxPath) execCmd := exec.Command(vmrunPath, vmrunArgs...) out, err := execCmd.Output() if err != nil { - return fmt.Errorf("Error starting vmrun: %v", err) + return fmt.Errorf("error starting vmrun: %v", err) } // check there is output to push to logging diff --git a/src/cmd/linuxkit/scaleway.go b/src/cmd/linuxkit/scaleway.go index a7f571571..986a713ed 100644 --- a/src/cmd/linuxkit/scaleway.go +++ b/src/cmd/linuxkit/scaleway.go @@ -112,7 +112,7 @@ func (s *ScalewayClient) getImageID(imageName, commercialType, arch string) (str } } } - return "", errors.New("No image matching given requests") + return "", errors.New("no image matching given requests") } // CreateInstance create an instance with one additional volume @@ -185,7 +185,7 @@ func (s *ScalewayClient) GetSecondVolumeID(instanceID string) (string, error) { secondVolume, ok := serverResp.Server.Volumes["1"] if !ok { - return "", errors.New("No second volume found") + return "", errors.New("no second volume found") } return secondVolume.ID, nil @@ -242,7 +242,9 @@ func (s *ScalewayClient) BootInstanceAndWait(instanceID string) error { for { conn, err := net.Dial("tcp", dest) if err == nil { - defer conn.Close() + defer func() { + _ = conn.Close() + }() break } else { time.Sleep(1 * time.Second) @@ -275,7 +277,7 @@ func getSSHAuth(sshKeyPath string) (ssh.Signer, error) { if err != nil { return nil, err } - defer f.Close() + defer func() { _ = f.Close() }() buf, err := io.ReadAll(f) if err != nil { @@ -334,13 +336,17 @@ func (s *ScalewayClient) CopyImageToInstance(instanceID, path, sshKeyPath string if err != nil { return err } - defer session.Close() + defer func() { + _ = session.Close() + }() f, err := os.Open(path) if err != nil { return err } - defer f.Close() + defer func() { + _ = f.Close() + }() // code taken from bramvdbogaerde/go-scp contentBytes, err := io.ReadAll(f) @@ -356,10 +362,10 @@ func (s *ScalewayClient) CopyImageToInstance(instanceID, path, sshKeyPath string if err != nil { return } - defer w.Close() - fmt.Fprintln(w, "C0600", int64(len(contentBytes)), base) + defer func() { _ = w.Close() }() + _, _ = fmt.Fprintln(w, "C0600", int64(len(contentBytes)), base) _, _ = io.Copy(w, bytesReader) - fmt.Fprintln(w, "\x00") + _, _ = fmt.Fprintln(w, "\x00") }() _ = session.Run("/usr/bin/scp -t /root/") // TODO remove hardcoded remote path? @@ -386,7 +392,7 @@ func (s *ScalewayClient) WriteImageToVolume(instanceID, deviceName string) error if err != nil { return err } - defer session.Close() + defer func() { _ = session.Close() }() var ddPathBuf bytes.Buffer session.Stdout = &ddPathBuf @@ -400,7 +406,7 @@ func (s *ScalewayClient) WriteImageToVolume(instanceID, deviceName string) error if err != nil { return err } - defer session.Close() + defer func() { _ = session.Close() }() ddCommand := strings.Trim(ddPathBuf.String(), " \n") command := fmt.Sprintf("%s if=%s of=%s", ddCommand, s.fileName, deviceName) @@ -549,7 +555,7 @@ func (s *ScalewayClient) CreateLinuxkitInstance(instanceName, imageName, instanc return "", err } if len(imageResp.Images) != 1 { - return "", fmt.Errorf("Image %s not found or found multiple times", imageName) + return "", fmt.Errorf("image %s not found or found multiple times", imageName) } imageID := imageResp.Images[0].ID @@ -589,7 +595,7 @@ func (s *ScalewayClient) ConnectSerialPort(instanceID string) error { case scw.ZoneNlAms1: gottyURL = "https://tty-ams1.scaleway.com/" default: - return errors.New("Instance have no region") + return errors.New("instance have no region") } fullURL := fmt.Sprintf("%s?arg=%s&arg=%s", gottyURL, s.secretKey, instanceID) diff --git a/src/cmd/linuxkit/util.go b/src/cmd/linuxkit/util.go index 0dc5efd3c..b33dc04da 100644 --- a/src/cmd/linuxkit/util.go +++ b/src/cmd/linuxkit/util.go @@ -234,7 +234,7 @@ func (l *Disks) Set(value string) error { case "format": d.Format = c[1] default: - return fmt.Errorf("Unknown disk config: %s", c[0]) + return fmt.Errorf("unknown disk config: %s", c[0]) } } } @@ -255,12 +255,12 @@ func NewPublishedPort(publish string) (PublishedPort, error) { slice := strings.Split(publish, ":") if len(slice) < 2 { - return p, fmt.Errorf("Unable to parse the ports to be published, should be in format : or :/") + return p, fmt.Errorf("unable to parse the ports to be published, should be in format : or :/") } hostPort, err := strconv.ParseUint(slice[0], 10, 16) if err != nil { - return p, fmt.Errorf("The provided hostPort can't be converted to uint16") + return p, fmt.Errorf("the provided hostPort can't be converted to uint16") } right := strings.Split(slice[1], "/") @@ -270,19 +270,19 @@ func NewPublishedPort(publish string) (PublishedPort, error) { protocol = strings.TrimSpace(strings.ToLower(right[1])) } if protocol != "tcp" && protocol != "udp" { - return p, fmt.Errorf("Provided protocol is not valid, valid options are: udp and tcp") + return p, fmt.Errorf("provided protocol is not valid, valid options are: udp and tcp") } guestPort, err := strconv.ParseUint(right[0], 10, 16) if err != nil { - return p, fmt.Errorf("The provided guestPort can't be converted to uint16") + return p, fmt.Errorf("the provided guestPort can't be converted to uint16") } if hostPort < 1 || hostPort > 65535 { - return p, fmt.Errorf("Invalid hostPort: %d", hostPort) + return p, fmt.Errorf("invalid hostPort: %d", hostPort) } if guestPort < 1 || guestPort > 65535 { - return p, fmt.Errorf("Invalid guestPort: %d", guestPort) + return p, fmt.Errorf("invalid guestPort: %d", guestPort) } p.Guest = uint16(guestPort) @@ -298,7 +298,7 @@ func CreateMetadataISO(state, data string, dataPath string) ([]string, error) { // if we have neither data nor dataPath, nothing to return switch { case data != "" && dataPath != "": - return nil, fmt.Errorf("Cannot specify options for both data and dataPath") + return nil, fmt.Errorf("cannot specify options for both data and dataPath") case data == "" && dataPath == "": return []string{}, nil case data != "": @@ -307,13 +307,13 @@ func CreateMetadataISO(state, data string, dataPath string) ([]string, error) { var err error d, err = os.ReadFile(dataPath) if err != nil { - return nil, fmt.Errorf("Cannot read user data from path %s: %v", dataPath, err) + return nil, fmt.Errorf("cannot read user data from path %s: %v", dataPath, err) } } isoPath := filepath.Join(state, "data.iso") if err := WriteMetadataISO(isoPath, d); err != nil { - return nil, fmt.Errorf("Cannot write user data ISO: %v", err) + return nil, fmt.Errorf("cannot write user data ISO: %v", err) } return []string{isoPath}, nil } diff --git a/tools/go-compile/Dockerfile b/tools/go-compile/Dockerfile index b3a5a38ac..d0c536e00 100644 --- a/tools/go-compile/Dockerfile +++ b/tools/go-compile/Dockerfile @@ -17,7 +17,7 @@ RUN [ $(uname -m) = aarch64 ] && apk add --no-cache --initdb -p /out gcc || true RUN rm -rf /out/etc/apk /out/lib/apk /out/var/cache # installing golangci-lint -RUN curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b /out/go/bin v1.50.1 +RUN curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b /out/go/bin v2.0.2 FROM scratch diff --git a/tools/go-compile/compile.sh b/tools/go-compile/compile.sh index aa399df38..395458414 100755 --- a/tools/go-compile/compile.sh +++ b/tools/go-compile/compile.sh @@ -84,7 +84,7 @@ test -z $(gofmt -s -l .| grep -v .pb. | grep -v vendor/ | tee /dev/stderr) test -z $(GOOS=linux go vet $MOD_ARG -printf=false . 2>&1 | grep -v "^#" | grep -v vendor/ | tee /dev/stderr) >&2 echo "golint..." -test -z $(golangci-lint run ./... | tee /dev/stderr) +golangci-lint run ./... >&2 >&2 echo "ineffassign..." test -z $(ineffassign ./... | tee /dev/stderr)