1
0
mirror of https://github.com/ko-build/ko.git synced 2025-02-07 19:30:23 +02:00

Enforce more lint checks, fix findings (#492)

This commit is contained in:
Jason Hall 2021-11-05 13:26:09 -04:00 committed by GitHub
parent 9821190605
commit 0015a81537
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 96 additions and 87 deletions

View File

@ -1,19 +1,30 @@
run:
timeout: 5m
linters:
enable:
- asciicheck
- gosec
- prealloc
- stylecheck
- unconvert
- unparam
disable:
- errcheck
issues:
exclude-rules:
- path: test # Excludes /test, *_test.go etc.
linters:
- gosec
linters:
enable:
- asciicheck
- deadcode
- depguard
- errorlint
- gofmt
- gosec
- goimports
- importas
- prealloc
- revive
- misspell
- stylecheck
- tparallel
- unconvert
- unparam
- whitespace
disable:
- errcheck

View File

@ -148,7 +148,7 @@ func (g *gobuild) QualifyImport(importpath string) (string, error) {
var err error
importpath, err = g.qualifyLocalImport(importpath)
if err != nil {
return "", fmt.Errorf("qualifying local import %s: %v", importpath, err)
return "", fmt.Errorf("qualifying local import %s: %w", importpath, err)
}
}
if !strings.HasPrefix(importpath, StrictScheme) {
@ -187,7 +187,7 @@ func getGoarm(platform v1.Platform) (string, error) {
vs := strings.TrimPrefix(platform.Variant, "v")
variant, err := strconv.Atoi(vs)
if err != nil {
return "", fmt.Errorf("cannot parse arm variant %q: %v", platform.Variant, err)
return "", fmt.Errorf("cannot parse arm variant %q: %w", platform.Variant, err)
}
if variant >= 5 {
// TODO(golang/go#29373): Allow for 8 in later go versions if this is fixed.
@ -229,7 +229,7 @@ func build(ctx context.Context, ip string, dir string, platform v1.Platform, con
env, err := buildEnv(platform, os.Environ(), config.Env)
if err != nil {
return "", fmt.Errorf("could not create env for %s: %v", ip, err)
return "", fmt.Errorf("could not create env for %s: %w", ip, err)
}
cmd.Env = env
@ -260,7 +260,7 @@ func buildEnv(platform v1.Platform, userEnv, configEnv []string) ([]string, erro
if strings.HasPrefix(platform.Architecture, "arm") && platform.Variant != "" {
goarm, err := getGoarm(platform)
if err != nil {
return nil, fmt.Errorf("goarm failure: %v", err)
return nil, fmt.Errorf("goarm failure: %w", err)
}
if goarm != "" {
env = append(env, "GOARM="+goarm)
@ -318,7 +318,7 @@ func tarBinary(name, binary string, creationTime v1.Time, platform *v1.Platform)
Mode: 0555,
ModTime: creationTime.Time,
}); err != nil {
return nil, fmt.Errorf("writing dir %q: %v", dir, err)
return nil, fmt.Errorf("writing dir %q: %w", dir, err)
}
}
@ -494,7 +494,7 @@ func (g *gobuild) tarKoData(ref reference, platform *v1.Platform) (*bytes.Buffer
Mode: 0555,
ModTime: creationTime.Time,
}); err != nil {
return nil, fmt.Errorf("writing dir %q: %v", dir, err)
return nil, fmt.Errorf("writing dir %q: %w", dir, err)
}
}

View File

@ -19,6 +19,7 @@ package build
import (
"archive/tar"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
@ -431,7 +432,7 @@ func validateImage(t *testing.T, img v1.Image, baseLayers int64, creationTime v1
}
defer r.Close()
tr := tar.NewReader(r)
if _, err := tr.Next(); err == io.EOF {
if _, err := tr.Next(); errors.Is(err, io.EOF) {
t.Errorf("Layer contained no files")
}
})
@ -449,7 +450,7 @@ func validateImage(t *testing.T, img v1.Image, baseLayers int64, creationTime v1
tr := tar.NewReader(r)
for {
header, err := tr.Next()
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
} else if err != nil {
t.Errorf("Next() = %v", err)

View File

@ -142,7 +142,7 @@ func relativePath(baseDir string, importpath string) (string, error) {
}
relPath, err := filepath.Rel(baseDir, importpath)
if err != nil {
return "", fmt.Errorf("cannot determine relative path of baseDir (%q) and local path (%q): %v", baseDir, importpath, err)
return "", fmt.Errorf("cannot determine relative path of baseDir (%q) and local path (%q): %w", baseDir, importpath, err)
}
if strings.HasPrefix(relPath, "..") {
// TODO Is this assumption correct?

View File

@ -43,7 +43,6 @@ func (r reference) Path() string {
func (r reference) String() string {
if r.IsStrict() {
return StrictScheme + r.Path()
} else {
return r.Path()
}
return r.Path()
}

View File

@ -90,11 +90,11 @@ func addApply(topLevel *cobra.Command) {
bo.InsecureRegistry = po.InsecureRegistry
builder, err := makeBuilder(ctx, bo)
if err != nil {
return fmt.Errorf("error creating builder: %v", err)
return fmt.Errorf("error creating builder: %w", err)
}
publisher, err := makePublisher(po)
if err != nil {
return fmt.Errorf("error creating publisher: %v", err)
return fmt.Errorf("error creating publisher: %w", err)
}
defer publisher.Close()
@ -121,7 +121,7 @@ func addApply(topLevel *cobra.Command) {
// Wire up kubectl stdin to resolveFilesToWriter.
stdin, err := kubectlCmd.StdinPipe()
if err != nil {
return fmt.Errorf("error piping to 'kubectl apply': %v", err)
return fmt.Errorf("error piping to 'kubectl apply': %w", err)
}
// Make sure builds are cancelled if kubectl apply fails.
@ -144,7 +144,7 @@ func addApply(topLevel *cobra.Command) {
g.Go(func() error {
// Run it.
if err := kubectlCmd.Run(); err != nil {
return fmt.Errorf("error executing 'kubectl apply': %v", err)
return fmt.Errorf("error executing 'kubectl apply': %w", err)
}
return nil
})

View File

@ -63,16 +63,16 @@ func addBuild(topLevel *cobra.Command) {
bo.InsecureRegistry = po.InsecureRegistry
builder, err := makeBuilder(ctx, bo)
if err != nil {
return fmt.Errorf("error creating builder: %v", err)
return fmt.Errorf("error creating builder: %w", err)
}
publisher, err := makePublisher(po)
if err != nil {
return fmt.Errorf("error creating publisher: %v", err)
return fmt.Errorf("error creating publisher: %w", err)
}
defer publisher.Close()
images, err := publishImages(ctx, args, publisher, builder)
if err != nil {
return fmt.Errorf("failed to publish images: %v", err)
return fmt.Errorf("failed to publish images: %w", err)
}
for _, img := range images {
fmt.Println(img)

View File

@ -57,7 +57,7 @@ func getBaseImage(platform string, bo *options.BuildOptions) build.GetBase {
}
ref, err := name.ParseReference(baseImage, nameOpts...)
if err != nil {
return nil, nil, fmt.Errorf("parsing base image (%q): %v", baseImage, err)
return nil, nil, fmt.Errorf("parsing base image (%q): %w", baseImage, err)
}
// For ko.local, look in the daemon.
@ -128,7 +128,7 @@ func getTimeFromEnv(env string) (*v1.Time, error) {
seconds, err := strconv.ParseInt(epoch, 10, 64)
if err != nil {
return nil, fmt.Errorf("the environment variable %s should be the number of seconds since January 1st 1970, 00:00 UTC, got: %v", env, err)
return nil, fmt.Errorf("the environment variable %s should be the number of seconds since January 1st 1970, 00:00 UTC, got: %w", env, err)
}
return &v1.Time{Time: time.Unix(seconds, 0)}, nil
}

View File

@ -75,11 +75,11 @@ func addCreate(topLevel *cobra.Command) {
bo.InsecureRegistry = po.InsecureRegistry
builder, err := makeBuilder(ctx, bo)
if err != nil {
return fmt.Errorf("error creating builder: %v", err)
return fmt.Errorf("error creating builder: %w", err)
}
publisher, err := makePublisher(po)
if err != nil {
return fmt.Errorf("error creating publisher: %v", err)
return fmt.Errorf("error creating publisher: %w", err)
}
defer publisher.Close()
@ -106,7 +106,7 @@ func addCreate(topLevel *cobra.Command) {
// Wire up kubectl stdin to resolveFilesToWriter.
stdin, err := kubectlCmd.StdinPipe()
if err != nil {
return fmt.Errorf("error piping to 'kubectl create': %v", err)
return fmt.Errorf("error piping to 'kubectl create': %w", err)
}
// Make sure builds are cancelled if kubectl create fails.
@ -129,7 +129,7 @@ func addCreate(topLevel *cobra.Command) {
g.Go(func() error {
// Run it.
if err := kubectlCmd.Run(); err != nil {
return fmt.Errorf("error executing 'kubectl create': %v", err)
return fmt.Errorf("error executing 'kubectl create': %w", err)
}
return nil
})

View File

@ -16,6 +16,7 @@ package commands
import (
"archive/tar"
"errors"
"fmt"
"io"
"io/ioutil"
@ -80,7 +81,7 @@ If the image was not built using ko, or if it was built without embedding depend
// keep reading.
}
h, err := tr.Next()
if err == io.EOF {
if errors.Is(err, io.EOF) {
return fmt.Errorf("no ko-built executable named %q found", bin)
}
if err != nil {

View File

@ -17,6 +17,7 @@ limitations under the License.
package options
import (
"errors"
"fmt"
"os"
"path/filepath"
@ -91,15 +92,15 @@ func (bo *BuildOptions) LoadConfig() error {
v.AddConfigPath(bo.WorkingDirectory)
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return fmt.Errorf("error reading config file: %v", err)
if !errors.As(err, &viper.ConfigFileNotFoundError{}) {
return fmt.Errorf("error reading config file: %w", err)
}
}
if bo.BaseImage == "" {
ref := v.GetString("defaultBaseImage")
if _, err := name.ParseReference(ref); err != nil {
return fmt.Errorf("'defaultBaseImage': error parsing %q as image reference: %v", ref, err)
return fmt.Errorf("'defaultBaseImage': error parsing %q as image reference: %w", ref, err)
}
bo.BaseImage = ref
}
@ -109,7 +110,7 @@ func (bo *BuildOptions) LoadConfig() error {
overrides := v.GetStringMapString("baseImageOverrides")
for key, value := range overrides {
if _, err := name.ParseReference(value); err != nil {
return fmt.Errorf("'baseImageOverrides': error parsing %q as image reference: %v", value, err)
return fmt.Errorf("'baseImageOverrides': error parsing %q as image reference: %w", value, err)
}
baseImageOverrides[key] = value
}
@ -172,7 +173,7 @@ func createBuildConfigMap(workingDirectory string, configs []build.Config) (map[
pkgs, err := packages.Load(&packages.Config{Mode: packages.NeedName, Dir: baseDir}, localImportPath)
if err != nil {
return nil, fmt.Errorf("'builds': entry #%d does not contain a valid local import path (%s) for directory (%s): %v", i, localImportPath, baseDir, err)
return nil, fmt.Errorf("'builds': entry #%d does not contain a valid local import path (%s) for directory (%s): %w", i, localImportPath, baseDir, err)
}
if len(pkgs) != 1 {

View File

@ -38,16 +38,16 @@ func publishImages(ctx context.Context, importpaths []string, pub publish.Interf
return nil, err
}
if err := b.IsSupportedReference(importpath); err != nil {
return nil, fmt.Errorf("importpath %q is not supported: %v", importpath, err)
return nil, fmt.Errorf("importpath %q is not supported: %w", importpath, err)
}
img, err := b.Build(ctx, importpath)
if err != nil {
return nil, fmt.Errorf("error building %q: %v", importpath, err)
return nil, fmt.Errorf("error building %q: %w", importpath, err)
}
ref, err := pub.Publish(ctx, img, importpath)
if err != nil {
return nil, fmt.Errorf("error publishing %s: %v", importpath, err)
return nil, fmt.Errorf("error publishing %s: %w", importpath, err)
}
imgs[importpath] = ref
}

View File

@ -60,11 +60,11 @@ func addResolve(topLevel *cobra.Command) {
bo.InsecureRegistry = po.InsecureRegistry
builder, err := makeBuilder(ctx, bo)
if err != nil {
return fmt.Errorf("error creating builder: %v", err)
return fmt.Errorf("error creating builder: %w", err)
}
publisher, err := makePublisher(po)
if err != nil {
return fmt.Errorf("error creating publisher: %v", err)
return fmt.Errorf("error creating publisher: %w", err)
}
defer publisher.Close()
return resolveFilesToWriter(ctx, builder, publisher, fo, so, os.Stdout)

View File

@ -125,7 +125,7 @@ func makeBuilder(ctx context.Context, bo *options.BuildOptions) (*build.Caching,
}
opt, err := gobuildOptions(bo)
if err != nil {
return nil, fmt.Errorf("error setting up builder options: %v", err)
return nil, fmt.Errorf("error setting up builder options: %w", err)
}
innerBuilder, err := build.NewGobuilds(ctx, bo.WorkingDirectory, bo.BuildConfigs, opt...)
if err != nil {
@ -185,7 +185,7 @@ func makePublisher(po *options.PublishOptions) (publish.Interface, error) {
}
if _, err := name.NewRegistry(repoName); err != nil {
if _, err := name.NewRepository(repoName); err != nil {
return nil, fmt.Errorf("failed to parse %q as repository: %v", repoName, err)
return nil, fmt.Errorf("failed to parse %q as repository: %w", repoName, err)
}
}
@ -193,7 +193,7 @@ func makePublisher(po *options.PublishOptions) (publish.Interface, error) {
if po.OCILayoutPath != "" {
lp, err := publish.NewLayout(po.OCILayoutPath)
if err != nil {
return nil, fmt.Errorf("failed to create LayoutPublisher for %q: %v", po.OCILayoutPath, err)
return nil, fmt.Errorf("failed to create LayoutPublisher for %q: %w", po.OCILayoutPath, err)
}
publishers = append(publishers, lp)
}
@ -303,7 +303,7 @@ func resolveFilesToWriter(
})
})
if err != nil {
return fmt.Errorf("creating dep-notify graph: %v", err)
return fmt.Errorf("creating dep-notify graph: %w", err)
}
// Cleanup the fsnotify hooks when we're done.
defer g.Shutdown()
@ -358,7 +358,7 @@ func resolveFilesToWriter(
if err != nil {
// This error is sometimes expected during watch mode, so this
// isn't fatal. Just print it and keep the watch open.
err := fmt.Errorf("error processing import paths in %q: %v", f, err)
err := fmt.Errorf("error processing import paths in %q: %w", f, err)
if fo.Watch {
log.Print(err)
return nil
@ -379,7 +379,7 @@ func resolveFilesToWriter(
// yamls, and no new builds or deploys.
if err := g.Add(ip); err != nil {
// If we're in watch mode, just fail.
err := fmt.Errorf("adding importpath %q to dep graph: %v", ip, err)
err := fmt.Errorf("adding importpath %q to dep graph: %w", ip, err)
errCh <- err
return err
}
@ -402,7 +402,7 @@ func resolveFilesToWriter(
}
case err := <-errCh:
return fmt.Errorf("watching dependencies: %v", err)
return fmt.Errorf("watching dependencies: %w", err)
}
}
@ -417,14 +417,13 @@ func resolveFile(
builder build.Interface,
pub publish.Interface,
so *options.SelectorOptions) (b []byte, err error) {
var selector labels.Selector
if so.Selector != "" {
var err error
selector, err = labels.Parse(so.Selector)
if err != nil {
return nil, fmt.Errorf("unable to parse selector: %v", err)
return nil, fmt.Errorf("unable to parse selector: %w", err)
}
}
@ -446,7 +445,7 @@ func resolveFile(
for {
var doc yaml.Node
if err := decoder.Decode(&doc); err != nil {
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
return nil, err
@ -454,18 +453,17 @@ func resolveFile(
if selector != nil {
if match, err := resolve.MatchesSelector(&doc, selector); err != nil {
return nil, fmt.Errorf("error evaluating selector: %v", err)
return nil, fmt.Errorf("error evaluating selector: %w", err)
} else if !match {
continue
}
}
docNodes = append(docNodes, &doc)
}
if err := resolve.ImageReferences(ctx, docNodes, builder, pub); err != nil {
return nil, fmt.Errorf("error resolving image references: %v", err)
return nil, fmt.Errorf("error resolving image references: %w", err)
}
buf := &bytes.Buffer{}
@ -475,7 +473,7 @@ func resolveFile(
for _, doc := range docNodes {
err := e.Encode(doc)
if err != nil {
return nil, fmt.Errorf("failed to encode output: %v", err)
return nil, fmt.Errorf("failed to encode output: %w", err)
}
}
e.Close()

View File

@ -19,6 +19,7 @@ package commands
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
@ -109,7 +110,7 @@ func TestResolveMultiDocumentYAMLs(t *testing.T) {
var output string
if err := decoder.Decode(&output); err == nil {
outStructured = append(outStructured, output)
} else if err == io.EOF {
} else if errors.Is(err, io.EOF) {
break
} else {
t.Errorf("yaml.Unmarshal(%v) = %v", string(outYAML), err)
@ -314,7 +315,7 @@ func registryServerWithImage(namespace string) (*httptest.Server, error) {
imageName := fmt.Sprintf("%s/%s", s.Listener.Addr().String(), namespace)
image, err := random.Image(1024, 1)
if err != nil {
return nil, fmt.Errorf("random.Image(): %v", err)
return nil, fmt.Errorf("random.Image(): %w", err)
}
crane.Push(image, imageName)
return s, nil

View File

@ -70,11 +70,11 @@ func addRun(topLevel *cobra.Command) {
bo.InsecureRegistry = po.InsecureRegistry
builder, err := makeBuilder(ctx, bo)
if err != nil {
return fmt.Errorf("error creating builder: %v", err)
return fmt.Errorf("error creating builder: %w", err)
}
publisher, err := makePublisher(po)
if err != nil {
return fmt.Errorf("error creating publisher: %v", err)
return fmt.Errorf("error creating publisher: %w", err)
}
defer publisher.Close()
@ -87,7 +87,7 @@ func addRun(topLevel *cobra.Command) {
}
imgs, err := publishImages(ctx, importPaths, publisher, builder)
if err != nil {
return fmt.Errorf("failed to publish images: %v", err)
return fmt.Errorf("failed to publish images: %w", err)
}
// Usually only one, but this is the simple way to access the

View File

@ -241,5 +241,4 @@ func TestDefaultWithReleaseTag(t *testing.T) {
} else if strings.Contains(d.String(), "@sha256:") {
t.Errorf("Publish() = %v, wanted no digest", d.String())
}
}

View File

@ -42,7 +42,7 @@ func ImageReferences(ctx context.Context, docs []*yaml.Node, builder build.Inter
ref := strings.TrimSpace(node.Value)
if err := builder.IsSupportedReference(ref); err != nil {
return fmt.Errorf("found strict reference but %s is not a valid import path: %v", ref, err)
return fmt.Errorf("found strict reference but %s is not a valid import path: %w", ref, err)
}
refs[ref] = append(refs[ref], node)

View File

@ -17,7 +17,7 @@ package resolve
import (
"errors"
. "github.com/dprotaso/go-yit" //nolint: stylecheck // Allow this dot import.
y "github.com/dprotaso/go-yit"
"gopkg.in/yaml.v3"
"k8s.io/apimachinery/pkg/labels"
)
@ -52,19 +52,19 @@ func docKind(doc *yaml.Node) (string, error) {
return "", nil
}
it := FromNode(doc).
Filter(Intersect(
WithKind(yaml.MappingNode),
WithMapKeyValue(
WithStringValue("apiVersion"),
StringValue,
it := y.FromNode(doc).
Filter(y.Intersect(
y.WithKind(yaml.MappingNode),
y.WithMapKeyValue(
y.WithStringValue("apiVersion"),
y.StringValue,
),
)).
ValuesForMap(
// Key Predicate
WithStringValue("kind"),
y.WithStringValue("kind"),
// Value Predicate
StringValue,
y.StringValue,
)
node, ok := it()
@ -77,21 +77,21 @@ func docKind(doc *yaml.Node) (string, error) {
}
func objMatchesSelector(doc *yaml.Node, selector labels.Selector) bool {
it := FromNode(doc).
Filter(WithKind(yaml.MappingNode)).
it := y.FromNode(doc).
Filter(y.WithKind(yaml.MappingNode)).
// Return the metadata map
ValuesForMap(
// Key Predicate
WithStringValue("metadata"),
y.WithStringValue("metadata"),
// Value Predicate
WithKind(yaml.MappingNode),
y.WithKind(yaml.MappingNode),
).
// Return the labels map
ValuesForMap(
// Key Predicate
WithStringValue("labels"),
y.WithStringValue("labels"),
// Value Predicate
WithKind(yaml.MappingNode),
y.WithKind(yaml.MappingNode),
)
node, ok := it()
@ -104,11 +104,11 @@ func objMatchesSelector(doc *yaml.Node, selector labels.Selector) bool {
}
func listMatchesSelector(doc *yaml.Node, selector labels.Selector) (bool, error) {
it := FromNode(doc).ValuesForMap(
it := y.FromNode(doc).ValuesForMap(
// Key Predicate
WithStringValue("items"),
y.WithStringValue("items"),
// Value Predicate
WithKind(yaml.SequenceNode),
y.WithKind(yaml.SequenceNode),
)
node, ok := it()
@ -120,7 +120,6 @@ func listMatchesSelector(doc *yaml.Node, selector labels.Selector) (bool, error)
var matches []*yaml.Node
for _, content := range node.Content {
if _, err := docKind(content); err != nil {
return false, err
}

View File

@ -148,7 +148,6 @@ func TestMatchesSelector(t *testing.T) {
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
doc := strToYAML(t, test.input)
matches, err := MatchesSelector(doc, test.selector)
if err != nil {