Skip to content

Commit

Permalink
linter feature code
Browse files Browse the repository at this point in the history
- errcheck
- stylecheck
- nestif
- prealloc
- errorlint
- nonamedreturns

Signed-off-by: Jordan Keister <[email protected]>
  • Loading branch information
grokspawn committed Feb 7, 2025
1 parent c9deb72 commit 6c4be88
Show file tree
Hide file tree
Showing 80 changed files with 445 additions and 301 deletions.
13 changes: 9 additions & 4 deletions alpha/action/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,13 @@ func (r Render) Run(ctx context.Context) (*declcfg.DeclarativeConfig, error) {
if err != nil {
return nil, fmt.Errorf("create registry: %v", err)
}
defer reg.Destroy()
defer func() {
_ = reg.Destroy()
}()
r.Registry = reg
}

// nolint:prealloc
var cfgs []declcfg.DeclarativeConfig
for _, ref := range r.Refs {
cfg, err := r.renderReference(ctx, ref)
Expand Down Expand Up @@ -123,6 +126,7 @@ func (r Render) renderReference(ctx context.Context, ref string) (*declcfg.Decla
if err != nil {
return r.imageToDeclcfg(ctx, ref)
}
// nolint:nestif
if stat.IsDir() {
dirEntries, err := os.ReadDir(ref)
if err != nil {
Expand Down Expand Up @@ -178,6 +182,7 @@ func (r Render) imageToDeclcfg(ctx context.Context, imageRef string) (*declcfg.D
}

var cfg *declcfg.DeclarativeConfig
// nolint:nestif
if dbFile, ok := labels[containertools.DbLocationLabel]; ok {
if !r.AllowedRefMask.Allowed(RefSqliteImage) {
return nil, fmt.Errorf("cannot render sqlite image: %w", ErrNotAllowed)
Expand Down Expand Up @@ -326,10 +331,10 @@ func bundleToDeclcfg(bundle *registry.Bundle) (*declcfg.Bundle, error) {
return nil, fmt.Errorf("get related images for bundle %q: %v", bundle.Name, err)
}

var csvJson []byte
var csvJSON []byte
for _, obj := range bundle.Objects {
if obj.GetKind() == "ClusterServiceVersion" {
csvJson, err = json.Marshal(obj)
csvJSON, err = json.Marshal(obj)
if err != nil {
return nil, fmt.Errorf("marshal CSV JSON for bundle %q: %v", bundle.Name, err)
}
Expand All @@ -344,7 +349,7 @@ func bundleToDeclcfg(bundle *registry.Bundle) (*declcfg.Bundle, error) {
Properties: props,
RelatedImages: relatedImages,
Objects: objs,
CsvJSON: string(csvJson),
CsvJSON: string(csvJSON),
}, nil
}

Expand Down
6 changes: 3 additions & 3 deletions alpha/declcfg/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ func sendPaths(ctx context.Context, root fs.FS, pathChan chan<- string) error {
})
}

func parseMetaPaths(ctx context.Context, root fs.FS, pathChan <-chan string, walkFn WalkMetasFSFunc, options LoadOptions) error {
func parseMetaPaths(ctx context.Context, root fs.FS, pathChan <-chan string, walkFn WalkMetasFSFunc, _ LoadOptions) error {
for {
select {
case <-ctx.Done(): // don't block on receiving from pathChan
Expand Down Expand Up @@ -205,11 +205,11 @@ func readBundleObjects(b *Bundle) error {
if err := json.Unmarshal(props.Value, &obj); err != nil {
return fmt.Errorf("package %q, bundle %q: parse property at index %d as bundle object: %v", b.Package, b.Name, i, err)
}
objJson, err := yaml.ToJSON(obj.Data)
objJSON, err := yaml.ToJSON(obj.Data)
if err != nil {
return fmt.Errorf("package %q, bundle %q: convert bundle object property at index %d to JSON: %v", b.Package, b.Name, i, err)
}
b.Objects = append(b.Objects, string(objJson))
b.Objects = append(b.Objects, string(objJSON))
}
b.CsvJSON = extractCSV(b.Objects)
return nil
Expand Down
1 change: 1 addition & 0 deletions alpha/declcfg/model_to_declcfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ func traverseModelChannels(mpkg model.Package) ([]Channel, []Bundle) {
channels = append(channels, c)
}

// nolint:prealloc
var bundles []Bundle
for _, b := range bundleMap {
b.Properties = property.Deduplicate(b.Properties)
Expand Down
34 changes: 18 additions & 16 deletions alpha/declcfg/write.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ func (writer *MermaidWriter) WriteChannels(cfg DeclarativeConfig, out io.Writer)

for _, c := range cfg.Channels {
filteredChannel := writer.filterChannel(&c, versionMap, minVersion, minEdgePackage)
// nolint:nestif
if filteredChannel != nil {
pkgBuilder, ok := pkgs[c.Package]
if !ok {
Expand All @@ -154,26 +155,26 @@ func (writer *MermaidWriter) WriteChannels(cfg DeclarativeConfig, out io.Writer)
bundleDeprecation = ":::deprecated"
}

entryId := fmt.Sprintf("%s-%s", channelID, ce.Name)
pkgBuilder.WriteString(fmt.Sprintf(" %s[%q]%s\n", entryId, ce.Name, bundleDeprecation))
entryID := fmt.Sprintf("%s-%s", channelID, ce.Name)
pkgBuilder.WriteString(fmt.Sprintf(" %s[%q]%s\n", entryID, ce.Name, bundleDeprecation))

if len(ce.Replaces) > 0 {
replacesId := fmt.Sprintf("%s-%s", channelID, ce.Replaces)
pkgBuilder.WriteString(fmt.Sprintf(" %s[%q]-- %s --> %s[%q]\n", replacesId, ce.Replaces, "replace", entryId, ce.Name))
replacesID := fmt.Sprintf("%s-%s", channelID, ce.Replaces)
pkgBuilder.WriteString(fmt.Sprintf(" %s[%q]-- %s --> %s[%q]\n", replacesID, ce.Replaces, "replace", entryID, ce.Name))
}
if len(ce.Skips) > 0 {
for _, s := range ce.Skips {
skipsId := fmt.Sprintf("%s-%s", channelID, s)
pkgBuilder.WriteString(fmt.Sprintf(" %s[%q]-- %s --> %s[%q]\n", skipsId, s, "skip", entryId, ce.Name))
skipsID := fmt.Sprintf("%s-%s", channelID, s)
pkgBuilder.WriteString(fmt.Sprintf(" %s[%q]-- %s --> %s[%q]\n", skipsID, s, "skip", entryID, ce.Name))
}
}
if len(ce.SkipRange) > 0 {
skipRange, err := semver.ParseRange(ce.SkipRange)
if err == nil {
for _, edgeName := range filteredChannel.Entries {
if skipRange(versionMap[edgeName.Name]) {
skipRangeId := fmt.Sprintf("%s-%s", channelID, edgeName.Name)
pkgBuilder.WriteString(fmt.Sprintf(" %s[%q]-- \"%s(%s)\" --> %s[%q]\n", skipRangeId, edgeName.Name, "skipRange", ce.SkipRange, entryId, ce.Name))
skipRangeID := fmt.Sprintf("%s-%s", channelID, edgeName.Name)
pkgBuilder.WriteString(fmt.Sprintf(" %s[%q]-- \"%s(%s)\" --> %s[%q]\n", skipRangeID, edgeName.Name, "skipRange", ce.SkipRange, entryID, ce.Name))
}
}
} else {
Expand All @@ -186,8 +187,8 @@ func (writer *MermaidWriter) WriteChannels(cfg DeclarativeConfig, out io.Writer)
}
}

out.Write([]byte("graph LR\n"))
out.Write([]byte(fmt.Sprintf(" classDef deprecated fill:#E8960F\n")))
_, _ = out.Write([]byte("graph LR\n"))
_, _ = out.Write([]byte(" classDef deprecated fill:#E8960F\n"))
pkgNames := []string{}
for pname := range pkgs {
pkgNames = append(pkgNames, pname)
Expand All @@ -196,19 +197,19 @@ func (writer *MermaidWriter) WriteChannels(cfg DeclarativeConfig, out io.Writer)
return pkgNames[i] < pkgNames[j]
})
for _, pkgName := range pkgNames {
out.Write([]byte(fmt.Sprintf(" %%%% package %q\n", pkgName)))
out.Write([]byte(fmt.Sprintf(" subgraph %q\n", pkgName)))
out.Write([]byte(pkgs[pkgName].String()))
out.Write([]byte(" end\n"))
_, _ = out.Write([]byte(fmt.Sprintf(" %%%% package %q\n", pkgName)))
_, _ = out.Write([]byte(fmt.Sprintf(" subgraph %q\n", pkgName)))
_, _ = out.Write([]byte(pkgs[pkgName].String()))
_, _ = out.Write([]byte(" end\n"))
}

if deprecatedPackage != "" {
out.Write([]byte(fmt.Sprintf("style %s fill:#989695\n", deprecatedPackage)))
_, _ = out.Write([]byte(fmt.Sprintf("style %s fill:#989695\n", deprecatedPackage)))
}

if len(deprecatedChannels) > 0 {
for _, deprecatedChannel := range deprecatedChannels {
out.Write([]byte(fmt.Sprintf("style %s fill:#DCD0FF\n", deprecatedChannel)))
_, _ = out.Write([]byte(fmt.Sprintf("style %s fill:#DCD0FF\n", deprecatedChannel)))
}
}

Expand Down Expand Up @@ -236,6 +237,7 @@ func (writer *MermaidWriter) filterChannel(c *Channel, versionMap map[string]sem
out := &Channel{Name: c.Name, Package: c.Package, Properties: c.Properties, Entries: []ChannelEntry{}}
for _, ce := range c.Entries {
filteredCe := ChannelEntry{Name: ce.Name}
// nolint:nestif
if writer.MinEdgeName == "" {
// no minimum-edge specified
filteredCe.SkipRange = ce.SkipRange
Expand Down
7 changes: 5 additions & 2 deletions alpha/model/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package model

import (
"bytes"
"errors"
"fmt"
"strings"
)
Expand Down Expand Up @@ -31,7 +32,7 @@ func (v *validationError) Error() string {

func (v *validationError) errorPrefix(prefix []rune, last bool, seen []error) string {
for _, s := range seen {
if v == s {
if errors.Is(v, s) {
return ""
}
}
Expand All @@ -56,7 +57,9 @@ func (v *validationError) errorPrefix(prefix []rune, last bool, seen []error) st
} else {
subPrefix = append(subPrefix, []rune("├── ")...)
}
if verr, ok := serr.(*validationError); ok {

var verr *validationError
if errors.As(serr, &verr) {
errMsg.WriteString(verr.errorPrefix(subPrefix, subLast, seen))
} else {
errMsg.WriteString(fmt.Sprintf("%s%s\n", string(subPrefix), serr))
Expand Down
1 change: 1 addition & 0 deletions alpha/model/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ func (i *Icon) Validate() error {
return result.orNil()
}

// nolint:unused
func (i *Icon) validateData() error {
if !filetype.IsImage(i.Data) {
return errors.New("icon data is not an image")
Expand Down
3 changes: 3 additions & 0 deletions alpha/template/semver/semver.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func (t Template) Render(ctx context.Context) (*declcfg.DeclarativeConfig, error
return nil, fmt.Errorf("render: unable to read file: %v", err)
}

// nolint:prealloc
var cfgs []declcfg.DeclarativeConfig

bundleDict := buildBundleList(*sv)
Expand Down Expand Up @@ -211,6 +212,7 @@ func (sv *semverTemplate) generateChannels(semverChannels *bundleVersions) []dec

// sort the channel archetypes in ascending order so we can traverse the bundles in order of
// their source channel's priority
// nolint:prealloc
var archetypesByPriority []channelArchetype
for k := range channelPriorities {
archetypesByPriority = append(archetypesByPriority, k)
Expand Down Expand Up @@ -391,6 +393,7 @@ func getMinorVersion(v semver.Version) semver.Version {
}
}

// nolint:unused
func getMajorVersion(v semver.Version) semver.Version {
return semver.Version{
Major: v.Major,
Expand Down
2 changes: 1 addition & 1 deletion cmd/opm/alpha/bundle/extract.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func init() {
extractCmd.Flags().StringP("namespace", "n", "openshift-operator-lifecycle-manager", "namespace to write configmap data")
extractCmd.Flags().Uint64P("datalimit", "l", 1<<20, "maximum limit in bytes for total bundle data")
extractCmd.Flags().BoolP("gzip", "z", false, "enable gzip compression of configmap data")
extractCmd.MarkPersistentFlagRequired("configmapname")
_ = extractCmd.MarkPersistentFlagRequired("configmapname")
}

func runExtractCmd(cmd *cobra.Command, _ []string) error {
Expand Down
1 change: 1 addition & 0 deletions cmd/opm/alpha/bundle/unpack.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ func unpackBundle(cmd *cobra.Command, args []string) error {
return err
}

// nolint:nestif
if info, err := os.Stat(out); err != nil {
if os.IsNotExist(err) {
err = os.MkdirAll(out, 0755)
Expand Down
12 changes: 9 additions & 3 deletions cmd/opm/alpha/list/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ func newPackagesCmd() *cobra.Command {
if err != nil {
logger.Fatal(err)
}
defer reg.Destroy()
defer func() {
_ = reg.Destroy()
}()
lp := action.ListPackages{IndexReference: args[0], Registry: reg}
res, err := lp.Run(cmd.Context())
if err != nil {
Expand Down Expand Up @@ -72,7 +74,9 @@ func newChannelsCmd() *cobra.Command {
if err != nil {
logger.Fatal(err)
}
defer reg.Destroy()
defer func() {
_ = reg.Destroy()
}()
lc := action.ListChannels{IndexReference: args[0], Registry: reg}
if len(args) > 1 {
lc.PackageName = args[1]
Expand Down Expand Up @@ -106,7 +110,9 @@ for each channel in which the bundle is present).
if err != nil {
logger.Fatal(err)
}
defer reg.Destroy()
defer func() {
_ = reg.Destroy()
}()
lb := action.ListBundles{IndexReference: args[0], Registry: reg}
if len(args) > 1 {
lb.PackageName = args[1]
Expand Down
4 changes: 3 additions & 1 deletion cmd/opm/alpha/template/basic.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ When FILE is '-' or not provided, the template is read from standard input`,
if err != nil {
log.Fatalf("creating containerd registry: %v", err)
}
defer reg.Destroy()
defer func() {
_ = reg.Destroy()
}()

var m *migrations.Migrations
if migrateLevel != "" {
Expand Down
4 changes: 3 additions & 1 deletion cmd/opm/alpha/template/semver.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ When FILE is '-' or not provided, the template is read from standard input`,
if err != nil {
log.Fatalf("creating containerd registry: %v", err)
}
defer reg.Destroy()
defer func() {
_ = reg.Destroy()
}()

var m *migrations.Migrations
if migrateLevel != "" {
Expand Down
2 changes: 1 addition & 1 deletion cmd/opm/generate/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ A separate builder and base image can be specified. The builder image may not be
cmd.Flags().StringVarP(&baseImage, "base-image", "i", containertools.DefaultBinarySourceImage, "Image base to use to build catalog.")
cmd.Flags().StringVarP(&builderImage, "builder-image", "b", containertools.DefaultBinarySourceImage, "Image to use as a build stage.")
cmd.Flags().StringSliceVarP(&extraLabelStrs, "extra-labels", "l", []string{}, "Extra labels to include in the generated Dockerfile. Labels should be of the form 'key=value'.")
cmd.Flags().MarkDeprecated("binary-image", "use --base-image instead")
_ = cmd.Flags().MarkDeprecated("binary-image", "use --base-image instead")
cmd.MarkFlagsMutuallyExclusive("binary-image", "base-image")
return cmd
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/opm/internal/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func GetTLSOptions(cmd *cobra.Command) (bool, bool, error) {
// This works in tandem with opm/index/cmd, which adds the relevant flags as persistent
// as part of the root command (cmd/root/cmd) initialization
func CreateCLIRegistry(cmd *cobra.Command) (*containerdregistry.Registry, error) {
skipTlsVerify, useHTTP, err := GetTLSOptions(cmd)
skipTLSVerify, useHTTP, err := GetTLSOptions(cmd)
if err != nil {
return nil, err
}
Expand All @@ -58,7 +58,7 @@ func CreateCLIRegistry(cmd *cobra.Command) (*containerdregistry.Registry, error)

reg, err := containerdregistry.NewRegistry(
containerdregistry.WithCacheDir(cacheDir),
containerdregistry.SkipTLSVerify(skipTlsVerify),
containerdregistry.SkipTLSVerify(skipTLSVerify),
containerdregistry.WithPlainHTTP(useHTTP),
containerdregistry.WithLog(log.Null()),
)
Expand Down
11 changes: 7 additions & 4 deletions cmd/opm/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"errors"
"os"
"os/signal"
"syscall"
Expand All @@ -20,15 +21,17 @@ func main() {
defer cancel()

if err := cmd.ExecuteContext(ctx); err != nil {
agg, ok := err.(utilerrors.Aggregate)
if !ok {
var agg utilerrors.Aggregate
if !errors.As(err, &agg) {
os.Exit(1)
}
for _, e := range agg.Errors() {
if _, ok := e.(registrylib.BundleImageAlreadyAddedErr); ok {
var bundleAlreadyAddedErr registrylib.BundleImageAlreadyAddedErr
if errors.As(e, &bundleAlreadyAddedErr) {
os.Exit(2)
}
if _, ok := e.(registrylib.PackageVersionAlreadyAddedErr); ok {
var packageVersionAlreadyAddedErr registrylib.PackageVersionAlreadyAddedErr
if errors.As(e, &packageVersionAlreadyAddedErr) {
os.Exit(3)
}
}
Expand Down
4 changes: 3 additions & 1 deletion cmd/opm/render/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ database files.
if err != nil {
log.Fatal(err)
}
defer reg.Destroy()
defer func() {
_ = reg.Destroy()
}()

render.Registry = reg

Expand Down
Loading

0 comments on commit 6c4be88

Please sign in to comment.