| 1 |
package diff |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"io" |
| 6 |
"regexp" |
| 7 |
"strconv" |
| 8 |
"strings" |
| 9 |
|
| 10 |
"github.com/go-git/go-git/v5/plumbing" |
| 11 |
) |
| 12 |
|
| 13 |
// DefaultContextLines is the default number of context lines. |
| 14 |
const DefaultContextLines = 3 |
| 15 |
|
| 16 |
var ( |
| 17 |
splitLinesRegexp = regexp.MustCompile(`[^\n]*(\n|$)`) |
| 18 |
|
| 19 |
operationChar = map[Operation]byte{ |
| 20 |
Add: '+', |
| 21 |
Delete: '-', |
| 22 |
Equal: ' ', |
| 23 |
} |
| 24 |
|
| 25 |
operationColorKey = map[Operation]ColorKey{ |
| 26 |
Add: New, |
| 27 |
Delete: Old, |
| 28 |
Equal: Context, |
| 29 |
} |
| 30 |
) |
| 31 |
|
| 32 |
// UnifiedEncoder encodes an unified diff into the provided Writer. It does not |
| 33 |
// support similarity index for renames or sorting hash representations. |
| 34 |
type UnifiedEncoder struct { |
| 35 |
io.Writer |
| 36 |
|
| 37 |
// contextLines is the count of unchanged lines that will appear surrounding |
| 38 |
// a change. |
| 39 |
contextLines int |
| 40 |
|
| 41 |
// srcPrefix and dstPrefix are prepended to file paths when encoding a diff. |
| 42 |
srcPrefix string |
| 43 |
dstPrefix string |
| 44 |
|
| 45 |
// colorConfig is the color configuration. The default is no color. |
| 46 |
color ColorConfig |
| 47 |
} |
| 48 |
|
| 49 |
// NewUnifiedEncoder returns a new UnifiedEncoder that writes to w. |
| 50 |
func NewUnifiedEncoder(w io.Writer, contextLines int) *UnifiedEncoder { |
| 51 |
return &UnifiedEncoder{ |
| 52 |
Writer: w, |
| 53 |
srcPrefix: "a/", |
| 54 |
dstPrefix: "b/", |
| 55 |
contextLines: contextLines, |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
// SetColor sets e's color configuration and returns e. |
| 60 |
func (e *UnifiedEncoder) SetColor(colorConfig ColorConfig) *UnifiedEncoder { |
| 61 |
e.color = colorConfig |
| 62 |
return e |
| 63 |
} |
| 64 |
|
| 65 |
// SetSrcPrefix sets e's srcPrefix and returns e. |
| 66 |
func (e *UnifiedEncoder) SetSrcPrefix(prefix string) *UnifiedEncoder { |
| 67 |
e.srcPrefix = prefix |
| 68 |
return e |
| 69 |
} |
| 70 |
|
| 71 |
// SetDstPrefix sets e's dstPrefix and returns e. |
| 72 |
func (e *UnifiedEncoder) SetDstPrefix(prefix string) *UnifiedEncoder { |
| 73 |
e.dstPrefix = prefix |
| 74 |
return e |
| 75 |
} |
| 76 |
|
| 77 |
// Encode encodes patch. |
| 78 |
func (e *UnifiedEncoder) Encode(patch Patch) error { |
| 79 |
sb := &strings.Builder{} |
| 80 |
|
| 81 |
if message := patch.Message(); message != "" { |
| 82 |
sb.WriteString(message) |
| 83 |
if !strings.HasSuffix(message, "\n") { |
| 84 |
sb.WriteByte('\n') |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
for _, filePatch := range patch.FilePatches() { |
| 89 |
e.writeFilePatchHeader(sb, filePatch) |
| 90 |
g := newHunksGenerator(filePatch.Chunks(), e.contextLines) |
| 91 |
for _, hunk := range g.Generate() { |
| 92 |
hunk.writeTo(sb, e.color) |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
_, err := e.Write([]byte(sb.String())) |
| 97 |
return err |
| 98 |
} |
| 99 |
|
| 100 |
func (e *UnifiedEncoder) writeFilePatchHeader(sb *strings.Builder, filePatch FilePatch) { |
| 101 |
from, to := filePatch.Files() |
| 102 |
if from == nil && to == nil { |
| 103 |
return |
| 104 |
} |
| 105 |
isBinary := filePatch.IsBinary() |
| 106 |
|
| 107 |
var lines []string |
| 108 |
switch { |
| 109 |
case from != nil && to != nil: |
| 110 |
hashEquals := from.Hash() == to.Hash() |
| 111 |
lines = append(lines, |
| 112 |
fmt.Sprintf("diff --git %s%s %s%s", |
| 113 |
e.srcPrefix, from.Path(), e.dstPrefix, to.Path()), |
| 114 |
) |
| 115 |
if from.Mode() != to.Mode() { |
| 116 |
lines = append(lines, |
| 117 |
fmt.Sprintf("old mode %o", from.Mode()), |
| 118 |
fmt.Sprintf("new mode %o", to.Mode()), |
| 119 |
) |
| 120 |
} |
| 121 |
if from.Path() != to.Path() { |
| 122 |
lines = append(lines, |
| 123 |
fmt.Sprintf("rename from %s", from.Path()), |
| 124 |
fmt.Sprintf("rename to %s", to.Path()), |
| 125 |
) |
| 126 |
} |
| 127 |
if from.Mode() != to.Mode() && !hashEquals { |
| 128 |
lines = append(lines, |
| 129 |
fmt.Sprintf("index %s..%s", from.Hash(), to.Hash()), |
| 130 |
) |
| 131 |
} else if !hashEquals { |
| 132 |
lines = append(lines, |
| 133 |
fmt.Sprintf("index %s..%s %o", from.Hash(), to.Hash(), from.Mode()), |
| 134 |
) |
| 135 |
} |
| 136 |
if !hashEquals { |
| 137 |
lines = e.appendPathLines(lines, e.srcPrefix+from.Path(), e.dstPrefix+to.Path(), isBinary) |
| 138 |
} |
| 139 |
case from == nil: |
| 140 |
lines = append(lines, |
| 141 |
fmt.Sprintf("diff --git %s %s", e.srcPrefix+to.Path(), e.dstPrefix+to.Path()), |
| 142 |
fmt.Sprintf("new file mode %o", to.Mode()), |
| 143 |
fmt.Sprintf("index %s..%s", plumbing.ZeroHash, to.Hash()), |
| 144 |
) |
| 145 |
lines = e.appendPathLines(lines, "/dev/null", e.dstPrefix+to.Path(), isBinary) |
| 146 |
case to == nil: |
| 147 |
lines = append(lines, |
| 148 |
fmt.Sprintf("diff --git %s %s", e.srcPrefix+from.Path(), e.dstPrefix+from.Path()), |
| 149 |
fmt.Sprintf("deleted file mode %o", from.Mode()), |
| 150 |
fmt.Sprintf("index %s..%s", from.Hash(), plumbing.ZeroHash), |
| 151 |
) |
| 152 |
lines = e.appendPathLines(lines, e.srcPrefix+from.Path(), "/dev/null", isBinary) |
| 153 |
} |
| 154 |
|
| 155 |
sb.WriteString(e.color[Meta]) |
| 156 |
sb.WriteString(lines[0]) |
| 157 |
for _, line := range lines[1:] { |
| 158 |
sb.WriteByte('\n') |
| 159 |
sb.WriteString(line) |
| 160 |
} |
| 161 |
sb.WriteString(e.color.Reset(Meta)) |
| 162 |
sb.WriteByte('\n') |
| 163 |
} |
| 164 |
|
| 165 |
func (e *UnifiedEncoder) appendPathLines(lines []string, fromPath, toPath string, isBinary bool) []string { |
| 166 |
if isBinary { |
| 167 |
return append(lines, |
| 168 |
fmt.Sprintf("Binary files %s and %s differ", fromPath, toPath), |
| 169 |
) |
| 170 |
} |
| 171 |
return append(lines, |
| 172 |
fmt.Sprintf("--- %s", fromPath), |
| 173 |
fmt.Sprintf("+++ %s", toPath), |
| 174 |
) |
| 175 |
} |
| 176 |
|
| 177 |
type hunksGenerator struct { |
| 178 |
fromLine, toLine int |
| 179 |
ctxLines int |
| 180 |
chunks []Chunk |
| 181 |
current *hunk |
| 182 |
hunks []*hunk |
| 183 |
beforeContext, afterContext []string |
| 184 |
} |
| 185 |
|
| 186 |
func newHunksGenerator(chunks []Chunk, ctxLines int) *hunksGenerator { |
| 187 |
return &hunksGenerator{ |
| 188 |
chunks: chunks, |
| 189 |
ctxLines: ctxLines, |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
func (g *hunksGenerator) Generate() []*hunk { |
| 194 |
for i, chunk := range g.chunks { |
| 195 |
lines := splitLines(chunk.Content()) |
| 196 |
nLines := len(lines) |
| 197 |
|
| 198 |
switch chunk.Type() { |
| 199 |
case Equal: |
| 200 |
g.fromLine += nLines |
| 201 |
g.toLine += nLines |
| 202 |
g.processEqualsLines(lines, i) |
| 203 |
case Delete: |
| 204 |
if nLines != 0 { |
| 205 |
g.fromLine++ |
| 206 |
} |
| 207 |
|
| 208 |
g.processHunk(i, chunk.Type()) |
| 209 |
g.fromLine += nLines - 1 |
| 210 |
g.current.AddOp(chunk.Type(), lines...) |
| 211 |
case Add: |
| 212 |
if nLines != 0 { |
| 213 |
g.toLine++ |
| 214 |
} |
| 215 |
g.processHunk(i, chunk.Type()) |
| 216 |
g.toLine += nLines - 1 |
| 217 |
g.current.AddOp(chunk.Type(), lines...) |
| 218 |
} |
| 219 |
|
| 220 |
if i == len(g.chunks)-1 && g.current != nil { |
| 221 |
g.hunks = append(g.hunks, g.current) |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
return g.hunks |
| 226 |
} |
| 227 |
|
| 228 |
func (g *hunksGenerator) processHunk(i int, op Operation) { |
| 229 |
if g.current != nil { |
| 230 |
return |
| 231 |
} |
| 232 |
|
| 233 |
var ctxPrefix string |
| 234 |
linesBefore := len(g.beforeContext) |
| 235 |
if linesBefore > g.ctxLines { |
| 236 |
ctxPrefix = g.beforeContext[linesBefore-g.ctxLines-1] |
| 237 |
g.beforeContext = g.beforeContext[linesBefore-g.ctxLines:] |
| 238 |
linesBefore = g.ctxLines |
| 239 |
} |
| 240 |
|
| 241 |
g.current = &hunk{ctxPrefix: strings.TrimSuffix(ctxPrefix, "\n")} |
| 242 |
g.current.AddOp(Equal, g.beforeContext...) |
| 243 |
|
| 244 |
switch op { |
| 245 |
case Delete: |
| 246 |
g.current.fromLine, g.current.toLine = |
| 247 |
g.addLineNumbers(g.fromLine, g.toLine, linesBefore, i, Add) |
| 248 |
case Add: |
| 249 |
g.current.toLine, g.current.fromLine = |
| 250 |
g.addLineNumbers(g.toLine, g.fromLine, linesBefore, i, Delete) |
| 251 |
} |
| 252 |
|
| 253 |
g.beforeContext = nil |
| 254 |
} |
| 255 |
|
| 256 |
// addLineNumbers obtains the line numbers in a new chunk. |
| 257 |
func (g *hunksGenerator) addLineNumbers(la, lb int, linesBefore int, i int, op Operation) (cla, clb int) { |
| 258 |
cla = la - linesBefore |
| 259 |
// we need to search for a reference for the next diff |
| 260 |
switch { |
| 261 |
case linesBefore != 0 && g.ctxLines != 0: |
| 262 |
if lb > g.ctxLines { |
| 263 |
clb = lb - g.ctxLines + 1 |
| 264 |
} else { |
| 265 |
clb = 1 |
| 266 |
} |
| 267 |
case g.ctxLines == 0: |
| 268 |
clb = lb |
| 269 |
case i != len(g.chunks)-1: |
| 270 |
next := g.chunks[i+1] |
| 271 |
if next.Type() == op || next.Type() == Equal { |
| 272 |
// this diff will be into this chunk |
| 273 |
clb = lb + 1 |
| 274 |
} |
| 275 |
} |
| 276 |
|
| 277 |
return |
| 278 |
} |
| 279 |
|
| 280 |
func (g *hunksGenerator) processEqualsLines(ls []string, i int) { |
| 281 |
if g.current == nil { |
| 282 |
g.beforeContext = append(g.beforeContext, ls...) |
| 283 |
return |
| 284 |
} |
| 285 |
|
| 286 |
g.afterContext = append(g.afterContext, ls...) |
| 287 |
if len(g.afterContext) <= g.ctxLines*2 && i != len(g.chunks)-1 { |
| 288 |
g.current.AddOp(Equal, g.afterContext...) |
| 289 |
g.afterContext = nil |
| 290 |
} else { |
| 291 |
ctxLines := g.ctxLines |
| 292 |
if ctxLines > len(g.afterContext) { |
| 293 |
ctxLines = len(g.afterContext) |
| 294 |
} |
| 295 |
g.current.AddOp(Equal, g.afterContext[:ctxLines]...) |
| 296 |
g.hunks = append(g.hunks, g.current) |
| 297 |
|
| 298 |
g.current = nil |
| 299 |
g.beforeContext = g.afterContext[ctxLines:] |
| 300 |
g.afterContext = nil |
| 301 |
} |
| 302 |
} |
| 303 |
|
| 304 |
func splitLines(s string) []string { |
| 305 |
out := splitLinesRegexp.FindAllString(s, -1) |
| 306 |
if out[len(out)-1] == "" { |
| 307 |
out = out[:len(out)-1] |
| 308 |
} |
| 309 |
return out |
| 310 |
} |
| 311 |
|
| 312 |
type hunk struct { |
| 313 |
fromLine int |
| 314 |
toLine int |
| 315 |
|
| 316 |
fromCount int |
| 317 |
toCount int |
| 318 |
|
| 319 |
ctxPrefix string |
| 320 |
ops []*op |
| 321 |
} |
| 322 |
|
| 323 |
func (h *hunk) writeTo(sb *strings.Builder, color ColorConfig) { |
| 324 |
sb.WriteString(color[Frag]) |
| 325 |
sb.WriteString("@@ -") |
| 326 |
|
| 327 |
if h.fromCount == 1 { |
| 328 |
sb.WriteString(strconv.Itoa(h.fromLine)) |
| 329 |
} else { |
| 330 |
sb.WriteString(strconv.Itoa(h.fromLine)) |
| 331 |
sb.WriteByte(',') |
| 332 |
sb.WriteString(strconv.Itoa(h.fromCount)) |
| 333 |
} |
| 334 |
|
| 335 |
sb.WriteString(" +") |
| 336 |
|
| 337 |
if h.toCount == 1 { |
| 338 |
sb.WriteString(strconv.Itoa(h.toLine)) |
| 339 |
} else { |
| 340 |
sb.WriteString(strconv.Itoa(h.toLine)) |
| 341 |
sb.WriteByte(',') |
| 342 |
sb.WriteString(strconv.Itoa(h.toCount)) |
| 343 |
} |
| 344 |
|
| 345 |
sb.WriteString(" @@") |
| 346 |
sb.WriteString(color.Reset(Frag)) |
| 347 |
|
| 348 |
if h.ctxPrefix != "" { |
| 349 |
sb.WriteByte(' ') |
| 350 |
sb.WriteString(color[Func]) |
| 351 |
sb.WriteString(h.ctxPrefix) |
| 352 |
sb.WriteString(color.Reset(Func)) |
| 353 |
} |
| 354 |
|
| 355 |
sb.WriteByte('\n') |
| 356 |
|
| 357 |
for _, op := range h.ops { |
| 358 |
op.writeTo(sb, color) |
| 359 |
} |
| 360 |
} |
| 361 |
|
| 362 |
func (h *hunk) AddOp(t Operation, ss ...string) { |
| 363 |
n := len(ss) |
| 364 |
switch t { |
| 365 |
case Add: |
| 366 |
h.toCount += n |
| 367 |
case Delete: |
| 368 |
h.fromCount += n |
| 369 |
case Equal: |
| 370 |
h.toCount += n |
| 371 |
h.fromCount += n |
| 372 |
} |
| 373 |
|
| 374 |
for _, s := range ss { |
| 375 |
h.ops = append(h.ops, &op{s, t}) |
| 376 |
} |
| 377 |
} |
| 378 |
|
| 379 |
type op struct { |
| 380 |
text string |
| 381 |
t Operation |
| 382 |
} |
| 383 |
|
| 384 |
func (o *op) writeTo(sb *strings.Builder, color ColorConfig) { |
| 385 |
colorKey := operationColorKey[o.t] |
| 386 |
sb.WriteString(color[colorKey]) |
| 387 |
sb.WriteByte(operationChar[o.t]) |
| 388 |
if strings.HasSuffix(o.text, "\n") { |
| 389 |
sb.WriteString(strings.TrimSuffix(o.text, "\n")) |
| 390 |
} else { |
| 391 |
sb.WriteString(o.text + "\n\\ No newline at end of file") |
| 392 |
} |
| 393 |
sb.WriteString(color.Reset(colorKey)) |
| 394 |
sb.WriteByte('\n') |
| 395 |
} |