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 enhanced deprecation logging support. #894

Merged
merged 8 commits into from
Jan 14, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
@@ -12,7 +12,6 @@ linters:
- ineffassign
- staticcheck
- typecheck
- contextcheck
- durationcheck
- copyloopvar
- gocheckcompilerdirectives
21 changes: 9 additions & 12 deletions cmd/mockery.go
Original file line number Diff line number Diff line change
@@ -196,6 +196,10 @@ func (r *RootApp) Run() error {
fmt.Fprintf(os.Stderr, "Failed to initialize logger: %v\n", err)
return err
}
logging.DisableDeprecationWarnings = r.Config.DisableDeprecationWarnings
logging.DisabledDeprecationWarnings = r.Config.DisabledDeprecationWarnings
defer logging.LogDeprecationWarnings()

log = log.With().Bool(logging.LogKeyDryRun, r.Config.DryRun).Logger()
log.Info().Msgf("Starting mockery")
log.Info().Msgf("Using config: %s", r.Config.Config)
@@ -228,12 +232,13 @@ func (r *RootApp) Run() error {
boilerplate = string(data)
}

if !r.Config.WithExpecter {
if r.Config.Packages == nil {
logging.WarnDeprecated(
ctx,
"with-expecter will be permanently set to True in v3",
"packages",
"use of the packages config will be the only way to generate mocks in v3. Please migrate your config to use the packages feature.",
map[string]any{
"url": logging.DocsURL("/deprecations/#with-expecter"),
"url": logging.DocsURL("/features/#packages-configuration"),
"migration": logging.DocsURL("/migrating_to_packages/"),
},
)
}
@@ -309,14 +314,6 @@ func (r *RootApp) Run() error {
log.Fatal().Msgf("Use --name to specify the name of the interface or --all for all interfaces found")
}

logging.WarnDeprecated(
ctx,
"use of the packages config will be the only way to generate mocks in v3. Please migrate your config to use the packages feature.",
map[string]any{
"url": logging.DocsURL("/features/#packages-configuration"),
"migration": logging.DocsURL("/migrating_to_packages/"),
})

if r.Config.Profile != "" {
f, err := os.Create(r.Config.Profile)
if err != nil {
24 changes: 14 additions & 10 deletions docs/configuration.md

Large diffs are not rendered by default.

48 changes: 44 additions & 4 deletions docs/deprecations.md
Original file line number Diff line number Diff line change
@@ -21,7 +21,7 @@ The [`packages`](features.md#packages-configuration) feature will be the only wa
!!! tip ""

To resolve this warning:

```yaml title=".mockery.yaml"
issue-845-fix: True
```
@@ -60,7 +60,7 @@ if being generated with `#!yaml inpackage: True`.
!!! tip ""

To resolve this warning:

```yaml title=".mockery.yaml"
resolve-type-alias: False
```
@@ -84,10 +84,50 @@ be set to `False`. This will be the permanent behavior in Mockery v3.
!!! tip ""

To resolve this warning:

```yaml title=".mockery.yaml"
with-expecter: True
```

This parameter enables the [expecter structs](features.md#expecter-structs). In Mockery v3, this parameter will be permanently
enabled. In order to remove the deprecation warning, you must set this parameter to `#!yaml with-expecter: True`.
enabled. In order to remove the deprecation warning, you must set this parameter to `#!yaml with-expecter: True`.

`quiet`
-------

!!! tip ""

To resolve this warning:

```yaml title=".mockery.yaml"
quiet: False
```

The `--quiet` parameter is superseded by `--log-level=""`. It will be removed in v3.

`disable-version-string`
-----------------------

!!! tip ""

To resolve this warning:

```yaml title=".mockery.yaml"
disable-version-string: True
```

Mockery will no longer print the version of mockery used as a comment in the mock files.

`structname`
------------

!!! tip ""

To resolve this warning:

```yaml title=".mockery.yaml"
structname: ""
mockname: "NameOfMock"
```

If you're receiving this warning, you are likely not using the `packages` config feature anyway. It should be noted that `structname` will not be a config option in v3. Receipt of this warning means you need to upgrade to use the `packages` config feature.
14 changes: 14 additions & 0 deletions docs/stylesheets/extra.css
Original file line number Diff line number Diff line change
@@ -13,3 +13,17 @@
.md-grid {
max-width: none;
}

.deprecated {
color: var(--md-code-hl-number-color);
font-weight: bold;
}

a .deprecation {
transition: color 125ms;
color: var(--md-code-hl-number-color);
}

.deprecation:hover {
color: darkred;
}
10 changes: 7 additions & 3 deletions mkdocs.yml
Original file line number Diff line number Diff line change
@@ -31,6 +31,7 @@ theme:
- content.code.copy
- content.action.edit
- content.action.view
- content.tooltips
- navigation.indexes
- navigation.sections
- navigation.tracking
@@ -39,6 +40,9 @@ markdown_extensions:
- admonition
- attr_list
- md_in_html
- pymdownx.caret
- pymdownx.mark
- pymdownx.tilde
- pymdownx.emoji:
emoji_index: !!python/name:material.extensions.emoji.twemoji
emoji_generator: !!python/name:material.extensions.emoji.to_svg
@@ -50,10 +54,10 @@ markdown_extensions:
- pymdownx.magiclink
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: true
alternate_style: true
- toc:
permalink: true


nav:
- Home: index.md
@@ -63,7 +67,7 @@ nav:
- Running: running.md
- Examples: examples.md
- Features: features.md
- Notes:
- Notes:
- FAQ: notes.md
- Changelog: changelog.md
- Migrating to Packages: migrating_to_packages.md
2 changes: 1 addition & 1 deletion mockery-tools.env
Original file line number Diff line number Diff line change
@@ -1 +1 @@
VERSION=v2.50.4
VERSION=v2.51.0
116 changes: 78 additions & 38 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
@@ -32,44 +32,46 @@ type Interface struct {
}

type Config struct {
All bool `mapstructure:"all"`
Anchors map[string]any `mapstructure:"_anchors"`
BoilerplateFile string `mapstructure:"boilerplate-file"`
BuildTags string `mapstructure:"tags"`
Case string `mapstructure:"case"`
Config string `mapstructure:"config"`
Cpuprofile string `mapstructure:"cpuprofile"`
Dir string `mapstructure:"dir"`
DisableConfigSearch bool `mapstructure:"disable-config-search"`
DisableFuncMocks bool `mapstructure:"disable-func-mocks"`
DisableVersionString bool `mapstructure:"disable-version-string"`
DryRun bool `mapstructure:"dry-run"`
Exclude []string `mapstructure:"exclude"`
ExcludeRegex string `mapstructure:"exclude-regex"`
Exported bool `mapstructure:"exported"`
FileName string `mapstructure:"filename"`
InPackage bool `mapstructure:"inpackage"`
InPackageSuffix bool `mapstructure:"inpackage-suffix"`
IncludeAutoGenerated bool `mapstructure:"include-auto-generated"`
IncludeRegex string `mapstructure:"include-regex"`
Issue845Fix bool `mapstructure:"issue-845-fix"`
KeepTree bool `mapstructure:"keeptree"`
LogLevel string `mapstructure:"log-level"`
MockBuildTags string `mapstructure:"mock-build-tags"`
MockName string `mapstructure:"mockname"`
Name string `mapstructure:"name"`
Note string `mapstructure:"note"`
Outpkg string `mapstructure:"outpkg"`
Output string `mapstructure:"output"`
Packageprefix string `mapstructure:"packageprefix"`
Packages map[string]interface{} `mapstructure:"packages"`
Print bool `mapstructure:"print"`
Profile string `mapstructure:"profile"`
Quiet bool `mapstructure:"quiet"`
Recursive bool `mapstructure:"recursive"`
ReplaceType []string `mapstructure:"replace-type"`
ResolveTypeAlias bool `mapstructure:"resolve-type-alias"`
SrcPkg string `mapstructure:"srcpkg"`
All bool `mapstructure:"all"`
Anchors map[string]any `mapstructure:"_anchors"`
BoilerplateFile string `mapstructure:"boilerplate-file"`
BuildTags string `mapstructure:"tags"`
Case string `mapstructure:"case"`
Config string `mapstructure:"config"`
Cpuprofile string `mapstructure:"cpuprofile"`
Dir string `mapstructure:"dir"`
DisableConfigSearch bool `mapstructure:"disable-config-search"`
DisableDeprecationWarnings bool `mapstructure:"disable-deprecation-warnings"`
DisabledDeprecationWarnings []string `mapstructure:"disabled-deprecation-warnings"`
DisableFuncMocks bool `mapstructure:"disable-func-mocks"`
DisableVersionString bool `mapstructure:"disable-version-string"`
DryRun bool `mapstructure:"dry-run"`
Exclude []string `mapstructure:"exclude"`
ExcludeRegex string `mapstructure:"exclude-regex"`
Exported bool `mapstructure:"exported"`
FileName string `mapstructure:"filename"`
InPackage bool `mapstructure:"inpackage"`
InPackageSuffix bool `mapstructure:"inpackage-suffix"`
IncludeAutoGenerated bool `mapstructure:"include-auto-generated"`
IncludeRegex string `mapstructure:"include-regex"`
Issue845Fix bool `mapstructure:"issue-845-fix"`
KeepTree bool `mapstructure:"keeptree"`
LogLevel string `mapstructure:"log-level"`
MockBuildTags string `mapstructure:"mock-build-tags"`
MockName string `mapstructure:"mockname"`
Name string `mapstructure:"name"`
Note string `mapstructure:"note"`
Outpkg string `mapstructure:"outpkg"`
Output string `mapstructure:"output"`
Packageprefix string `mapstructure:"packageprefix"`
Packages map[string]interface{} `mapstructure:"packages"`
Print bool `mapstructure:"print"`
Profile string `mapstructure:"profile"`
Quiet bool `mapstructure:"quiet"`
Recursive bool `mapstructure:"recursive"`
ReplaceType []string `mapstructure:"replace-type"`
ResolveTypeAlias bool `mapstructure:"resolve-type-alias"`
SrcPkg string `mapstructure:"srcpkg"`
// StructName overrides the name given to the mock struct and should only be nonempty
// when generating for an exact match (non regex expression in -name).
StructName string `mapstructure:"structname"`
@@ -825,3 +827,41 @@ func (c *Config) LogUnsupportedPackagesConfig(ctx context.Context) {
Logger()
l.Error().Msg("use of unsupported options detected. mockery behavior is undefined.")
}

func (c *Config) LogDeprecatedConfig(ctx context.Context) {
if !c.WithExpecter {
logging.WarnDeprecated(
"with-expecter",
"with-expecter will be permanently set to True in v3",
nil,
)
}
if c.Quiet {
logging.WarnDeprecated(
"quiet",
"The --quiet parameter will be removed in v3. Use --log-level=\"\" instead",
nil,
)
}
if c.ResolveTypeAlias {
logging.WarnDeprecated(
"resolve-type-alias",
"resolve-type-alias will be permanently set to False in v3. Please modify your config to set the parameter to False.",
nil,
)
}
if c.DisableVersionString {
logging.WarnDeprecated(
"disable-version-string",
"disable-version-string will be permanently set to True in v3",
nil,
)
}
if c.StructName != "" {
logging.WarnDeprecated(
"structname",
"structname will be removed as a parameter in v3",
nil,
)
}
}

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.

9 changes: 1 addition & 8 deletions pkg/generator.go
Original file line number Diff line number Diff line change
@@ -425,7 +425,7 @@ func (g *Generator) GeneratePrologue(ctx context.Context, pkg string) {

if !g.config.Issue845Fix {
logging.WarnDeprecated(
ctx,
"issue-845-fix",
"issue-845-fix must be set to True to remove this warning. Visit the link for more details.",
map[string]any{
"url": logging.DocsURL("/deprecations/#issue-845-fix"),
@@ -540,13 +540,6 @@ func (g *Generator) renderType(ctx context.Context, typ types.Type) string {
case *types.Alias:
log.Debug().Msg("found type alias")
if g.config.ResolveTypeAlias {
logging.WarnDeprecated(
ctx,
"resolve-type-alias will be permanently set to False in v3. Please modify your config to set the parameter to False.",
map[string]any{
"url": logging.DocsURL("/deprecations/#resolve-type-alias"),
},
)
return g.renderType(ctx, t.Rhs())
}
log.Debug().Msg("not resolving type alias to underlying type")
46 changes: 41 additions & 5 deletions pkg/logging/logging.go
Original file line number Diff line number Diff line change
@@ -28,8 +28,13 @@ const (
defaultSemVer = "v0.0.0-dev"
)

// SemVer is the version of mockery at build time.
var SemVer = ""
var (
SemVer = ""
DisableDeprecationWarnings bool
DisabledDeprecationWarnings []string
seenWarnings []string
deferredCalls []func()
)

var ErrPkgNotExist = errors.New("package does not exist")

@@ -44,6 +49,12 @@ func GetSemverInfo() string {
return defaultSemVer
}

func LogDeprecationWarnings() {
for _, warn := range deferredCalls {
warn()
}
}

func getMinorSemver(semver string) string {
split := strings.Split(semver, ".")
return strings.Join(split[0:2], ".")
@@ -86,7 +97,6 @@ func GetLogger(levelStr string) (zerolog.Logger, error) {
With().
Str("version", GetSemverInfo()).
Logger()

return log, nil
}

@@ -108,6 +118,32 @@ func Info(ctx context.Context, prefix string, message string, fields map[string]
event.Msgf("%s: %s", prefix, message)
}

func WarnDeprecated(ctx context.Context, message string, fields map[string]any) {
Warn(ctx, "DEPRECATION", message, fields)
func WarnDeprecated(name, message string, fields map[string]any) {
log, _ := GetLogger("warn")
ctx := log.WithContext(context.Background())
if DisableDeprecationWarnings {
return
}
for _, disabledWarning := range DisabledDeprecationWarnings {
if disabledWarning == name {
return
}
}
for _, seenWarning := range seenWarnings {
if seenWarning == name {
return
}
}
seenWarnings = append(seenWarnings, name)
if fields == nil {
fields = map[string]any{}
}
fields["deprecation-name"] = name
if _, ok := fields["url"]; !ok {
fields["url"] = DocsURL(fmt.Sprintf("/deprecations/#%s", name))
}

deferredCalls = append(deferredCalls, func() {
Warn(ctx, "DEPRECATION", message, fields)
})
}
1 change: 1 addition & 0 deletions pkg/outputter.go
Original file line number Diff line number Diff line change
@@ -326,6 +326,7 @@ func (m *Outputter) Generate(ctx context.Context, iface *Interface) error {
if err := parseConfigTemplates(ctx, interfaceConfig, iface); err != nil {
return fmt.Errorf("failed to parse config template: %w", err)
}
interfaceConfig.LogDeprecatedConfig(ctx)

g := GeneratorConfig{
Boilerplate: m.boilerplate,