Skip to content

Commit

Permalink
fix: use template
Browse files Browse the repository at this point in the history
  • Loading branch information
wolfogre committed May 5, 2020
1 parent d6e8969 commit 9605543
Show file tree
Hide file tree
Showing 3 changed files with 136 additions and 35 deletions.
40 changes: 5 additions & 35 deletions internal/gtag/gtag.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package gtag

import (
"bytes"
"context"
"fmt"
"go/ast"
Expand Down Expand Up @@ -34,42 +33,13 @@ func Generate(ctx context.Context, file, name string) (*GenerateResult, error) {
}
pkg := f.Name.Name

buffer := &bytes.Buffer{}

fmt.Fprintf(buffer, "// Code generated by gtag. DO NOT EDIT.\n")
fmt.Fprintf(buffer, "// See: https://github.com/wolfogre/gtag\n\n")

fmt.Fprintf(buffer, "//go:generate gtag\n")

fmt.Fprintf(buffer, "package %s\n", pkg)

fmt.Fprintf(buffer, "import \"reflect\"\n")

fmt.Fprintf(buffer, "var (\n")
fmt.Fprintf(buffer, "valueOf%s = %s{}\n", name, name)
fmt.Fprintf(buffer, "typeOf%s = reflect.TypeOf(valueOf%s)\n\n", name, name)
for _, field := range fields {
fmt.Fprintf(buffer, "_ = valueOfUser.%s\n", field)
fmt.Fprintf(buffer, "fieldOf%s%s, _ = typeOf%s.FieldByName(\"%s\")\n", name, field, name, field)
fmt.Fprintf(buffer, "tagOf%s%s = fieldOf%s%s.Tag\n\n", name, field, name, field)

}
fmt.Fprintf(buffer, ")\n")

fmt.Fprintf(buffer, "type %sTags struct {\n", name)
for _, field := range fields {
fmt.Fprintf(buffer, "\t%s string\n", field)
}
fmt.Fprintf(buffer, "}\n")

fmt.Fprintf(buffer, "func (%s) Tags(tag string) %sTags {\n", name, name)
fmt.Fprintf(buffer, "return %sTags{\n", name)
for _, field := range fields {
fmt.Fprintf(buffer, "%s: tagOf%s%s.Get(tag),\n", field, name, field)
data := templateData{
Package: pkg,
Type: name,
Fields: fields,
}
fmt.Fprintf(buffer, "}\n}\n")

src, err := format.Source(buffer.Bytes())
src, err := format.Source(execute(data))
if err != nil {
return nil, err
}
Expand Down
60 changes: 60 additions & 0 deletions internal/gtag/template.go

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

71 changes: 71 additions & 0 deletions internal/gtag/template_test.go

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

0 comments on commit 9605543

Please sign in to comment.