|
| 1 | +/* |
| 2 | +Copyright 2015 The Kubernetes Authors All rights reserved. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package main |
| 18 | + |
| 19 | +import ( |
| 20 | + "fmt" |
| 21 | + "regexp" |
| 22 | + "strings" |
| 23 | +) |
| 24 | + |
| 25 | +var headerRegex = regexp.MustCompile(`^(#+)\s*(.*)$`) |
| 26 | +var whitespaceRegex = regexp.MustCompile(`^\s*$`) |
| 27 | + |
| 28 | +func fixHeaderLines(fileBytes []byte) []byte { |
| 29 | + lines := splitLines(fileBytes) |
| 30 | + out := []string{} |
| 31 | + for i := range lines { |
| 32 | + matches := headerRegex.FindStringSubmatch(lines[i]) |
| 33 | + if matches == nil { |
| 34 | + out = append(out, lines[i]) |
| 35 | + continue |
| 36 | + } |
| 37 | + if i > 0 && !whitespaceRegex.Match([]byte(out[len(out)-1])) { |
| 38 | + out = append(out, "") |
| 39 | + } |
| 40 | + out = append(out, fmt.Sprintf("%s %s", matches[1], matches[2])) |
| 41 | + if i+1 < len(lines) && !whitespaceRegex.Match([]byte(lines[i+1])) { |
| 42 | + out = append(out, "") |
| 43 | + } |
| 44 | + } |
| 45 | + final := strings.Join(out, "\n") |
| 46 | + // Preserve the end of the file. |
| 47 | + if len(fileBytes) > 0 && fileBytes[len(fileBytes)-1] == '\n' { |
| 48 | + final += "\n" |
| 49 | + } |
| 50 | + return []byte(final) |
| 51 | +} |
| 52 | + |
| 53 | +// Header lines need whitespace around them and after the #s. |
| 54 | +func checkHeaderLines(filePath string, fileBytes []byte) ([]byte, error) { |
| 55 | + fbs := splitByPreformatted(fileBytes) |
| 56 | + fbs = append([]fileBlock{{false, []byte{}}}, fbs...) |
| 57 | + fbs = append(fbs, fileBlock{false, []byte{}}) |
| 58 | + |
| 59 | + for i := range fbs { |
| 60 | + block := &fbs[i] |
| 61 | + if block.preformatted { |
| 62 | + continue |
| 63 | + } |
| 64 | + block.data = fixHeaderLines(block.data) |
| 65 | + } |
| 66 | + output := []byte{} |
| 67 | + for _, block := range fbs { |
| 68 | + output = append(output, block.data...) |
| 69 | + } |
| 70 | + return output, nil |
| 71 | +} |
0 commit comments