Skip to content

Commit

Permalink
Merge pull request #682 from LandonTClipp/issue_681
Browse files Browse the repository at this point in the history
Include auto-generated files in recursive discovery by default
  • Loading branch information
LandonTClipp committed Aug 3, 2023
2 parents 532f248 + b70c07a commit dbad753
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 25 deletions.
1 change: 1 addition & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ Parameter Descriptions
| `disable-version-string` | :fontawesome-solid-x: | `#!yaml false` | Disable the version string in the generated mock files. |
| `dry-run` | :fontawesome-solid-x: | `#!yaml false` | Print the actions that would be taken, but don't perform the actions. |
| `filename` | :fontawesome-solid-check: | `#!yaml "mock_{{.InterfaceName}}.go"` | The name of the file the mock will reside in. |
| `include-auto-generated` | :fontawesome-solid-x: | `#!yaml true` | Set to `#!yaml false` if you need mockery to skip auto-generated files during its recursive package discovery. When set to `#!yaml true`, mockery includes auto-generated files when determining if a particular directory is an importable package. |
| `inpackage` | :fontawesome-solid-x: | `#!yaml false` | When generating mocks alongside the original interfaces, you must specify `inpackage: True` to inform mockery that the mock is being placed in the same package as the original interface. |
| `mockname` | :fontawesome-solid-check: | `#!yaml "Mock{{.InterfaceName}}"` | The name of the generated mock. |
| `outpkg` | :fontawesome-solid-check: | `#!yaml "{{.PackageName}}"` | Use `outpkg` to specify the package name of the generated mocks. |
Expand Down
41 changes: 28 additions & 13 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ type Config struct {
DryRun bool `mapstructure:"dry-run"`
Exported bool `mapstructure:"exported"`
FileName string `mapstructure:"filename"`
IncludeAutoGenerated bool `mapstructure:"include-auto-generated"`
InPackage bool `mapstructure:"inpackage"`
InPackageSuffix bool `mapstructure:"inpackage-suffix"`
KeepTree bool `mapstructure:"keeptree"`
Expand Down Expand Up @@ -93,6 +94,7 @@ func NewConfigFromViper(v *viper.Viper) (*Config, error) {
} else {
v.SetDefault("dir", "mocks/{{.PackagePath}}")
v.SetDefault("filename", "mock_{{.InterfaceName}}.go")
v.SetDefault("include-auto-generated", true)
v.SetDefault("mockname", "Mock{{.InterfaceName}}")
v.SetDefault("outpkg", "{{.PackageName}}")
v.SetDefault("with-expecter", true)
Expand Down Expand Up @@ -429,6 +431,24 @@ func (c *Config) addSubPkgConfig(ctx context.Context, subPkgPath string, parentP
return nil
}

func isAutoGenerated(path *pathlib.Path) (bool, error) {
file, err := path.OpenFile(os.O_RDONLY)
if err != nil {
return false, stackerr.NewStackErr(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := scanner.Text()
if strings.Contains(text, "DO NOT EDIT") {
return true, nil
} else if strings.HasPrefix(text, "package ") {
break
}
}
return false, nil
}

func (c *Config) subPackages(
ctx context.Context,
pkgPath string,
Expand Down Expand Up @@ -484,23 +504,18 @@ func (c *Config) subPackages(
return err
}

file, err := path.OpenFile(os.O_RDONLY)
if err != nil {
return err
}
defer file.Close()

_, haveVisitedDir := visitedDirs[path.Parent().String()]
if !haveVisitedDir && strings.HasSuffix(path.Name(), ".go") {
// Skip auto-generated files
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := scanner.Text()
if strings.Contains(text, "DO NOT EDIT") {

if !c.IncludeAutoGenerated {
autoGenerated, err := isAutoGenerated(path)
if err != nil {
log.Err(err).Stringer("path", path).Msg("failed to determine if file is auto-generated")
return err
}
if autoGenerated {
log.Debug().Stringer("path", path).Msg("skipping file as auto-generated")
return nil
} else if strings.HasPrefix(text, "package ") {
break
}
}

Expand Down
74 changes: 62 additions & 12 deletions pkg/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -721,12 +721,13 @@ packages:
github.com/vektra/mockery/v2/pkg:
`,
want: &Config{
Dir: "mocks/{{.PackagePath}}",
FileName: "mock_{{.InterfaceName}}.go",
MockName: "Mock{{.InterfaceName}}",
Outpkg: "{{.PackageName}}",
WithExpecter: true,
LogLevel: "info",
Dir: "mocks/{{.PackagePath}}",
FileName: "mock_{{.InterfaceName}}.go",
IncludeAutoGenerated: true,
MockName: "Mock{{.InterfaceName}}",
Outpkg: "{{.PackageName}}",
WithExpecter: true,
LogLevel: "info",
},
},
{
Expand All @@ -738,12 +739,13 @@ packages:
github.com/vektra/mockery/v2/pkg:
`,
want: &Config{
Dir: "barfoo",
FileName: "foobar.go",
MockName: "Mock{{.InterfaceName}}",
Outpkg: "{{.PackageName}}",
WithExpecter: true,
LogLevel: "info",
Dir: "barfoo",
FileName: "foobar.go",
IncludeAutoGenerated: true,
MockName: "Mock{{.InterfaceName}}",
Outpkg: "{{.PackageName}}",
WithExpecter: true,
LogLevel: "info",
},
},
}
Expand Down Expand Up @@ -983,3 +985,51 @@ want
})
}
}

func Test_isAutoGenerated(t *testing.T) {
tests := []struct {
name string
args func(t *testing.T) *pathlib.Path
want bool
wantErr bool
}{
{
name: "file is autogenerated",
args: func(t *testing.T) *pathlib.Path {
path := pathlib.NewPath(t.TempDir()).Join("file.go")
assert.NoError(t, path.WriteFile([]byte("// Code generated by mockery. DO NOT EDIT.")))
return path
},
want: true,
},
{
name: "file is not autogenerated",
args: func(t *testing.T) *pathlib.Path {
path := pathlib.NewPath(t.TempDir()).Join("file.go")
assert.NoError(t, path.WriteFile([]byte("package foobar")))
return path
},
want: false,
},
{
name: "error when reading file",
args: func(t *testing.T) *pathlib.Path {
path := pathlib.NewPath(t.TempDir()).Join("file.go")
return path
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := isAutoGenerated(tt.args(t))
if (err != nil) != tt.wantErr {
t.Errorf("isAutoGenerated() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("isAutoGenerated() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit dbad753

Please sign in to comment.