Skip to content

Commit

Permalink
v0.0.3
Browse files Browse the repository at this point in the history
  • Loading branch information
bogdan_dinu committed Feb 13, 2020
1 parent 237940b commit ba13357
Show file tree
Hide file tree
Showing 13 changed files with 210 additions and 125 deletions.
15 changes: 10 additions & 5 deletions cmd/stroo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ func main() {
if err := codeBuilder.Flags.Parse(os.Args[1:]); err != nil {
log.Fatalf("error parsing flags: %v", err)
}

// create a command from our analyzer (so we don't pass parameters around)
command := NewCommand(codeBuilder)
if command.Serve {
StartPlayground(command)
return
}

// check if vital things are missing from the configuration
if command.TemplateFile == "" || command.SelectedType == "" || (!command.TestMode && command.OutputFile == "") {
codeBuilder.Flags.Usage()
Expand All @@ -29,16 +31,19 @@ func main() {

// print the current configuration
log.Printf("received params : %s\n", Print(codeBuilder, true))
if loaded, err := LoadPackage("."); err != nil {
loaded, err := LoadPackage(".")
if err != nil {
log.Fatalf("error loading : %v", err)
} else {
if err := command.Analyse(codeBuilder, loaded); err != nil {
log.Fatalf("error analysing : %v", err)
}
}
log.Printf("loaded %q from %q", loaded.Name, loaded.PkgPath)
if err := command.Analyse(codeBuilder, loaded); err != nil {
log.Fatalf("error analysing : %v", err)
}

if err := command.Generate(codeBuilder); err != nil {
log.Fatalf("error generating : %v", err)
}

if command.TestMode {
log.Printf("%s\n", command.Out.String())
log.Println("file not written because test mode is set")
Expand Down
10 changes: 8 additions & 2 deletions code.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,14 @@ func (c *Code) PackageName() string { return c.PackageInfo.Name }
func (c *Code) StructByKey(key string) (*TypeInfo, error) {
result := c.PackageInfo.Types.Extract(key)
if result == nil {
log.Printf("error looking for %q into types", key)
return nil, fmt.Errorf("error looking for %q into types", key)
if c.DebugPrint() {
log.Printf("error looking for %q into types", key)
}
knowntypes := ""
for _, t := range c.PackageInfo.Types {
knowntypes += "`" + t.Name + "` " + t.Kind + "\n"
}
return nil, fmt.Errorf("error looking for %q into known types :\n %s\n", key, knowntypes)
}
return result, nil
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ require (
github.com/mitchellh/copystructure v1.0.0 // indirect
github.com/rakyll/statik v0.1.6
github.com/stretchr/testify v1.4.0 // indirect
golang.org/x/tools v0.0.0-20200204230316-67a4523381ef
golang.org/x/tools v0.0.0-20200213050514-49b8ac185c84
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20200204230316-67a4523381ef h1:mdhEDFpO1Tfj7PXIflIuP1tbXt4rJgHIvbzdh62SARw=
golang.org/x/tools v0.0.0-20200204230316-67a4523381ef/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200213050514-49b8ac185c84 h1:0QCtZnPx0LFDcPMUX7Qg328Twbm3c/Jx1d0XT/x9jcg=
golang.org/x/tools v0.0.0-20200213050514-49b8ac185c84/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898 h1:/atklqdjdhuosWIl6AIbOeHJjicWYPqR9bpxqxYG2pA=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
Expand Down
53 changes: 25 additions & 28 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,17 +165,17 @@ func (c *Command) Run(pass *analysis.Pass) (interface{}, error) {
result.Types = append(result.Types, typeInfo)
result.Interfaces = append(result.Interfaces, typeInfo)
} else {
err = infoErr
log.Printf("error reading interface : %v", infoErr)
err = infoErr
}
case *ast.ArrayType:
// e.g. `type Array []string`
typeInfo, infoErr := readType(pass.Pkg, typeSpec, nodeType.Doc)
if infoErr == nil {
result.Types = append(result.Types, typeInfo)
} else {
err = infoErr
log.Printf("error reading array : %v", infoErr)
err = infoErr
}
case *ast.StructType:
// e.g. `type Stru struct {}`
Expand All @@ -184,12 +184,12 @@ func (c *Command) Run(pass *analysis.Pass) (interface{}, error) {
if fixErr := fixFieldsInfo(result.TypesInfo, typeInfo); fixErr == nil {
result.Types = append(result.Types, typeInfo)
} else {
err = fixErr
log.Printf("error fixing struct : %v", fixErr)
err = fixErr
}
} else {
err = infoErr
log.Printf("error reading struct : %v", infoErr)
err = infoErr
}
case *ast.Ident:
// e.g. : `type String string`
Expand All @@ -198,8 +198,8 @@ func (c *Command) Run(pass *analysis.Pass) (interface{}, error) {
typeInfo := NewAliasFromField(pass.Pkg, fieldInfo, typeSpec.Name.Name)
result.Types = append(result.Types, typeInfo)
} else {
err = infoErr
log.Printf("error reading ident : %v", infoErr)
err = infoErr
}
case *ast.SelectorExpr:
// e.g. : `type Timer time.Ticker`
Expand All @@ -208,8 +208,8 @@ func (c *Command) Run(pass *analysis.Pass) (interface{}, error) {
typeInfo := NewAliasFromField(pass.Pkg, fieldInfo, typeSpec.Name.Name)
result.Types = append(result.Types, typeInfo)
} else {
err = infoErr
log.Printf("error reading selector : %v", infoErr)
err = infoErr
}
case *ast.StarExpr:
// e.g. : `type Timer *time.Ticker`
Expand All @@ -218,8 +218,8 @@ func (c *Command) Run(pass *analysis.Pass) (interface{}, error) {
typeInfo := NewAliasFromField(pass.Pkg, fieldInfo, typeSpec.Name.Name)
result.Types = append(result.Types, typeInfo)
} else {
err = infoErr
log.Printf("error reading pointer : %v", infoErr)
err = infoErr
}
case *ast.FuncType:
// e.g. `type encoderFunc func(e *encodeState, v reflect.Value, opts encOpts)`
Expand All @@ -230,12 +230,12 @@ func (c *Command) Run(pass *analysis.Pass) (interface{}, error) {
typeInfo.IsFunc = true
result.Types = append(result.Types, typeInfo)
} else {
err = fixErr
log.Printf("error fixing func type : %v", fixErr)
err = fixErr
}
} else {
err = infoErr
log.Printf("error reading func type : %v", infoErr)
err = infoErr
}
default:
log.Printf("have you modified the filter ? Unhandled : %#v\n", typedType)
Expand All @@ -251,8 +251,8 @@ func (c *Command) Run(pass *analysis.Pass) (interface{}, error) {
if results, infoErr := readValue(def, vl); infoErr == nil {
result.Vars = append(result.Vars, results...)
} else {
err = infoErr
log.Printf("error reading variable/constant : %v", infoErr)
err = infoErr
}
} else {
log.Printf("%q was not found ", vl.Names[0])
Expand Down Expand Up @@ -401,7 +401,6 @@ func (c *Command) Analyse(analyzer *analysis.Analyzer, loadedPackage *packages.P

result := mkAction(analyzer, loadedPackage)
result.exec()

if result.err != nil {
return result.err
}
Expand All @@ -414,10 +413,23 @@ func (c *Command) Analyse(analyzer *analysis.Analyzer, loadedPackage *packages.P
}

func (c *Command) Generate(analyzer *analysis.Analyzer) error {
result, err := c.NewCode()
templatePath, err := filepath.Abs(c.TemplateFile)
if err != nil {
return err
}
if _, err := os.Stat(templatePath); os.IsNotExist(err) {
return fmt.Errorf("template-error : %v ; path = %q", err, templatePath)
}
tmpl, err := template.New(filepath.Base(templatePath)).Funcs(DefaultFuncMap()).ParseFiles(templatePath)
if err != nil {
return fmt.Errorf("template-parse-error : %v ; path = %q", err, templatePath)
}

result, err := New(c.Result, c.CodeConfig, tmpl)
if err != nil {
return fmt.Errorf("error making code object : %v", err)
return fmt.Errorf("error-building-code : %v", err)
}
result.ResetKeeper()

var buf bytes.Buffer
if err := result.Tmpl().Execute(&buf, &result); err != nil {
Expand Down Expand Up @@ -637,21 +649,6 @@ func DefaultFuncMap() template.FuncMap {
return result
}

func (c *Command) NewCode() (*Code, error) {
templatePath, err := filepath.Abs(c.TemplateFile)
if err != nil {
return nil, err
}
if _, err := os.Stat(templatePath); os.IsNotExist(err) {
return nil, fmt.Errorf("template-error : %v ; path = %q", err, templatePath)
}
tmpl, err := template.New(filepath.Base(templatePath)).Funcs(DefaultFuncMap()).ParseFiles(templatePath)
if err != nil {
return nil, fmt.Errorf("template-parse-error : %v ; path = %q", err, templatePath)
}
return New(c.Result, c.CodeConfig, tmpl)
}

// below is copy paste (with some modifications) from golang.org/x/tools/go/analysis/internal/checker,
// because we cannot use that internal package
type Action struct {
Expand Down
10 changes: 6 additions & 4 deletions pack.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,12 @@ func fixFieldsInfo(defs *types.Info, forType TypeInfo) error {
switch underType := underlyingValue.(type) {
case *types.Pointer:
underlyingPointer := underType.Elem().Underlying()
forType.Fields[idx].IsPointer = true
if !forType.Fields[idx].IsPointer {
forType.Fields[idx].IsPointer = true
}
switch underPtr := underlyingPointer.(type) {
case *types.Struct:
forType.Fields[idx].IsStruct = true
forType.Fields[idx].IsStruct = true // this is mandatory
case *types.Slice:
if !forType.Fields[idx].IsArray {
forType.Fields[idx].IsArray = true
Expand All @@ -59,7 +61,7 @@ func fixFieldsInfo(defs *types.Info, forType TypeInfo) error {
log.Printf("Fixer [pointer]: %#v", underPtr)
}
case *types.Struct:
forType.Fields[idx].IsStruct = true
forType.Fields[idx].IsStruct = true // this is mandatory
case *types.Slice:
if !forType.Fields[idx].IsArray {
forType.Fields[idx].IsArray = true
Expand All @@ -69,7 +71,7 @@ func fixFieldsInfo(defs *types.Info, forType TypeInfo) error {
forType.Fields[idx].IsInterface = true
}
case *types.Basic:
log.Printf("Fixer [basic]: %#v", underType)
log.Printf("Fixer [basic]: %#v", underType) // this is never? the case ?
case *types.Signature:
// ignore signatures
//log.Printf("Fixer [signature]: %#v", underType)
Expand Down
41 changes: 23 additions & 18 deletions pack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,8 @@ var cases = []testCase{
PackagePath: testPackagePath,
Name: "T15",
Kind: "T15",
Fields: Fields{
FieldInfo{
Fields: TypesSlice{
TypeInfo{
PackagePath: testPackagePath,
Package: testPackage,
Kind: "EmbeddedS",
Expand All @@ -150,7 +150,7 @@ var cases = []testCase{
},
},
},
FieldInfo{
TypeInfo{
PackagePath: testPackagePath,
Package: testPackage,
Kind: "EmbeddedS2",
Expand All @@ -166,7 +166,7 @@ var cases = []testCase{
},
},
},
FieldInfo{
TypeInfo{
PackagePath: testPackagePath,
Package: testPackage,
Kind: "error",
Expand All @@ -181,32 +181,29 @@ var cases = []testCase{
},
},
},
FieldInfo{
TypeInfo{
PackagePath: testPackagePath,
Package: testPackage,
Name: "Name",
Kind: "string",
IsBasic: true,
IsExported: true,
Tags: Tags{
&Tag{Key: "json", Name: "name"},
},
},
FieldInfo{
TypeInfo{
PackagePath: testPackagePath,
Package: testPackage,
Name: "PtrName",
Kind: "string",
IsBasic: true,
IsPointer: true,
IsExported: true,
},
FieldInfo{
TypeInfo{
PackagePath: testPackagePath,
Package: testPackage,
Name: "unexported",
Kind: "string",
IsBasic: true,
},
},
},
Expand All @@ -219,16 +216,16 @@ var cases = []testCase{
Kind: "T16",
PackagePath: testPackagePath,
Package: testPackage,
Fields: Fields{
FieldInfo{
Fields: TypesSlice{
TypeInfo{
PackagePath: testPackagePath,
Package: testPackage,
Name: "S",
Kind: "S5",
IsExported: true,
IsStruct: true,
},
FieldInfo{
TypeInfo{
PackagePath: testPackagePath,
Package: testPackage,
Name: "Itemz",
Expand All @@ -239,7 +236,7 @@ var cases = []testCase{
},
IsArray: true,
},
FieldInfo{
TypeInfo{
PackagePath: testPackagePath,
Package: testPackage,
Name: "Pricez",
Expand All @@ -261,8 +258,8 @@ var cases = []testCase{
PackagePath: testPackagePath,
Name: "T17",
Kind: "T17",
Fields: Fields{
FieldInfo{
Fields: TypesSlice{
TypeInfo{
Package: testPackage,
PackagePath: testPackagePath,
Kind: "Items",
Expand All @@ -280,8 +277,8 @@ var cases = []testCase{
Kind: "T18",
Package: testPackage,
PackagePath: testPackagePath,
Fields: Fields{
FieldInfo{
Fields: TypesSlice{
TypeInfo{
Package: testPackage,
PackagePath: testPackagePath,
Name: "Child",
Expand All @@ -307,6 +304,14 @@ var cases = []testCase{
IsPointer: true,
IsArray: true,
IsImported: true,
Comment: &ast.CommentGroup{
List: []*ast.Comment{
&ast.Comment{
Slash: 529859,
Text: "// times comment @time.Time",
},
},
},
},
}, // 19 - type ExternalSliceOfPointers []*time.Time
{
Expand Down
2 changes: 1 addition & 1 deletion playground.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
)

const (
playgroundVersion = "0.0.2"
playgroundVersion = "0.0.3"

storageFolder = "/server"
assetsFolder = "/assets/"
Expand Down
2 changes: 1 addition & 1 deletion statik/statik.go

Large diffs are not rendered by default.

Loading

0 comments on commit ba13357

Please sign in to comment.