normalizer.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. /*
  14. This file is copied from /pkg/kubectl/cmd/templates/normalizer.go
  15. In a future PR we should remove the original copy and use
  16. /pkg/util/normalizer everywhere.
  17. */
  18. package normalizer
  19. import (
  20. "strings"
  21. "github.com/MakeNowJust/heredoc"
  22. "github.com/russross/blackfriday"
  23. )
  24. const indentation = ` `
  25. // LongDesc normalizes a command's long description to follow the conventions.
  26. func LongDesc(s string) string {
  27. if len(s) == 0 {
  28. return s
  29. }
  30. return normalizer{s}.Heredoc().Markdown().Trim().string
  31. }
  32. // Examples normalizes a command's examples to follow the conventions.
  33. func Examples(s string) string {
  34. if len(s) == 0 {
  35. return s
  36. }
  37. return normalizer{s}.Trim().Indent().string
  38. }
  39. type normalizer struct {
  40. string
  41. }
  42. func (s normalizer) Markdown() normalizer {
  43. bytes := []byte(s.string)
  44. formatted := blackfriday.Markdown(bytes, &ASCIIRenderer{Indentation: indentation}, 0)
  45. s.string = string(formatted)
  46. return s
  47. }
  48. func (s normalizer) Heredoc() normalizer {
  49. s.string = heredoc.Doc(s.string)
  50. return s
  51. }
  52. func (s normalizer) Trim() normalizer {
  53. s.string = strings.TrimSpace(s.string)
  54. return s
  55. }
  56. func (s normalizer) Indent() normalizer {
  57. indentedLines := []string{}
  58. for _, line := range strings.Split(s.string, "\n") {
  59. trimmed := strings.TrimSpace(line)
  60. indented := indentation + trimmed
  61. indentedLines = append(indentedLines, indented)
  62. }
  63. s.string = strings.Join(indentedLines, "\n")
  64. return s
  65. }