-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_diff.go
More file actions
769 lines (723 loc) · 18.9 KB
/
task_diff.go
File metadata and controls
769 lines (723 loc) · 18.9 KB
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"unicode/utf8"
)
type diffOptions struct {
leftPath string
rightPath string
viewer bool
summaryOnly bool
context int
ignoreWhitespace bool
ignoreEOL bool
wordDiff bool
noColor bool
}
type diffOpKind int
const (
diffEqual diffOpKind = iota
diffDelete
diffAdd
)
type diffOp struct {
kind diffOpKind
leftNo int
rightNo int
text string
}
type diffBlock struct {
start int
end int
}
// jotDiff is the direct command entry point for local text diffs.
func jotDiff(w io.Writer, args []string) error {
return jotDiffWithInput(os.Stdin, w, args, os.Getwd)
}
func jotDiffWithInput(stdin io.Reader, w io.Writer, args []string, getwd func() (string, error)) error {
opts, helpRequested, err := parseDiffArgs(args)
if err != nil {
return err
}
if helpRequested {
_, writeErr := io.WriteString(w, renderDiffHelp(isTTY(w)))
return writeErr
}
cwd, err := getwd()
if err != nil {
return err
}
return executeDiff(stdin, w, cwd, opts)
}
func renderDiffHelp(color bool) string {
style := helpStyler{color: color}
var b strings.Builder
writeHelpHeader(&b, style, "jot diff", "Compare two local text files from the terminal.")
writeUsageSection(&b, style, []string{
"jot diff before.txt after.txt",
"jot diff before.txt after.txt --viewer",
"jot diff before.txt after.txt --summary-only",
}, []string{
"`jot diff` rejects binary files and stays local.",
"`--viewer` renders a detailed terminal diff instead of opening a browser.",
})
writeFlagSection(&b, style, []helpFlag{
{name: "--viewer", description: "Show the detailed local diff render after the summary."},
{name: "--summary-only", description: "Skip the detailed render and print only the terminal summary."},
{name: "--context N", description: "Show N context lines around each changed block."},
{name: "--ignore-whitespace", description: "Treat whitespace-only changes as unchanged."},
{name: "--ignore-eol", description: "Treat line-ending differences as unchanged."},
{name: "--word-diff", description: "Show inline word changes inside modified lines."},
{name: "--no-color", description: "Force plain text output."},
})
writeExamplesSection(&b, style, []string{
"jot diff README.md README.new.md",
"jot diff before.txt after.txt --viewer",
"jot task diff",
})
return b.String()
}
func renderTaskDiffHelp(color bool) string {
style := helpStyler{color: color}
var b strings.Builder
writeHelpHeader(&b, style, "jot task", "Discover and run terminal-first tasks without leaving the current folder.")
writeUsageSection(&b, style, []string{
"jot task",
"jot task diff",
}, []string{
"`jot task` is the guided front door for jot's task layer.",
"`jot task diff` keeps the current terminal UI and teaches the direct command after the first run.",
})
writeExamplesSection(&b, style, []string{
"jot task",
"jot task diff",
"jot diff before.txt after.txt --viewer",
})
return b.String()
}
func parseDiffArgs(args []string) (diffOptions, bool, error) {
opts := diffOptions{context: 3, ignoreEOL: true}
var positional []string
for i := 0; i < len(args); i++ {
arg := strings.TrimSpace(args[i])
if arg == "" {
continue
}
if isHelpFlag(arg) {
return opts, true, nil
}
if strings.HasPrefix(arg, "--") || strings.HasPrefix(arg, "-") {
name, value, hasValue := strings.Cut(arg, "=")
switch name {
case "--viewer":
opts.viewer = true
case "--summary-only":
opts.summaryOnly = true
case "--ignore-whitespace":
opts.ignoreWhitespace = true
case "--ignore-eol":
opts.ignoreEOL = true
case "--word-diff":
opts.wordDiff = true
case "--no-color":
opts.noColor = true
case "--context":
if !hasValue {
if i+1 >= len(args) {
return opts, false, fmt.Errorf("missing value for %s", name)
}
i++
value = args[i]
}
context, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil || context < 0 {
return opts, false, errors.New("--context must be a non-negative integer")
}
opts.context = context
default:
return opts, false, fmt.Errorf("unknown flag %q", arg)
}
continue
}
positional = append(positional, arg)
}
if opts.viewer && opts.summaryOnly {
return opts, false, errors.New("--viewer cannot be combined with --summary-only")
}
if len(positional) != 2 {
return opts, false, errors.New("usage: jot diff <left-path> <right-path>")
}
opts.leftPath = positional[0]
opts.rightPath = positional[1]
return opts, false, nil
}
func executeDiff(stdin io.Reader, w io.Writer, cwd string, opts diffOptions) error {
_ = stdin
leftPath, err := resolveDiffPath(cwd, opts.leftPath)
if err != nil {
return err
}
rightPath, err := resolveDiffPath(cwd, opts.rightPath)
if err != nil {
return err
}
if samePath(leftPath, rightPath) {
return errors.New("cannot diff the same file against itself")
}
leftDoc, err := loadDiffDocument(leftPath, opts.ignoreEOL)
if err != nil {
return err
}
rightDoc, err := loadDiffDocument(rightPath, opts.ignoreEOL)
if err != nil {
return err
}
ui := newTermUI(w)
if opts.noColor {
ui.color = false
}
result := buildDiffResult(leftDoc, rightDoc, opts)
renderDiffSummary(w, ui, result)
if opts.viewer && !opts.summaryOnly {
if _, err := fmt.Fprintln(w, ""); err != nil {
return err
}
return renderDiffViewer(w, ui, result, opts)
}
return nil
}
func runDiffTask(stdin io.Reader, w io.Writer, dir string) error {
ui := newTermUI(w)
reader := bufio.NewReader(stdin)
if _, err := fmt.Fprint(w, ui.header("Diff")); err != nil {
return err
}
if _, err := fmt.Fprint(w, ui.sectionLabel("files")); err != nil {
return err
}
files, err := listDiffFiles(dir)
if err != nil {
return err
}
for i, item := range files {
if _, err := fmt.Fprintln(w, ui.listItem(i+1, filepath.Base(item), "", "")); err != nil {
return err
}
}
if _, err := fmt.Fprintln(w, ""); err != nil {
return err
}
leftPath, err := promptDiffPath(reader, w, ui, dir, "Left file", files)
if err != nil {
return err
}
rightPath, err := promptDiffPath(reader, w, ui, dir, "Right file", files)
if err != nil {
return err
}
viewer := false
wordDiff := false
context := 3
if _, err := fmt.Fprint(w, ui.sectionLabel("options")); err != nil {
return err
}
advanced, err := promptLine(reader, w, ui.styledPrompt("Advanced settings", "y/N"))
if err != nil {
return err
}
if strings.EqualFold(strings.TrimSpace(advanced), "y") || strings.EqualFold(strings.TrimSpace(advanced), "yes") {
viewerSel, err := promptLine(reader, w, ui.styledPrompt("Show detailed render", "y/N"))
if err != nil {
return err
}
viewer = strings.EqualFold(strings.TrimSpace(viewerSel), "y") || strings.EqualFold(strings.TrimSpace(viewerSel), "yes")
wordSel, err := promptLine(reader, w, ui.styledPrompt("Enable word diff", "y/N"))
if err != nil {
return err
}
wordDiff = strings.EqualFold(strings.TrimSpace(wordSel), "y") || strings.EqualFold(strings.TrimSpace(wordSel), "yes")
contextSel, err := promptLine(reader, w, ui.styledPrompt("Context lines", "3"))
if err != nil {
return err
}
if strings.TrimSpace(contextSel) != "" {
parsed, parseErr := strconv.Atoi(strings.TrimSpace(contextSel))
if parseErr != nil || parsed < 0 {
return errors.New("context lines must be a non-negative integer")
}
context = parsed
}
}
opts := diffOptions{
leftPath: leftPath,
rightPath: rightPath,
viewer: viewer,
context: context,
wordDiff: wordDiff,
noColor: false,
ignoreEOL: true,
summaryOnly: false,
}
if err := executeDiff(nil, w, dir, opts); err != nil {
return err
}
if _, err := fmt.Fprintln(w, ui.tip(fmt.Sprintf("next time: jot diff %s %s%s", filepath.Base(leftPath), filepath.Base(rightPath), diffTipSuffix(opts)))); err != nil {
return err
}
_, err = fmt.Fprintln(w, "")
return err
}
func diffTipSuffix(opts diffOptions) string {
var parts []string
if opts.viewer {
parts = append(parts, "--viewer")
}
if opts.wordDiff {
parts = append(parts, "--word-diff")
}
if opts.context != 3 {
parts = append(parts, fmt.Sprintf("--context %d", opts.context))
}
if len(parts) == 0 {
return ""
}
return " " + strings.Join(parts, " ")
}
type diffDocument struct {
path string
name string
display []string
compare []string
original string
isText bool
}
func loadDiffDocument(path string, ignoreEOL bool) (diffDocument, error) {
info, err := os.Stat(path)
if err != nil {
return diffDocument{}, err
}
if info.IsDir() {
return diffDocument{}, fmt.Errorf("%s is a directory, expected a text file", path)
}
data, err := os.ReadFile(path)
if err != nil {
return diffDocument{}, err
}
if !isDiffTextBytes(data) {
return diffDocument{}, fmt.Errorf("%s is binary and outside the text diff scope", path)
}
text := normalizeDiffContent(string(data), ignoreEOL)
display := splitDiffLines(text)
compare := make([]string, len(display))
for i, line := range display {
compare[i] = normalizeDiffCompareLine(line, false)
}
return diffDocument{
path: path,
name: filepath.Base(path),
display: display,
compare: compare,
original: text,
isText: true,
}, nil
}
func isDiffTextBytes(data []byte) bool {
if bytes.IndexByte(data, 0) >= 0 {
return false
}
return utf8.Valid(data)
}
func normalizeDiffContent(text string, ignoreEOL bool) string {
text = stripUTF8BOM(text)
if ignoreEOL {
text = strings.ReplaceAll(text, "\r\n", "\n")
text = strings.ReplaceAll(text, "\r", "\n")
}
return text
}
func splitDiffLines(text string) []string {
if text == "" {
return nil
}
if strings.HasSuffix(text, "\n") {
text = strings.TrimSuffix(text, "\n")
}
if text == "" {
return []string{""}
}
return strings.Split(text, "\n")
}
func normalizeDiffCompareLine(line string, ignoreWhitespace bool) string {
if !ignoreWhitespace {
return line
}
fields := strings.Fields(line)
return strings.Join(fields, " ")
}
type diffResult struct {
left diffDocument
right diffDocument
ops []diffOp
additions int
deletions int
hunks int
}
func buildDiffResult(left, right diffDocument, opts diffOptions) diffResult {
leftKeys := make([]string, len(left.display))
for i, line := range left.display {
leftKeys[i] = normalizeDiffCompareLine(line, opts.ignoreWhitespace)
}
rightKeys := make([]string, len(right.display))
for i, line := range right.display {
rightKeys[i] = normalizeDiffCompareLine(line, opts.ignoreWhitespace)
}
ops := buildDiffOps(leftKeys, rightKeys, left.display, right.display)
additions := 0
deletions := 0
hunks := 0
inHunk := false
for _, op := range ops {
switch op.kind {
case diffAdd:
additions++
if !inHunk {
hunks++
inHunk = true
}
case diffDelete:
deletions++
if !inHunk {
hunks++
inHunk = true
}
default:
inHunk = false
}
}
return diffResult{left: left, right: right, ops: ops, additions: additions, deletions: deletions, hunks: hunks}
}
func buildDiffOps(leftKeys, rightKeys, leftLines, rightLines []string) []diffOp {
n := len(leftKeys)
m := len(rightKeys)
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := n - 1; i >= 0; i-- {
for j := m - 1; j >= 0; j-- {
if leftKeys[i] == rightKeys[j] {
dp[i][j] = dp[i+1][j+1] + 1
continue
}
if dp[i+1][j] >= dp[i][j+1] {
dp[i][j] = dp[i+1][j]
} else {
dp[i][j] = dp[i][j+1]
}
}
}
var ops []diffOp
i, j := 0, 0
for i < n || j < m {
switch {
case i < n && j < m && leftKeys[i] == rightKeys[j]:
ops = append(ops, diffOp{
kind: diffEqual,
leftNo: i + 1,
rightNo: j + 1,
text: leftLines[i],
})
i++
j++
case j < m && (i == n || dp[i][j+1] >= dp[i+1][j]):
ops = append(ops, diffOp{
kind: diffAdd,
leftNo: 0,
rightNo: j + 1,
text: rightLines[j],
})
j++
default:
ops = append(ops, diffOp{
kind: diffDelete,
leftNo: i + 1,
rightNo: 0,
text: leftLines[i],
})
i++
}
}
return ops
}
func renderDiffSummary(w io.Writer, ui termUI, result diffResult) {
if result.additions == 0 && result.deletions == 0 {
_, _ = fmt.Fprintln(w, ui.success(fmt.Sprintf("%s and %s are identical", result.left.name, result.right.name)))
return
}
_, _ = fmt.Fprintln(w, ui.listItem(1, "files", fmt.Sprintf("%s -> %s", result.left.name, result.right.name), ""))
_, _ = fmt.Fprintln(w, ui.listItem(2, "summary", fmt.Sprintf("+%d -%d %d hunk(s)", result.additions, result.deletions, result.hunks), ""))
}
func renderDiffViewer(w io.Writer, ui termUI, result diffResult, opts diffOptions) error {
if _, err := fmt.Fprint(w, ui.header("Diff Viewer")); err != nil {
return err
}
if _, err := fmt.Fprint(w, ui.sectionLabel("summary")); err != nil {
return err
}
if _, err := fmt.Fprintf(w, " %s -> %s\n", result.left.name, result.right.name); err != nil {
return err
}
if _, err := fmt.Fprintf(w, " +%d -%d %d hunk(s)\n", result.additions, result.deletions, result.hunks); err != nil {
return err
}
if result.additions == 0 && result.deletions == 0 {
return nil
}
if _, err := fmt.Fprint(w, ui.sectionLabel("diff")); err != nil {
return err
}
for _, block := range diffBlocks(result.ops, opts.context) {
if _, err := fmt.Fprintf(w, "%s\n", ui.tdim(fmt.Sprintf("@@ block %d-%d @@", block.start+1, block.end))); err != nil {
return err
}
for i := block.start; i < block.end; {
op := result.ops[i]
if opts.wordDiff && i+1 < block.end {
next := result.ops[i+1]
switch {
case op.kind == diffDelete && next.kind == diffAdd:
oldMarked, newMarked := diffWordMarkup(op.text, next.text)
if _, err := fmt.Fprintln(w, renderDiffLine(ui, diffDelete, op.leftNo, 0, oldMarked)); err != nil {
return err
}
if _, err := fmt.Fprintln(w, renderDiffLine(ui, diffAdd, 0, next.rightNo, newMarked)); err != nil {
return err
}
i += 2
continue
case op.kind == diffAdd && next.kind == diffDelete:
oldMarked, newMarked := diffWordMarkup(next.text, op.text)
if _, err := fmt.Fprintln(w, renderDiffLine(ui, diffDelete, next.leftNo, 0, oldMarked)); err != nil {
return err
}
if _, err := fmt.Fprintln(w, renderDiffLine(ui, diffAdd, 0, op.rightNo, newMarked)); err != nil {
return err
}
i += 2
continue
}
}
if _, err := fmt.Fprintln(w, renderDiffLine(ui, op.kind, op.leftNo, op.rightNo, op.text)); err != nil {
return err
}
i++
}
if _, err := fmt.Fprintln(w, ""); err != nil {
return err
}
}
return nil
}
func diffBlocks(ops []diffOp, context int) []diffBlock {
if len(ops) == 0 {
return nil
}
var raw []diffBlock
for i := 0; i < len(ops); {
if ops[i].kind == diffEqual {
i++
continue
}
start := i
for start > 0 && ops[start-1].kind == diffEqual && i-start < context {
start--
}
end := i
for end < len(ops) && ops[end].kind != diffEqual {
end++
}
after := end
for after < len(ops) && ops[after].kind == diffEqual && after-end < context {
after++
}
raw = append(raw, diffBlock{start: start, end: after})
i = after
}
if len(raw) == 0 {
return nil
}
merged := []diffBlock{raw[0]}
for _, block := range raw[1:] {
last := &merged[len(merged)-1]
if block.start <= last.end {
if block.end > last.end {
last.end = block.end
}
continue
}
merged = append(merged, block)
}
return merged
}
func renderDiffLine(ui termUI, kind diffOpKind, leftNo, rightNo int, text string) string {
left := diffNumber(leftNo)
right := diffNumber(rightNo)
prefix := " "
switch kind {
case diffDelete:
prefix = "-"
if ui.color {
prefix = ui.tmagenta("-")
}
case diffAdd:
prefix = "+"
if ui.color {
prefix = ui.tgreen("+")
}
default:
if ui.color {
prefix = ui.tdim(" ")
}
}
return fmt.Sprintf(" %s %s %s %s", prefix, left, right, text)
}
func diffNumber(n int) string {
if n <= 0 {
return " "
}
return fmt.Sprintf("%3d", n)
}
func diffWordMarkup(oldLine, newLine string) (string, string) {
oldTokens := strings.Fields(oldLine)
newTokens := strings.Fields(newLine)
type tokenOp int
const (
tokenEqual tokenOp = iota
tokenDelete
tokenAdd
)
type tokenStep struct {
op tokenOp
text string
}
n := len(oldTokens)
m := len(newTokens)
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := n - 1; i >= 0; i-- {
for j := m - 1; j >= 0; j-- {
if oldTokens[i] == newTokens[j] {
dp[i][j] = dp[i+1][j+1] + 1
continue
}
if dp[i+1][j] >= dp[i][j+1] {
dp[i][j] = dp[i+1][j]
} else {
dp[i][j] = dp[i][j+1]
}
}
}
var oldParts []string
var newParts []string
i, j := 0, 0
for i < n || j < m {
switch {
case i < n && j < m && oldTokens[i] == newTokens[j]:
oldParts = append(oldParts, oldTokens[i])
newParts = append(newParts, newTokens[j])
i++
j++
case j < m && (i == n || dp[i][j+1] >= dp[i+1][j]):
newParts = append(newParts, "{+"+newTokens[j]+"+}")
j++
default:
oldParts = append(oldParts, "[-"+oldTokens[i]+"-]")
i++
}
}
return strings.Join(oldParts, " "), strings.Join(newParts, " ")
}
func resolveDiffPath(cwd, input string) (string, error) {
input = strings.TrimSpace(input)
if input == "" {
return "", errors.New("path must be provided")
}
if !filepath.IsAbs(input) {
input = filepath.Join(cwd, input)
}
return filepath.Abs(input)
}
func promptDiffPath(reader *bufio.Reader, w io.Writer, ui termUI, dir, label string, files []string) (string, error) {
hint := ""
if len(files) > 0 {
hint = "1"
}
selection, err := promptLine(reader, w, ui.styledPrompt(label, hint))
if err != nil {
return "", err
}
if selection == "" {
if len(files) == 0 {
return "", errors.New("file path must be provided")
}
return "", fmt.Errorf("%s must be provided", strings.ToLower(label))
}
if idx, parseErr := strconv.Atoi(selection); parseErr == nil {
if idx < 1 || idx > len(files) {
return "", fmt.Errorf("file selection must be between 1 and %d", len(files))
}
return files[idx-1], nil
}
if !filepath.IsAbs(selection) {
selection = filepath.Join(dir, selection)
}
return selection, nil
}
func listDiffFiles(dir string) ([]string, error) {
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
var files []string
for _, entry := range entries {
if entry.IsDir() {
continue
}
if !isDiffTextCandidate(entry.Name()) {
continue
}
files = append(files, filepath.Join(dir, entry.Name()))
}
sort.Strings(files)
return files, nil
}
func isDiffTextCandidate(name string) bool {
switch strings.ToLower(filepath.Ext(name)) {
case ".md", ".markdown", ".txt", ".log", ".json", ".jsonl", ".xml", ".yaml", ".yml", ".toml", ".csv", ".env":
return true
default:
return false
}
}
func samePath(a, b string) bool {
aa, errA := filepath.Abs(a)
if errA != nil {
aa = filepath.Clean(a)
}
bb, errB := filepath.Abs(b)
if errB != nil {
bb = filepath.Clean(b)
}
return strings.EqualFold(aa, bb)
}