Skip to content

Commit

Permalink
fix(comments): correctly parse args with cobra and strengthen regexp …
Browse files Browse the repository at this point in the history
…search

Signed-off-by: kilianpaquier <[email protected]>
  • Loading branch information
kilianpaquier committed Aug 14, 2024
1 parent 3adc1a4 commit 471a3f6
Show file tree
Hide file tree
Showing 15 changed files with 52 additions and 28 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module github.com/kilianpaquier/go-builder-generator

go 1.22.0

toolchain go1.22.6
toolchain go1.23.0

require (
github.com/Masterminds/sprig/v3 v3.2.3
Expand Down
10 changes: 9 additions & 1 deletion internal/cobra/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,14 @@ var (
generateCmd = &cobra.Command{
Use: "generate",
Short: "Generate builders for structs arguments present in file argument.",
RunE: func(_ *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, args []string) error {
// now that we have the raw flags in args slice, reenable flag parsing for ParseFlags
cmd.DisableFlagParsing = false
// parse flags into generateOpts (yeah it's wobbly but cobra is missing this issue https://github.com/spf13/cobra/issues/1832)
if err := cmd.ParseFlags(args); err != nil {
return err
}

if err := generate.Run(generateOpts, args); err != nil {
return fmt.Errorf("generate builders: %w", err)
}
Expand All @@ -24,6 +31,7 @@ var (
)

func init() {
generateCmd.DisableFlagParsing = true // disable flags parsing to get raw flags in args slice
rootCmd.AddCommand(generateCmd)

// dest flag
Expand Down
11 changes: 5 additions & 6 deletions internal/generate/gomod.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,12 @@ func fileImport(file *modfile.File, pkg string) string {
}

// hasGenerate checks whether a 'go:generate' comment is present in input file for go-builder-generator.
func hasGenerate(file *ast.File, rawArgs []string) bool {
args := regexp.QuoteMeta(strings.Join(rawArgs, " "))
func hasGenerate(file *ast.File, args []string) bool {
options := regexp.QuoteMeta(strings.Join(args, " "))

rexps := []*regexp.Regexp{
regexp.MustCompile(`//go:generate go run github\.com/kilianpaquier/go-builder-generator/cmd/go-builder-generator@[^\s]+ generate ` + args),
regexp.MustCompile(`//go:generate ([^\s]+)?go-builder-generator generate ` + args),
regexp.MustCompile(fmt.Sprint(`^//go:generate go run github\.com/kilianpaquier/go-builder-generator/cmd/go-builder-generator@[^\s]+ generate `, options, "$")),
regexp.MustCompile(fmt.Sprint(`^//go:generate ([^\s]+)?go-builder-generator generate `, options, "$")),
}

for _, group := range file.Comments {
Expand All @@ -147,8 +147,7 @@ func hasGenerate(file *ast.File, rawArgs []string) bool {
continue
}

_, ok := lo.Find(rexps, func(reg *regexp.Regexp) bool { return reg.MatchString(comment.Text) })
if ok {
if _, ok := lo.Find(rexps, func(reg *regexp.Regexp) bool { return reg.MatchString(comment.Text) }); ok {
return true
}
}
Expand Down
4 changes: 2 additions & 2 deletions internal/generate/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
var tmpl embed.FS

// Run runs the builder generation with input options.
func Run(options CLIOptions, rawArgs []string) error {
func Run(options CLIOptions, args []string) error {
// force first rune to lowercase in case of unexported types
// it will be titled in gen template in case the type is exported
options.Prefix = xstrings.FirstRuneToLower(options.Prefix)
Expand Down Expand Up @@ -86,7 +86,7 @@ func Run(options CLIOptions, rawArgs []string) error {
Destdir: destdir,
DestName: destPackage,
GeneratedFrom: path.Join(srcpkg, filepath.Base(options.File)),
HasGenerate: hasGenerate(file, rawArgs),
HasGenerate: hasGenerate(file, args),
Imports: imports,
SameModule: destfile.Module.Mod.String() == srcfile.Module.Mod.String(),
SourceName: sourcePackage,
Expand Down
32 changes: 25 additions & 7 deletions internal/generate/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package generate_test
import (
"os"
"path/filepath"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -143,73 +144,84 @@ func TestRun_DifferentPackage(t *testing.T) {
{
DirName: "success_channels",
CLIOptions: generate.CLIOptions{
NoCMD: true,
Structs: []string{"Chan"},
},
},
{
DirName: "success_export",
CLIOptions: generate.CLIOptions{
NoCMD: true,
Structs: []string{"Export"},
},
},
{
DirName: "success_funcs",
CLIOptions: generate.CLIOptions{
NoCMD: true,
Structs: []string{"Func"},
},
},
{
DirName: "success_generic",
CLIOptions: generate.CLIOptions{
NoCMD: true,
Structs: []string{"Struct", "SimpleGeneric", "AliasGeneric", "ComplexGeneric", "GenericAnonymousStruct", "ComplexSliceGeneric"},
},
},
{
DirName: "success_interface",
CLIOptions: generate.CLIOptions{
NoCMD: false, // enforce testing at least with one case that the cmd can be printed (and is right) in generated files
Structs: []string{"Interface", "InterfaceNoFields"},
},
},
{
DirName: "success_maps",
CLIOptions: generate.CLIOptions{
NoCMD: true,
Structs: []string{"Map"},
},
},
{
DirName: "success_naming",
CLIOptions: generate.CLIOptions{
NoCMD: true,
Structs: []string{"Naming"},
},
},
{
DirName: "success_root_gomod",
CLIOptions: generate.CLIOptions{
NoCMD: true,
Structs: []string{"RootType"},
},
},
{
DirName: "success_slices",
CLIOptions: generate.CLIOptions{
NoCMD: true,
Structs: []string{"ArrayAndSlice"},
},
},
{
DirName: "success_struct",
CLIOptions: generate.CLIOptions{
NoCMD: true,
Structs: []string{"Struct", "StructNoFields"},
},
},
{
DirName: "success_with_options",
CLIOptions: generate.CLIOptions{
NoCMD: true,
NoNotice: true,
Prefix: "Set",
ReturnCopy: true,
Structs: []string{"Options", "Empty", "GenericOptions"},
ValidateFunc: "Validate",
},
},
{
DirName: "success_generic",
CLIOptions: generate.CLIOptions{
Structs: []string{"Struct", "SimpleGeneric", "AliasGeneric", "ComplexGeneric", "GenericAnonymousStruct", "ComplexSliceGeneric"},
},
},
} {
t.Run(tc.DirName, func(t *testing.T) {
// Arrange
Expand Down Expand Up @@ -241,20 +253,23 @@ func TestRun_ExternalModule(t *testing.T) {
DirName: "success_module_replace",
CLIOptions: generate.CLIOptions{
File: "module::github.com/stretchr/testify/mock/mock.go",
NoCMD: true,
Structs: []string{"Mock"},
},
},
{
DirName: "success_module_root",
CLIOptions: generate.CLIOptions{
File: "module::github.com/go-playground/validator/v10/errors.go",
NoCMD: true,
Structs: []string{"InvalidValidationError"},
},
},
{
DirName: "success_module_subdir",
CLIOptions: generate.CLIOptions{
File: "module::github.com/stretchr/testify/mock/mock.go",
NoCMD: true,
Structs: []string{"Mock"},
},
},
Expand Down Expand Up @@ -282,16 +297,19 @@ func TestRun_SamePackage(t *testing.T) {

for _, tc := range []struct {
generate.CLIOptions
Args string
DirName string
}{
{
DirName: "success_same_package",
Args: "-f types.go -s SamePackage,unexportedType",
CLIOptions: generate.CLIOptions{
Structs: []string{"SamePackage", "unexportedType"},
},
},
{
DirName: "success_same_package_options",
Args: "-f types.go -s unexportedTypeOptions -p set --package-name unused",
CLIOptions: generate.CLIOptions{
Structs: []string{"unexportedTypeOptions"},
Prefix: "Set",
Expand All @@ -311,7 +329,7 @@ func TestRun_SamePackage(t *testing.T) {
t.Cleanup(func() { require.NoError(t, os.RemoveAll(tc.CLIOptions.Destdir)) })

// Act
err := generate.Run(tc.CLIOptions, nil)
err := generate.Run(tc.CLIOptions, strings.Split(tc.Args, " "))

// Assert
assert.NoError(t, err)
Expand Down
2 changes: 2 additions & 0 deletions testdata/success_interface/builders/interface_builder_gen.go

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

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

3 changes: 2 additions & 1 deletion testdata/success_interface/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ package success_interface

import "context"

//go:generate ../../go-builder-generator generate -f types.go -s Interface,InterfaceNoFields -d builders
// execute this command from your terminal
// ./go-builder-generator generate -f testdata/success_interface/types.go -s Interface,InterfaceNoFields -d testdata/success_interface/builders --package-name builders

type Int64Alias int64

Expand Down
2 changes: 0 additions & 2 deletions testdata/success_module_replace/builders/mock_builder_gen.go

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

2 changes: 1 addition & 1 deletion testdata/success_module_replace/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"github.com/stretchr/testify/mock"
)

//go:generate ../../go-builder-generator generate -f module::github.com/stretchr/testify/mock/mock.go -s Mock -d builders
//go:generate ../../go-builder-generator generate -f module::github.com/stretchr/testify/mock/mock.go -s Mock -d builders --no-cmd

// Mock is just an alias of testify Mock.
type Mock mock.Mock

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

2 changes: 1 addition & 1 deletion testdata/success_module_root/types.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package success_pkg

//go:generate ../../go-builder-generator generate -f module::github.com/go-playground/validator/v10/errors.go -s InvalidValidationError -d builders
//go:generate ../../go-builder-generator generate -f module::github.com/go-playground/validator/v10/errors.go -s InvalidValidationError -d builders --no-cmd
2 changes: 0 additions & 2 deletions testdata/success_module_subdir/builders/mock_builder_gen.go

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

2 changes: 1 addition & 1 deletion testdata/success_module_subdir/types.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package success_pkg

//go:generate ../../go-builder-generator generate -f module::github.com/stretchr/testify/mock/mock.go -s Mock -d builders
//go:generate ../../go-builder-generator generate -f module::github.com/stretchr/testify/mock/mock.go -s Mock -d builders --no-cmd
2 changes: 1 addition & 1 deletion testdata/success_same_package_options/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package success_spo

import "context"

//go:generate ../../go-builder-generator generate -f types.go -s unexportedTypeOptions -p set --package-name invalid
//go:generate ../../go-builder-generator generate -f types.go -s unexportedTypeOptions -p set --package-name unused

type Int64Alias int64

Expand Down

0 comments on commit 471a3f6

Please sign in to comment.