headers.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. Copyright 2015 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. package main
  14. import (
  15. "fmt"
  16. "regexp"
  17. )
  18. var headerRegex = regexp.MustCompile(`^(#+)\s*(.*)$`)
  19. func fixHeaderLine(mlines mungeLines, newlines mungeLines, linenum int) mungeLines {
  20. var out mungeLines
  21. mline := mlines[linenum]
  22. line := mlines[linenum].data
  23. matches := headerRegex.FindStringSubmatch(line)
  24. if matches == nil {
  25. out = append(out, mline)
  26. return out
  27. }
  28. // There must be a blank line before the # (unless first line in file)
  29. if linenum != 0 {
  30. newlen := len(newlines)
  31. if newlines[newlen-1].data != "" {
  32. out = append(out, blankMungeLine)
  33. }
  34. }
  35. // There must be a space AFTER the ##'s
  36. newline := fmt.Sprintf("%s %s", matches[1], matches[2])
  37. newmline := newMungeLine(newline)
  38. out = append(out, newmline)
  39. // The next line needs to be a blank line (unless last line in file)
  40. if len(mlines) > linenum+1 && mlines[linenum+1].data != "" {
  41. out = append(out, blankMungeLine)
  42. }
  43. return out
  44. }
  45. // Header lines need whitespace around them and after the #s.
  46. func updateHeaderLines(filePath string, mlines mungeLines) (mungeLines, error) {
  47. var out mungeLines
  48. for i, mline := range mlines {
  49. if mline.preformatted {
  50. out = append(out, mline)
  51. continue
  52. }
  53. if !mline.header {
  54. out = append(out, mline)
  55. continue
  56. }
  57. newLines := fixHeaderLine(mlines, out, i)
  58. out = append(out, newLines...)
  59. }
  60. return out, nil
  61. }