flag.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. package cli
  2. import (
  3. "flag"
  4. "fmt"
  5. "io/ioutil"
  6. "reflect"
  7. "runtime"
  8. "strconv"
  9. "strings"
  10. "syscall"
  11. "time"
  12. )
  13. const defaultPlaceholder = "value"
  14. // BashCompletionFlag enables bash-completion for all commands and subcommands
  15. var BashCompletionFlag Flag = BoolFlag{
  16. Name: "generate-bash-completion",
  17. Hidden: true,
  18. }
  19. // VersionFlag prints the version for the application
  20. var VersionFlag Flag = BoolFlag{
  21. Name: "version, v",
  22. Usage: "print the version",
  23. }
  24. // HelpFlag prints the help for all commands and subcommands
  25. // Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand
  26. // unless HideHelp is set to true)
  27. var HelpFlag Flag = BoolFlag{
  28. Name: "help, h",
  29. Usage: "show help",
  30. }
  31. // FlagStringer converts a flag definition to a string. This is used by help
  32. // to display a flag.
  33. var FlagStringer FlagStringFunc = stringifyFlag
  34. // FlagNamePrefixer converts a full flag name and its placeholder into the help
  35. // message flag prefix. This is used by the default FlagStringer.
  36. var FlagNamePrefixer FlagNamePrefixFunc = prefixedNames
  37. // FlagEnvHinter annotates flag help message with the environment variable
  38. // details. This is used by the default FlagStringer.
  39. var FlagEnvHinter FlagEnvHintFunc = withEnvHint
  40. // FlagFileHinter annotates flag help message with the environment variable
  41. // details. This is used by the default FlagStringer.
  42. var FlagFileHinter FlagFileHintFunc = withFileHint
  43. // FlagsByName is a slice of Flag.
  44. type FlagsByName []Flag
  45. func (f FlagsByName) Len() int {
  46. return len(f)
  47. }
  48. func (f FlagsByName) Less(i, j int) bool {
  49. return lexicographicLess(f[i].GetName(), f[j].GetName())
  50. }
  51. func (f FlagsByName) Swap(i, j int) {
  52. f[i], f[j] = f[j], f[i]
  53. }
  54. // Flag is a common interface related to parsing flags in cli.
  55. // For more advanced flag parsing techniques, it is recommended that
  56. // this interface be implemented.
  57. type Flag interface {
  58. fmt.Stringer
  59. // Apply Flag settings to the given flag set
  60. Apply(*flag.FlagSet)
  61. GetName() string
  62. }
  63. // errorableFlag is an interface that allows us to return errors during apply
  64. // it allows flags defined in this library to return errors in a fashion backwards compatible
  65. // TODO remove in v2 and modify the existing Flag interface to return errors
  66. type errorableFlag interface {
  67. Flag
  68. ApplyWithError(*flag.FlagSet) error
  69. }
  70. func flagSet(name string, flags []Flag) (*flag.FlagSet, error) {
  71. set := flag.NewFlagSet(name, flag.ContinueOnError)
  72. for _, f := range flags {
  73. //TODO remove in v2 when errorableFlag is removed
  74. if ef, ok := f.(errorableFlag); ok {
  75. if err := ef.ApplyWithError(set); err != nil {
  76. return nil, err
  77. }
  78. } else {
  79. f.Apply(set)
  80. }
  81. }
  82. return set, nil
  83. }
  84. func eachName(longName string, fn func(string)) {
  85. parts := strings.Split(longName, ",")
  86. for _, name := range parts {
  87. name = strings.Trim(name, " ")
  88. fn(name)
  89. }
  90. }
  91. // Generic is a generic parseable type identified by a specific flag
  92. type Generic interface {
  93. Set(value string) error
  94. String() string
  95. }
  96. // Apply takes the flagset and calls Set on the generic flag with the value
  97. // provided by the user for parsing by the flag
  98. // Ignores parsing errors
  99. func (f GenericFlag) Apply(set *flag.FlagSet) {
  100. f.ApplyWithError(set)
  101. }
  102. // ApplyWithError takes the flagset and calls Set on the generic flag with the value
  103. // provided by the user for parsing by the flag
  104. func (f GenericFlag) ApplyWithError(set *flag.FlagSet) error {
  105. val := f.Value
  106. if fileEnvVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  107. if err := val.Set(fileEnvVal); err != nil {
  108. return fmt.Errorf("could not parse %s as value for flag %s: %s", fileEnvVal, f.Name, err)
  109. }
  110. }
  111. eachName(f.Name, func(name string) {
  112. set.Var(f.Value, name, f.Usage)
  113. })
  114. return nil
  115. }
  116. // StringSlice is an opaque type for []string to satisfy flag.Value and flag.Getter
  117. type StringSlice []string
  118. // Set appends the string value to the list of values
  119. func (f *StringSlice) Set(value string) error {
  120. *f = append(*f, value)
  121. return nil
  122. }
  123. // String returns a readable representation of this value (for usage defaults)
  124. func (f *StringSlice) String() string {
  125. return fmt.Sprintf("%s", *f)
  126. }
  127. // Value returns the slice of strings set by this flag
  128. func (f *StringSlice) Value() []string {
  129. return *f
  130. }
  131. // Get returns the slice of strings set by this flag
  132. func (f *StringSlice) Get() interface{} {
  133. return *f
  134. }
  135. // Apply populates the flag given the flag set and environment
  136. // Ignores errors
  137. func (f StringSliceFlag) Apply(set *flag.FlagSet) {
  138. f.ApplyWithError(set)
  139. }
  140. // ApplyWithError populates the flag given the flag set and environment
  141. func (f StringSliceFlag) ApplyWithError(set *flag.FlagSet) error {
  142. if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  143. newVal := &StringSlice{}
  144. for _, s := range strings.Split(envVal, ",") {
  145. s = strings.TrimSpace(s)
  146. if err := newVal.Set(s); err != nil {
  147. return fmt.Errorf("could not parse %s as string value for flag %s: %s", envVal, f.Name, err)
  148. }
  149. }
  150. if f.Value == nil {
  151. f.Value = newVal
  152. } else {
  153. *f.Value = *newVal
  154. }
  155. }
  156. eachName(f.Name, func(name string) {
  157. if f.Value == nil {
  158. f.Value = &StringSlice{}
  159. }
  160. set.Var(f.Value, name, f.Usage)
  161. })
  162. return nil
  163. }
  164. // IntSlice is an opaque type for []int to satisfy flag.Value and flag.Getter
  165. type IntSlice []int
  166. // Set parses the value into an integer and appends it to the list of values
  167. func (f *IntSlice) Set(value string) error {
  168. tmp, err := strconv.Atoi(value)
  169. if err != nil {
  170. return err
  171. }
  172. *f = append(*f, tmp)
  173. return nil
  174. }
  175. // String returns a readable representation of this value (for usage defaults)
  176. func (f *IntSlice) String() string {
  177. return fmt.Sprintf("%#v", *f)
  178. }
  179. // Value returns the slice of ints set by this flag
  180. func (f *IntSlice) Value() []int {
  181. return *f
  182. }
  183. // Get returns the slice of ints set by this flag
  184. func (f *IntSlice) Get() interface{} {
  185. return *f
  186. }
  187. // Apply populates the flag given the flag set and environment
  188. // Ignores errors
  189. func (f IntSliceFlag) Apply(set *flag.FlagSet) {
  190. f.ApplyWithError(set)
  191. }
  192. // ApplyWithError populates the flag given the flag set and environment
  193. func (f IntSliceFlag) ApplyWithError(set *flag.FlagSet) error {
  194. if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  195. newVal := &IntSlice{}
  196. for _, s := range strings.Split(envVal, ",") {
  197. s = strings.TrimSpace(s)
  198. if err := newVal.Set(s); err != nil {
  199. return fmt.Errorf("could not parse %s as int slice value for flag %s: %s", envVal, f.Name, err)
  200. }
  201. }
  202. if f.Value == nil {
  203. f.Value = newVal
  204. } else {
  205. *f.Value = *newVal
  206. }
  207. }
  208. eachName(f.Name, func(name string) {
  209. if f.Value == nil {
  210. f.Value = &IntSlice{}
  211. }
  212. set.Var(f.Value, name, f.Usage)
  213. })
  214. return nil
  215. }
  216. // Int64Slice is an opaque type for []int to satisfy flag.Value and flag.Getter
  217. type Int64Slice []int64
  218. // Set parses the value into an integer and appends it to the list of values
  219. func (f *Int64Slice) Set(value string) error {
  220. tmp, err := strconv.ParseInt(value, 10, 64)
  221. if err != nil {
  222. return err
  223. }
  224. *f = append(*f, tmp)
  225. return nil
  226. }
  227. // String returns a readable representation of this value (for usage defaults)
  228. func (f *Int64Slice) String() string {
  229. return fmt.Sprintf("%#v", *f)
  230. }
  231. // Value returns the slice of ints set by this flag
  232. func (f *Int64Slice) Value() []int64 {
  233. return *f
  234. }
  235. // Get returns the slice of ints set by this flag
  236. func (f *Int64Slice) Get() interface{} {
  237. return *f
  238. }
  239. // Apply populates the flag given the flag set and environment
  240. // Ignores errors
  241. func (f Int64SliceFlag) Apply(set *flag.FlagSet) {
  242. f.ApplyWithError(set)
  243. }
  244. // ApplyWithError populates the flag given the flag set and environment
  245. func (f Int64SliceFlag) ApplyWithError(set *flag.FlagSet) error {
  246. if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  247. newVal := &Int64Slice{}
  248. for _, s := range strings.Split(envVal, ",") {
  249. s = strings.TrimSpace(s)
  250. if err := newVal.Set(s); err != nil {
  251. return fmt.Errorf("could not parse %s as int64 slice value for flag %s: %s", envVal, f.Name, err)
  252. }
  253. }
  254. if f.Value == nil {
  255. f.Value = newVal
  256. } else {
  257. *f.Value = *newVal
  258. }
  259. }
  260. eachName(f.Name, func(name string) {
  261. if f.Value == nil {
  262. f.Value = &Int64Slice{}
  263. }
  264. set.Var(f.Value, name, f.Usage)
  265. })
  266. return nil
  267. }
  268. // Apply populates the flag given the flag set and environment
  269. // Ignores errors
  270. func (f BoolFlag) Apply(set *flag.FlagSet) {
  271. f.ApplyWithError(set)
  272. }
  273. // ApplyWithError populates the flag given the flag set and environment
  274. func (f BoolFlag) ApplyWithError(set *flag.FlagSet) error {
  275. val := false
  276. if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  277. if envVal == "" {
  278. val = false
  279. } else {
  280. envValBool, err := strconv.ParseBool(envVal)
  281. if err != nil {
  282. return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err)
  283. }
  284. val = envValBool
  285. }
  286. }
  287. eachName(f.Name, func(name string) {
  288. if f.Destination != nil {
  289. set.BoolVar(f.Destination, name, val, f.Usage)
  290. return
  291. }
  292. set.Bool(name, val, f.Usage)
  293. })
  294. return nil
  295. }
  296. // Apply populates the flag given the flag set and environment
  297. // Ignores errors
  298. func (f BoolTFlag) Apply(set *flag.FlagSet) {
  299. f.ApplyWithError(set)
  300. }
  301. // ApplyWithError populates the flag given the flag set and environment
  302. func (f BoolTFlag) ApplyWithError(set *flag.FlagSet) error {
  303. val := true
  304. if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  305. if envVal == "" {
  306. val = false
  307. } else {
  308. envValBool, err := strconv.ParseBool(envVal)
  309. if err != nil {
  310. return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err)
  311. }
  312. val = envValBool
  313. }
  314. }
  315. eachName(f.Name, func(name string) {
  316. if f.Destination != nil {
  317. set.BoolVar(f.Destination, name, val, f.Usage)
  318. return
  319. }
  320. set.Bool(name, val, f.Usage)
  321. })
  322. return nil
  323. }
  324. // Apply populates the flag given the flag set and environment
  325. // Ignores errors
  326. func (f StringFlag) Apply(set *flag.FlagSet) {
  327. f.ApplyWithError(set)
  328. }
  329. // ApplyWithError populates the flag given the flag set and environment
  330. func (f StringFlag) ApplyWithError(set *flag.FlagSet) error {
  331. if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  332. f.Value = envVal
  333. }
  334. eachName(f.Name, func(name string) {
  335. if f.Destination != nil {
  336. set.StringVar(f.Destination, name, f.Value, f.Usage)
  337. return
  338. }
  339. set.String(name, f.Value, f.Usage)
  340. })
  341. return nil
  342. }
  343. // Apply populates the flag given the flag set and environment
  344. // Ignores errors
  345. func (f IntFlag) Apply(set *flag.FlagSet) {
  346. f.ApplyWithError(set)
  347. }
  348. // ApplyWithError populates the flag given the flag set and environment
  349. func (f IntFlag) ApplyWithError(set *flag.FlagSet) error {
  350. if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  351. envValInt, err := strconv.ParseInt(envVal, 0, 64)
  352. if err != nil {
  353. return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err)
  354. }
  355. f.Value = int(envValInt)
  356. }
  357. eachName(f.Name, func(name string) {
  358. if f.Destination != nil {
  359. set.IntVar(f.Destination, name, f.Value, f.Usage)
  360. return
  361. }
  362. set.Int(name, f.Value, f.Usage)
  363. })
  364. return nil
  365. }
  366. // Apply populates the flag given the flag set and environment
  367. // Ignores errors
  368. func (f Int64Flag) Apply(set *flag.FlagSet) {
  369. f.ApplyWithError(set)
  370. }
  371. // ApplyWithError populates the flag given the flag set and environment
  372. func (f Int64Flag) ApplyWithError(set *flag.FlagSet) error {
  373. if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  374. envValInt, err := strconv.ParseInt(envVal, 0, 64)
  375. if err != nil {
  376. return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err)
  377. }
  378. f.Value = envValInt
  379. }
  380. eachName(f.Name, func(name string) {
  381. if f.Destination != nil {
  382. set.Int64Var(f.Destination, name, f.Value, f.Usage)
  383. return
  384. }
  385. set.Int64(name, f.Value, f.Usage)
  386. })
  387. return nil
  388. }
  389. // Apply populates the flag given the flag set and environment
  390. // Ignores errors
  391. func (f UintFlag) Apply(set *flag.FlagSet) {
  392. f.ApplyWithError(set)
  393. }
  394. // ApplyWithError populates the flag given the flag set and environment
  395. func (f UintFlag) ApplyWithError(set *flag.FlagSet) error {
  396. if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  397. envValInt, err := strconv.ParseUint(envVal, 0, 64)
  398. if err != nil {
  399. return fmt.Errorf("could not parse %s as uint value for flag %s: %s", envVal, f.Name, err)
  400. }
  401. f.Value = uint(envValInt)
  402. }
  403. eachName(f.Name, func(name string) {
  404. if f.Destination != nil {
  405. set.UintVar(f.Destination, name, f.Value, f.Usage)
  406. return
  407. }
  408. set.Uint(name, f.Value, f.Usage)
  409. })
  410. return nil
  411. }
  412. // Apply populates the flag given the flag set and environment
  413. // Ignores errors
  414. func (f Uint64Flag) Apply(set *flag.FlagSet) {
  415. f.ApplyWithError(set)
  416. }
  417. // ApplyWithError populates the flag given the flag set and environment
  418. func (f Uint64Flag) ApplyWithError(set *flag.FlagSet) error {
  419. if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  420. envValInt, err := strconv.ParseUint(envVal, 0, 64)
  421. if err != nil {
  422. return fmt.Errorf("could not parse %s as uint64 value for flag %s: %s", envVal, f.Name, err)
  423. }
  424. f.Value = uint64(envValInt)
  425. }
  426. eachName(f.Name, func(name string) {
  427. if f.Destination != nil {
  428. set.Uint64Var(f.Destination, name, f.Value, f.Usage)
  429. return
  430. }
  431. set.Uint64(name, f.Value, f.Usage)
  432. })
  433. return nil
  434. }
  435. // Apply populates the flag given the flag set and environment
  436. // Ignores errors
  437. func (f DurationFlag) Apply(set *flag.FlagSet) {
  438. f.ApplyWithError(set)
  439. }
  440. // ApplyWithError populates the flag given the flag set and environment
  441. func (f DurationFlag) ApplyWithError(set *flag.FlagSet) error {
  442. if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  443. envValDuration, err := time.ParseDuration(envVal)
  444. if err != nil {
  445. return fmt.Errorf("could not parse %s as duration for flag %s: %s", envVal, f.Name, err)
  446. }
  447. f.Value = envValDuration
  448. }
  449. eachName(f.Name, func(name string) {
  450. if f.Destination != nil {
  451. set.DurationVar(f.Destination, name, f.Value, f.Usage)
  452. return
  453. }
  454. set.Duration(name, f.Value, f.Usage)
  455. })
  456. return nil
  457. }
  458. // Apply populates the flag given the flag set and environment
  459. // Ignores errors
  460. func (f Float64Flag) Apply(set *flag.FlagSet) {
  461. f.ApplyWithError(set)
  462. }
  463. // ApplyWithError populates the flag given the flag set and environment
  464. func (f Float64Flag) ApplyWithError(set *flag.FlagSet) error {
  465. if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok {
  466. envValFloat, err := strconv.ParseFloat(envVal, 10)
  467. if err != nil {
  468. return fmt.Errorf("could not parse %s as float64 value for flag %s: %s", envVal, f.Name, err)
  469. }
  470. f.Value = float64(envValFloat)
  471. }
  472. eachName(f.Name, func(name string) {
  473. if f.Destination != nil {
  474. set.Float64Var(f.Destination, name, f.Value, f.Usage)
  475. return
  476. }
  477. set.Float64(name, f.Value, f.Usage)
  478. })
  479. return nil
  480. }
  481. func visibleFlags(fl []Flag) []Flag {
  482. visible := []Flag{}
  483. for _, flag := range fl {
  484. field := flagValue(flag).FieldByName("Hidden")
  485. if !field.IsValid() || !field.Bool() {
  486. visible = append(visible, flag)
  487. }
  488. }
  489. return visible
  490. }
  491. func prefixFor(name string) (prefix string) {
  492. if len(name) == 1 {
  493. prefix = "-"
  494. } else {
  495. prefix = "--"
  496. }
  497. return
  498. }
  499. // Returns the placeholder, if any, and the unquoted usage string.
  500. func unquoteUsage(usage string) (string, string) {
  501. for i := 0; i < len(usage); i++ {
  502. if usage[i] == '`' {
  503. for j := i + 1; j < len(usage); j++ {
  504. if usage[j] == '`' {
  505. name := usage[i+1 : j]
  506. usage = usage[:i] + name + usage[j+1:]
  507. return name, usage
  508. }
  509. }
  510. break
  511. }
  512. }
  513. return "", usage
  514. }
  515. func prefixedNames(fullName, placeholder string) string {
  516. var prefixed string
  517. parts := strings.Split(fullName, ",")
  518. for i, name := range parts {
  519. name = strings.Trim(name, " ")
  520. prefixed += prefixFor(name) + name
  521. if placeholder != "" {
  522. prefixed += " " + placeholder
  523. }
  524. if i < len(parts)-1 {
  525. prefixed += ", "
  526. }
  527. }
  528. return prefixed
  529. }
  530. func withEnvHint(envVar, str string) string {
  531. envText := ""
  532. if envVar != "" {
  533. prefix := "$"
  534. suffix := ""
  535. sep := ", $"
  536. if runtime.GOOS == "windows" {
  537. prefix = "%"
  538. suffix = "%"
  539. sep = "%, %"
  540. }
  541. envText = " [" + prefix + strings.Join(strings.Split(envVar, ","), sep) + suffix + "]"
  542. }
  543. return str + envText
  544. }
  545. func withFileHint(filePath, str string) string {
  546. fileText := ""
  547. if filePath != "" {
  548. fileText = fmt.Sprintf(" [%s]", filePath)
  549. }
  550. return str + fileText
  551. }
  552. func flagValue(f Flag) reflect.Value {
  553. fv := reflect.ValueOf(f)
  554. for fv.Kind() == reflect.Ptr {
  555. fv = reflect.Indirect(fv)
  556. }
  557. return fv
  558. }
  559. func stringifyFlag(f Flag) string {
  560. fv := flagValue(f)
  561. switch f.(type) {
  562. case IntSliceFlag:
  563. return FlagFileHinter(
  564. fv.FieldByName("FilePath").String(),
  565. FlagEnvHinter(
  566. fv.FieldByName("EnvVar").String(),
  567. stringifyIntSliceFlag(f.(IntSliceFlag)),
  568. ),
  569. )
  570. case Int64SliceFlag:
  571. return FlagFileHinter(
  572. fv.FieldByName("FilePath").String(),
  573. FlagEnvHinter(
  574. fv.FieldByName("EnvVar").String(),
  575. stringifyInt64SliceFlag(f.(Int64SliceFlag)),
  576. ),
  577. )
  578. case StringSliceFlag:
  579. return FlagFileHinter(
  580. fv.FieldByName("FilePath").String(),
  581. FlagEnvHinter(
  582. fv.FieldByName("EnvVar").String(),
  583. stringifyStringSliceFlag(f.(StringSliceFlag)),
  584. ),
  585. )
  586. }
  587. placeholder, usage := unquoteUsage(fv.FieldByName("Usage").String())
  588. needsPlaceholder := false
  589. defaultValueString := ""
  590. if val := fv.FieldByName("Value"); val.IsValid() {
  591. needsPlaceholder = true
  592. defaultValueString = fmt.Sprintf(" (default: %v)", val.Interface())
  593. if val.Kind() == reflect.String && val.String() != "" {
  594. defaultValueString = fmt.Sprintf(" (default: %q)", val.String())
  595. }
  596. }
  597. if defaultValueString == " (default: )" {
  598. defaultValueString = ""
  599. }
  600. if needsPlaceholder && placeholder == "" {
  601. placeholder = defaultPlaceholder
  602. }
  603. usageWithDefault := strings.TrimSpace(usage + defaultValueString)
  604. return FlagFileHinter(
  605. fv.FieldByName("FilePath").String(),
  606. FlagEnvHinter(
  607. fv.FieldByName("EnvVar").String(),
  608. FlagNamePrefixer(fv.FieldByName("Name").String(), placeholder)+"\t"+usageWithDefault,
  609. ),
  610. )
  611. }
  612. func stringifyIntSliceFlag(f IntSliceFlag) string {
  613. defaultVals := []string{}
  614. if f.Value != nil && len(f.Value.Value()) > 0 {
  615. for _, i := range f.Value.Value() {
  616. defaultVals = append(defaultVals, strconv.Itoa(i))
  617. }
  618. }
  619. return stringifySliceFlag(f.Usage, f.Name, defaultVals)
  620. }
  621. func stringifyInt64SliceFlag(f Int64SliceFlag) string {
  622. defaultVals := []string{}
  623. if f.Value != nil && len(f.Value.Value()) > 0 {
  624. for _, i := range f.Value.Value() {
  625. defaultVals = append(defaultVals, strconv.FormatInt(i, 10))
  626. }
  627. }
  628. return stringifySliceFlag(f.Usage, f.Name, defaultVals)
  629. }
  630. func stringifyStringSliceFlag(f StringSliceFlag) string {
  631. defaultVals := []string{}
  632. if f.Value != nil && len(f.Value.Value()) > 0 {
  633. for _, s := range f.Value.Value() {
  634. if len(s) > 0 {
  635. defaultVals = append(defaultVals, strconv.Quote(s))
  636. }
  637. }
  638. }
  639. return stringifySliceFlag(f.Usage, f.Name, defaultVals)
  640. }
  641. func stringifySliceFlag(usage, name string, defaultVals []string) string {
  642. placeholder, usage := unquoteUsage(usage)
  643. if placeholder == "" {
  644. placeholder = defaultPlaceholder
  645. }
  646. defaultVal := ""
  647. if len(defaultVals) > 0 {
  648. defaultVal = fmt.Sprintf(" (default: %s)", strings.Join(defaultVals, ", "))
  649. }
  650. usageWithDefault := strings.TrimSpace(usage + defaultVal)
  651. return FlagNamePrefixer(name, placeholder) + "\t" + usageWithDefault
  652. }
  653. func flagFromFileEnv(filePath, envName string) (val string, ok bool) {
  654. for _, envVar := range strings.Split(envName, ",") {
  655. envVar = strings.TrimSpace(envVar)
  656. if envVal, ok := syscall.Getenv(envVar); ok {
  657. return envVal, true
  658. }
  659. }
  660. for _, fileVar := range strings.Split(filePath, ",") {
  661. if data, err := ioutil.ReadFile(fileVar); err == nil {
  662. return string(data), true
  663. }
  664. }
  665. return "", false
  666. }