|
6 | 6 | "fmt" |
7 | 7 | "io" |
8 | 8 | "os" |
| 9 | + "reflect" |
9 | 10 | "regexp" |
10 | 11 | "runtime" |
11 | 12 | "sort" |
@@ -277,7 +278,7 @@ func prepareFlags( |
277 | 278 | // flagDetails returns a string containing the flags metadata |
278 | 279 | func flagDetails(flag cli.DocGenerationFlag) string { |
279 | 280 | description := flag.GetUsage() |
280 | | - value := flag.GetValue() |
| 281 | + value := getFlagDefaultValue(flag) |
281 | 282 | if value != "" { |
282 | 283 | description += " (default: " + value + ")" |
283 | 284 | } |
@@ -404,7 +405,7 @@ func (tt tabularTemplate) PrepareFlags(flags []cli.Flag) []cliTabularFlagTemplat |
404 | 405 | Usage: tt.PrepareMultilineString(flag.GetUsage()), |
405 | 406 | EnvVars: flag.GetEnvVars(), |
406 | 407 | TakesValue: flag.TakesValue(), |
407 | | - Default: flag.GetValue(), |
| 408 | + Default: getFlagDefaultValue(flag), |
408 | 409 | } |
409 | 410 |
|
410 | 411 | if boolFlag, isBool := appFlag.(*cli.BoolFlag); isBool { |
@@ -554,3 +555,34 @@ func (tabularTemplate) Prettify(s string) string { |
554 | 555 |
|
555 | 556 | return s + "\n" // add an extra newline |
556 | 557 | } |
| 558 | + |
| 559 | +// getFlagDefaultValue returns the default value of a flag. Previously, the [cli.DocGenerationFlag] interface included |
| 560 | +// a GetValue string method, but it was removed in https://github.com/urfave/cli/pull/1988. |
| 561 | +// This function serves as a workaround, attempting to retrieve the value using the removed method; if that fails, it |
| 562 | +// tries to obtain it via reflection (the [cli.FlagBase] still has a Value field). |
| 563 | +func getFlagDefaultValue(f cli.DocGenerationFlag) string { |
| 564 | + if !f.TakesValue() { |
| 565 | + return "" |
| 566 | + } |
| 567 | + |
| 568 | + if v, ok := f.(interface{ GetValue() string }); ok { |
| 569 | + return v.GetValue() |
| 570 | + } |
| 571 | + |
| 572 | + var ref = reflect.ValueOf(f) |
| 573 | + if ref.Kind() != reflect.Ptr { |
| 574 | + return "" |
| 575 | + } else { |
| 576 | + ref = ref.Elem() |
| 577 | + } |
| 578 | + |
| 579 | + if ref.Kind() != reflect.Struct { |
| 580 | + return "" |
| 581 | + } |
| 582 | + |
| 583 | + if val := ref.FieldByName("Value"); val.IsValid() && val.Type().Kind() != reflect.Bool { |
| 584 | + return fmt.Sprintf("%v", val.Interface()) |
| 585 | + } |
| 586 | + |
| 587 | + return "" |
| 588 | +} |
0 commit comments