Skip to content

Commit

Permalink
Add a CLI option to change output filenames (#141)
Browse files Browse the repository at this point in the history
* ✨ (generate.go, root.go, generator.go, argtype.go): Add option to generate filenames with underscores for better readability and consistency with some coding standards

* ✨ (Makefile): Add new testdata/with-underscores target to support testing of models with underscores in their names

✨ (testmodels): Add new CompositePrimaryKey model for testing composite primary keys
📝 (testmodels): Add methods for CompositePrimaryKey model to handle CRUD operations and queries

✨ Add new functions to read and find CompositePrimaryKeys by ZYError and XY
♻️ Refactor the way CompositePrimaryKeys are read and found by ZError, now using a new decoder
💡 Update comments to reflect changes in function behavior and usage

✨ (testmodels): Add new FereignItem model for testing underscore handling in model names
📝 (testmodels): Add methods for FereignItem model to handle CRUD operations and column value manipulation

✨ Add new test model 'FullType' in 'full_type.yo.go' for testing various data types

✨ Add new functions to handle FullType operations in the database

This commit introduces new functions to handle FullType operations such as Insert, Update, Delete, and Find. These functions are necessary to perform CRUD operations on the FullType table in the database.

✨ Add new functions to retrieve rows from 'FullTypes' by different keys and indexes. This allows more flexible data retrieval based on different criteria.

✨ (generated_column.yo.go): Add new generated model for 'GeneratedColumns' table with CRUD operations and helper functions. This will allow us to interact with the 'GeneratedColumns' table in a type-safe manner.

✨ Add new test models for 'Items' and 'MaxLengths' to improve test coverage and validate functionality for different data types and operations.

✨ (testmodels): Add new test model 'OutOfOrderPrimaryKey' to handle primary keys in non-sequential order
📝 (testmodels): Document the usage and functions of 'OutOfOrderPrimaryKey' model

✨ (testmodels/underscores): Add new test models for handling snake_case naming convention
📝 (snake_case.yo.go): Add new model SnakeCase with CRUD operations and helper functions
📝 (yo_db.yo.go): Add new database interface YODB and YORODB for common database operations
💡 These changes are necessary to test and ensure the correct handling of snake_case naming convention in the application.

* 📝 (README.md): Add documentation for new flag --with-underscores to allow underscores in file names

* 💚 (testdata-from-ddl) fix sorting storing columns

* ♻️ (generator.go): Replace custom toSnakeCase function with snaker.CamelToSnake for better maintainability and reliability
🔧 (generator.go): Add dependency on "github.com/kenshaw/snaker" for string conversion functionality

* ♻️ Rename 'FilenameWithUnderscores' to 'FilenameUnderscore' across multiple files for consistency and clarity
🐛 Fix typo in comment in 'internal/argtype.go' file

* 🐛 (Makefile): Fix incorrect directory name from 'underscores' to 'underscore' for consistency and to avoid potential confusion

✨ (testmodels): Add new CompositePrimaryKey model for testing composite primary keys
📝 (testmodels): Add methods for CompositePrimaryKey model to handle CRUD operations and queries

✨ Add new functions to read and find CompositePrimaryKeys by ZYError and XY
💡 These functions allow retrieving multiple rows from 'CompositePrimaryKeys' as a slice of CompositePrimaryKey using different parameters and indices.

✨ (testmodels): Add new FereignItem model in testmodels for testing purposes
📝 (fereign_item.yo.go): Add methods for FereignItem model to interact with database (insert, update, delete, find, read)

✨ Add new FullType model in testmodels for testing various data types and their nullable versions. This will help in ensuring the robustness of the application by testing all possible data types.

✨ Add new functions to handle FullType operations in the database

This commit introduces new functions to handle FullType operations such as Insert, Update, Delete, and Find. These functions are necessary to perform CRUD operations on the FullType table in the database.

✨ Add new functions to retrieve rows from 'FullTypes' by different keys and indexes. This allows more flexible data retrieval based on different parameters.

✨ (generated_column.yo.go): Add new generated model for 'GeneratedColumns' table. This includes methods for CRUD operations, and helper functions for handling column values. This change is necessary to interact with the 'GeneratedColumns' table in the database.

✨ Add new test models 'Item' and 'MaxLength' for testing purposes. These models will be used in unit tests to ensure the correct functionality of the application.

✨ (testmodels): Add new test model 'OutOfOrderPrimaryKey' to verify primary key order handling in the application. This model will help in testing the functionality of the application when the primary keys are not in order.

✨ (testmodels/underscore): Add new test models for snake_case handling
📝 (testmodels/underscore): Add documentation for new test models
💡 (testmodels/underscore): Add comments to new test models for better understanding of the code

* ♻️ (generate.go, root.go): Refactor code to improve readability by aligning the properties of the GeneratorOption object.

* 📝 (README.md): Update flag name from '--with-underscores' to '--underscore' to match the actual flag name in the code
  • Loading branch information
iwata committed Apr 5, 2024
1 parent d29eb93 commit 9f3f92a
Show file tree
Hide file tree
Showing 15 changed files with 2,520 additions and 39 deletions.
12 changes: 10 additions & 2 deletions 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/underscore 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/underscore:
rm -rf test/testmodels/underscore && mkdir -p test/testmodels/underscore
$(YOBIN) $(SPANNER_PROJECT_NAME) $(SPANNER_INSTANCE_NAME) $(SPANNER_DATABASE_NAME) --package models --underscore --out test/testmodels/underscore/

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 All @@ -58,12 +62,16 @@ testdata/customtypes:
$(YOBIN) $(SPANNER_PROJECT_NAME) $(SPANNER_INSTANCE_NAME) $(SPANNER_DATABASE_NAME) --custom-types-file test/testdata/custom_column_types.yml --out test/testmodels/customtypes/

testdata-from-ddl:
$(MAKE) -j4 testdata-from-ddl/default testdata-from-ddl/customtypes testdata-from-ddl/single
$(MAKE) -j4 testdata-from-ddl/default testdata-from-ddl/underscore testdata-from-ddl/customtypes testdata-from-ddl/single

testdata-from-ddl/default:
rm -rf test/testmodels/default && mkdir -p test/testmodels/default
$(YOBIN) generate ./test/testdata/schema.sql --from-ddl --package models --out test/testmodels/default/

testdata-from-ddl/underscore:
rm -rf test/testmodels/underscores && mkdir -p test/testmodels/underscores
$(YOBIN) generate ./test/testdata/schema.sql --from-ddl --package models --underscore --out test/testmodels/underscores/

testdata-from-ddl/single:
rm -rf test/testmodels/single && mkdir -p test/testmodels/single
$(YOBIN) generate ./test/testdata/schema.sql --from-ddl --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
--underscore 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,
FilenameUnderscore: generateOpts.FilenameUnderscore,
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,
FilenameUnderscore: rootOpts.FilenameUnderscore,
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.FilenameUnderscore, "underscore", false, "toggle underscores in file names")
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
45 changes: 27 additions & 18 deletions generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
"strings"
"text/template"

"github.com/kenshaw/snaker"
"golang.org/x/tools/imports"

"go.mercari.io/yo/internal"
Expand All @@ -45,14 +46,15 @@ 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
FilenameUnderscore bool
Path string
}

func NewGenerator(loader Loader, inflector internal.Inflector, opt GeneratorOption) *Generator {
Expand All @@ -67,6 +69,7 @@ func NewGenerator(loader Loader, inflector internal.Inflector, opt GeneratorOpti
filenameSuffix: opt.FilenameSuffix,
singleFile: opt.SingleFile,
filename: opt.Filename,
filenameUnderscore: opt.FilenameUnderscore,
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
filenameUnderscore 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.filenameUnderscore:
filename = snaker.CamelToSnake(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 Down
7 changes: 4 additions & 3 deletions internal/argtype.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,14 @@ 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
FilenameUnderscore bool

// DDLFilepath is the filepath of the ddl file.
DDLFilepath string

// FromDDL indicates generating from ddl flie or not.
// FromDDL indicates generating from ddl file or not.
FromDDL bool

// InflectionRuleFile is custom inflection rule file.
Expand Down
Loading

0 comments on commit 9f3f92a

Please sign in to comment.