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

fix(flag): skip hidden flags for --generate-default-config command #8046

Merged
merged 5 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
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
17 changes: 16 additions & 1 deletion pkg/commands/artifact/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,22 @@ func Run(ctx context.Context, opts flag.Options, targetKind TargetKind) (err err

if opts.GenerateDefaultConfig {
log.Info("Writing the default config to trivy-default.yaml...")
return viper.SafeWriteConfigAs("trivy-default.yaml")

hiddenFlags := flag.HiddenFlags()
// Viper does not have the ability to remove flags.
// So we only save the necessary flags and set these flags after viper.Reset
v := viper.New()
for _, k := range viper.AllKeys() {
// Skip the `GenerateDefaultConfigFlag` flags to avoid errors with default config file.
// Users often use "normal" formats instead of compliance. So we'll skip ComplianceFlag
// Also don't keep removed or deprecated flags to avoid confusing users.
if k == flag.GenerateDefaultConfigFlag.ConfigName || k == flag.ComplianceFlag.ConfigName || slices.Contains(hiddenFlags, k) {
continue
}
v.Set(k, viper.Get(k))
}

return v.SafeWriteConfigAs("trivy-default.yaml")
}

r, err := NewRunner(ctx, opts)
Expand Down
35 changes: 35 additions & 0 deletions pkg/flag/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"os"
"reflect"
"slices"
"strings"
"sync"
Expand Down Expand Up @@ -856,3 +857,37 @@ func (a flagAliases) NormalizeFunc() func(*pflag.FlagSet, string) pflag.Normaliz
return pflag.NormalizedName(name)
}
}

func HiddenFlags() []string {
var allFlagGroups = []FlagGroup{
NewGlobalFlagGroup(),
NewCacheFlagGroup(),
NewCleanFlagGroup(),
NewClientFlags(),
NewDBFlagGroup(),
NewImageFlagGroup(),
NewK8sFlagGroup(),
NewLicenseFlagGroup(),
NewMisconfFlagGroup(),
NewModuleFlagGroup(),
NewPackageFlagGroup(),
NewRegistryFlagGroup(),
NewRegoFlagGroup(),
NewReportFlagGroup(),
NewRepoFlagGroup(),
NewScanFlagGroup(),
NewSecretFlagGroup(),
NewServerFlags(),
NewVulnerabilityFlagGroup(),
}

var hiddenFlags []string
for _, flagGroup := range allFlagGroups {
for _, flag := range flagGroup.Flags() {
if !reflect.ValueOf(flag).IsNil() && flag.Hidden() {
hiddenFlags = append(hiddenFlags, flag.GetConfigName())
}
}
}
return hiddenFlags
}
Loading