SplitMessage splits a commit message. Returns two strings: * subject (the one line commit summary, like "git log --oneline" or "git log --format=%s), * body only (like "git log --format=%b").
(message string)
| 88 | // * subject (the one line commit summary, like "git log --oneline" or "git log --format=%s), |
| 89 | // * body only (like "git log --format=%b"). |
| 90 | func SplitMessage(message string) (string, string) { |
| 91 | var state int |
| 92 | var lastLineEmpty bool |
| 93 | const ( |
| 94 | stateInit = iota |
| 95 | stateSubject |
| 96 | stateSeparator |
| 97 | stateBody |
| 98 | ) |
| 99 | |
| 100 | const eol = '\n' |
| 101 | |
| 102 | subjectBuilder := strings.Builder{} |
| 103 | bodyBuilder := strings.Builder{} |
| 104 | |
| 105 | scan := bufio.NewScanner(strings.NewReader(message)) |
| 106 | for scan.Scan() { |
| 107 | line := strings.TrimRightFunc(scan.Text(), unicode.IsSpace) |
| 108 | |
| 109 | // process empty lines |
| 110 | if len(line) == 0 { |
| 111 | switch state { |
| 112 | case stateInit, stateSeparator: |
| 113 | // ignore all empty lines before the first line of the subject |
| 114 | case stateSubject: |
| 115 | state = stateSeparator |
| 116 | case stateBody: |
| 117 | lastLineEmpty = true |
| 118 | } |
| 119 | continue |
| 120 | } |
| 121 | |
| 122 | switch state { |
| 123 | case stateInit: |
| 124 | state = stateSubject |
| 125 | subjectBuilder.WriteString(strings.TrimLeftFunc(line, unicode.IsSpace)) |
| 126 | case stateSubject: |
| 127 | subjectBuilder.WriteByte(' ') |
| 128 | subjectBuilder.WriteString(strings.TrimLeftFunc(line, unicode.IsSpace)) |
| 129 | case stateSeparator: |
| 130 | state = stateBody |
| 131 | bodyBuilder.WriteString(line) |
| 132 | bodyBuilder.WriteByte(eol) |
| 133 | lastLineEmpty = false |
| 134 | case stateBody: |
| 135 | if lastLineEmpty { |
| 136 | bodyBuilder.WriteByte(eol) |
| 137 | } |
| 138 | bodyBuilder.WriteString(line) |
| 139 | bodyBuilder.WriteByte(eol) |
| 140 | lastLineEmpty = false |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | return subjectBuilder.String(), bodyBuilder.String() |
| 145 | } |
searching dependent graphs…