param.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // This file is subject to a 1-clause BSD license.
  2. // Its contents can be found in the enclosed LICENSE file.
  3. package cmd
  4. import (
  5. "regexp"
  6. "strconv"
  7. "strings"
  8. )
  9. // ParamList defines a list of command parameters.
  10. type ParamList []Param
  11. func (p ParamList) Len() int { return len(p) }
  12. func (p ParamList) String(n int) string { return p[n].String() }
  13. func (p ParamList) Int(n int) int64 { return p[n].Int() }
  14. func (p ParamList) Uint(n int) uint64 { return p[n].Uint() }
  15. func (p ParamList) Float(n int) float64 { return p[n].Float() }
  16. func (p ParamList) Bool(n int) bool { return p[n].Bool() }
  17. // Join returns all parameter values, concatenated into a single string.
  18. // Each entry is separated by a blank space.
  19. func (p ParamList) Join() string {
  20. out := make([]string, len(p))
  21. for i := range p {
  22. out[i] = p[i].Value
  23. }
  24. return strings.Join(out, " ")
  25. }
  26. // Param defines a parameter for a command.
  27. type Param struct {
  28. Name string // Parameter name -- used in help listing.
  29. Description string // Parameter description -- used in help listing.
  30. Value string // Parameter value.
  31. Pattern *regexp.Regexp // Pattern defining the type of accepted value.
  32. Required bool // Parameter is required or not?
  33. }
  34. // validate returns true if the given value matches the param pattern.
  35. func (p *Param) validate(v string) bool { return p.Pattern.MatchString(v) }
  36. func (p *Param) String() string { return p.Value }
  37. func (p *Param) Int() int64 {
  38. n, _ := strconv.ParseInt(p.Value, 0, 64)
  39. return n
  40. }
  41. func (p *Param) Uint() uint64 {
  42. n, _ := strconv.ParseUint(p.Value, 0, 64)
  43. return n
  44. }
  45. func (p *Param) Float() float64 {
  46. n, _ := strconv.ParseFloat(p.Value, 64)
  47. return n
  48. }
  49. // Bool returns the boolean value represented by the parameter.
  50. // True is represented by the values: "1", "t", "true", "y", "yes", "on"
  51. // Any other value returns false.
  52. func (p *Param) Bool() bool {
  53. switch strings.ToLower(p.Value) {
  54. case "1", "t", "true", "y", "yes", "on":
  55. return true
  56. default:
  57. return false
  58. }
  59. }