Skip to content
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

Add a CLI option to change output filenames #141

Merged
merged 9 commits into from
Apr 5, 2024
6 changes: 5 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,16 @@ test: ## run test
go test -race -v ./test

testdata: ## generate test models
$(MAKE) -j4 testdata/default testdata/customtypes testdata/single
$(MAKE) -j4 testdata/default testdata/with-underscores testdata/customtypes testdata/single

testdata/default:
rm -rf test/testmodels/default && mkdir -p test/testmodels/default
$(YOBIN) $(SPANNER_PROJECT_NAME) $(SPANNER_INSTANCE_NAME) $(SPANNER_DATABASE_NAME) --package models --out test/testmodels/default/

testdata/with-underscores:
rm -rf test/testmodels/underscores && mkdir -p test/testmodels/underscores
$(YOBIN) $(SPANNER_PROJECT_NAME) $(SPANNER_INSTANCE_NAME) $(SPANNER_DATABASE_NAME) --package models --with-underscores --out test/testmodels/underscores/

testdata/single:
rm -rf test/testmodels/single && mkdir -p test/testmodels/single
$(YOBIN) $(SPANNER_PROJECT_NAME) $(SPANNER_INSTANCE_NAME) $(SPANNER_DATABASE_NAME) --out test/testmodels/single/single_file.go --single-file
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ Flags:
--suffix string output file suffix (default ".yo.go")
--tags string build tags to add to package header
--template-path string user supplied template path
--with-underscores toggle underscores in file names
```

## Generated code
Expand Down
17 changes: 9 additions & 8 deletions cmd/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,14 +90,15 @@ var (
}

g := generator.NewGenerator(loader, inflector, generator.GeneratorOption{
PackageName: generateOpts.Package,
Tags: generateOpts.Tags,
TemplatePath: generateOpts.TemplatePath,
CustomTypePackage: generateOpts.CustomTypePackage,
FilenameSuffix: generateOpts.Suffix,
SingleFile: generateOpts.SingleFile,
Filename: generateOpts.Filename,
Path: generateOpts.Path,
PackageName: generateOpts.Package,
Tags: generateOpts.Tags,
TemplatePath: generateOpts.TemplatePath,
CustomTypePackage: generateOpts.CustomTypePackage,
FilenameSuffix: generateOpts.Suffix,
SingleFile: generateOpts.SingleFile,
Filename: generateOpts.Filename,
FilenameWithUnderscores: generateOpts.FilenameWithUnderscores,
Path: generateOpts.Path,
})
if err := g.Generate(tableMap, ixMap); err != nil {
return fmt.Errorf("error: %v", err)
Expand Down
18 changes: 10 additions & 8 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,15 @@ var (
}

g := generator.NewGenerator(loader, inflector, generator.GeneratorOption{
PackageName: rootOpts.Package,
Tags: rootOpts.Tags,
TemplatePath: rootOpts.TemplatePath,
CustomTypePackage: rootOpts.CustomTypePackage,
FilenameSuffix: rootOpts.Suffix,
SingleFile: rootOpts.SingleFile,
Filename: rootOpts.Filename,
Path: rootOpts.Path,
PackageName: rootOpts.Package,
Tags: rootOpts.Tags,
TemplatePath: rootOpts.TemplatePath,
CustomTypePackage: rootOpts.CustomTypePackage,
FilenameSuffix: rootOpts.Suffix,
SingleFile: rootOpts.SingleFile,
Filename: rootOpts.Filename,
FilenameWithUnderscores: rootOpts.FilenameWithUnderscores,
Path: rootOpts.Path,
})
if err := g.Generate(tableMap, ixMap); err != nil {
return fmt.Errorf("error: %v", err)
Expand All @@ -123,6 +124,7 @@ func setRootOpts(cmd *cobra.Command, opts *internal.ArgType) {
cmd.Flags().StringVarP(&opts.Out, "out", "o", "", "output path or file name")
cmd.Flags().StringVar(&opts.Suffix, "suffix", defaultSuffix, "output file suffix")
cmd.Flags().BoolVar(&opts.SingleFile, "single-file", false, "toggle single file output")
cmd.Flags().BoolVar(&opts.FilenameWithUnderscores, "with-underscores", false, "toggle underscores in file names")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To align with the other options such as the suffix flag, how about removing with and naming it underscore?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed 2c06c11

cmd.Flags().StringVarP(&opts.Package, "package", "p", "", "package name used in generated Go code")
cmd.Flags().StringVar(&opts.CustomTypePackage, "custom-type-package", "", "Go package name to use for custom or unknown types")
cmd.Flags().StringArrayVar(&opts.TargetTables, "target-tables", nil, "tables to include from the generated Go code")
Expand Down
86 changes: 56 additions & 30 deletions generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
"sort"
"strings"
"text/template"
"unicode"

"golang.org/x/tools/imports"

Expand All @@ -45,30 +46,32 @@ type Loader interface {
}

type GeneratorOption struct {
PackageName string
Tags string
TemplatePath string
CustomTypePackage string
FilenameSuffix string
SingleFile bool
Filename string
Path string
PackageName string
Tags string
TemplatePath string
CustomTypePackage string
FilenameSuffix string
SingleFile bool
Filename string
FilenameWithUnderscores bool
Path string
}

func NewGenerator(loader Loader, inflector internal.Inflector, opt GeneratorOption) *Generator {
return &Generator{
loader: loader,
inflector: inflector,
templatePath: opt.TemplatePath,
nameConflictSuffix: "z",
packageName: opt.PackageName,
tags: opt.Tags,
customTypePackage: opt.CustomTypePackage,
filenameSuffix: opt.FilenameSuffix,
singleFile: opt.SingleFile,
filename: opt.Filename,
path: opt.Path,
files: make(map[string]*os.File),
loader: loader,
inflector: inflector,
templatePath: opt.TemplatePath,
nameConflictSuffix: "z",
packageName: opt.PackageName,
tags: opt.Tags,
customTypePackage: opt.CustomTypePackage,
filenameSuffix: opt.FilenameSuffix,
singleFile: opt.SingleFile,
filename: opt.Filename,
filenameWithUnderscores: opt.FilenameWithUnderscores,
path: opt.Path,
files: make(map[string]*os.File),
}
}

Expand All @@ -83,13 +86,14 @@ type Generator struct {
// generated is the generated templates after a run.
generated []TBuf

packageName string
tags string
customTypePackage string
filenameSuffix string
singleFile bool
filename string
path string
packageName string
tags string
customTypePackage string
filenameSuffix string
singleFile bool
filename string
filenameWithUnderscores bool
path string

nameConflictSuffix string
}
Expand Down Expand Up @@ -152,9 +156,14 @@ func (g *Generator) Generate(tableMap map[string]*internal.Type, ixMap map[strin
// the os.OpenFile with the correct parameters depending on the state of args.
func (g *Generator) getFile(ds *basicDataSet, t *TBuf) (*os.File, error) {
// determine filename
var filename = strings.ToLower(t.Name) + g.filenameSuffix
if g.singleFile {
var filename string
switch {
case g.singleFile:
filename = g.filename
case g.filenameWithUnderscores:
filename = toSnakeCase(t.Name) + g.filenameSuffix
default:
filename = strings.ToLower(t.Name) + g.filenameSuffix
}
filename = path.Join(g.path, filename)

Expand All @@ -174,7 +183,7 @@ func (g *Generator) getFile(ds *basicDataSet, t *TBuf) (*os.File, error) {
}

// open file
f, err = os.OpenFile(filename, mode, 0666)
f, err = os.OpenFile(filename, mode, 0o666)
if err != nil {
return nil, err
}
Expand All @@ -195,6 +204,23 @@ func (g *Generator) getFile(ds *basicDataSet, t *TBuf) (*os.File, error) {
return f, nil
}

func toSnakeCase(s string) string {
b := &strings.Builder{}
for i, r := range s {
if i == 0 {
b.WriteRune(unicode.ToLower(r))
continue
}
if unicode.IsUpper(r) {
b.WriteRune('_')
b.WriteRune(unicode.ToLower(r))
continue
}
b.WriteRune(r)
}
return b.String()
}

// importsOptions is the same as x/tools/cmd/goimports options except Fragment.
var importsOptions = &imports.Options{
TabWidth: 8,
Expand Down
5 changes: 3 additions & 2 deletions internal/argtype.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,9 @@ type ArgType struct {
// Tags is the list of build tags to add to generated Go files.
Tags string

Path string
Filename string
Path string
Filename string
FilenameWithUnderscores bool

// DDLFilepath is the filepath of the ddl file.
DDLFilepath string
Expand Down
2 changes: 1 addition & 1 deletion test/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ func TestDefaultCompositePrimaryKey(t *testing.T) {
})

t.Run("ReadByError3", func(t *testing.T) {
got, err := models.ReadCompositePrimaryKeysByZYError(ctx, client.Single(), spanner.Key{cpk.Error})
got, err := models.ReadCompositePrimaryKeysByYZError(ctx, client.Single(), spanner.Key{cpk.Error})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
Expand Down
16 changes: 8 additions & 8 deletions test/testmodels/customtypes/compositeprimarykey.yo.go

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

16 changes: 8 additions & 8 deletions test/testmodels/default/compositeprimarykey.yo.go

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

Loading