Debian Codegraph @

lintcmd/cmd.go

raw
1 // Package lintcmd implements the frontend of an analysis runner.
2 // It serves as the entry-point for the staticcheck command, and can also be used to implement custom linters that behave like staticcheck.
3 package lintcmd
4
5 import (
6 "bufio"
7 "encoding/gob"
8 "flag"
9 "fmt"
10 "go/token"
11 stdversion "go/version"
12 "io"
13 "log"
14 "maps"
15 "os"
16 "path/filepath"
17 "reflect"
18 "runtime"
19 "runtime/pprof"
20 "runtime/trace"
21 "slices"
22 "sort"
23 "strings"
24 "sync"
25 "time"
26
27 "honnef.co/go/tools/analysis/lint"
28 "honnef.co/go/tools/config"
29 "honnef.co/go/tools/go/loader"
30 "honnef.co/go/tools/lintcmd/version"
31
32 "golang.org/x/tools/go/analysis"
33 "golang.org/x/tools/go/buildutil"
34 )
35
36 type buildConfig struct {
37 Name string
38 Envs []string
39 Flags []string
40 }
41
42 // Command represents a linter command line tool.
43 type Command struct {
44 name string
45 analyzers map[string]*lint.Analyzer
46 version string
47 machineVersion string
48
49 flags struct {
50 fs *flag.FlagSet
51
52 tags string
53 tests bool
54 showIgnored bool
55 formatter string
56
57 // mutually exclusive mode flags
58 explain string
59 printVersion bool
60 listChecks bool
61 merge bool
62
63 matrix bool
64
65 debugCpuprofile string
66 debugMemprofile string
67 debugVersion bool
68 debugNoCompileErrors bool
69 debugMeasureAnalyzers string
70 debugTrace string
71
72 checks list
73 fail list
74 goVersion versionFlag
75 }
76 }
77
78 // NewCommand returns a new Command.
79 func NewCommand(name string) *Command {
80 cmd := &Command{
81 name: name,
82 analyzers: map[string]*lint.Analyzer{},
83 version: "devel",
84 machineVersion: "devel",
85 }
86 cmd.initFlagSet(name)
87 return cmd
88 }
89
90 // SetVersion sets the command's version.
91 // It is divided into a human part and a machine part.
92 // For example, Staticcheck 2020.2.1 had the human version "2020.2.1" and the machine version "v0.1.1".
93 // If you only use Semver, you can set both parts to the same value.
94 //
95 // Calling this method is optional. Both versions default to "devel", and we'll attempt to deduce more version information from the Go module.
96 func (cmd *Command) SetVersion(human, machine string) {
97 cmd.version = human
98 cmd.machineVersion = machine
99 }
100
101 // FlagSet returns the command's flag set.
102 // This can be used to add additional command line arguments.
103 func (cmd *Command) FlagSet() *flag.FlagSet {
104 return cmd.flags.fs
105 }
106
107 // AddAnalyzers adds analyzers to the command.
108 // These are lint.Analyzer analyzers, which wrap analysis.Analyzer analyzers, bundling them with structured documentation.
109 //
110 // To add analysis.Analyzer analyzers without providing structured documentation, use AddBareAnalyzers.
111 func (cmd *Command) AddAnalyzers(as ...*lint.Analyzer) {
112 for _, a := range as {
113 cmd.analyzers[a.Analyzer.Name] = a
114 }
115 }
116
117 // AddBareAnalyzers adds bare analyzers to the command.
118 func (cmd *Command) AddBareAnalyzers(as ...*analysis.Analyzer) {
119 for _, a := range as {
120 var title, text string
121 if idx := strings.Index(a.Doc, "\n\n"); idx > -1 {
122 title = a.Doc[:idx]
123 text = a.Doc[idx+2:]
124 }
125
126 doc := &lint.RawDocumentation{
127 Title: title,
128 Text: text,
129 Severity: lint.SeverityWarning,
130 }
131
132 cmd.analyzers[a.Name] = &lint.Analyzer{
133 Doc: doc,
134 Analyzer: a,
135 }
136 }
137 }
138
139 func (cmd *Command) initFlagSet(name string) {
140 flags := flag.NewFlagSet("", flag.ExitOnError)
141 cmd.flags.fs = flags
142 flags.Usage = usage(name, flags)
143
144 flags.StringVar(&cmd.flags.tags, "tags", "", "List of `build tags`")
145 flags.BoolVar(&cmd.flags.tests, "tests", true, "Include tests")
146 flags.BoolVar(&cmd.flags.printVersion, "version", false, "Print version and exit")
147 flags.BoolVar(&cmd.flags.showIgnored, "show-ignored", false, "Don't filter ignored diagnostics")
148 flags.StringVar(&cmd.flags.formatter, "f", "text", "Output `format` (valid choices are 'stylish', 'text' and 'json')")
149 flags.StringVar(&cmd.flags.explain, "explain", "", "Print description of `check`")
150 flags.BoolVar(&cmd.flags.listChecks, "list-checks", false, "List all available checks")
151 flags.BoolVar(&cmd.flags.merge, "merge", false, "Merge results of multiple Staticcheck runs")
152 flags.BoolVar(&cmd.flags.matrix, "matrix", false, "Read a build config matrix from stdin")
153
154 flags.StringVar(&cmd.flags.debugCpuprofile, "debug.cpuprofile", "", "Write CPU profile to `file`")
155 flags.StringVar(&cmd.flags.debugMemprofile, "debug.memprofile", "", "Write memory profile to `file`")
156 flags.BoolVar(&cmd.flags.debugVersion, "debug.version", false, "Print detailed version information about this program")
157 flags.BoolVar(&cmd.flags.debugNoCompileErrors, "debug.no-compile-errors", false, "Don't print compile errors")
158 flags.StringVar(&cmd.flags.debugMeasureAnalyzers, "debug.measure-analyzers", "", "Write analysis measurements to `file`. `file` will be opened for appending if it already exists.")
159 flags.StringVar(&cmd.flags.debugTrace, "debug.trace", "", "Write trace to `file`")
160
161 cmd.flags.checks = list{"inherit"}
162 cmd.flags.fail = list{"all"}
163 cmd.flags.goVersion = versionFlag("module")
164 flags.Var(&cmd.flags.checks, "checks", "Comma-separated list of `checks` to enable.")
165 flags.Var(&cmd.flags.fail, "fail", "Comma-separated list of `checks` that can cause a non-zero exit status.")
166 flags.Var(&cmd.flags.goVersion, "go", "Target Go `version` in the format '1.x', or the literal 'module' to use the module's Go version")
167 }
168
169 type list []string
170
171 func (list *list) String() string {
172 return `"` + strings.Join(*list, ",") + `"`
173 }
174
175 func (list *list) Set(s string) error {
176 if s == "" {
177 *list = nil
178 return nil
179 }
180
181 elems := strings.Split(s, ",")
182 for i, elem := range elems {
183 elems[i] = strings.TrimSpace(elem)
184 }
185 *list = elems
186 return nil
187 }
188
189 type versionFlag string
190
191 func (v *versionFlag) String() string {
192 return fmt.Sprintf("%q", string(*v))
193 }
194
195 func (v *versionFlag) Set(s string) error {
196 if s == "module" {
197 *v = "module"
198 } else {
199 orig := s
200 if !strings.HasPrefix(s, "go") {
201 s = "go" + s
202 }
203 if stdversion.IsValid(s) {
204 *v = versionFlag(s)
205 } else {
206 return fmt.Errorf("%q is not a valid Go version", orig)
207 }
208 }
209 return nil
210 }
211
212 // ParseFlags parses command line flags.
213 // It must be called before calling Run.
214 // After calling ParseFlags, the values of flags can be accessed.
215 //
216 // Example:
217 //
218 // cmd.ParseFlags(os.Args[1:])
219 func (cmd *Command) ParseFlags(args []string) {
220 cmd.flags.fs.Parse(args)
221 }
222
223 // diagnosticDescriptor represents the uniquely identifying information of diagnostics.
224 type diagnosticDescriptor struct {
225 Position token.Position
226 End token.Position
227 Category string
228 Message string
229 }
230
231 func (diag diagnostic) descriptor() diagnosticDescriptor {
232 return diagnosticDescriptor{
233 Position: diag.Position,
234 End: diag.End,
235 Category: diag.Category,
236 Message: diag.Message,
237 }
238 }
239
240 type run struct {
241 checkedFiles map[string]struct{}
242 diagnostics map[diagnosticDescriptor]diagnostic
243 }
244
245 func runFromLintResult(res lintResult) run {
246 out := run{
247 checkedFiles: map[string]struct{}{},
248 diagnostics: map[diagnosticDescriptor]diagnostic{},
249 }
250
251 for _, cf := range res.CheckedFiles {
252 out.checkedFiles[cf] = struct{}{}
253 }
254 for _, diag := range res.Diagnostics {
255 out.diagnostics[diag.descriptor()] = diag
256 }
257 return out
258 }
259
260 func decodeGob(br io.ByteReader) ([]run, error) {
261 var runs []run
262 for {
263 var res lintResult
264 if err := gob.NewDecoder(br.(io.Reader)).Decode(&res); err != nil {
265 if err == io.EOF {
266 break
267 } else {
268 return nil, err
269 }
270 }
271 runs = append(runs, runFromLintResult(res))
272 }
273 return runs, nil
274 }
275
276 // Execute runs all registered analyzers and reports their findings.
277 // The status code returned can be used for os.Exit(cmd.Execute()).
278 func (cmd *Command) Execute() int {
279 // Set up profiling and tracing
280 if path := cmd.flags.debugCpuprofile; path != "" {
281 f, err := os.Create(path)
282 if err != nil {
283 log.Fatal(err)
284 }
285 pprof.StartCPUProfile(f)
286 }
287 if path := cmd.flags.debugTrace; path != "" {
288 f, err := os.Create(path)
289 if err != nil {
290 log.Fatal(err)
291 }
292 trace.Start(f)
293 }
294
295 // Update the default config's list of enabled checks
296 defaultChecks := []string{"all"}
297 for _, a := range cmd.analyzers {
298 if a.Doc.NonDefault {
299 defaultChecks = append(defaultChecks, "-"+a.Analyzer.Name)
300 }
301 }
302 config.DefaultConfig.Checks = defaultChecks
303
304 // Run the appropriate mode
305 var exit int
306 switch {
307 case cmd.flags.debugVersion:
308 exit = cmd.printDebugVersion()
309 case cmd.flags.listChecks:
310 exit = cmd.listChecks()
311 case cmd.flags.printVersion:
312 exit = cmd.printVersion()
313 case cmd.flags.explain != "":
314 exit = cmd.explain()
315 case cmd.flags.merge:
316 exit = cmd.merge()
317 default:
318 exit = cmd.lint()
319 }
320
321 // Stop profiling
322 if cmd.flags.debugCpuprofile != "" {
323 pprof.StopCPUProfile()
324 }
325 if path := cmd.flags.debugMemprofile; path != "" {
326 f, err := os.Create(path)
327 if err != nil {
328 panic(err)
329 }
330 runtime.GC()
331 pprof.WriteHeapProfile(f)
332 }
333 if cmd.flags.debugTrace != "" {
334 trace.Stop()
335 }
336
337 return exit
338 }
339
340 // Run runs all registered analyzers and reports their findings.
341 // It always calls os.Exit and does not return.
342 func (cmd *Command) Run() {
343 os.Exit(cmd.Execute())
344 }
345
346 func (cmd *Command) printDebugVersion() int {
347 version.Verbose(cmd.version, cmd.machineVersion)
348 return 0
349 }
350
351 func (cmd *Command) listChecks() int {
352 cs := slices.Collect(maps.Values(cmd.analyzers))
353 sort.Slice(cs, func(i, j int) bool {
354 return cs[i].Analyzer.Name < cs[j].Analyzer.Name
355 })
356 for _, c := range cs {
357 var title string
358 if c.Doc != nil {
359 title = c.Doc.Compile().Title
360 }
361 fmt.Printf("%s %s\n", c.Analyzer.Name, title)
362 }
363 return 0
364 }
365
366 func (cmd *Command) printVersion() int {
367 version.Print(cmd.version, cmd.machineVersion)
368 return 0
369 }
370
371 func (cmd *Command) explain() int {
372 explain := cmd.flags.explain
373 check, ok := cmd.analyzers[explain]
374 if !ok {
375 fmt.Fprintln(os.Stderr, "Couldn't find check", explain)
376 return 1
377 }
378 if check.Analyzer.Doc == "" {
379 fmt.Fprintln(os.Stderr, explain, "has no documentation")
380 return 1
381 }
382 fmt.Println(check.Doc.Compile())
383 fmt.Println("Online documentation\n https://staticcheck.dev/docs/checks#" + check.Analyzer.Name)
384 return 0
385 }
386
387 func (cmd *Command) merge() int {
388 var runs []run
389 if len(cmd.flags.fs.Args()) == 0 {
390 var err error
391 runs, err = decodeGob(bufio.NewReader(os.Stdin))
392 if err != nil {
393 fmt.Fprintln(os.Stderr, fmt.Errorf("couldn't parse stdin: %s", err))
394 return 1
395 }
396 } else {
397 for _, path := range cmd.flags.fs.Args() {
398 someRuns, err := func(path string) ([]run, error) {
399 f, err := os.Open(path)
400 if err != nil {
401 return nil, err
402 }
403 defer f.Close()
404 br := bufio.NewReader(f)
405 return decodeGob(br)
406 }(path)
407 if err != nil {
408 fmt.Fprintln(os.Stderr, fmt.Errorf("couldn't parse file %s: %s", path, err))
409 return 1
410 }
411 runs = append(runs, someRuns...)
412 }
413 }
414
415 relevantDiagnostics := mergeRuns(runs)
416 cs := slices.Collect(maps.Values(cmd.analyzers))
417 return cmd.printDiagnostics(cs, relevantDiagnostics)
418 }
419
420 func (cmd *Command) lint() int {
421 switch cmd.flags.formatter {
422 case "text", "stylish", "json", "sarif", "binary", "null":
423 default:
424 fmt.Fprintf(os.Stderr, "unsupported output format %q\n", cmd.flags.formatter)
425 return 2
426 }
427
428 var bconfs []buildConfig
429 if cmd.flags.matrix {
430 if cmd.flags.tags != "" {
431 fmt.Fprintln(os.Stderr, "cannot use -matrix and -tags together")
432 return 2
433 }
434
435 var err error
436 bconfs, err = parseBuildConfigs(os.Stdin)
437 if err != nil {
438 if perr, ok := err.(parseBuildConfigError); ok {
439 fmt.Fprintf(os.Stderr, "<stdin>:%d couldn't parse build matrix: %s\n", perr.line, perr.err)
440 } else {
441 fmt.Fprintln(os.Stderr, err)
442 }
443 return 2
444 }
445 } else {
446 bc := buildConfig{}
447 if cmd.flags.tags != "" {
448 // Validate that the tags argument is well-formed. go/packages
449 // doesn't detect malformed build flags and returns unhelpful
450 // errors.
451 tf := buildutil.TagsFlag{}
452 if err := tf.Set(cmd.flags.tags); err != nil {
453 fmt.Fprintln(os.Stderr, fmt.Errorf("invalid value %q for flag -tags: %s", cmd.flags.tags, err))
454 return 1
455 }
456
457 bc.Flags = []string{"-tags", cmd.flags.tags}
458 }
459 bconfs = append(bconfs, bc)
460 }
461
462 var measureAnalyzers func(analysis *analysis.Analyzer, pkg *loader.PackageSpec, d time.Duration)
463 if path := cmd.flags.debugMeasureAnalyzers; path != "" {
464 f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
465 if err != nil {
466 log.Fatal(err)
467 }
468
469 mu := &sync.Mutex{}
470 measureAnalyzers = func(analysis *analysis.Analyzer, pkg *loader.PackageSpec, d time.Duration) {
471 mu.Lock()
472 defer mu.Unlock()
473 // FIXME(dh): print pkg.ID
474 if _, err := fmt.Fprintf(f, "%s\t%s\t%d\n", analysis.Name, pkg, d.Nanoseconds()); err != nil {
475 log.Println("error writing analysis measurements:", err)
476 }
477 }
478 }
479
480 var runs []run
481 cs := slices.Collect(maps.Values(cmd.analyzers))
482 opts := options{
483 analyzers: cs,
484 patterns: cmd.flags.fs.Args(),
485 lintTests: cmd.flags.tests,
486 goVersion: string(cmd.flags.goVersion),
487 config: config.Config{
488 Checks: cmd.flags.checks,
489 },
490 printAnalyzerMeasurement: measureAnalyzers,
491 }
492 l, err := newLinter(opts)
493 if err != nil {
494 fmt.Fprintln(os.Stderr, err)
495 return 1
496 }
497 for _, bconf := range bconfs {
498 res, err := l.run(bconf)
499 if err != nil {
500 fmt.Fprintln(os.Stderr, err)
501 return 1
502 }
503
504 for _, w := range res.Warnings {
505 fmt.Fprintln(os.Stderr, "warning:", w)
506 }
507
508 cwd, err := os.Getwd()
509 if err != nil {
510 cwd = ""
511 }
512 relPath := func(s string) string {
513 if cwd == "" {
514 return filepath.ToSlash(s)
515 }
516 out, err := filepath.Rel(cwd, s)
517 if err != nil {
518 return filepath.ToSlash(s)
519 }
520 return filepath.ToSlash(out)
521 }
522
523 if cmd.flags.formatter == "binary" {
524 for i, s := range res.CheckedFiles {
525 res.CheckedFiles[i] = relPath(s)
526 }
527 for i := range res.Diagnostics {
528 // We turn all paths into relative, /-separated paths. This is to make -merge work correctly when
529 // merging runs from different OSs, with different absolute paths.
530 //
531 // We zero out Offset, because checkouts of code on different OSs may have different kinds of
532 // newlines and thus different offsets. We don't ever make use of the Offset, anyway. Line and
533 // column numbers are precomputed.
534
535 d := &res.Diagnostics[i]
536 d.Position.Filename = relPath(d.Position.Filename)
537 d.Position.Offset = 0
538 d.End.Filename = relPath(d.End.Filename)
539 d.End.Offset = 0
540 for j := range d.Related {
541 r := &d.Related[j]
542 r.Position.Filename = relPath(r.Position.Filename)
543 r.Position.Offset = 0
544 r.End.Filename = relPath(r.End.Filename)
545 r.End.Offset = 0
546 }
547 }
548 err := gob.NewEncoder(os.Stdout).Encode(res)
549 if err != nil {
550 fmt.Fprintf(os.Stderr, "failed writing output: %s\n", err)
551 return 2
552 }
553 } else {
554 runs = append(runs, runFromLintResult(res))
555 }
556 }
557
558 l.cache.Trim()
559
560 if cmd.flags.formatter != "binary" {
561 diags := mergeRuns(runs)
562 return cmd.printDiagnostics(cs, diags)
563 }
564 return 0
565 }
566
567 func mergeRuns(runs []run) []diagnostic {
568 var relevantDiagnostics []diagnostic
569 for _, r := range runs {
570 for _, diag := range r.diagnostics {
571 switch diag.MergeIf {
572 case lint.MergeIfAny:
573 relevantDiagnostics = append(relevantDiagnostics, diag)
574 case lint.MergeIfAll:
575 doPrint := true
576 for _, r := range runs {
577 if _, ok := r.checkedFiles[diag.Position.Filename]; ok {
578 if _, ok := r.diagnostics[diag.descriptor()]; !ok {
579 doPrint = false
580 }
581 }
582 }
583 if doPrint {
584 relevantDiagnostics = append(relevantDiagnostics, diag)
585 }
586 }
587 }
588 }
589 return relevantDiagnostics
590 }
591
592 // printDiagnostics prints the diagnostics and exits the process.
593 func (cmd *Command) printDiagnostics(cs []*lint.Analyzer, diagnostics []diagnostic) int {
594 if len(diagnostics) > 1 {
595 sort.Slice(diagnostics, func(i, j int) bool {
596 di := diagnostics[i]
597 dj := diagnostics[j]
598 pi := di.Position
599 pj := dj.Position
600
601 if pi.Filename != pj.Filename {
602 return pi.Filename < pj.Filename
603 }
604 if pi.Line != pj.Line {
605 return pi.Line < pj.Line
606 }
607 if pi.Column != pj.Column {
608 return pi.Column < pj.Column
609 }
610 if di.Message != dj.Message {
611 return di.Message < dj.Message
612 }
613 if di.BuildName != dj.BuildName {
614 return di.BuildName < dj.BuildName
615 }
616 return di.Category < dj.Category
617 })
618
619 filtered := []diagnostic{
620 diagnostics[0],
621 }
622 builds := []map[string]struct{}{
623 {diagnostics[0].BuildName: {}},
624 }
625 for _, diag := range diagnostics[1:] {
626 // We may encounter duplicate diagnostics because one file
627 // can be part of many packages, and because multiple
628 // build configurations may check the same files.
629 if !filtered[len(filtered)-1].equal(diag) {
630 if filtered[len(filtered)-1].descriptor() == diag.descriptor() {
631 // Diagnostics only differ in build name, track new name
632 builds[len(filtered)-1][diag.BuildName] = struct{}{}
633 } else {
634 filtered = append(filtered, diag)
635 builds = append(builds, map[string]struct{}{})
636 builds[len(filtered)-1][diag.BuildName] = struct{}{}
637 }
638 }
639 }
640
641 var names []string
642 for i := range filtered {
643 names = names[:0]
644 for k := range builds[i] {
645 names = append(names, k)
646 }
647 sort.Strings(names)
648 filtered[i].BuildName = strings.Join(names, ",")
649 }
650 diagnostics = filtered
651 }
652
653 var f formatter
654 switch cmd.flags.formatter {
655 case "text":
656 f = textFormatter{W: os.Stdout}
657 case "stylish":
658 f = &stylishFormatter{W: os.Stdout}
659 case "json":
660 f = jsonFormatter{W: os.Stdout}
661 case "sarif":
662 f = &sarifFormatter{
663 driverName: cmd.name,
664 driverVersion: cmd.version,
665 }
666 if cmd.name == "staticcheck" {
667 f.(*sarifFormatter).driverName = "Staticcheck"
668 f.(*sarifFormatter).driverWebsite = "https://staticcheck.dev"
669 }
670 case "binary":
671 fmt.Fprintln(os.Stderr, "'-f binary' not supported in this context")
672 return 2
673 case "null":
674 f = nullFormatter{}
675 default:
676 fmt.Fprintf(os.Stderr, "unsupported output format %q\n", cmd.flags.formatter)
677 return 2
678 }
679
680 fail := cmd.flags.fail
681 analyzerNames := make([]string, len(cs))
682 for i, a := range cs {
683 analyzerNames[i] = a.Analyzer.Name
684 }
685 shouldExit := filterAnalyzerNames(analyzerNames, fail)
686 shouldExit["staticcheck"] = true
687 shouldExit["compile"] = true
688 shouldExit["config"] = true
689
690 var (
691 numErrors int
692 numWarnings int
693 numIgnored int
694 )
695 notIgnored := make([]diagnostic, 0, len(diagnostics))
696 for _, diag := range diagnostics {
697 if diag.Category == "compile" && cmd.flags.debugNoCompileErrors {
698 continue
699 }
700 if diag.Severity == severityIgnored && !cmd.flags.showIgnored {
701 numIgnored++
702 continue
703 }
704 if shouldExit[diag.Category] {
705 numErrors++
706 } else {
707 diag.Severity = severityWarning
708 numWarnings++
709 }
710 notIgnored = append(notIgnored, diag)
711 }
712
713 f.Format(cs, notIgnored)
714 if f, ok := f.(statter); ok {
715 f.Stats(len(diagnostics), numErrors, numWarnings, numIgnored)
716 }
717
718 if numErrors > 0 {
719 if _, ok := f.(*sarifFormatter); ok {
720 // When emitting SARIF, finding errors is considered success.
721 return 0
722 } else {
723 return 1
724 }
725 }
726 return 0
727 }
728
729 func usage(name string, fs *flag.FlagSet) func() {
730 return func() {
731 fmt.Fprintf(os.Stderr, "Usage: %s [flags] [packages]\n", name)
732
733 fmt.Fprintln(os.Stderr)
734 fmt.Fprintln(os.Stderr, "Flags:")
735 printDefaults(fs)
736
737 fmt.Fprintln(os.Stderr)
738 fmt.Fprintln(os.Stderr, "For help about specifying packages, see 'go help packages'")
739 }
740 }
741
742 // isZeroValue determines whether the string represents the zero
743 // value for a flag.
744 //
745 // this function has been copied from the Go standard library's 'flag' package.
746 func isZeroValue(f *flag.Flag, value string) bool {
747 // Build a zero value of the flag's Value type, and see if the
748 // result of calling its String method equals the value passed in.
749 // This works unless the Value type is itself an interface type.
750 typ := reflect.TypeOf(f.Value)
751 var z reflect.Value
752 if typ.Kind() == reflect.Pointer {
753 z = reflect.New(typ.Elem())
754 } else {
755 z = reflect.Zero(typ)
756 }
757 return value == z.Interface().(flag.Value).String()
758 }
759
760 // this function has been copied from the Go standard library's 'flag' package and modified to skip debug flags.
761 func printDefaults(fs *flag.FlagSet) {
762 fs.VisitAll(func(f *flag.Flag) {
763 // Don't print debug flags
764 if strings.HasPrefix(f.Name, "debug.") {
765 return
766 }
767
768 var b strings.Builder
769 fmt.Fprintf(&b, " -%s", f.Name) // Two spaces before -; see next two comments.
770 name, usage := flag.UnquoteUsage(f)
771 if len(name) > 0 {
772 b.WriteString(" ")
773 b.WriteString(name)
774 }
775 // Boolean flags of one ASCII letter are so common we
776 // treat them specially, putting their usage on the same line.
777 if b.Len() <= 4 { // space, space, '-', 'x'.
778 b.WriteString("\t")
779 } else {
780 // Four spaces before the tab triggers good alignment
781 // for both 4- and 8-space tab stops.
782 b.WriteString("\n \t")
783 }
784 b.WriteString(strings.ReplaceAll(usage, "\n", "\n \t"))
785
786 if !isZeroValue(f, f.DefValue) {
787 if T := reflect.TypeOf(f.Value); T.Name() == "*stringValue" && T.PkgPath() == "flag" {
788 // put quotes on the value
789 fmt.Fprintf(&b, " (default %q)", f.DefValue)
790 } else {
791 fmt.Fprintf(&b, " (default %v)", f.DefValue)
792 }
793 }
794 fmt.Fprint(fs.Output(), b.String(), "\n")
795 })
796 }