Skip to content

Commit

Permalink
fix: modify generated columns function names (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
ginokent authored Nov 11, 2023
2 parents ba2cb2c + c3cee98 commit fc764a0
Show file tree
Hide file tree
Showing 13 changed files with 234 additions and 93 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ module github.com/kunitsucom/arcgen

go 1.21.4

require github.com/kunitsucom/util.go v0.0.59-rc.6
require github.com/kunitsucom/util.go v0.0.59-rc.7
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
github.com/kunitsucom/util.go v0.0.59-rc.6 h1:QJkGrG4ZlzbLcYCkbdOoUuJjFnCgUKfT7/58aeFVNbc=
github.com/kunitsucom/util.go v0.0.59-rc.6/go.mod h1:bYFf2JvRqVF1brBtpdt3xkkTGJBxmYBxZlItrc/lf7Y=
github.com/kunitsucom/util.go v0.0.59-rc.7 h1:hckWP+/z4mY14Fe304+8yvMQAyxXUMMG2yaccxnBlJY=
github.com/kunitsucom/util.go v0.0.59-rc.7/go.mod h1:bYFf2JvRqVF1brBtpdt3xkkTGJBxmYBxZlItrc/lf7Y=
9 changes: 7 additions & 2 deletions internal/arcgen/lang/go/extract_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package arcgengo

import (
"context"
"fmt"
goast "go/ast"
"go/token"
"reflect"
"sort"
"strings"

errorz "github.com/kunitsucom/util.go/errors"
Expand Down Expand Up @@ -32,7 +34,6 @@ func extractSource(_ context.Context, fset *token.FileSet, f *goast.File) (*ARCS
logs.Debug.Printf("🔍: %s: type=%s", pos.String(), n.Name.Name)
arcSrcMap[pos.String()] = &ARCSource{
Source: pos,
Package: f.Name,
TypeSpec: typeSpec,
StructType: structType,
}
Expand Down Expand Up @@ -67,7 +68,6 @@ func extractSource(_ context.Context, fset *token.FileSet, f *goast.File) (*ARCS
logs.Debug.Printf("🖋️: %s: overwrite with comment group: type=%s", fset.Position(t.Pos()).String(), n.Name.Name)
arcSrcMap[pos.String()] = &ARCSource{
Source: pos,
Package: f.Name,
TypeSpec: typeSpec,
StructType: structType,
CommentGroup: commentGroup,
Expand Down Expand Up @@ -101,6 +101,11 @@ func extractSource(_ context.Context, fset *token.FileSet, f *goast.File) (*ARCS
return nil, errorz.Errorf("column-tag-go=%s: %w", config.ColumnTagGo(), apperr.ErrColumnTagGoAnnotationNotFoundInSource)
}

sort.Slice(arcSrcSet.ARCSources, func(i, j int) bool {
return fmt.Sprintf("%s:%07d", arcSrcSet.ARCSources[i].Source.Filename, arcSrcSet.ARCSources[i].Source.Line) <
fmt.Sprintf("%s:%07d", arcSrcSet.ARCSources[j].Source.Filename, arcSrcSet.ARCSources[j].Source.Line)
})

return arcSrcSet, nil
}

Expand Down
126 changes: 73 additions & 53 deletions internal/arcgen/lang/go/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"context"
"fmt"
"go/ast"
"go/format"
"go/printer"
"go/token"
"io"
"os"
Expand All @@ -19,6 +19,7 @@ import (
"github.com/kunitsucom/arcgen/internal/arcgen/lang/util"
"github.com/kunitsucom/arcgen/internal/config"
"github.com/kunitsucom/arcgen/internal/logs"
"github.com/kunitsucom/arcgen/pkg/errors"
)

//nolint:cyclop,funlen
Expand All @@ -28,68 +29,87 @@ func Generate(ctx context.Context, src string) error {
return errorz.Errorf("parse: %w", err)
}

newFile := token.NewFileSet()
if err := generate(arcSrcSets); err != nil {
return errorz.Errorf("generate: %w", err)
}

return nil
}

func generate(arcSrcSets ARCSourceSets) error {
for _, arcSrcSet := range arcSrcSets {
filePrefix := strings.TrimSuffix(arcSrcSet.Filename, fileSuffix)
filename := fmt.Sprintf("%s.%s.gen%s", filePrefix, config.ColumnTagGo(), fileSuffix)
osFile, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return errorz.Errorf("os.OpenFile: %w", err)
}

astFile := &ast.File{
// package
Name: &ast.Ident{
Name: arcSrcSet.PackageName,
},
// methods
Decls: []ast.Decl{},
if err := fprint(f, bytes.NewBuffer(nil), arcSrcSet); err != nil {
return errorz.Errorf("sprint: %w", err)
}
}

for _, arcSrc := range arcSrcSet.ARCSources {
structName := arcSrc.TypeSpec.Name.Name
tableName := extractTableNameFromCommentGroup(arcSrc.CommentGroup)
columnNames := func() []string {
columnNames := make([]string, 0)
for _, field := range arcSrc.StructType.Fields.List {
if field.Tag != nil {
tag := reflect.StructTag(strings.Trim(field.Tag.Value, "`"))
switch columnName := tag.Get(config.ColumnTagGo()); columnName {
case "", "-":
logs.Trace.Printf("SKIP: %s: field.Names=%s, columnName=%q", arcSrc.Source.String(), field.Names, columnName)
// noop
default:
columnNames = append(columnNames, columnName)
}
}
}
return columnNames
}()
return nil
}

appendAST(astFile, structName, tableName, config.MethodPrefixGlobal(), config.MethodPrefixColumn(), columnNames)
}
type buffer interface {
io.Writer
fmt.Stringer
}

buf := bytes.NewBuffer(nil)
if err := format.Node(buf, newFile, astFile); err != nil {
return errorz.Errorf("format.Node: %w", err)
func fprint(osFile io.Writer, buf buffer, arcSrcSet *ARCSourceSet) error {
if arcSrcSet == nil || arcSrcSet.PackageName == "" {
return errors.ErrInvalidSourceSet
}
astFile := &ast.File{
// package
Name: &ast.Ident{
Name: arcSrcSet.PackageName,
},
// methods
Decls: []ast.Decl{},
}

for _, arcSrc := range arcSrcSet.ARCSources {
structName := arcSrc.TypeSpec.Name.Name
tableName := extractTableNameFromCommentGroup(arcSrc.CommentGroup)
fieldNames, columnNames := make([]string, 0), make([]string, 0)
for _, field := range arcSrc.StructType.Fields.List {
if field.Tag != nil {
tag := reflect.StructTag(strings.Trim(field.Tag.Value, "`"))
switch columnName := tag.Get(config.ColumnTagGo()); columnName {
case "", "-":
logs.Trace.Printf("SKIP: %s: field.Names=%s, columnName=%q", arcSrc.Source.String(), field.Names, columnName)
// noop
default:
logs.Trace.Printf("%s: field.Names=%s, columnName=%q", arcSrc.Source.String(), field.Names, columnName)
fieldNames, columnNames = append(fieldNames, field.Names[0].Name), append(columnNames, columnName)
}
}
}

// add header comment
content := "" +
"// Code generated by arcgen. DO NOT EDIT." + "\n" +
"//" + "\n" +
fmt.Sprintf("// source: %s", filepathz.Short(arcSrcSet.Source.Filename)) + "\n" +
"\n" +
buf.String()
appendAST(astFile, structName, tableName, config.MethodNameTable(), config.MethodPrefixColumn(), fieldNames, columnNames)
}

// add blank line between methods
content = strings.ReplaceAll(content, "\n}\nfunc ", "\n}\n\nfunc ")
if err := printer.Fprint(buf, token.NewFileSet(), astFile); err != nil {
return errorz.Errorf("printer.Fprint: %w", err)
}

// write to file
if _, err := io.WriteString(osFile, content); err != nil {
return errorz.Errorf("io.WriteString: %w", err)
}
// add header comment
content := "" +
"// Code generated by arcgen. DO NOT EDIT." + "\n" +
"//" + "\n" +
fmt.Sprintf("// source: %s", filepathz.Short(arcSrcSet.Source.Filename)) + "\n" +
"\n" +
buf.String()

// add blank line between methods
content = strings.ReplaceAll(content, "\n}\nfunc ", "\n}\n\nfunc ")

// write to file
if _, err := io.WriteString(osFile, content); err != nil {
return errorz.Errorf("io.WriteString: %w", err)
}

return nil
Expand All @@ -99,7 +119,7 @@ func extractTableNameFromCommentGroup(commentGroup *ast.CommentGroup) string {
if commentGroup != nil {
for _, comment := range commentGroup.List {
if matches := util.RegexIndexTableName.Regex.FindStringSubmatch(comment.Text); len(matches) > util.RegexIndexTableName.Index {
return matches[util.RegexIndexTableName.Index]
return strings.Trim(matches[util.RegexIndexTableName.Index], "`")
}
}
}
Expand All @@ -109,7 +129,7 @@ func extractTableNameFromCommentGroup(commentGroup *ast.CommentGroup) string {
}

//nolint:funlen
func appendAST(file *ast.File, structName string, tableName string, prefixGlobal string, prefixColumn string, columnNames []string) {
func appendAST(file *ast.File, structName string, tableName string, prefixGlobal string, prefixColumn string, fieldNames, columnNames []string) {
if tableName != "" {
file.Decls = append(file.Decls, &ast.FuncDecl{
Recv: &ast.FieldList{
Expand Down Expand Up @@ -157,13 +177,13 @@ func appendAST(file *ast.File, structName string, tableName string, prefixGlobal
})
}

file.Decls = append(file.Decls, generateASTColumnMethods(structName, prefixGlobal, prefixColumn, columnNames)...)
file.Decls = append(file.Decls, generateASTColumnMethods(structName, prefixGlobal, prefixColumn, fieldNames, columnNames)...)

return //nolint:gosimple
}

//nolint:funlen
func generateASTColumnMethods(structName string, prefixGlobal string, prefixColumn string, columnNames []string) []ast.Decl {
func generateASTColumnMethods(structName string, prefixGlobal string, prefixColumn string, fieldNames, columnNames []string) []ast.Decl {
decls := make([]ast.Decl, 0)

// all column names method
Expand Down Expand Up @@ -225,7 +245,7 @@ func generateASTColumnMethods(structName string, prefixGlobal string, prefixColu
})

// each column name methods
for _, columnName := range columnNames {
for i, columnName := range columnNames {
decls = append(decls, &ast.FuncDecl{
Recv: &ast.FieldList{
List: []*ast.Field{
Expand All @@ -244,7 +264,7 @@ func generateASTColumnMethods(structName string, prefixGlobal string, prefixColu
},
},
Name: &ast.Ident{
Name: prefixGlobal + prefixColumn + columnName,
Name: prefixGlobal + prefixColumn + fieldNames[i],
},
Type: &ast.FuncType{
Params: &ast.FieldList{},
Expand Down
Loading

0 comments on commit fc764a0

Please sign in to comment.