File: patch.go

package info (click to toggle)
kitty 0.45.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 27,468 kB
  • sloc: ansic: 84,285; python: 57,992; objc: 5,432; sh: 1,333; xml: 364; makefile: 144; javascript: 78
file content (379 lines) | stat: -rw-r--r-- 9,565 bytes parent folder | download
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>

package diff

import (
	"bytes"
	"errors"
	"fmt"
	"github.com/kovidgoyal/kitty/tools/utils"
	"github.com/kovidgoyal/kitty/tools/utils/images"
	"github.com/kovidgoyal/kitty/tools/utils/shlex"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
)

var _ = fmt.Print

const GIT_DIFF = `git diff --no-color --no-ext-diff --exit-code -U_CONTEXT_ --no-index --`
const DIFF_DIFF = `diff -p -U _CONTEXT_ --`

var diff_cmd []string

var GitExe = sync.OnceValue(func() string {
	return utils.FindExe("git")
})

var DiffExe = sync.OnceValue(func() string {
	return utils.FindExe("diff")
})

func find_differ() {
	if GitExe() != "git" && exec.Command(GitExe(), "--help").Run() == nil {
		diff_cmd, _ = shlex.Split(GIT_DIFF)
	} else if DiffExe() != "diff" && exec.Command(DiffExe(), "--help").Run() == nil {
		diff_cmd, _ = shlex.Split(DIFF_DIFF)
	} else {
		diff_cmd = []string{}
	}
}

func set_diff_command(q string) error {
	switch q {
	case "auto":
		find_differ()
	case "builtin", "":
		diff_cmd = []string{}
	case "diff":
		diff_cmd, _ = shlex.Split(DIFF_DIFF)
	case "git":
		diff_cmd, _ = shlex.Split(GIT_DIFF)
	default:
		c, err := shlex.Split(q)
		if err != nil {
			return err
		}
		diff_cmd = c
	}
	return nil
}

type Center struct{ offset, left_size, right_size int }

type Chunk struct {
	is_context              bool
	left_start, right_start int
	left_count, right_count int
	centers                 []Center
}

func (self *Chunk) add_line() {
	self.right_count++
}

func (self *Chunk) remove_line() {
	self.left_count++
}

func (self *Chunk) context_line() {
	self.left_count++
	self.right_count++
}

func changed_center(left, right string) (ans Center) {
	if len(left) > 0 && len(right) > 0 {
		ll, rl := len(left), len(right)
		ml := utils.Min(ll, rl)
		for ; ans.offset < ml && left[ans.offset] == right[ans.offset]; ans.offset++ {
		}
		suffix_count := 0
		for ; suffix_count < ml && left[ll-1-suffix_count] == right[rl-1-suffix_count]; suffix_count++ {
		}
		ans.left_size = ll - suffix_count - ans.offset
		ans.right_size = rl - suffix_count - ans.offset
	}
	return
}

func (self *Chunk) finalize(left_lines, right_lines []string) {
	if !self.is_context && self.left_count == self.right_count {
		for i := 0; i < self.left_count; i++ {
			self.centers = append(self.centers, changed_center(left_lines[self.left_start+i], right_lines[self.right_start+i]))
		}
	}
}

type Hunk struct {
	left_start, left_count     int
	right_start, right_count   int
	title                      string
	added_count, removed_count int
	chunks                     []*Chunk
	current_chunk              *Chunk
	largest_line_number        int
}

func (self *Hunk) new_chunk(is_context bool) *Chunk {
	left_start, right_start := self.left_start, self.right_start
	if len(self.chunks) > 0 {
		c := self.chunks[len(self.chunks)-1]
		left_start = c.left_start + c.left_count
		right_start = c.right_start + c.right_count
	}
	return &Chunk{is_context: is_context, left_start: left_start, right_start: right_start}
}

func (self *Hunk) ensure_diff_chunk() {
	if self.current_chunk == nil || self.current_chunk.is_context {
		if self.current_chunk != nil {
			self.chunks = append(self.chunks, self.current_chunk)
		}
		self.current_chunk = self.new_chunk(false)
	}
}

func (self *Hunk) ensure_context_chunk() {
	if self.current_chunk == nil || !self.current_chunk.is_context {
		if self.current_chunk != nil {
			self.chunks = append(self.chunks, self.current_chunk)
		}
		self.current_chunk = self.new_chunk(true)
	}
}

func (self *Hunk) add_line() {
	self.ensure_diff_chunk()
	self.current_chunk.add_line()
	self.added_count++
}

func (self *Hunk) remove_line() {
	self.ensure_diff_chunk()
	self.current_chunk.remove_line()
	self.removed_count++
}

func (self *Hunk) context_line() {
	self.ensure_context_chunk()
	self.current_chunk.context_line()
}

func (self *Hunk) finalize(left_lines, right_lines []string) error {
	if self.current_chunk != nil {
		self.chunks = append(self.chunks, self.current_chunk)
	}
	// Sanity check
	c := self.chunks[len(self.chunks)-1]
	if c.left_start+c.left_count != self.left_start+self.left_count {
		return fmt.Errorf("Left side line mismatch %d != %d", c.left_start+c.left_count, self.left_start+self.left_count)
	}
	if c.right_start+c.right_count != self.right_start+self.right_count {
		return fmt.Errorf("Right side line mismatch %d != %d", c.right_start+c.right_count, self.right_start+self.right_count)
	}
	for _, c := range self.chunks {
		c.finalize(left_lines, right_lines)
	}
	return nil
}

type Patch struct {
	all_hunks                                       []*Hunk
	largest_line_number, added_count, removed_count int
}

func (self *Patch) Len() int { return len(self.all_hunks) }

