Skip to content

Commit

Permalink
Merge pull request #10 from k-yomo/fix-missing-package-name
Browse files Browse the repository at this point in the history
Fix import bug happened when the package name is same as th target package
  • Loading branch information
k-yomo authored Sep 9, 2021
2 parents efe6206 + d550521 commit 49fb370
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 25 deletions.
6 changes: 3 additions & 3 deletions cmd/fixtory/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ func main() {
outputPath = filepath.Join(targetDir, "fixtory_gen.go")
}

outputDir, _ := path.Split(outputPath)
newWriter := func() (io.Writer, func(), error) {
dir, _ := path.Split(outputPath)
if err := os.MkdirAll(dir, 0755); err != nil {
if err := os.MkdirAll(outputDir, 0755); err != nil {
return nil, nil, xerrors.Errorf("create directory: %w", err)
}
writer, err := os.Create(outputPath)
Expand All @@ -64,7 +64,7 @@ func main() {
}
return writer, func() { _ = writer.Close() }, nil
}
if err := fixtory.Generate(targetDir, types, *pkgName, newWriter); err != nil {
if err := fixtory.Generate(targetDir, filepath.Dir(outputDir), types, *pkgName, newWriter); err != nil {
color.Red("%+v", err)
os.Exit(1)
}
Expand Down
3 changes: 2 additions & 1 deletion example/article.fixtory.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions factory_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package fixtory

import (
"github.com/google/go-cmp/cmp"
"reflect"
"testing"

"github.com/google/go-cmp/cmp"
)

type testStruct struct {
Expand Down Expand Up @@ -89,7 +90,7 @@ func TestBuilder_Build(t *testing.T) {
want: &testStruct{Int: 5},
},
{
name: "struct is overwritten by traits, zero, each param",
name: "struct is overwritten by traits, zero, each param",
builder: fac.NewBuilder(bluePrint, testStruct{String: "setByTrait1", Int: 10}, testStruct{String: "setByTrait2", Array: []int{1, 2, 3}}).Zero("Map").EachParam(testStruct{Float: 10.9}),
want: &testStruct{
String: "setByTrait2",
Expand All @@ -104,7 +105,7 @@ func TestBuilder_Build(t *testing.T) {
},
},
{
name: "empty fields do not overwrite",
name: "empty fields do not overwrite",
builder: fac.NewBuilder(bluePrint, testStruct{}).EachParam(testStruct{}),
want: &testStruct{
String: "setByBlueprint",
Expand Down
7 changes: 4 additions & 3 deletions factorytpl.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 28 additions & 13 deletions generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,41 @@ package fixtory
import (
"bytes"
"fmt"
"github.com/k-yomo/fixtory/pkg/astutil"
"go/ast"
"go/format"
"golang.org/x/xerrors"
"io"
"strings"
"text/template"

"github.com/k-yomo/fixtory/pkg/astutil"
"golang.org/x/xerrors"
)

func Generate(targetDir string, types []string, pkgName string, newWriter func() (writer io.Writer, close func(), err error)) error {
func Generate(targetDir string, outputDir string, types []string, pkgName string, newWriter func() (writer io.Writer, close func(), err error)) error {
targetTypeMap := map[string]bool{}
for _, t := range types {
targetTypeMap[t] = true
}
if len(targetTypeMap) == 0 {
return nil
}

walkerMap, err := astutil.DirToAstWalker(targetDir)
if err != nil {
return err
}
if len(walkerMap) == 0 {
return nil
}
for _, walker := range walkerMap {
if len(targetTypeMap) == 0 {
break
if pkgName == "" {
pkgName = walker.Pkg.Name
}

importPkgName := walker.Pkg.Name
shouldImportPkg := outputDir != targetDir
if shouldImportPkg && pkgName == walker.Pkg.Name {
importPkgName = fmt.Sprintf("_%s", importPkgName)
}
body := new(bytes.Buffer)
for _, spec := range walker.AllStructSpecs() {
Expand All @@ -43,16 +56,16 @@ func Generate(targetDir string, types []string, pkgName string, newWriter func()
}
tpl := template.Must(template.New("factory").Funcs(template.FuncMap{"ToLower": strings.ToLower}).Parse(factoryTpl))
st := spec.Name.Name
if pkgName != "" {
st = fmt.Sprintf("%s.%s", walker.Pkg.Name, st)
if shouldImportPkg {
st = fmt.Sprintf("%s.%s", importPkgName, st)
}
params := struct {
StructName string
Struct string
Struct string
FieldNames []string
}{
StructName: spec.Name.Name,
Struct: st,
Struct: st,
FieldNames: fieldNames,
}
if err := tpl.Execute(body, params); err != nil {
Expand All @@ -64,10 +77,12 @@ func Generate(targetDir string, types []string, pkgName string, newWriter func()
}

var importPackages []string
if pkgName == "" {
pkgName = walker.Pkg.Name
} else {
importPackages = append(importPackages, walker.PkgPath)
if shouldImportPkg {
if pkgName == walker.Pkg.Name {
importPackages = append(importPackages, fmt.Sprintf(`%s "%s"`, importPkgName, walker.PkgPath))
} else {
importPackages = append(importPackages, fmt.Sprintf(`"%s"`, walker.PkgPath))
}
}

out := new(bytes.Buffer)
Expand Down
6 changes: 4 additions & 2 deletions generate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
func TestGenerate(t *testing.T) {
type args struct {
targetDir string
outputDir string
types []string
pkgName string
newWriter func() (io.Writer, func(), error)
Expand All @@ -22,17 +23,18 @@ func TestGenerate(t *testing.T) {
name: "generate factory for Author, Article in example directory",
args: args{
targetDir: "example",
outputDir: "example",
types: []string{"Article", "Author"},
newWriter: func() (io.Writer, func(), error) {
var b bytes.Buffer
return &b, func() { }, nil
return &b, func() {}, nil
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := Generate(tt.args.targetDir, tt.args.types, tt.args.pkgName, tt.args.newWriter); (err != nil) != tt.wantErr {
if err := Generate(tt.args.targetDir, tt.args.outputDir, tt.args.types, tt.args.pkgName, tt.args.newWriter); (err != nil) != tt.wantErr {
t.Errorf("Generate() error = %v, wantErr %v", err, tt.wantErr)
}
})
Expand Down

0 comments on commit 49fb370

Please sign in to comment.