transform.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package survey
  2. import (
  3. "reflect"
  4. "strings"
  5. )
  6. // TransformString returns a `Transformer` based on the "f"
  7. // function which accepts a string representation of the answer
  8. // and returns a new one, transformed, answer.
  9. // Take for example the functions inside the std `strings` package,
  10. // they can be converted to a compatible `Transformer` by using this function,
  11. // i.e: `TransformString(strings.Title)`, `TransformString(strings.ToUpper)`.
  12. //
  13. // Note that `TransformString` is just a helper, `Transformer` can be used
  14. // to transform any type of answer.
  15. func TransformString(f func(s string) string) Transformer {
  16. return func(ans interface{}) interface{} {
  17. // if the answer value passed in is the zero value of the appropriate type
  18. if isZero(reflect.ValueOf(ans)) {
  19. // skip this `Transformer` by returning a nil value.
  20. // The original answer will be not affected,
  21. // see survey.go#L125.
  22. return nil
  23. }
  24. // "ans" is never nil here, so we don't have to check that
  25. // see survey.go#L97 for more.
  26. // Make sure that the the answer's value was a typeof string.
  27. s, ok := ans.(string)
  28. if !ok {
  29. return nil
  30. }
  31. return f(s)
  32. }
  33. }
  34. // ToLower is a `Transformer`.
  35. // It receives an answer value
  36. // and returns a copy of the "ans"
  37. // with all Unicode letters mapped to their lower case.
  38. //
  39. // Note that if "ans" is not a string then it will
  40. // return a nil value, meaning that the above answer
  41. // will not be affected by this call at all.
  42. func ToLower(ans interface{}) interface{} {
  43. transformer := TransformString(strings.ToLower)
  44. return transformer(ans)
  45. }
  46. // Title is a `Transformer`.
  47. // It receives an answer value
  48. // and returns a copy of the "ans"
  49. // with all Unicode letters that begin words
  50. // mapped to their title case.
  51. //
  52. // Note that if "ans" is not a string then it will
  53. // return a nil value, meaning that the above answer
  54. // will not be affected by this call at all.
  55. func Title(ans interface{}) interface{} {
  56. transformer := TransformString(strings.Title)
  57. return transformer(ans)
  58. }
  59. // ComposeTransformers is a variadic function used to create one transformer from many.
  60. func ComposeTransformers(transformers ...Transformer) Transformer {
  61. // return a transformer that calls each one sequentially
  62. return func(ans interface{}) interface{} {
  63. // execute each transformer
  64. for _, t := range transformers {
  65. ans = t(ans)
  66. }
  67. return ans
  68. }
  69. }