Skip to content

Commit

Permalink
refactor: Fix misc
Browse files Browse the repository at this point in the history
  • Loading branch information
ginokent committed Aug 10, 2024
1 parent 6a0a69a commit 4db50f8
Show file tree
Hide file tree
Showing 19 changed files with 258 additions and 222 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ type Group struct {
EOF

$ # == 2. generate file ================================
$ arcgen --method-name-table TableName --method-name-columns ColumnNames --method-prefix-column ColumnName_ --slice-type-suffix Slice /tmp/sample.go
$ arcgen --go-method-name-table TableName --go-method-name-columns ColumnNames --go-method-prefix-column ColumnName_ --go-slice-type-suffix Slice /tmp/sample.go
INFO: 2023/11/12 03:56:59 arcgen.go:33: source: /tmp/sample.go

$ # == 3. Check generated file ================================
Expand Down Expand Up @@ -172,13 +172,13 @@ options:
programming language to generate DDL
--go-column-tag (env: ARCGEN_GO_COLUMN_TAG, default: db)
column annotation key for Go struct tag
--method-name-table (env: ARCGEN_METHOD_NAME_TABLE, default: TableName)
--go-method-name-table (env: ARCGEN_METHOD_NAME_TABLE, default: TableName)
method name for table
--method-name-columns (env: ARCGEN_METHOD_NAME_COLUMNS, default: ColumnNames)
--go-method-name-columns (env: ARCGEN_METHOD_NAME_COLUMNS, default: ColumnNames)
method name for columns
--method-prefix-column (env: ARCGEN_METHOD_PREFIX_COLUMN, default: ColumnName_)
--go-method-prefix-column (env: ARCGEN_METHOD_PREFIX_COLUMN, default: ColumnName_)
method prefix for column name
--slice-type-suffix (env: ARCGEN_SLICE_TYPE_SUFFIX, default: )
--go-slice-type-suffix (env: ARCGEN_SLICE_TYPE_SUFFIX, default: )
suffix for slice type
--help (default: false)
show usage
Expand Down
4 changes: 2 additions & 2 deletions cmd/arcgen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import (
"os"

"github.com/kunitsucom/arcgen/internal/contexts"
"github.com/kunitsucom/arcgen/pkg/arcgen"
"github.com/kunitsucom/arcgen/pkg/entrypoint/arcgen"
)

func main() {
if err := arcgen.ARCGen(contexts.WithArgs(context.Background(), os.Args)); err != nil {
if err := arcgen.Run(contexts.WithArgs(context.Background(), os.Args)); err != nil {
log.Fatalf("arcgen: %+v", err)
}
}
2 changes: 1 addition & 1 deletion internal/arcgen/lang/go/dump_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (

func dumpSource(fset *token.FileSet, arcSrcSet *ARCSourceSet) {
if arcSrcSet != nil {
for _, arcSrc := range arcSrcSet.ARCSources {
for _, arcSrc := range arcSrcSet.ARCSourceSlice {
logs.Trace.Print("== Source ================================================================================================================================")
_, _ = io.WriteString(logs.Trace.LineWriter("r.CommentGroup.Text: "), arcSrc.CommentGroup.Text())
logs.Trace.Print("-- CommentGroup --------------------------------------------------------------------------------------------------------------------------------")
Expand Down
18 changes: 9 additions & 9 deletions internal/arcgen/lang/go/extract_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,23 +87,23 @@ func extractSource(_ context.Context, fset *token.FileSet, f *goast.File) (*ARCS
}

arcSrcSet := &ARCSourceSet{
Filename: fset.Position(f.Pos()).Filename,
PackageName: f.Name.Name,
Source: fset.Position(f.Pos()),
ARCSources: make([]*ARCSource, 0),
Filename: fset.Position(f.Pos()).Filename,
PackageName: f.Name.Name,
Source: fset.Position(f.Pos()),
ARCSourceSlice: make([]*ARCSource, 0),
}

for _, arcSrc := range arcSrcMap {
arcSrcSet.ARCSources = append(arcSrcSet.ARCSources, arcSrc)
arcSrcSet.ARCSourceSlice = append(arcSrcSet.ARCSourceSlice, arcSrc)
}

if len(arcSrcSet.ARCSources) == 0 {
if len(arcSrcSet.ARCSourceSlice) == 0 {
return nil, errorz.Errorf("go-column-tag=%s: %w", config.GoColumnTag(), apperr.ErrGoColumnTagAnnotationNotFoundInSource)
}

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)
sort.Slice(arcSrcSet.ARCSourceSlice, func(i, j int) bool {
return fmt.Sprintf("%s:%07d", arcSrcSet.ARCSourceSlice[i].Source.Filename, arcSrcSet.ARCSourceSlice[i].Source.Line) <
fmt.Sprintf("%s:%07d", arcSrcSet.ARCSourceSlice[j].Source.Filename, arcSrcSet.ARCSourceSlice[j].Source.Line)
})

return arcSrcSet, nil
Expand Down
87 changes: 36 additions & 51 deletions internal/arcgen/lang/go/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,12 @@ import (
"go/token"
"io"
"os"
"reflect"
"strconv"
"strings"

errorz "github.com/kunitsucom/util.go/errors"
filepathz "github.com/kunitsucom/util.go/path/filepath"

"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"
)

Expand All @@ -36,18 +32,28 @@ func Generate(ctx context.Context, src string) error {
return nil
}

func generate(arcSrcSets ARCSourceSets) error {
func generate(arcSrcSets ARCSourceSetSlice) error {
for _, arcSrcSet := range arcSrcSets {
filePrefix := strings.TrimSuffix(arcSrcSet.Filename, fileSuffix)
filename := fmt.Sprintf("%s.%s.gen%s", filePrefix, config.GoColumnTag(), fileSuffix)
const rw_r__r__ = 0o644 //nolint:revive,stylecheck // rw-r--r--
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, rw_r__r__)
if err != nil {
return errorz.Errorf("os.OpenFile: %w", err)

generateColumns := func() error {
filePathWithoutExt := strings.TrimSuffix(arcSrcSet.Filename, fileExt)
newExt := fmt.Sprintf(".%s.gen%s", config.GoColumnTag(), fileExt)
filename := filePathWithoutExt + newExt
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, rw_r__r__)
if err != nil {
return errorz.Errorf("os.OpenFile: %w", err)
}
defer f.Close()

if err := fprintColumns(f, bytes.NewBuffer(nil), arcSrcSet); err != nil {
return errorz.Errorf("sprint: %w", err)
}
return nil
}

if err := fprint(f, bytes.NewBuffer(nil), arcSrcSet); err != nil {
return errorz.Errorf("sprint: %w", err)
if err := generateColumns(); err != nil {
return errorz.Errorf("f: %w", err)
}
}

Expand All @@ -59,7 +65,7 @@ type buffer interface {
fmt.Stringer
}

func fprint(osFile io.Writer, buf buffer, arcSrcSet *ARCSourceSet) error {
func fprintColumns(osFile io.Writer, buf buffer, arcSrcSet *ARCSourceSet) error {
if arcSrcSet == nil || arcSrcSet.PackageName == "" {
return errors.ErrInvalidSourceSet
}
Expand All @@ -72,38 +78,30 @@ func fprint(osFile io.Writer, buf buffer, arcSrcSet *ARCSourceSet) error {
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.GoColumnTag()); 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)
}
}
}
for _, arcSrc := range arcSrcSet.ARCSourceSlice {
structName := arcSrc.extractStructName()
tableName := arcSrc.extractTableNameFromCommentGroup()
fieldNames, columnNames := arcSrc.extractFieldNamesAndColumnNames()

appendAST(astFile, structName, config.SliceTypeSuffix(), tableName, config.MethodNameTable(), config.MethodNameColumns(), config.MethodPrefixColumn(), fieldNames, columnNames)
appendAST(
astFile,
structName,
config.GoSliceTypeSuffix(),
tableName,
config.GoMethodNameTable(),
config.GoMethodNameColumns(),
config.GoMethodPrefixColumn(),
fieldNames,
columnNames,
)
}

if err := printer.Fprint(buf, token.NewFileSet(), astFile); err != nil {
return errorz.Errorf("printer.Fprint: %w", err)
}

// add header comment
content := "" +
"// Code generated by arcgen. DO NOT EDIT." + "\n" +
"//" + "\n" +
"// source: " + filepathz.Short(arcSrcSet.Source.Filename) + "\n" +
"\n" +
buf.String()
content := arcSrcSet.generateGoFileHeader() + buf.String()

// add blank line between methods
content = strings.ReplaceAll(content, "\n}\nfunc ", "\n}\n\nfunc ")
Expand All @@ -116,19 +114,6 @@ func fprint(osFile io.Writer, buf buffer, arcSrcSet *ARCSourceSet) error {
return nil
}

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 strings.Trim(strings.Trim(strings.Trim(matches[util.RegexIndexTableName.Index], "`"), `"`), "'")
}
}
}

logs.Debug.Printf("WARN: table name in comment not found: `// \"%s\": table: *`: comment=%q", config.GoColumnTag(), commentGroup.Text())
return ""
}

//nolint:funlen
func appendAST(file *ast.File, structName string, sliceTypeSuffix string, tableName string, methodNameTable string, methodNameColumns string, methodPrefixColumn string, fieldNames, columnNames []string) {
if tableName != "" {
Expand Down Expand Up @@ -180,10 +165,10 @@ func appendAST(file *ast.File, structName string, sliceTypeSuffix string, tableN
},
})

// type StructNameSlice []*StructName
if sliceTypeSuffix != "" {
file.Decls = append(
file.Decls,
// type StructNameSlice []*StructName
&ast.GenDecl{
Tok: token.TYPE,
Specs: []ast.Spec{
Expand Down
Loading

0 comments on commit 4db50f8

Please sign in to comment.