-
Notifications
You must be signed in to change notification settings - Fork 24
feat(wip): schema struct gen #80
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
Open
gm0stache
wants to merge
8
commits into
Oudwins:master
Choose a base branch
from
gm0stache:feat/schema-struct-gen
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
7a40650
feat: draft generator logic
gm0stache 11a4893
refactor: use template for output
gm0stache 2067efa
feat: dump generated file
gm0stache af9e75c
feat: enable custom path dumping
gm0stache 9b42c99
feat: convert field types to 'zog.ZogSchema'
gm0stache 8666729
feat: use 'zog' cmd
gm0stache e33286c
chore: cleanup
gm0stache 8146af7
chore: fix typo
gm0stache File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"os" | ||
|
||
"github.com/Oudwins/zog/cmd/zog/ssg" | ||
) | ||
|
||
func main() { | ||
switch os.Args[1] { | ||
case "ssg": | ||
ssg.Run(os.Args[2:]) | ||
default: | ||
fmt.Println("Unknown command") | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,216 @@ | ||
// package ssg provides the functionality for the ssg (aka: schema struct generation) command. | ||
package ssg | ||
|
||
import ( | ||
"flag" | ||
"fmt" | ||
"go/ast" | ||
"go/parser" | ||
"go/token" | ||
"log" | ||
"os" | ||
"path/filepath" | ||
"strconv" | ||
"strings" | ||
"text/template" | ||
) | ||
|
||
const ( | ||
defaultGenFileSuffix = "_gen.go" | ||
defaultGenStructSuffix = "Schema" | ||
) | ||
|
||
type GeneratorOutput struct { | ||
PackageName string | ||
StructName string | ||
Fields []Field | ||
} | ||
|
||
type Field struct { | ||
Name string | ||
Type string | ||
Tags *string | ||
} | ||
|
||
func Run(osArgs []string) { | ||
gofile := os.Getenv("GOFILE") | ||
if gofile == "" { | ||
log.Fatal("GOFILE environment variable is not set") | ||
} | ||
|
||
filename := filepath.Base(gofile) | ||
ext := filepath.Ext(gofile) | ||
filenameWithoutExt := strings.TrimSuffix(filename, ext) | ||
|
||
fs := flag.NewFlagSet("ssg", flag.ContinueOnError) | ||
outputFilename := fs.String("output", filenameWithoutExt+defaultGenFileSuffix, "output file") | ||
if err := fs.Parse(osArgs); err != nil { | ||
log.Fatalf("could not parse command: %s", err.Error()) | ||
} | ||
|
||
fset := token.NewFileSet() | ||
node, err := parser.ParseFile(fset, gofile, nil, parser.ParseComments) | ||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
|
||
genLine, err := strconv.Atoi(os.Getenv("GOLINE")) | ||
if err != nil { | ||
log.Fatal("couldn't parse $GOLINE:", err) | ||
} | ||
|
||
var targetType string | ||
ast.Inspect(node, func(n ast.Node) bool { | ||
switch x := n.(type) { | ||
case *ast.GenDecl: | ||
if x.Tok != token.TYPE { | ||
return true | ||
} | ||
if fset.Position(x.Pos()).Line != genLine+1 { | ||
return true | ||
} | ||
for _, spec := range x.Specs { | ||
if ts, ok := spec.(*ast.TypeSpec); ok { | ||
if _, ok := ts.Type.(*ast.StructType); !ok { | ||
log.Fatalf("%s is not a struct type", ts.Name.Name) | ||
} | ||
targetType = ts.Name.Name | ||
return false | ||
} | ||
} | ||
} | ||
return true | ||
}) | ||
|
||
if targetType == "" { | ||
log.Fatal("no struct type found after //go:generate directive") | ||
} | ||
|
||
metadata, err := aggregateMetadata(node, targetType) | ||
if err != nil { | ||
log.Fatal("couldn't aggregate metadata:", err) | ||
} | ||
metadata.StructName += defaultGenStructSuffix | ||
metadata.Fields = convertFieldTypes(metadata.Fields) | ||
|
||
outputDir := filepath.Dir(*outputFilename) | ||
if outputDir != "." { | ||
if err := os.MkdirAll(outputDir, 0o755); err != nil { | ||
log.Fatal("failed to create output directory:", err) | ||
} | ||
} | ||
|
||
of, err := os.Create(*outputFilename) | ||
if err != nil { | ||
log.Fatal("failed to create output file:", err) | ||
} | ||
defer of.Close() | ||
|
||
t, err := template.New("gen").Parse(`// Code generated by zog ssg; DO NOT EDIT. | ||
|
||
package {{.PackageName}} | ||
|
||
import ( | ||
"github.com/Oudwins/zog" | ||
) | ||
|
||
type {{.StructName}} struct { | ||
{{- range $field := .Fields}} | ||
{{$field.Name}} {{$field.Type}}{{if $field.Tags}} {{$field.Tags}}{{end}} | ||
{{- end}} | ||
} | ||
`) | ||
if err != nil { | ||
log.Fatal("failed to parse template:", err) | ||
} | ||
|
||
err = t.Execute(of, metadata) | ||
if err != nil { | ||
log.Fatal("failed to execute template:", err) | ||
} | ||
} | ||
|
||
func aggregateMetadata(node *ast.File, targetType string) (*GeneratorOutput, error) { | ||
var res *GeneratorOutput | ||
|
||
ast.Inspect(node, func(n ast.Node) bool { | ||
switch x := n.(type) { | ||
case *ast.TypeSpec: | ||
if x.Name.Name == targetType { | ||
if st, ok := x.Type.(*ast.StructType); ok { | ||
o := GeneratorOutput{ | ||
PackageName: node.Name.Name, | ||
StructName: targetType, | ||
Fields: []Field{}, | ||
} | ||
|
||
for _, field := range st.Fields.List { | ||
typeExpr := exprToString(field.Type) | ||
|
||
for _, name := range field.Names { | ||
f := Field{ | ||
Name: name.Name, | ||
Type: typeExpr, | ||
} | ||
|
||
if field.Tag != nil { | ||
f.Tags = &field.Tag.Value | ||
} | ||
|
||
o.Fields = append(o.Fields, f) | ||
} | ||
} | ||
res = &o | ||
} | ||
} | ||
} | ||
return true | ||
}) | ||
|
||
if res == nil { | ||
return nil, fmt.Errorf("could not aggregate metadata") | ||
} | ||
|
||
return res, nil | ||
} | ||
|
||
func exprToString(expr ast.Expr) string { | ||
switch t := expr.(type) { | ||
case *ast.Ident: | ||
return t.Name | ||
case *ast.SelectorExpr: | ||
return exprToString(t.X) + "." + t.Sel.Name | ||
case *ast.StarExpr: | ||
return "*" + exprToString(t.X) | ||
case *ast.ArrayType: | ||
if t.Len == nil { | ||
return "[]" + exprToString(t.Elt) | ||
} | ||
return fmt.Sprintf("[%s]%s", exprToString(t.Len), exprToString(t.Elt)) | ||
case *ast.MapType: | ||
return fmt.Sprintf("map[%s]%s", exprToString(t.Key), exprToString(t.Value)) | ||
default: | ||
return fmt.Sprintf("%#v", expr) | ||
} | ||
} | ||
|
||
func convertFieldTypes(fields []Field) []Field { | ||
converted := make([]Field, len(fields)) | ||
for i, field := range fields { | ||
switch field.Type { | ||
// todo: this is where types should be mapped to the most narrowly corresponding schema types | ||
// | ||
// case "string": | ||
// fields[i].Type = "string" | ||
// case "int": | ||
// fields[i].Type = "int" | ||
// case "float64": | ||
// fields[i].Type = "float64" | ||
default: | ||
field.Type = "zog.ZogSchema" | ||
converted[i] = field | ||
} | ||
} | ||
|
||
return converted | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package main | ||
|
||
// example with most basic usage | ||
// | ||
//go:generate go run github.com/Oudwins/zog/cmd/zog ssg | ||
type MyType struct { | ||
Field1 string `json:"field1"` | ||
Field2 int | ||
} | ||
|
||
// example with custom output path | ||
// | ||
//go:generate go run github.com/Oudwins/zog/cmd/zog ssg -output=./schema/generated.go | ||
type MyOtherType struct { | ||
Field1 string | ||
Field2 int | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Prevent potential index out-of-range panic.
Calling os.Args[1] directly can crash if no arguments are passed. Ensure that len(os.Args) > 1 before switching on os.Args[1].
Apply this fix:
📝 Committable suggestion