Skip to content

Commit 5e68bdc

Browse files
authored
fix(flag): skip hidden flags for --generate-default-config command (#8046)
1 parent 9d9f80d commit 5e68bdc

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

pkg/commands/artifact/run.go

+16-1
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,22 @@ func Run(ctx context.Context, opts flag.Options, targetKind TargetKind) (err err
356356

357357
if opts.GenerateDefaultConfig {
358358
log.Info("Writing the default config to trivy-default.yaml...")
359-
return viper.SafeWriteConfigAs("trivy-default.yaml")
359+
360+
hiddenFlags := flag.HiddenFlags()
361+
// Viper does not have the ability to remove flags.
362+
// So we only save the necessary flags and set these flags after viper.Reset
363+
v := viper.New()
364+
for _, k := range viper.AllKeys() {
365+
// Skip the `GenerateDefaultConfigFlag` flags to avoid errors with default config file.
366+
// Users often use "normal" formats instead of compliance. So we'll skip ComplianceFlag
367+
// Also don't keep removed or deprecated flags to avoid confusing users.
368+
if k == flag.GenerateDefaultConfigFlag.ConfigName || k == flag.ComplianceFlag.ConfigName || slices.Contains(hiddenFlags, k) {
369+
continue
370+
}
371+
v.Set(k, viper.Get(k))
372+
}
373+
374+
return v.SafeWriteConfigAs("trivy-default.yaml")
360375
}
361376

362377
r, err := NewRunner(ctx, opts)

pkg/flag/options.go

+35
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"fmt"
66
"io"
77
"os"
8+
"reflect"
89
"slices"
910
"strings"
1011
"sync"
@@ -856,3 +857,37 @@ func (a flagAliases) NormalizeFunc() func(*pflag.FlagSet, string) pflag.Normaliz
856857
return pflag.NormalizedName(name)
857858
}
858859
}
860+
861+
func HiddenFlags() []string {
862+
var allFlagGroups = []FlagGroup{
863+
NewGlobalFlagGroup(),
864+
NewCacheFlagGroup(),
865+
NewCleanFlagGroup(),
866+
NewClientFlags(),
867+
NewDBFlagGroup(),
868+
NewImageFlagGroup(),
869+
NewK8sFlagGroup(),
870+
NewLicenseFlagGroup(),
871+
NewMisconfFlagGroup(),
872+
NewModuleFlagGroup(),
873+
NewPackageFlagGroup(),
874+
NewRegistryFlagGroup(),
875+
NewRegoFlagGroup(),
876+
NewReportFlagGroup(),
877+
NewRepoFlagGroup(),
878+
NewScanFlagGroup(),
879+
NewSecretFlagGroup(),
880+
NewServerFlags(),
881+
NewVulnerabilityFlagGroup(),
882+
}
883+
884+
var hiddenFlags []string
885+
for _, flagGroup := range allFlagGroups {
886+
for _, flag := range flagGroup.Flags() {
887+
if !reflect.ValueOf(flag).IsNil() && flag.Hidden() {
888+
hiddenFlags = append(hiddenFlags, flag.GetConfigName())
889+
}
890+
}
891+
}
892+
return hiddenFlags
893+
}

0 commit comments

Comments
 (0)