Skip to content

Commit

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

Signed-off-by: Jordan Keister <[email protected]>
  • Loading branch information
grokspawn committed Feb 6, 2025
1 parent c9deb72 commit 663f843
Show file tree
Hide file tree
Showing 61 changed files with 259 additions and 152 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
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
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
16 changes: 8 additions & 8 deletions cmd/opm/serve/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ type serve struct {
}

const (
defaultCpuStartupPath string = "/debug/pprof/startup/cpu"
defaultCPUStartupPath string = "/debug/pprof/startup/cpu"
)

func NewCmd() *cobra.Command {
Expand Down Expand Up @@ -99,7 +99,7 @@ func (s *serve) run(ctx context.Context) error {
return fmt.Errorf("could not start pprof endpoint: %v", err)
}
if s.captureProfiles {
if err := p.startCpuProfileCache(); err != nil {
if err := p.startCPUProfileCache(); err != nil {
return fmt.Errorf("could not start CPU profile: %v", err)
}
}
Expand Down Expand Up @@ -169,7 +169,7 @@ func (s *serve) run(ctx context.Context) error {
health.RegisterHealthServer(grpcServer, server.NewHealthServer())
reflection.Register(grpcServer)
mainLogger.Info("serving registry")
p.stopCpuProfileCache()
p.stopCPUProfileCache()

go func() {
<-ctx.Done()
Expand Down Expand Up @@ -224,7 +224,7 @@ func (p *profilerInterface) startEndpoint() error {
mux.HandleFunc("/debug/pprof/profile", endpoint.Profile)
mux.HandleFunc("/debug/pprof/symbol", endpoint.Symbol)
mux.HandleFunc("/debug/pprof/trace", endpoint.Trace)
mux.HandleFunc(defaultCpuStartupPath, p.httpHandler)
mux.HandleFunc(defaultCPUStartupPath, p.httpHandler)

p.server = http.Server{
Addr: p.addr,
Expand All @@ -249,21 +249,21 @@ func (p *profilerInterface) startEndpoint() error {
return nil
}

func (p *profilerInterface) startCpuProfileCache() error {
func (p *profilerInterface) startCPUProfileCache() error {
// short-circuit if not enabled
if !p.isEnabled() {
return nil
}

p.logger.Infof("start caching cpu profile data at %q", defaultCpuStartupPath)
p.logger.Infof("start caching cpu profile data at %q", defaultCPUStartupPath)
if err := pprof.StartCPUProfile(&p.cache); err != nil {
return err
}

return nil
}

func (p *profilerInterface) stopCpuProfileCache() {
func (p *profilerInterface) stopCPUProfileCache() {
// short-circuit if not enabled
if !p.isEnabled() {
return
Expand All @@ -277,7 +277,7 @@ func (p *profilerInterface) httpHandler(w http.ResponseWriter, r *http.Request)
if !p.isCacheReady() {
http.Error(w, "cpu profile cache is not yet ready", http.StatusServiceUnavailable)
}
w.Write(p.cache.Bytes())
_, _ = w.Write(p.cache.Bytes())
}

func (p *profilerInterface) stopEndpoint(ctx context.Context) error {
Expand Down
1 change: 1 addition & 0 deletions pkg/api/api_to_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func ConvertAPIBundleToModelBundle(b *Bundle) (*model.Bundle, error) {
}

func convertAPIBundleToModelProperties(b *Bundle) ([]property.Property, error) {
// nolint:prealloc
var out []property.Property

providedGVKs := map[property.GVK]struct{}{}
Expand Down
Loading

0 comments on commit 663f843

Please sign in to comment.