Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix template path in generated code uses OS specific path separators #75 #88

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions cmd_generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"regexp"
"strings"
Expand Down Expand Up @@ -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"`)
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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}")
Expand Down
24 changes: 10 additions & 14 deletions cmd_generate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package gowrap
import (
"io"
"os"
"path/filepath"
"path"
"testing"
"time"

Expand All @@ -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",
Expand Down Expand Up @@ -100,23 +100,21 @@ 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
init func(t minimock.Tester) *GenerateCommand

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 {
Expand Down Expand Up @@ -149,7 +147,6 @@ func TestGenerateCommand_getOptions(t *testing.T) {
} else {
assert.NoError(t, err)
}

})
}
}
Expand All @@ -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",
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -289,7 +286,6 @@ func TestGenerateCommand_Run(t *testing.T) {
} else {
assert.NoError(t, err)
}

})
}
}
Expand Down Expand Up @@ -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
}{
{
Expand Down
47 changes: 24 additions & 23 deletions generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
}

Expand All @@ -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
}

Expand Down
4 changes: 2 additions & 2 deletions loader/gitpath_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package loader

import (
"path/filepath"
"path"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -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))
})
}
}
Expand Down
3 changes: 1 addition & 2 deletions loader/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"io"
"net/http"
"os"
"path/filepath"
"strings"

"github.com/pkg/errors"
Expand Down Expand Up @@ -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")
Expand Down
4 changes: 2 additions & 2 deletions pkg/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"go/ast"
"go/parser"
"go/token"
"path/filepath"
"path"

"golang.org/x/tools/go/packages"
)
Expand Down Expand Up @@ -54,5 +54,5 @@ func Dir(p *packages.Package) string {
return p.PkgPath
}

return filepath.Dir(files[0])
return path.Dir(files[0])
}