-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
options.go
836 lines (731 loc) · 20.9 KB
/
options.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
package flag
import (
"context"
"fmt"
"io"
"os"
"slices"
"strings"
"sync"
"time"
"github.com/samber/lo"
"github.com/spf13/cast"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"golang.org/x/xerrors"
"github.com/aquasecurity/trivy/pkg/cache"
"github.com/aquasecurity/trivy/pkg/fanal/analyzer"
ftypes "github.com/aquasecurity/trivy/pkg/fanal/types"
"github.com/aquasecurity/trivy/pkg/log"
"github.com/aquasecurity/trivy/pkg/plugin"
"github.com/aquasecurity/trivy/pkg/result"
"github.com/aquasecurity/trivy/pkg/types"
"github.com/aquasecurity/trivy/pkg/version/app"
)
type FlagType interface {
int | string | []string | bool | time.Duration | float64
}
type Flag[T FlagType] struct {
// Name is for CLI flag and environment variable.
// If this field is empty, it will be available only in config file.
Name string
// ConfigName is a key in config file. It is also used as a key of viper.
ConfigName string
// Shorthand is a shorthand letter.
Shorthand string
// Default is the default value. It should be defined when the value is different from the zero value.
Default T
// Values is a list of allowed values.
// It currently supports string flags and string slice flags only.
Values []string
// ValueNormalize is a function to normalize the value.
// It can be used for aliases, etc.
ValueNormalize func(T) T
// Usage explains how to use the flag.
Usage string
// Persistent represents if the flag is persistent
Persistent bool
// Deprecated represents if the flag is deprecated
Deprecated string
// Removed represents if the flag is removed and no longer works
Removed string
// Aliases represents aliases
Aliases []Alias
// value is the value passed through CLI flag, env, or config file.
// It is populated after flag.Parse() is called.
value T
}
type Alias struct {
Name string
ConfigName string
Deprecated bool
}
func (f *Flag[T]) Clone() *Flag[T] {
var t T
ff := *f
ff.value = t
fff := &ff
return fff
}
func (f *Flag[T]) Parse() error {
if f == nil {
return nil
}
v := f.parse()
if v == nil {
f.value = lo.Empty[T]()
return nil
}
value, ok := f.cast(v).(T)
if !ok {
return xerrors.Errorf("failed to parse flag %s", f.Name)
}
if f.ValueNormalize != nil {
value = f.ValueNormalize(value)
}
if f.isSet() && !f.allowedValue(value) {
return xerrors.Errorf(`invalid argument "%s" for "--%s" flag: must be one of %q`, value, f.Name, f.Values)
}
if f.Deprecated != "" && f.isSet() {
log.Warnf(`"--%s" is deprecated. %s`, f.Name, f.Deprecated)
}
if f.Removed != "" && f.isSet() {
log.Errorf(`"--%s" was removed. %s`, f.Name, f.Removed)
return xerrors.Errorf(`removed flag ("--%s")`, f.Name)
}
f.value = value
return nil
}
func (f *Flag[T]) parse() any {
// First, looks for aliases in config file (trivy.yaml).
// Note that viper.RegisterAlias cannot be used for this purpose.
var v any
for _, alias := range f.Aliases {
if alias.ConfigName == "" {
continue
}
v = viper.Get(alias.ConfigName)
if v != nil {
log.Warnf("'%s' in config file is deprecated. Use '%s' instead.", alias.ConfigName, f.ConfigName)
return v
}
}
return viper.Get(f.ConfigName)
}
// cast converts the value to the type of the flag.
func (f *Flag[T]) cast(val any) any {
switch any(f.Default).(type) {
case bool:
return cast.ToBool(val)
case string:
return cast.ToString(val)
case int:
return cast.ToInt(val)
case float64, float32:
return cast.ToFloat64(val)
case time.Duration:
return cast.ToDuration(val)
case []string:
if s, ok := val.(string); ok && strings.Contains(s, ",") {
// Split environmental variables by comma as it is not done by viper.
// cf. https://github.com/spf13/viper/issues/380
// It is split by spaces only.
// https://github.com/spf13/cast/blob/48ddde5701366ade1d3aba346e09bb58430d37c6/caste.go#L1296-L1297
val = strings.Split(s, ",")
}
return cast.ToStringSlice(val)
}
return val
}
func (f *Flag[T]) isSet() bool {
configNames := lo.FilterMap(f.Aliases, func(alias Alias, _ int) (string, bool) {
return alias.ConfigName, alias.ConfigName != ""
})
configNames = append(configNames, f.ConfigName)
return lo.SomeBy(configNames, viper.IsSet)
}
func (f *Flag[T]) allowedValue(v any) bool {
if len(f.Values) == 0 {
return true
}
switch value := v.(type) {
case string:
return slices.Contains(f.Values, value)
case []string:
for _, v := range value {
if !slices.Contains(f.Values, v) {
return false
}
}
}
return true
}
func (f *Flag[T]) GetName() string {
return f.Name
}
func (f *Flag[T]) GetConfigName() string {
return f.ConfigName
}
func (f *Flag[T]) GetDefaultValue() any {
return f.Default
}
func (f *Flag[T]) GetAliases() []Alias {
return f.Aliases
}
func (f *Flag[T]) Value() (t T) {
if f == nil {
return t
}
return f.value
}
func (f *Flag[T]) Add(cmd *cobra.Command) {
if f == nil || f.Name == "" {
return
}
var flags *pflag.FlagSet
if f.Persistent {
flags = cmd.PersistentFlags()
} else {
flags = cmd.Flags()
}
switch v := any(f.Default).(type) {
case int:
flags.IntP(f.Name, f.Shorthand, v, f.Usage)
case string:
usage := f.Usage
if len(f.Values) > 0 {
usage += fmt.Sprintf(" (%s)", strings.Join(f.Values, ","))
}
flags.StringP(f.Name, f.Shorthand, v, usage)
case []string:
usage := f.Usage
if len(f.Values) > 0 {
usage += fmt.Sprintf(" (%s)", strings.Join(f.Values, ","))
}
flags.StringSliceP(f.Name, f.Shorthand, v, usage)
case bool:
flags.BoolP(f.Name, f.Shorthand, v, f.Usage)
case time.Duration:
flags.DurationP(f.Name, f.Shorthand, v, f.Usage)
case float64:
flags.Float64P(f.Name, f.Shorthand, v, f.Usage)
}
if f.Deprecated != "" || f.Removed != "" {
_ = flags.MarkHidden(f.Name)
}
}
func (f *Flag[T]) Bind(cmd *cobra.Command) error {
if f == nil {
return nil
} else if f.Name == "" {
// This flag is available only in trivy.yaml
viper.SetDefault(f.ConfigName, f.Default)
return nil
}
// Bind CLI flags
flag := cmd.Flags().Lookup(f.Name)
if f == nil {
// Lookup local persistent flags
flag = cmd.PersistentFlags().Lookup(f.Name)
}
if err := viper.BindPFlag(f.ConfigName, flag); err != nil {
return xerrors.Errorf("bind flag error: %w", err)
}
// Bind environmental variable
if err := f.BindEnv(); err != nil {
return err
}
return nil
}
func (f *Flag[T]) BindEnv() error {
// We don't use viper.AutomaticEnv, so we need to add a prefix manually here.
envName := strings.ToUpper("trivy_" + strings.ReplaceAll(f.Name, "-", "_"))
if err := viper.BindEnv(f.ConfigName, envName); err != nil {
return xerrors.Errorf("bind env error: %w", err)
}
// Bind env aliases
for _, alias := range f.Aliases {
envAlias := strings.ToUpper("trivy_" + strings.ReplaceAll(alias.Name, "-", "_"))
if err := viper.BindEnv(f.ConfigName, envAlias); err != nil {
return xerrors.Errorf("bind env error: %w", err)
}
if alias.Deprecated {
if _, ok := os.LookupEnv(envAlias); ok {
log.Warnf("'%s' is deprecated. Use '%s' instead.", envAlias, envName)
}
}
}
return nil
}
type FlagGroup interface {
Name() string
Flags() []Flagger
}
type Flagger interface {
GetName() string
GetConfigName() string
GetDefaultValue() any
GetAliases() []Alias
Parse() error
Add(cmd *cobra.Command)
Bind(cmd *cobra.Command) error
}
type Flags struct {
GlobalFlagGroup *GlobalFlagGroup
AWSFlagGroup *AWSFlagGroup
CacheFlagGroup *CacheFlagGroup
CleanFlagGroup *CleanFlagGroup
DBFlagGroup *DBFlagGroup
ImageFlagGroup *ImageFlagGroup
K8sFlagGroup *K8sFlagGroup
LicenseFlagGroup *LicenseFlagGroup
MisconfFlagGroup *MisconfFlagGroup
ModuleFlagGroup *ModuleFlagGroup
PackageFlagGroup *PackageFlagGroup
RemoteFlagGroup *RemoteFlagGroup
RegistryFlagGroup *RegistryFlagGroup
RegoFlagGroup *RegoFlagGroup
RepoFlagGroup *RepoFlagGroup
ReportFlagGroup *ReportFlagGroup
ScanFlagGroup *ScanFlagGroup
SecretFlagGroup *SecretFlagGroup
VulnerabilityFlagGroup *VulnerabilityFlagGroup
}
// Options holds all the runtime configuration
type Options struct {
GlobalOptions
AWSOptions
CacheOptions
CleanOptions
DBOptions
ImageOptions
K8sOptions
LicenseOptions
MisconfOptions
ModuleOptions
PackageOptions
RegistryOptions
RegoOptions
RemoteOptions
RepoOptions
ReportOptions
ScanOptions
SecretOptions
VulnerabilityOptions
// Trivy's version, not populated via CLI flags
AppVersion string
// We don't want to allow disabled analyzers to be passed by users, but it is necessary for internal use.
DisabledAnalyzers []analyzer.Type
// outputWriter is not initialized via the CLI.
// It is mainly used for testing purposes or by tools that use Trivy as a library.
outputWriter io.Writer
}
// Align takes consistency of options
func (o *Options) Align(f *Flags) error {
if f.ScanFlagGroup != nil && f.ScanFlagGroup.Scanners != nil {
o.enableSBOM()
}
if f.PackageFlagGroup != nil && f.PackageFlagGroup.PkgRelationships != nil &&
slices.Compare(o.PkgRelationships, ftypes.Relationships) != 0 &&
(o.DependencyTree || slices.Contains(types.SupportedSBOMFormats, o.Format) || len(o.VEXSources) != 0) {
return xerrors.Errorf("'--pkg-relationships' cannot be used with '--dependency-tree', '--vex' or SBOM formats")
}
if o.Compliance.Spec.ID != "" {
if viper.IsSet(ScannersFlag.ConfigName) {
log.Info(`The option to change scanners is disabled for scanning with the "--compliance" flag. Default scanners used.`)
}
if viper.IsSet(ImageConfigScannersFlag.ConfigName) {
log.Info(`The option to change image config scanners is disabled for scanning with the "--compliance" flag. Default image config scanners used.`)
}
// set scanners types by spec
scanners, err := o.Compliance.Scanners()
if err != nil {
return xerrors.Errorf("scanner error: %w", err)
}
o.Scanners = scanners
o.ImageConfigScanners = nil
// TODO: define image-config-scanners in the spec
if o.Compliance.Spec.ID == types.ComplianceDockerCIS160 {
o.Scanners = types.Scanners{types.VulnerabilityScanner}
o.ImageConfigScanners = types.Scanners{
types.MisconfigScanner,
types.SecretScanner,
}
}
}
return nil
}
func (o *Options) enableSBOM() {
// Always need packages when the vulnerability scanner is enabled
if o.Scanners.Enabled(types.VulnerabilityScanner) {
o.Scanners.Enable(types.SBOMScanner)
}
// Enable the SBOM scanner when a list of packages is necessary.
if o.ListAllPkgs || slices.Contains(types.SupportedSBOMFormats, o.Format) {
o.Scanners.Enable(types.SBOMScanner)
}
if o.Format == types.FormatCycloneDX || o.Format == types.FormatSPDX || o.Format == types.FormatSPDXJSON {
// Vulnerability scanning is disabled by default for CycloneDX.
if !viper.IsSet(ScannersFlag.ConfigName) {
log.Info(fmt.Sprintf(`"--format %[1]s" disables security scanning. Specify "--scanners vuln" explicitly if you want to include vulnerabilities in the "%[1]s" report.`, o.Format))
o.Scanners = nil
}
o.Scanners.Enable(types.SBOMScanner)
}
}
// RegistryOpts returns options for OCI registries
func (o *Options) RegistryOpts() ftypes.RegistryOptions {
return ftypes.RegistryOptions{
Credentials: o.Credentials,
RegistryToken: o.RegistryToken,
Insecure: o.Insecure,
Platform: o.Platform,
AWSRegion: o.AWSOptions.Region,
}
}
// FilterOpts returns options for filtering
func (o *Options) FilterOpts() result.FilterOptions {
return result.FilterOptions{
Severities: o.Severities,
IgnoreStatuses: o.IgnoreStatuses,
IncludeNonFailures: o.IncludeNonFailures,
IgnoreFile: o.IgnoreFile,
PolicyFile: o.IgnorePolicy,
IgnoreLicenses: o.IgnoredLicenses,
CacheDir: o.CacheDir,
VEXSources: o.VEXSources,
}
}
// CacheOpts returns options for scan cache
func (o *Options) CacheOpts() cache.Options {
return cache.Options{
Backend: o.CacheBackend,
CacheDir: o.CacheDir,
RedisCACert: o.RedisCACert,
RedisCert: o.RedisCert,
RedisKey: o.RedisKey,
RedisTLS: o.RedisTLS,
TTL: o.CacheTTL,
}
}
// RemoteCacheOpts returns options for remote scan cache
func (o *Options) RemoteCacheOpts() cache.RemoteOptions {
return cache.RemoteOptions{
ServerAddr: o.ServerAddr,
CustomHeaders: o.CustomHeaders,
Insecure: o.Insecure,
}
}
// SetOutputWriter sets an output writer.
func (o *Options) SetOutputWriter(w io.Writer) {
o.outputWriter = w
}
// OutputWriter returns an output writer.
// If the output file is not specified, it returns os.Stdout.
func (o *Options) OutputWriter(ctx context.Context) (io.Writer, func() error, error) {
cleanup := func() error { return nil }
switch {
case o.outputWriter != nil:
return o.outputWriter, cleanup, nil
case o.Output == "":
return os.Stdout, cleanup, nil
case strings.HasPrefix(o.Output, "plugin="):
return o.outputPluginWriter(ctx)
}
f, err := os.Create(o.Output)
if err != nil {
return nil, nil, xerrors.Errorf("failed to create output file: %w", err)
}
return f, f.Close, nil
}
func (o *Options) outputPluginWriter(ctx context.Context) (io.Writer, func() error, error) {
pluginName := strings.TrimPrefix(o.Output, "plugin=")
pr, pw := io.Pipe()
wait, err := plugin.Start(ctx, pluginName, plugin.Options{
Args: o.OutputPluginArgs,
Stdin: pr,
})
if err != nil {
return nil, nil, xerrors.Errorf("plugin start: %w", err)
}
cleanup := func() error {
if err = pw.Close(); err != nil {
return xerrors.Errorf("failed to close pipe: %w", err)
}
if err = wait(); err != nil {
return xerrors.Errorf("plugin error: %w", err)
}
return nil
}
return pw, cleanup, nil
}
// groups returns all the flag groups other than global flags
func (f *Flags) groups() []FlagGroup {
var groups []FlagGroup
// This order affects the usage message, so they are sorted by frequency of use.
if f.ScanFlagGroup != nil {
groups = append(groups, f.ScanFlagGroup)
}
if f.ReportFlagGroup != nil {
groups = append(groups, f.ReportFlagGroup)
}
if f.CacheFlagGroup != nil {
groups = append(groups, f.CacheFlagGroup)
}
if f.CleanFlagGroup != nil {
groups = append(groups, f.CleanFlagGroup)
}
if f.DBFlagGroup != nil {
groups = append(groups, f.DBFlagGroup)
}
if f.RegistryFlagGroup != nil {
groups = append(groups, f.RegistryFlagGroup)
}
if f.ImageFlagGroup != nil {
groups = append(groups, f.ImageFlagGroup)
}
if f.VulnerabilityFlagGroup != nil {
groups = append(groups, f.VulnerabilityFlagGroup)
}
if f.MisconfFlagGroup != nil {
groups = append(groups, f.MisconfFlagGroup)
}
if f.ModuleFlagGroup != nil {
groups = append(groups, f.ModuleFlagGroup)
}
if f.SecretFlagGroup != nil {
groups = append(groups, f.SecretFlagGroup)
}
if f.LicenseFlagGroup != nil {
groups = append(groups, f.LicenseFlagGroup)
}
if f.RegoFlagGroup != nil {
groups = append(groups, f.RegoFlagGroup)
}
if f.AWSFlagGroup != nil {
groups = append(groups, f.AWSFlagGroup)
}
if f.K8sFlagGroup != nil {
groups = append(groups, f.K8sFlagGroup)
}
if f.PackageFlagGroup != nil {
groups = append(groups, f.PackageFlagGroup)
}
if f.RemoteFlagGroup != nil {
groups = append(groups, f.RemoteFlagGroup)
}
if f.RepoFlagGroup != nil {
groups = append(groups, f.RepoFlagGroup)
}
return groups
}
func (f *Flags) AddFlags(cmd *cobra.Command) {
aliases := make(flagAliases)
for _, group := range f.groups() {
for _, flag := range group.Flags() {
if lo.IsNil(flag) || flag.GetName() == "" {
continue
}
// Register the CLI flag
flag.Add(cmd)
// Register flag aliases
aliases.Add(flag)
}
}
cmd.Flags().SetNormalizeFunc(aliases.NormalizeFunc())
}
func (f *Flags) Usages(cmd *cobra.Command) string {
var usages string
for _, group := range f.groups() {
flags := pflag.NewFlagSet(cmd.Name(), pflag.ContinueOnError)
lflags := cmd.LocalFlags()
for _, flag := range group.Flags() {
if lo.IsNil(flag) || flag.GetName() == "" {
continue
}
flags.AddFlag(lflags.Lookup(flag.GetName()))
}
if !flags.HasAvailableFlags() {
continue
}
usages += fmt.Sprintf("%s Flags\n", group.Name())
usages += flags.FlagUsages() + "\n"
}
return strings.TrimSpace(usages)
}
func (f *Flags) Bind(cmd *cobra.Command) error {
for _, group := range f.groups() {
if group == nil {
continue
}
for _, flag := range group.Flags() {
if err := flag.Bind(cmd); err != nil {
return xerrors.Errorf("flag groups: %w", err)
}
}
}
return nil
}
// nolint: gocyclo
func (f *Flags) ToOptions(args []string) (Options, error) {
var err error
opts := Options{
AppVersion: app.Version(),
}
if f.GlobalFlagGroup != nil {
opts.GlobalOptions, err = f.GlobalFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("global flag error: %w", err)
}
}
if f.AWSFlagGroup != nil {
opts.AWSOptions, err = f.AWSFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("aws flag error: %w", err)
}
}
if f.CacheFlagGroup != nil {
opts.CacheOptions, err = f.CacheFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("cache flag error: %w", err)
}
}
if f.CleanFlagGroup != nil {
opts.CleanOptions, err = f.CleanFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("clean flag error: %w", err)
}
}
if f.DBFlagGroup != nil {
opts.DBOptions, err = f.DBFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("db flag error: %w", err)
}
}
if f.ImageFlagGroup != nil {
opts.ImageOptions, err = f.ImageFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("image flag error: %w", err)
}
}
if f.K8sFlagGroup != nil {
opts.K8sOptions, err = f.K8sFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("k8s flag error: %w", err)
}
}
if f.LicenseFlagGroup != nil {
opts.LicenseOptions, err = f.LicenseFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("license flag error: %w", err)
}
}
if f.MisconfFlagGroup != nil {
opts.MisconfOptions, err = f.MisconfFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("misconfiguration flag error: %w", err)
}
}
if f.ModuleFlagGroup != nil {
opts.ModuleOptions, err = f.ModuleFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("module flag error: %w", err)
}
}
if f.PackageFlagGroup != nil {
opts.PackageOptions, err = f.PackageFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("package flag error: %w", err)
}
}
if f.RegoFlagGroup != nil {
opts.RegoOptions, err = f.RegoFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("rego flag error: %w", err)
}
}
if f.RemoteFlagGroup != nil {
opts.RemoteOptions, err = f.RemoteFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("remote flag error: %w", err)
}
}
if f.RegistryFlagGroup != nil {
opts.RegistryOptions, err = f.RegistryFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("registry flag error: %w", err)
}
}
if f.RepoFlagGroup != nil {
opts.RepoOptions, err = f.RepoFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("rego flag error: %w", err)
}
}
if f.ReportFlagGroup != nil {
opts.ReportOptions, err = f.ReportFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("report flag error: %w", err)
}
}
if f.ScanFlagGroup != nil {
opts.ScanOptions, err = f.ScanFlagGroup.ToOptions(args)
if err != nil {
return Options{}, xerrors.Errorf("scan flag error: %w", err)
}
}
if f.SecretFlagGroup != nil {
opts.SecretOptions, err = f.SecretFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("secret flag error: %w", err)
}
}
if f.VulnerabilityFlagGroup != nil {
opts.VulnerabilityOptions, err = f.VulnerabilityFlagGroup.ToOptions()
if err != nil {
return Options{}, xerrors.Errorf("vulnerability flag error: %w", err)
}
}
if err := opts.Align(f); err != nil {
return Options{}, xerrors.Errorf("align options error: %w", err)
}
return opts, nil
}
func parseFlags(fg FlagGroup) error {
for _, flag := range fg.Flags() {
if err := flag.Parse(); err != nil {
return xerrors.Errorf("unable to parse flag: %w", err)
}
}
return nil
}
type flagAlias struct {
formalName string
deprecated bool
once sync.Once
}
// flagAliases have aliases for CLI flags
type flagAliases map[string]*flagAlias
func (a flagAliases) Add(flag Flagger) {
for _, alias := range flag.GetAliases() {
a[alias.Name] = &flagAlias{
formalName: flag.GetName(),
deprecated: alias.Deprecated,
}
}
}
func (a flagAliases) NormalizeFunc() func(*pflag.FlagSet, string) pflag.NormalizedName {
return func(_ *pflag.FlagSet, name string) pflag.NormalizedName {
if alias, ok := a[name]; ok {
if alias.deprecated {
// NormalizeFunc is called several times
alias.once.Do(func() {
log.Warnf("'--%s' is deprecated. Use '--%s' instead.", name, alias.formalName)
})
}
name = alias.formalName
}
return pflag.NormalizedName(name)
}
}