From f76b8744be9aef2684af967c40249c15a92585bd Mon Sep 17 00:00:00 2001 From: southclaws Date: Tue, 21 May 2024 10:36:16 +0100 Subject: [PATCH] fix template path in generated code uses OS specific path separators #75 --- cmd_generate.go | 11 ++++++---- cmd_generate_test.go | 24 +++++++++------------ generator/generator.go | 47 +++++++++++++++++++++--------------------- loader/gitpath_test.go | 4 ++-- loader/loader.go | 3 +-- pkg/package.go | 4 ++-- 6 files changed, 46 insertions(+), 47 deletions(-) diff --git a/cmd_generate.go b/cmd_generate.go index d809f5b0..80643384 100644 --- a/cmd_generate.go +++ b/cmd_generate.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "os" + "path" "path/filepath" "regexp" "strings" @@ -46,7 +47,7 @@ func NewGenerateCommand(l remoteTemplateLoader) *GenerateCommand { }, } - //this flagset loads flags values to the command fields + // this flagset loads flags values to the command fields fs := &flag.FlagSet{} fs.BoolVar(&gc.noGenerate, "g", false, "don't put //go:generate instruction to the generated code") fs.StringVar(&gc.interfaceName, "i", "", `the source interface name, i.e. "Reader"`) @@ -129,7 +130,7 @@ func (gc *GenerateCommand) getOptions() (*generator.Options, error) { HeaderTemplate: headerTemplate, HeaderVars: map[string]interface{}{ "DisableGoGenerate": gc.noGenerate, - "OutputFileName": filepath.Base(gc.outputFile), + "OutputFileName": path.Base(gc.outputFile), "VarsArgs": varsToArgs(gc.vars), }, Vars: gc.vars.toMap(), @@ -289,8 +290,10 @@ func downFirst(s string) string { return "" } -var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)") -var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])") +var ( + matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)") + matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])") +) func toSnakeCase(str string) string { result := matchFirstCap.ReplaceAllString(str, "${1}_${2}") diff --git a/cmd_generate_test.go b/cmd_generate_test.go index 17195b65..582905bb 100644 --- a/cmd_generate_test.go +++ b/cmd_generate_test.go @@ -3,7 +3,7 @@ package gowrap import ( "io" "os" - "path/filepath" + "path" "testing" "time" @@ -18,18 +18,18 @@ func TestNewGenerateCommand(t *testing.T) { } func Test_loader_Load(t *testing.T) { - var unexpectedErr = errors.New("unexpected error") + unexpectedErr := errors.New("unexpected error") tests := []struct { name string init func(t minimock.Tester) loader - inspect func(r loader, t *testing.T) //inspects loader after execution of Load + inspect func(r loader, t *testing.T) // inspects loader after execution of Load template string want1 []byte want2 string wantErr bool - inspectErr func(err error, t *testing.T) //use for more precise error evaluation + inspectErr func(err error, t *testing.T) // use for more precise error evaluation }{ { name: "file read error", @@ -100,13 +100,12 @@ func Test_loader_Load(t *testing.T) { } else { assert.NoError(t, err) } - }) } } func TestGenerateCommand_getOptions(t *testing.T) { - var absError = errors.New("abs error") + absError := errors.New("abs error") tests := []struct { name string @@ -114,9 +113,8 @@ func TestGenerateCommand_getOptions(t *testing.T) { want1 *generator.Options wantErr bool - inspectErr func(err error, t *testing.T) //use for more precise error evaluation + inspectErr func(err error, t *testing.T) // use for more precise error evaluation }{ - { name: "unexisting output path", init: func(t minimock.Tester) *GenerateCommand { @@ -149,7 +147,6 @@ func TestGenerateCommand_getOptions(t *testing.T) { } else { assert.NoError(t, err) } - }) } } @@ -158,12 +155,12 @@ func TestGenerateCommand_Run(t *testing.T) { tests := []struct { name string init func(t minimock.Tester) *GenerateCommand - inspect func(r *GenerateCommand, t *testing.T) //inspects *GenerateCommand after execution of Run + inspect func(r *GenerateCommand, t *testing.T) // inspects *GenerateCommand after execution of Run args []string wantErr bool - inspectErr func(err error, t *testing.T) //use for more precise error evaluation + inspectErr func(err error, t *testing.T) // use for more precise error evaluation }{ { name: "parse args error", @@ -244,7 +241,7 @@ func TestGenerateCommand_Run(t *testing.T) { )`), "local/file", nil) cmd.filepath.WriteFile = func(filename string, data []byte, perm os.FileMode) error { - cmd.outputFile = filepath.Join(t.TempDir(), cmd.outputFile) + cmd.outputFile = path.Join(t.TempDir(), cmd.outputFile) return os.WriteFile(cmd.outputFile, data, perm) } return cmd @@ -289,7 +286,6 @@ func TestGenerateCommand_Run(t *testing.T) { } else { assert.NoError(t, err) } - }) } } @@ -352,7 +348,7 @@ func TestVars_toMap(t *testing.T) { func TestVars_Set(t *testing.T) { tests := []struct { name string - inspect func(r vars, t *testing.T) //inspects vars after execution of Set + inspect func(r vars, t *testing.T) // inspects vars after execution of Set s string }{ { diff --git a/generator/generator.go b/generator/generator.go index 34e5e328..8d034c29 100644 --- a/generator/generator.go +++ b/generator/generator.go @@ -3,13 +3,12 @@ package generator import ( "bytes" "fmt" - "path/filepath" - "sort" - "strings" - "go/ast" "go/token" "io" + "path" + "sort" + "strings" "text/template" "github.com/pkg/errors" @@ -95,38 +94,38 @@ type TemplateInputInterface struct { // Options of the NewGenerator constructor type Options struct { - //InterfaceName is a name of interface type + // InterfaceName is a name of interface type InterfaceName string - //Imports from the file with interface definition + // Imports from the file with interface definition Imports []string - //SourcePackage is an import path or a relative path of the package that contains the source interface + // SourcePackage is an import path or a relative path of the package that contains the source interface SourcePackage string - //SourcePackageAlias is an import selector defauls is source package name + // SourcePackageAlias is an import selector defauls is source package name SourcePackageAlias string - //OutputFile name which is used to detect destination package name and also to fix imports in the resulting source + // OutputFile name which is used to detect destination package name and also to fix imports in the resulting source OutputFile string - //HeaderTemplate is used to generate package clause and comment over the generated source + // HeaderTemplate is used to generate package clause and comment over the generated source HeaderTemplate string - //BodyTemplate generates import section, decorator constructor and methods + // BodyTemplate generates import section, decorator constructor and methods BodyTemplate string - //Vars additional vars that are passed to the templates from the command line + // Vars additional vars that are passed to the templates from the command line Vars map[string]interface{} - //HeaderVars header specific variables + // HeaderVars header specific variables HeaderVars map[string]interface{} - //Funcs is a map of helper functions that can be used within a template + // Funcs is a map of helper functions that can be used within a template Funcs template.FuncMap - //LocalPrefix is a comma-separated string of import path prefixes, which, if set, instructs Process to sort the import - //paths with the given prefixes into another group after 3rd-party packages. + // LocalPrefix is a comma-separated string of import path prefixes, which, if set, instructs Process to sort the import + // paths with the given prefixes into another group after 3rd-party packages. LocalPrefix string } @@ -154,8 +153,10 @@ type processOutput struct { imports []*ast.ImportSpec } -var errEmptyInterface = errors.New("interface has no methods") -var errUnexportedMethod = errors.New("unexported method") +var ( + errEmptyInterface = errors.New("interface has no methods") + errUnexportedMethod = errors.New("unexported method") +) // NewGenerator returns Generator initialized with options func NewGenerator(options Options) (*Generator, error) { @@ -184,7 +185,7 @@ func NewGenerator(options Options) (*Generator, error) { return nil, errors.Wrap(err, "failed to load source package") } - dstPackagePath := filepath.Dir(options.OutputFile) + dstPackagePath := path.Dir(options.OutputFile) if !strings.HasPrefix(dstPackagePath, "/") && !strings.HasPrefix(dstPackagePath, "./") { dstPackagePath = "./" + dstPackagePath } @@ -265,7 +266,7 @@ func makeImports(imports []*ast.ImportSpec) []string { func loadDestinationPackage(path string) (*packages.Package, error) { dstPackage, err := pkg.Load(path) if err != nil { - //using directory name as a package name + // using directory name as a package name dstPackage, err = makePackage(path) } @@ -274,9 +275,9 @@ func loadDestinationPackage(path string) (*packages.Package, error) { var errNoPackageName = errors.New("failed to determine the destination package name") -func makePackage(path string) (*packages.Package, error) { - name := filepath.Base(path) - if name == string(filepath.Separator) || name == "." { +func makePackage(packagpath string) (*packages.Package, error) { + name := path.Base(packagpath) + if name == string("/") || name == "." { return nil, errNoPackageName } diff --git a/loader/gitpath_test.go b/loader/gitpath_test.go index c6adc629..0f0df0d7 100644 --- a/loader/gitpath_test.go +++ b/loader/gitpath_test.go @@ -1,7 +1,7 @@ package loader import ( - "path/filepath" + "path" "testing" "github.com/stretchr/testify/assert" @@ -24,7 +24,7 @@ func Test_gitRootPath(t *testing.T) { got, err := gitRootPath() require.NoError(t, err) - assert.Equal(t, tt.want, filepath.Base(got)) + assert.Equal(t, tt.want, path.Base(got)) }) } } diff --git a/loader/loader.go b/loader/loader.go index 71c735e0..b0bc52b3 100644 --- a/loader/loader.go +++ b/loader/loader.go @@ -6,7 +6,6 @@ import ( "io" "net/http" "os" - "path/filepath" "strings" "github.com/pkg/errors" @@ -123,7 +122,7 @@ func (l Loader) absGitPath(path string) (string, error) { return "", err } - return filepath.Join(gitRoot, path), nil + return path.Join(gitRoot, path), nil } var errTemplateNotFound = errors.New("remote template not found") diff --git a/pkg/package.go b/pkg/package.go index b58765e3..ea70de34 100644 --- a/pkg/package.go +++ b/pkg/package.go @@ -5,7 +5,7 @@ import ( "go/ast" "go/parser" "go/token" - "path/filepath" + "path" "golang.org/x/tools/go/packages" ) @@ -54,5 +54,5 @@ func Dir(p *packages.Package) string { return p.PkgPath } - return filepath.Dir(files[0]) + return path.Dir(files[0]) }