Skip to content

Commit

Permalink
fix(flag): skip hidden flags for --generate-default-config command (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
DmitriyLewen authored Dec 5, 2024
1 parent 9d9f80d commit 5e68bdc
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
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
}

0 comments on commit 5e68bdc

Please sign in to comment.