From 22f013f35766c142a05c030046a6cfa9d5829a5e Mon Sep 17 00:00:00 2001 From: Oleksandr Redko Date: Tue, 14 Jan 2025 13:41:57 +0200 Subject: [PATCH] Simplify with "slices" and "maps" instead of "sort" --- pkg/generator.go | 17 +++++------------ pkg/parse.go | 22 +++++----------------- 2 files changed, 10 insertions(+), 29 deletions(-) diff --git a/pkg/generator.go b/pkg/generator.go index 7108dc6c..74976966 100644 --- a/pkg/generator.go +++ b/pkg/generator.go @@ -8,10 +8,11 @@ import ( "go/ast" "go/types" "io" + "maps" "os" "path/filepath" "regexp" - "sort" + "slices" "strings" "text/template" "unicode" @@ -391,14 +392,6 @@ func (g *Generator) expecterName() string { return g.mockName() + "_Expecter" } -func (g *Generator) sortedImportNames() (importNames []string) { - for name := range g.nameToPackagePath { - importNames = append(importNames, name) - } - sort.Strings(importNames) - return -} - func (g *Generator) generateImports(ctx context.Context) { log := zerolog.Ctx(ctx) @@ -406,11 +399,11 @@ func (g *Generator) generateImports(ctx context.Context) { pkgPath := g.nameToPackagePath[g.iface.Pkg.Name()] // Sort by import name so that we get a deterministic order - for _, name := range g.sortedImportNames() { - logImport := log.With().Str(logging.LogKeyImport, g.nameToPackagePath[name]).Logger() + for _, name := range slices.Sorted(maps.Keys(g.nameToPackagePath)) { + path := g.nameToPackagePath[name] + logImport := log.With().Str(logging.LogKeyImport, path).Logger() logImport.Debug().Msgf("found import") - path := g.nameToPackagePath[name] if !g.config.KeepTree && g.config.InPackage && path == pkgPath { logImport.Debug().Msgf("import (%s) equals interface's package path (%s), skipping", path, pkgPath) continue diff --git a/pkg/parse.go b/pkg/parse.go index 235e286b..256bd0b3 100644 --- a/pkg/parse.go +++ b/pkg/parse.go @@ -8,7 +8,7 @@ import ( "go/types" "os" "path/filepath" - "sort" + "slices" "strings" "github.com/rs/zerolog" @@ -224,13 +224,15 @@ func (p *Parser) Find(name string) (*Interface, error) { } func (p *Parser) Interfaces() []*Interface { - ifaces := make(sortableIFaceList, 0) + var ifaces []*Interface for _, entry := range p.files { declaredIfaces := entry.interfaces ifaces = p.packageInterfaces(entry.pkg.Types, entry.fileName, declaredIfaces, ifaces) } - sort.Sort(ifaces) + slices.SortFunc(ifaces, func(a, b *Interface) int { + return strings.Compare(a.Name, b.Name) + }) return ifaces } @@ -335,20 +337,6 @@ func (iface *Interface) Methods() []*Method { return methods } -type sortableIFaceList []*Interface - -func (s sortableIFaceList) Len() int { - return len(s) -} - -func (s sortableIFaceList) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -func (s sortableIFaceList) Less(i, j int) bool { - return strings.Compare(s[i].Name, s[j].Name) == -1 -} - type NodeVisitor struct { declaredInterfaces []string disableFuncMocks bool