Skip to content

Commit

Permalink
chore: fitgen clean up code (#375)
Browse files Browse the repository at this point in the history
  • Loading branch information
muktihari authored Aug 29, 2024
1 parent ce8bbbb commit 23116cc
Show file tree
Hide file tree
Showing 14 changed files with 118 additions and 109 deletions.
22 changes: 0 additions & 22 deletions internal/cmd/fitgen/builder/builder.go

This file was deleted.

30 changes: 16 additions & 14 deletions internal/cmd/fitgen/factory/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"strings"
"text/template"

"github.com/muktihari/fit/internal/cmd/fitgen/builder"
"github.com/muktihari/fit/internal/cmd/fitgen/generator"
"github.com/muktihari/fit/internal/cmd/fitgen/lookup"
"github.com/muktihari/fit/internal/cmd/fitgen/parser"
"github.com/muktihari/fit/internal/cmd/fitgen/pkg/strutil"
Expand All @@ -23,7 +23,7 @@ type ( // type aliasing for better code reading.
FieldName = string
)

type factoryBuilder struct {
type Builder struct {
template *template.Template

mesgnumPackageName string
Expand All @@ -36,10 +36,12 @@ type factoryBuilder struct {
types []parser.Type
}

func NewBuilder(path string, lookup *lookup.Lookup, types []parser.Type, messages []parser.Message) builder.Builder {
var _ generator.Builder = (*Builder)(nil)

func NewBuilder(path string, lookup *lookup.Lookup, types []parser.Type, messages []parser.Message) *Builder {
_, filename, _, _ := runtime.Caller(0)
cd := filepath.Dir(filename)
f := &factoryBuilder{
f := &Builder{
template: template.Must(template.New("main").ParseFiles(filepath.Join(cd, "factory.tmpl"))),
path: filepath.Join(path, "factory"),
mesgnumPackageName: "typedef",
Expand All @@ -52,7 +54,7 @@ func NewBuilder(path string, lookup *lookup.Lookup, types []parser.Type, message
return f
}

func (b *factoryBuilder) preproccessMessageField() {
func (b *Builder) preproccessMessageField() {
// Prepare lookup table for field indexes
fieldIndexMapByMessageNameByFieldName := make(map[MessageName]map[FieldName]int)
for _, message := range b.messages {
Expand All @@ -79,7 +81,7 @@ func (b *factoryBuilder) preproccessMessageField() {
}
}

func (b *factoryBuilder) Build() ([]builder.Data, error) {
func (b *Builder) Build() ([]generator.Data, error) {
// Create message/field lookup structure as string using strings.Builder{},
// This way, we don't depend on generated value such as types and profile package to be able to generate factory.
// And also we don't need to process the data in the template which is a bit painful for complex data structure.
Expand All @@ -97,7 +99,7 @@ func (b *factoryBuilder) Build() ([]builder.Data, error) {
}
strbuf.WriteString("}")

return []builder.Data{
return []generator.Data{
{
Template: b.template,
TemplateExec: "factory",
Expand All @@ -121,7 +123,7 @@ func (b *factoryBuilder) Build() ([]builder.Data, error) {
}, nil
}

func (b *factoryBuilder) makeFieldBases(message parser.Message) string {
func (b *Builder) makeFieldBases(message parser.Message) string {
if len(message.Fields) == 0 {
return "nil"
}
Expand Down Expand Up @@ -158,7 +160,7 @@ func (b *factoryBuilder) makeFieldBases(message parser.Message) string {
return strbuf.String()
}

func (b *factoryBuilder) makeComponents(compField parser.ComponentField, messageName string) string {
func (b *Builder) makeComponents(compField parser.ComponentField, messageName string) string {
if len(compField.GetComponents()) == 0 {
return "nil"
}
Expand All @@ -184,7 +186,7 @@ func (b *factoryBuilder) makeComponents(compField parser.ComponentField, message
return strbuf.String()
}

func (b *factoryBuilder) makeSubFields(field parser.Field, messageName string) string {
func (b *Builder) makeSubFields(field parser.Field, messageName string) string {
if len(field.SubFields) == 0 {
return "nil"
}
Expand Down Expand Up @@ -213,7 +215,7 @@ func (b *factoryBuilder) makeSubFields(field parser.Field, messageName string) s
return strbuf.String()
}

func (b *factoryBuilder) makeSubFieldMaps(subfield parser.SubField, messageName string) string {
func (b *Builder) makeSubFieldMaps(subfield parser.SubField, messageName string) string {
if len(subfield.RefFieldNames) == 0 {
return "nil"
}
Expand All @@ -233,16 +235,16 @@ func (b *factoryBuilder) makeSubFieldMaps(subfield parser.SubField, messageName
return strbuf.String()
}

func (b *factoryBuilder) transformProfileType(fieldType string) string {
func (b *Builder) transformProfileType(fieldType string) string {
return b.profilePackageName + "." + strutil.ToTitle(fieldType) // profile.Uint8
}

func (b *factoryBuilder) transformBaseType(fieldType string) string {
func (b *Builder) transformBaseType(fieldType string) string {
baseType := b.lookup.BaseType(fieldType)
return "basetype." + strutil.ToTitle(baseType.String()) // basetype.Uint16z
}

func (b *factoryBuilder) transformMesgnum(s string) string {
func (b *Builder) transformMesgnum(s string) string {
return "mesgnum." + strutil.ToTitle(s) // mesgnum.FileId
}

Expand Down
42 changes: 31 additions & 11 deletions internal/cmd/fitgen/generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,38 @@ import (
"os"
"os/exec"
"path/filepath"

"github.com/muktihari/fit/internal/cmd/fitgen/builder"
"text/template"
)

// Builder is template data builder
type Builder interface {
// Build returns slice of template data and an error
Build() ([]Data, error)
}

// Data wraps template and data for generating proto.
type Data struct {
Template *template.Template
TemplateExec string
Path string
Filename string
Data any
}

// New return a generator
func New(verbose bool) *Generator { return &Generator{verbose: verbose} }
func New(verbose bool) *Generator {
return &Generator{
verbose: verbose,
buf: bytes.NewBuffer(nil),
}
}

type Generator struct {
verbose bool
buf *bytes.Buffer
}

func (g *Generator) Generate(builders []builder.Builder, perm os.FileMode) error {
func (g *Generator) Generate(builders []Builder, perm os.FileMode) error {
for _, builder := range builders {
dataBuilders, err := builder.Build()
if err != nil {
Expand All @@ -37,12 +57,12 @@ func (g *Generator) Generate(builders []builder.Builder, perm os.FileMode) error
}

for path := range paths { // format all files in the path
g.buf.Reset()
path = abspath(path)
stderr := new(bytes.Buffer)
cmd := exec.Command("gofmt", "-s", "-w", path)
cmd.Stderr = stderr
cmd.Stderr = g.buf
if err := cmd.Run(); err != nil {
fmt.Printf("gofmt -s -w %q, stderr: \n%s\n", path, stderr.String())
fmt.Printf("gofmt -s -w %q, stderr: \n%s\n", path, g.buf.String())
return fmt.Errorf("cmd err: %w", err)
}
}
Expand All @@ -51,19 +71,19 @@ func (g *Generator) Generate(builders []builder.Builder, perm os.FileMode) error
return nil
}

func (g *Generator) GenerateTemplateData(dataBuilder builder.Data, perm os.FileMode) error {
func (g *Generator) GenerateTemplateData(dataBuilder Data, perm os.FileMode) error {
if err := os.MkdirAll(dataBuilder.Path, 0755); err != nil {
return fmt.Errorf("mkdir %q: %w", dataBuilder.Path, err)
}
name := filepath.Join(dataBuilder.Path, dataBuilder.Filename)
name = abspath(name)

buf := new(bytes.Buffer)
if err := dataBuilder.Template.ExecuteTemplate(buf, dataBuilder.TemplateExec, dataBuilder.Data); err != nil {
g.buf.Reset()
if err := dataBuilder.Template.ExecuteTemplate(g.buf, dataBuilder.TemplateExec, dataBuilder.Data); err != nil {
return fmt.Errorf("template exec templ %q: %w", name, err)
}

if err := os.WriteFile(name, buf.Bytes(), perm); err != nil {
if err := os.WriteFile(name, g.buf.Bytes(), perm); err != nil {
return fmt.Errorf("write file %q: %w", name, err)
}

Expand Down
5 changes: 2 additions & 3 deletions internal/cmd/fitgen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"path/filepath"
"strings"

"github.com/muktihari/fit/internal/cmd/fitgen/builder"
"github.com/muktihari/fit/internal/cmd/fitgen/factory"
"github.com/muktihari/fit/internal/cmd/fitgen/generator"
"github.com/muktihari/fit/internal/cmd/fitgen/lookup"
Expand Down Expand Up @@ -138,14 +137,14 @@ func main() {
mesgdefb = mesgdef.NewBuilder(generatePath, lookup, parsedmesgs, parsedtypes)
)

var builders []builder.Builder
var builders []generator.Builder
whichBuilders := strings.Split(strutil.TrimRepeatedChar(whichBuilder, ','), ",")

loop:
for _, selected := range whichBuilders {
switch s := strings.TrimSpace(selected); s {
case "", "all":
builders = []builder.Builder{typedefb, profileb, factoryb, mesgnumb, fielnumb, mesgdefb}
builders = []generator.Builder{typedefb, profileb, factoryb, mesgnumb, fielnumb, mesgdefb}
break loop
case "typedef":
builders = append(builders, typedefb)
Expand Down
26 changes: 14 additions & 12 deletions internal/cmd/fitgen/profile/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ import (
"strings"
"text/template"

"github.com/muktihari/fit/internal/cmd/fitgen/builder"
"github.com/muktihari/fit/internal/cmd/fitgen/builder/shared"
"github.com/muktihari/fit/internal/cmd/fitgen/generator"
"github.com/muktihari/fit/internal/cmd/fitgen/parser"
"github.com/muktihari/fit/internal/cmd/fitgen/pkg/strutil"
"github.com/muktihari/fit/internal/cmd/fitgen/shared"
"github.com/muktihari/fit/profile/basetype"
)

Expand All @@ -25,37 +25,39 @@ const (
FitBaseType string = "fit_base_type"
)

type profilebuilder struct {
type Builder struct {
template *template.Template

path string // path to generate the file
profileVersion string // FIT SDK Profile Version
types []parser.Type // type parsed from profile.xlsx
}

func NewBuilder(path, profileVersion string, types []parser.Type) builder.Builder {
var _ generator.Builder = (*Builder)(nil)

func NewBuilder(path, profileVersion string, types []parser.Type) *Builder {
_, filename, _, _ := runtime.Caller(0)
cd := filepath.Dir(filename)
return &profilebuilder{
return &Builder{
template: template.Must(template.New("main").
Funcs(shared.FuncMap()).
ParseFiles(
filepath.Join(cd, "profile.tmpl"),
filepath.Join(cd, "..", "builder", "shared", "constant.tmpl"))),
filepath.Join(cd, "..", "shared", "constant.tmpl"))),
path: filepath.Join(path, "profile"),
profileVersion: profileVersion,
types: types,
}
}

func (b *profilebuilder) Build() ([]builder.Data, error) {
func (b *Builder) Build() ([]generator.Data, error) {
profileDataBuilder := b.buildProfile()
versionDataBuilder := b.buildVersion()

return []builder.Data{profileDataBuilder, versionDataBuilder}, nil
return []generator.Data{profileDataBuilder, versionDataBuilder}, nil
}

func (b *profilebuilder) buildProfile() builder.Data {
func (b *Builder) buildProfile() generator.Data {
constants := make([]shared.Constant, 0, len(b.types))
mappingProfileTypeToBaseTypes := make([]ProfileTypeBaseType, 0, len(b.types))
var mappingBaseTypeToProfileTypes []ProfileTypeBaseType
Expand Down Expand Up @@ -122,7 +124,7 @@ func (b *profilebuilder) buildProfile() builder.Data {
Comment: "INVALID",
}

return builder.Data{
return generator.Data{
Template: b.template,
TemplateExec: "profile",
Path: b.path,
Expand All @@ -135,8 +137,8 @@ func (b *profilebuilder) buildProfile() builder.Data {
}
}

func (b *profilebuilder) buildVersion() builder.Data {
return builder.Data{
func (b *Builder) buildVersion() generator.Data {
return generator.Data{
Template: b.template,
TemplateExec: "version",
Path: b.path,
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/fitgen/profile/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

package profile

import "github.com/muktihari/fit/internal/cmd/fitgen/builder/shared"
import "github.com/muktihari/fit/internal/cmd/fitgen/shared"

// ProfileData is data representative of profile.tmpl
type ProfileData struct {
Expand Down
Loading

0 comments on commit 23116cc

Please sign in to comment.