summaryrefslogtreecommitdiff
path: root/libgo/go/patch/textdiff.go
blob: c7e693fc6691c755b8192c5ddeec54f8049c2185 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package patch

import (
	"bytes"
	"os"
)

type TextDiff []TextChunk

// A TextChunk specifies an edit to a section of a file:
// the text beginning at Line, which should be exactly Old,
// is to be replaced with New.
type TextChunk struct {
	Line int
	Old  []byte
	New  []byte
}

func ParseTextDiff(raw []byte) (TextDiff, os.Error) {
	// Copy raw so it is safe to keep references to slices.
	_, chunks := sections(raw, "@@ -")
	delta := 0
	diff := make(TextDiff, len(chunks))
	for i, raw := range chunks {
		c := &diff[i]

		// Parse start line: @@ -oldLine,oldCount +newLine,newCount @@ junk
		chunk := splitLines(raw)
		chunkHeader := chunk[0]
		var ok bool
		var oldLine, oldCount, newLine, newCount int
		s := chunkHeader
		if oldLine, s, ok = atoi(s, "@@ -", 10); !ok {
		ErrChunkHdr:
			return nil, SyntaxError("unexpected chunk header line: " + string(chunkHeader))
		}
		if len(s) == 0 || s[0] != ',' {
			oldCount = 1
		} else if oldCount, s, ok = atoi(s, ",", 10); !ok {
			goto ErrChunkHdr
		}
		if newLine, s, ok = atoi(s, " +", 10); !ok {
			goto ErrChunkHdr
		}
		if len(s) == 0 || s[0] != ',' {
			newCount = 1
		} else if newCount, s, ok = atoi(s, ",", 10); !ok {
			goto ErrChunkHdr
		}
		if !hasPrefix(s, " @@") {
			goto ErrChunkHdr
		}

		// Special case: for created or deleted files, the empty half
		// is given as starting at line 0.  Translate to line 1.
		if oldCount == 0 && oldLine == 0 {
			oldLine = 1
		}
		if newCount == 0 && newLine == 0 {
			newLine = 1
		}

		// Count lines in text
		var dropOldNL, dropNewNL bool
		var nold, nnew int
		var lastch byte
		chunk = chunk[1:]
		for _, l := range chunk {
			if nold == oldCount && nnew == newCount && (len(l) == 0 || l[0] != '\\') {
				if len(bytes.TrimSpace(l)) != 0 {
					return nil, SyntaxError("too many chunk lines")
				}
				continue
			}
			if len(l) == 0 {
				return nil, SyntaxError("empty chunk line")
			}
			switch l[0] {
			case '+':
				nnew++
			case '-':
				nold++
			case ' ':
				nnew++
				nold++
			case '\\':
				if _, ok := skip(l, "\\ No newline at end of file"); ok {
					switch lastch {
					case '-':
						dropOldNL = true
					case '+':
						dropNewNL = true
					case ' ':
						dropOldNL = true
						dropNewNL = true
					default:
						return nil, SyntaxError("message `\\ No newline at end of file' out of context")
					}
					break
				}
				fallthrough
			default:
				return nil, SyntaxError("unexpected chunk line: " + string(l))
			}
			lastch = l[0]
		}

		// Does it match the header?
		if nold != oldCount || nnew != newCount {
			return nil, SyntaxError("chunk header does not match line count: " + string(chunkHeader))
		}
		if oldLine+delta != newLine {
			return nil, SyntaxError("chunk delta is out of sync with previous chunks")
		}
		delta += nnew - nold
		c.Line = oldLine

		var old, new bytes.Buffer
		nold = 0
		nnew = 0
		for _, l := range chunk {
			if nold == oldCount && nnew == newCount {
				break
			}
			ch, l := l[0], l[1:]
			if ch == '\\' {
				continue
			}
			if ch != '+' {
				old.Write(l)
				nold++
			}
			if ch != '-' {
				new.Write(l)
				nnew++
			}
		}
		c.Old = old.Bytes()
		c.New = new.Bytes()
		if dropOldNL {
			c.Old = c.Old[0 : len(c.Old)-1]
		}
		if dropNewNL {
			c.New = c.New[0 : len(c.New)-1]
		}
	}
	return diff, nil
}

var ErrPatchFailure = os.NewError("patch did not apply cleanly")

// Apply applies the changes listed in the diff
// to the data, returning the new version.
func (d TextDiff) Apply(data []byte) ([]byte, os.Error) {
	var buf bytes.Buffer
	line := 1
	for _, c := range d {
		var ok bool
		var prefix []byte
		prefix, data, ok = getLine(data, c.Line-line)
		if !ok || !bytes.HasPrefix(data, c.Old) {
			return nil, ErrPatchFailure
		}
		buf.Write(prefix)
		data = data[len(c.Old):]
		buf.Write(c.New)
		line = c.Line + bytes.Count(c.Old, newline)
	}
	buf.Write(data)
	return buf.Bytes(), nil
}