func splitlines_like_git(raw string, strip_trailing_lines bool, process_line func(string)) {
	sz := len(raw)
	if strip_trailing_lines {
		for sz > 0 && (raw[sz-1] == '\n' || raw[sz-1] == '\r') {
			sz--
		}
	}
	start := 0
	for i := 0; i < sz; i++ {
		switch raw[i] {
		case '\n':
			process_line(raw[start:i])
			start = i + 1
		case '\r':
			process_line(raw[start:i])
			start = i + 1
			if start < sz && raw[start] == '\n' {
				i++
				start++
			}
		}
	}
	if start < sz {
		process_line(raw[start:sz])
	}
}

func parse_range(x string) (start, count int) {
	s, c, found := strings.Cut(x, ",")
	start, _ = strconv.Atoi(s)
	if start < 0 {
		start = -start
	}
	count = 1
	if found {
		count, _ = strconv.Atoi(c)
	}
	return
}

func parse_hunk_header(line string) *Hunk {
	parts := strings.SplitN(line, "@@", 3)
	linespec := strings.TrimSpace(parts[1])
	title := ""
	if len(parts) == 3 {
		title = strings.TrimSpace(parts[2])
	}
	left, right, _ := strings.Cut(linespec, " ")
	ls, lc := parse_range(left)
	rs, rc := parse_range(right)
	return &Hunk{
		title: title, left_start: ls - 1, left_count: lc, right_start: rs - 1, right_count: rc,
		largest_line_number: utils.Max(ls-1+lc, rs-1+rc),
	}
}

func parse_patch(raw string, left_lines, right_lines []string) (ans *Patch, err error) {
	ans = &Patch{all_hunks: make([]*Hunk, 0, 32)}
	var current_hunk *Hunk
	splitlines_like_git(raw, true, func(line string) {
		if strings.HasPrefix(line, "@@ ") {
			current_hunk = parse_hunk_header(line)
			ans.all_hunks = append(ans.all_hunks, current_hunk)
		} else if current_hunk != nil {
			var ch byte
			if len(line) > 0 {
				ch = line[0]
			}
			switch ch {
			case '+':
				current_hunk.add_line()
			case '-':
				current_hunk.remove_line()
			case '\\':
			default:
				current_hunk.context_line()
			}
		}
	})
	for _, h := range ans.all_hunks {
		err = h.finalize(left_lines, right_lines)
		if err != nil {
			return
		}
		ans.added_count += h.added_count
		ans.removed_count += h.removed_count
	}
	if len(ans.all_hunks) > 0 {
		ans.largest_line_number = ans.all_hunks[len(ans.all_hunks)-1].largest_line_number
	}
	return
}

func run_diff(file1, file2 string, num_of_context_lines int) (ok, is_different bool, patch string, err error) {
	// we resolve symlinks because git diff does not follow symlinks, while diff
	// does. We want consistent behavior, also for integration with git difftool
	// we always want symlinks to be followed.
	path1, err := filepath.EvalSymlinks(file1)
	if err != nil {
		return
	}
	path2, err := filepath.EvalSymlinks(file2)
	if err != nil {
		return
	}
	if len(diff_cmd) == 0 {
		data1, err := data_for_path(path1)
		if err != nil {
			return false, false, "", err
		}
		data2, err := data_for_path(path2)
		if err != nil {
			return false, false, "", err
		}
		patchb := Diff(path1, data1, path2, data2, num_of_context_lines)
		if patchb == nil {
			return true, false, "", nil
		}
		return true, len(patchb) > 0, utils.UnsafeBytesToString(patchb), nil
	} else {
		context := strconv.Itoa(num_of_context_lines)
		cmd := utils.Map(func(x string) string {
			return strings.ReplaceAll(x, "_CONTEXT_", context)
		}, diff_cmd)

		cmd = append(cmd, path1, path2)
		c := exec.Command(cmd[0], cmd[1:]...)
		stdout, stderr := bytes.Buffer{}, bytes.Buffer{}
		c.Stdout, c.Stderr = &stdout, &stderr
		err = c.Run()
		if err != nil {
			var e *exec.ExitError
			if errors.As(err, &e) && e.ExitCode() == 1 {
				return true, true, stdout.String(), nil
			}
			return false, false, stderr.String(), err
		}
		return true, false, stdout.String(), nil
	}
}

func do_diff(file1, file2 string, context_count int) (ans *Patch, err error) {
	ok, _, raw, err := run_diff(file1, file2, context_count)
	if !ok {
		return nil, fmt.Errorf("Failed to diff %s vs. %s with errors:\n%s", file1, file2, raw)
	}
	if err != nil {
		return
	}
	left_lines, err := lines_for_path(file1)
	if err != nil {
		return
	}
	right_lines, err := lines_for_path(file2)
	if err != nil {
		return
	}
	ans, err = parse_patch(raw, left_lines, right_lines)
	return
}

type diff_job struct{ file1, file2 string }

func diff(jobs []diff_job, context_count int) (ans map[string]*Patch, err error) {
	ans = make(map[string]*Patch)
	ctx := images.Context{}
	type result struct {
		file1, file2 string
		err          error
		patch        *Patch
	}
	results := make(chan result, len(jobs))
	if err := ctx.SafeParallel(0, len(jobs), func(nums <-chan int) {
		for i := range nums {
			job := jobs[i]
			r := result{file1: job.file1, file2: job.file2}
			r.patch, r.err = do_diff(job.file1, job.file2, context_count)
			results <- r
		}
	}); err != nil {
		panic(err)
	}
	close(results)
	for r := range results {
		if r.err != nil {
			return nil, r.err
		}
		ans[r.file1] = r.patch
	}
	return ans, nil
}