MCPcopy Create free account
hub / github.com/alibaba/open-code-review / ParsePatch

Function ParsePatch

internal/diff/parser.go:108–190  ·  view source on GitHub ↗
(diffText string)

Source from the content-addressed store, hash-verified

106}
107
108func ParsePatch(diffText string) []model.Diff {
109 lines := splitDiffLines(diffText)
110 var diffs []model.Diff
111 var current *model.Diff
112 var buf strings.Builder
113 // inHunk tracks whether the current line sits inside a "@@" hunk of the
114 // current file's section. Only hunk content lines carry a leading
115 // "+"/"-"/" " marker, so insertion/deletion counting and the binary
116 // marker must look at hunk state: outside a hunk, "+++ b/file" and
117 // "--- a/file" are headers, not content; inside a hunk, an added line
118 // like "++i" renders as "+++i" and still counts as an insertion.
119 inHunk := false
120
121 for _, line := range lines {
122 if oldPath, newPath, ok := parseDiffHeaderLine(line); ok {
123 // Flush previous diff
124 if current != nil {
125 current.Diff = strings.TrimSuffix(buf.String(), "\n")
126 diffs = append(diffs, *current)
127 buf.Reset()
128 }
129 current = &model.Diff{
130 OldPath: oldPath,
131 NewPath: newPath,
132 }
133 inHunk = false
134 }
135 if current == nil {
136 continue
137 }
138
139 switch {
140 case strings.HasPrefix(line, "@@"):
141 inHunk = true
142 // The object IDs and mode in Git's extended "index" header are not
143 // useful review context. Keep index text in hunks, where it is file
144 // content and therefore carries a diff prefix.
145 case !inHunk && strings.HasPrefix(line, "index "):
146 continue
147 case !inHunk && binaryRe.MatchString(line):
148 current.IsBinary = true
149 // Extended header lines (unambiguous: content lines always carry a
150 // leading "+", "-" or " " prefix, so a bare prefix match is safe).
151 case strings.HasPrefix(line, "new file mode "):
152 current.IsNew = true
153 case strings.HasPrefix(line, "deleted file mode "):
154 current.IsDeleted = true
155 case strings.HasPrefix(line, "rename from "):
156 // Authoritative old path for renames; more reliable than the
157 // "diff --git" header when paths contain spaces.
158 current.OldPath = unquoteRenamePath(strings.TrimPrefix(line, "rename from "))
159 current.IsRenamed = true
160 case strings.HasPrefix(line, "rename to "):
161 current.NewPath = unquoteRenamePath(strings.TrimPrefix(line, "rename to "))
162 current.IsRenamed = true
163 case !inHunk && strings.HasPrefix(line, "copy from "):
164 current.OldPath = unquoteRenamePath(strings.TrimPrefix(line, "copy from "))
165 case !inHunk && strings.HasPrefix(line, "copy to "):

Callers 2

PrepareInputFunction · 0.92
ParseDiffTextFunction · 0.85

Calls 4

splitDiffLinesFunction · 0.85
parseDiffHeaderLineFunction · 0.85
unquoteRenamePathFunction · 0.85
StringMethod · 0.45

Tested by

no test coverage detected