delta-gitu 0.1.3

An experimental fork of gitu (a git client inspired by Magit), published as a library for delta to embed
Documentation
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
//! Which ops a piped patch admits.
//!
//! There is no such thing as staging a line of `git show HEAD`: that patch is a
//! committed change, and applying part of it to the index is cherry-picking.
//! git tells its pager nothing about the command that produced the patch, so
//! gitu finds it in the process tree; what it finds is what the patch is.

use super::*;
use crate::{app::App, ops::Op};

#[test]
fn a_working_tree_patch_admits_stage_and_not_unstage() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\ntesttest\n");
    fs::write(ctx.dir.join("firstfile"), "changed\ntesttest\n").unwrap();

    // git colours what it writes to its pager; the command survives that.
    let mut app = ctx.init_app_as_pager_of(&["git", "-c", "color.diff=always", "diff"]);
    ctx.update(&mut app, keys("j"));

    assert!(offers(&app, Op::Stage));
    assert!(!offers(&app, Op::Unstage));
}

#[test]
fn an_index_patch_admits_unstage_and_not_stage() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\ntesttest\n");
    fs::write(ctx.dir.join("firstfile"), "changed\ntesttest\n").unwrap();
    run(&ctx.dir, &["git", "add", "firstfile"]);

    let mut app = ctx.init_app_as_pager_of(&["git", "diff", "--cached"]);
    ctx.update(&mut app, keys("j"));

    assert!(offers(&app, Op::Unstage));
    assert!(!offers(&app, Op::Stage));
}

#[test]
fn a_commit_patch_admits_neither() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\ntesttest\n");

    let mut app = ctx.init_app_as_pager_of(&["git", "show", "HEAD"]);
    ctx.update(&mut app, keys("j"));

    assert!(!offers(&app, Op::Stage));
    assert!(!offers(&app, Op::Unstage));
}

#[test]
fn staging_a_hunk_of_a_piped_working_tree_patch_stages_it() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\ntesttest\n");
    fs::write(ctx.dir.join("firstfile"), "changed\ntesttest\n").unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys("js"));

    assert!(run(&ctx.dir, &["git", "diff", "--cached"]).contains("+changed"));
}

/// A patch recognised as the working tree is the working tree, so staging from
/// it leaves the view showing what is still unstaged — as the status screen
/// does. A view that keeps offering a change it has already staged is lying.
#[test]
fn a_staged_hunk_leaves_the_view_it_was_staged_from() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\ntesttest\n");
    fs::write(ctx.dir.join("firstfile"), "changed\ntesttest\n").unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys("js"));

    assert!(
        !ctx.redact_buffer().contains("changed"),
        "the staged line is still on screen:\n{}",
        ctx.redact_buffer()
    );
}

fn twenty_lines(tenth: &str) -> String {
    (1..=20)
        .map(|i| {
            if i == 10 {
                format!("{tenth}\n")
            } else {
                format!("line {i}\n")
            }
        })
        .collect()
}

/// A diff gitu can ask git for again can be asked for differently: the context
/// around a change is a property of the question, not of the answer.
#[test]
fn widening_the_context_asks_git_for_more_of_the_file() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", &twenty_lines("line 10"));
    fs::write(ctx.dir.join("firstfile"), twenty_lines("changed")).unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    assert!(
        !ctx.redact_buffer().contains("line 2 "),
        "three lines of context already reach line 2"
    );

    ctx.update(&mut app, keys("U8<enter>"));

    assert!(
        ctx.redact_buffer().contains("line 2 "),
        "the diff was not re-asked for:\n{}",
        ctx.redact_buffer()
    );
}

/// A commit's patch says which commit it is, so gitu can ask git for it again
/// — and ask differently. This is the case that matters for reading a commit
/// someone else wrote.
#[test]
fn widening_the_context_of_a_piped_commit() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", &twenty_lines("line 10"));
    commit(&ctx.dir, "firstfile", &twenty_lines("changed"));

    let mut app = ctx.init_app_as_pager_of(&["git", "show", "HEAD"]);
    assert!(!ctx.redact_buffer().contains("line 2 "));

    ctx.update(&mut app, keys("U8<enter>"));

    assert!(
        ctx.redact_buffer().contains("line 2 "),
        "the commit was not re-asked for:\n{}",
        ctx.redact_buffer()
    );
}

/// The key already said what is being set, so the prompt says nothing at all:
/// a line to type on, and no words explaining it every time.
#[test]
fn the_context_prompt_says_nothing() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", &twenty_lines("line 10"));
    fs::write(ctx.dir.join("firstfile"), twenty_lines("changed")).unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);

    ctx.update(&mut app, keys("U"));

    let buffer = ctx.redact_buffer();
    assert!(!buffer.contains('\u{203a}'), "{buffer}");
    assert!(!buffer.contains("Context"), "{buffer}");
    assert!(!buffer.contains("default"), "{buffer}");
}

/// The whole function is the other thing worth asking for, and is a letter
/// rather than a number.
#[test]
fn the_whole_function_is_asked_for_by_letter() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", &twenty_lines("line 10"));
    fs::write(ctx.dir.join("firstfile"), twenty_lines("changed")).unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);

    ctx.update(&mut app, keys("UW<enter>"));

    assert_eq!(app.state.context.as_deref(), Some("-W"));
}

/// Every property of a view is in the command it is the output of, so the
/// command itself is what is offered for editing — prefilled, and with nothing
/// said about it.
#[test]
fn the_command_is_offered_for_editing_as_it_is_being_asked() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", &twenty_lines("line 10"));
    fs::write(ctx.dir.join("firstfile"), twenty_lines("changed")).unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "-c", "color.diff=always", "diff"]);
    ctx.update(&mut app, keys("U8<enter>:"));

    let buffer = ctx.redact_buffer();
    assert!(
        buffer.contains("git -c color.diff=always diff -U8"),
        "{buffer}"
    );
}

/// The edit is a different question, so the answer is a different view: what
/// the patch is a diff of has changed, and with it which ops mean anything.
#[test]
fn editing_the_command_asks_the_new_question() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\ntesttest\n");
    fs::write(ctx.dir.join("firstfile"), "changed\ntesttest\n").unwrap();
    run(&ctx.dir, &["git", "add", "firstfile"]);
    fs::write(ctx.dir.join("firstfile"), "changed\nagain\n").unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys("j"));
    assert!(offers(&app, Op::Stage));
    assert!(ctx.redact_buffer().contains("+again"));

    ctx.update(&mut app, keys(": --cached<enter>j"));

    assert!(offers(&app, Op::Unstage));
    let buffer = ctx.redact_buffer();
    assert!(buffer.contains("+changed"), "{buffer}");
    assert!(!buffer.contains("+again"), "{buffer}");
}

/// The line handed over says what context it is asking for, so accepting it
/// keeps that: the command is the whole of what the view is, and the session's
/// own context override is spent.
#[test]
fn an_edit_takes_over_the_context_asked_for() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", &twenty_lines("line 10"));
    fs::write(ctx.dir.join("firstfile"), twenty_lines("changed")).unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys("U8<enter>:<enter>"));

    assert_eq!(app.state.context, None);
    assert!(
        ctx.redact_buffer().contains("line 2 "),
        "the widened context was lost:\n{}",
        ctx.redact_buffer()
    );
}

/// A command the user can edit is one the user can get wrong. git says what it
/// thought of it, and the view it could not answer stays as it was.
#[test]
fn a_command_git_refuses_says_so_and_changes_nothing() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\ntesttest\n");
    fs::write(ctx.dir.join("firstfile"), "changed\ntesttest\n").unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys(": --nonsense<enter>"));

    let buffer = ctx.redact_buffer();
    assert!(buffer.contains("invalid option: --nonsense"), "{buffer}");
    assert!(buffer.contains("+changed"), "{buffer}");
}

/// The editing keys reach the line being edited, rather than the view behind
/// it: `ctrl+w` in a prompt takes back a word, and does not scroll.
#[test]
fn a_command_can_be_edited_with_the_readline_keys() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\n");
    fs::write(ctx.dir.join("firstfile"), "changed\n").unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff", "--cached"]);
    ctx.update(&mut app, keys(":<ctrl+w>"));

    let buffer = ctx.redact_buffer();
    assert!(buffer.contains("git diff "), "{buffer}");
    assert!(!buffer.contains("--cached"), "{buffer}");
}

/// The cursor is drawn where the next character will land. A line that shows
/// it at the end while typing inserts in the middle is unusable.
#[test]
fn the_cursor_is_drawn_at_the_insertion_point() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\n");
    fs::write(ctx.dir.join("firstfile"), "changed\n").unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);

    // A prompt left open by one batch of keys is abandoned before the next, so
    // each of these is a fresh prompt typed into from the start.
    ctx.update(&mut app, keys(":"));
    assert_eq!(ctx.prompt_line(), "git diff|");

    ctx.update(&mut app, keys(":<ctrl+a>"));
    assert_eq!(ctx.prompt_line(), "|git diff");

    ctx.update(&mut app, keys(":<ctrl+a><alt+f>"));
    assert_eq!(ctx.prompt_line(), "git| diff");

    ctx.update(&mut app, keys(":<ctrl+a><alt+f>X"));
    assert_eq!(ctx.prompt_line(), "gitX| diff");
}

/// A patch with no command behind it has no question to edit.
#[test]
fn a_patch_with_no_command_cannot_be_edited() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\ntesttest\n");

    let patch = run(&ctx.dir, &["git", "show", "HEAD"]);
    let mut app = ctx.init_app_with_patch(patch);

    ctx.update(&mut app, keys(":"));

    assert!(
        ctx.redact_buffer()
            .contains("not something gitu asked git for"),
        "{}",
        ctx.redact_buffer()
    );
}

/// Two files whose contents say which is which, so that a view can be asserted
/// to have dropped one of them without reading its name off the row that says
/// what is being asked.
fn two_changed_files(ctx: &TestContext) {
    commit(&ctx.dir, "a.rs", "alpha\n");
    commit(&ctx.dir, "a_test.rs", "beta\n");
    fs::write(ctx.dir.join("a.rs"), "alpha changed\n").unwrap();
    fs::write(ctx.dir.join("a_test.rs"), "beta changed\n").unwrap();
}

/// A hidden file is not "diff not displayed": it is absent, as if the patch
/// never had it. What is left is a diff like any other.
#[test]
fn hiding_the_file_under_the_cursor_drops_it_from_the_view() {
    let mut ctx = setup_clone!();
    two_changed_files(&ctx);

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys("kdj"));

    let buffer = ctx.redact_buffer();
    assert!(!buffer.contains("alpha"), "{buffer}");
    assert!(buffer.contains("beta"), "{buffer}");
    assert!(offers(&app, Op::Stage));
}

/// Like `d` in the rebase list, `d` acts on the row under the cursor: within a
/// file's hunks there is no file there to drop.
#[test]
fn hiding_a_file_needs_the_cursor_on_its_header() {
    let mut ctx = setup_clone!();
    two_changed_files(&ctx);

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys("d"));

    let buffer = ctx.redact_buffer();
    assert!(buffer.contains("alpha"), "{buffer}");
    assert!(buffer.contains("beta"), "{buffer}");
}

/// The paths are the user's to say, in git's own language less the magic: a
/// bare pattern limits the view, `!` drops what it matches.
#[test]
fn the_files_to_show_can_be_said_by_pattern() {
    let mut ctx = setup_clone!();
    two_changed_files(&ctx);

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys("_!*_test.rs<enter>"));

    let buffer = ctx.redact_buffer();
    assert!(buffer.contains("alpha"), "{buffer}");
    assert!(!buffer.contains("beta"), "{buffer}");
}

/// Hiding a file is an edit of the command like any other, so it is there to
/// be read back, undone, or added to.
#[test]
fn the_files_asked_for_come_back_for_editing() {
    let mut ctx = setup_clone!();
    two_changed_files(&ctx);

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys("kd_"));
    assert!(
        ctx.redact_buffer().contains("Files: › !a.rs"),
        "{}",
        ctx.redact_buffer()
    );

    ctx.update(&mut app, keys("<enter>:"));
    assert!(
        ctx.redact_buffer()
            .contains("git diff -- ':(top,exclude)a.rs'"),
        "{}",
        ctx.redact_buffer()
    );
}

/// Commands and file patterns are two different kinds of question, and what
/// was answered before remains available after gitu itself has exited.
#[test]
fn command_and_file_histories_persist_separately() {
    let mut ctx = setup_clone!();
    two_changed_files(&ctx);

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(
        &mut app,
        keys(
            "_!a_test.rs<enter>_<ctrl+u>!a.rs<enter>\
             : HEAD<enter>:<ctrl+u>git diff --cached<enter>",
        ),
    );
    drop(app);

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys(":<up>"));
    assert_eq!(ctx.prompt_line(), "git diff --cached|");

    ctx.update(&mut app, keys("_<up>"));
    assert_eq!(ctx.prompt_line(), "? Files: › !a.rs|");

    ctx.update(&mut app, keys(":<up><up><down>"));
    assert_eq!(ctx.prompt_line(), "git diff --cached|");
}

/// Git shares one object store between linked worktrees, but prompt history is
/// about the question asked in one checkout and must not leak into another.
#[test]
fn command_history_is_scoped_to_the_worktree() {
    let mut ctx = setup_clone!();
    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys(": HEAD<enter>"));
    drop(app);

    let other = ctx.dir.parent().unwrap().join("other-worktree");
    let other_arg = other.to_str().unwrap();
    run(
        &ctx.dir,
        &["git", "worktree", "add", "-b", "other", other_arg],
    );
    let mut app = ctx.init_app_as_pager_of_at(other, &["git", "diff"]);
    ctx.update(&mut app, keys(":<up>"));

    assert_eq!(ctx.prompt_line(), "git diff|");
}

/// A view with files hidden from it must not pass for the whole patch, so a
/// question that is no longer git's own says so — in one line, and only then.
#[test]
fn a_view_that_is_not_what_git_asked_for_says_what_it_is() {
    let mut ctx = setup_clone!();
    two_changed_files(&ctx);

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    assert!(
        !ctx.redact_buffer().contains("git diff"),
        "nothing to say about git's own question:\n{}",
        ctx.redact_buffer()
    );

    ctx.update(&mut app, keys("kd"));

    assert!(
        ctx.redact_buffer()
            .contains("git diff -- ':(top,exclude)a.rs'"),
        "{}",
        ctx.redact_buffer()
    );
}

/// Folding everything leaves one folded thing, not a stack of them: opening a
/// file shows the diff inside it, rather than another thing to open.
#[test]
fn opening_a_folded_file_shows_its_diff() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\ntesttest\n");
    fs::write(ctx.dir.join("firstfile"), "changed\ntesttest\n").unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);

    ctx.update(&mut app, keys("<backtab><tab>"));

    assert!(
        ctx.redact_buffer().contains("changed"),
        "the file opened onto something still folded:\n{}",
        ctx.redact_buffer()
    );
}

/// A patch gitu found no command for — a saved file, a process already gone —
/// is not something git can be asked for again, so it stays exactly as it
/// arrived.
#[test]
fn a_patch_with_no_command_stays_as_it_arrived() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\ntesttest\n");

    let patch = run(&ctx.dir, &["git", "show", "HEAD"]);
    let mut app = ctx.init_app_with_patch(patch);

    ctx.update(&mut app, keys("g"));

    let buffer = ctx.redact_buffer();
    assert!(buffer.contains("add firstfile"), "{buffer}");
    assert!(buffer.contains("+testing"), "{buffer}");
}

/// A log rendered by something that states where each commit begins is a log,
/// not a wall of text: its commits are targets, and the ops that act on a
/// commit apply. git tells its pager nothing, so the renderer has to.
#[test]
fn a_piped_log_with_commit_records_is_navigable() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\n");
    let oid = run(&ctx.dir, &["git", "rev-parse", "HEAD"])
        .trim()
        .to_string();

    let app = ctx.init_app_with_patch(format!(
        "\x1b]1717;1\x1b\\\x1b]1717;1;C;;;{oid}\x1b\\commit {oid}\n\
         Author: Author Name <author@email.com>\n\
         \n\
         \x20   add firstfile\n"
    ));

    let item = app.state.screens.last().unwrap().get_selected_item();
    assert!(
        matches!(&item.data, crate::item_data::ItemData::Commit { oid: o, .. } if *o == oid),
        "got {:?}",
        item.data
    );
    assert!(Op::Show.implementation().get_action(&item.data).is_some());
    assert!(
        Op::CopyHash
            .implementation()
            .get_action(&item.data)
            .is_some()
    );
}

/// A renderer names the commit as git printed it, and most log formats print
/// `%h`. An id gitu cannot resolve costs more than the commit ops: the rows
/// fall back to being decoration, and the cursor cannot move at all.
#[test]
fn a_log_naming_its_commits_by_abbreviation_is_navigable() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\n");
    let short = run(&ctx.dir, &["git", "rev-parse", "--short", "HEAD"])
        .trim()
        .to_string();
    let oid = run(&ctx.dir, &["git", "rev-parse", "HEAD"])
        .trim()
        .to_string();

    let app = ctx.init_app_with_patch(format!(
        "\x1b]1717;1;C;;;{short}\x1b\\â–¸ {short} Author Name\n\
         \n\
         \x20   add firstfile\n"
    ));

    let item = app.state.screens.last().unwrap().get_selected_item();
    assert!(
        matches!(&item.data, crate::item_data::ItemData::Commit { oid: o, .. } if *o == oid),
        "got {:?}",
        item.data
    );
}

/// A view is legitimately empty: `git diff --cached` with nothing staged is no
/// bytes at all. A screen with no rows must still answer what is selected, or
/// the next keypress indexes into nothing.
#[test]
fn a_key_press_on_an_empty_view_does_nothing() {
    let mut ctx = setup_clone!();
    let mut app = ctx.init_app_with_patch(String::new());

    ctx.update(&mut app, keys("j"));
}

/// The same view, reached the other way: everything it showed has been staged.
#[test]
fn a_key_press_after_staging_everything_does_nothing() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\n");
    fs::write(ctx.dir.join("firstfile"), "changed\n").unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);

    ctx.update(&mut app, keys("jsj"));
}

/// Output gitu can find no structure in is still the renderer's to draw. Shown
/// as it arrived it would carry git's colours, and setting gitu as the pager
/// would cost the rendering of everything that is not a diff.
#[test]
fn output_with_no_structure_is_still_rendered() {
    let mut ctx = setup_clone!();
    ctx.config().general.diff_renderer.enabled = true;
    ctx.config().general.diff_renderer.command =
        ["sed", "s/^/rendered /"].map(String::from).to_vec();

    ctx.init_app_with_patch("plain output\n".to_string());

    let buffer = ctx.redact_buffer();
    assert!(buffer.contains("rendered plain output"), "{buffer}");
}

/// `/` finds rendered text, and `n`/`N` repeat in either direction. Repeating
/// past an end wraps, as it does in a pager.
#[test]
fn rendered_text_can_be_searched() {
    let mut ctx = setup_clone!();
    let mut app = ctx.init_app_with_patch("start\nmatch one\nmiddle\nmatch two\n".to_owned());

    ctx.update(&mut app, keys("/match<enter>"));
    assert_eq!(selected_rendered_row(&app), "match one");

    ctx.update(&mut app, keys("n"));
    assert_eq!(selected_rendered_row(&app), "match two");

    ctx.update(&mut app, keys("n"));
    assert_eq!(selected_rendered_row(&app), "match one");

    ctx.update(&mut app, keys("N"));
    assert_eq!(selected_rendered_row(&app), "match two");
}

/// Search patterns are regular expressions over the renderer's visible text,
/// not over its ANSI control sequences.
#[test]
fn search_is_a_regex_over_rendered_text() {
    let mut ctx = setup_clone!();
    let mut app = ctx
        .init_app_with_patch("\x1b[31mfirst needle\x1b[0m\nsecond needle\nnot this\n".to_owned());

    ctx.update(&mut app, keys(r"/^second .*le$<enter>"));

    assert_eq!(selected_rendered_row(&app), "second needle");
}

/// Folding changes presentation, not what the buffer contains: searching for
/// a hidden row opens its containing sections and lands on it.
#[test]
fn search_reveals_a_match_inside_a_fold() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "before\n");
    fs::write(ctx.dir.join("firstfile"), "changed\n").unwrap();
    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);

    ctx.update(&mut app, keys("<backtab>/changed<enter>"));

    assert!(
        matches!(
            app.screen().get_selected_item().data,
            crate::item_data::ItemData::HunkLine { .. }
        ),
        "search did not land on the changed line"
    );
    assert!(ctx.redact_buffer().contains("+changed"));
}

fn selected_rendered_row(app: &App) -> String {
    app.screen()
        .get_selected_item()
        .rendered
        .as_ref()
        .map(|row| {
            row.iter()
                .map(|(text, _)| crate::ui::display_text(text))
                .collect()
        })
        .unwrap_or_default()
}

/// And rendering it is what makes a log a log: git hands its pager an unmarked
/// wall of text, and the renderer is what says where each commit begins. So
/// gitu needs no pipeline in front of it, only its own renderer.
#[test]
fn a_raw_log_becomes_a_log_view_when_the_renderer_marks_commits() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\n");
    let oid = run(&ctx.dir, &["git", "rev-parse", "HEAD"])
        .trim()
        .to_string();

    ctx.config().general.diff_renderer.enabled = true;
    ctx.config().general.diff_renderer.command = [
        "awk",
        r#"/^commit /{printf "\033]1717;1;C;;;%s\033\\", $2} {print}"#,
    ]
    .map(String::from)
    .to_vec();

    let app = ctx.init_app_with_patch(run(&ctx.dir, &["git", "log"]));

    let item = app.state.screens.last().unwrap().get_selected_item();
    assert!(
        matches!(&item.data, crate::item_data::ItemData::Commit { oid: o, .. } if *o == oid),
        "got {:?}",
        item.data
    );
}

/// A commit whose message is taller than the screen leaves a run of rows with
/// nothing to select on it that is longer than a page. Paging into that run
/// must not be pulled back onto the commit above it: holding space reaches the
/// end of the stream.
#[test]
fn paging_past_a_commit_taller_than_the_screen_reaches_the_end() {
    let mut ctx = setup_clone!();
    let body = (1..=30).fold(String::new(), |mut acc, i| {
        use std::fmt::Write as _;

        writeln!(acc, "body line {i}").unwrap();
        acc
    });
    fs::write(ctx.dir.join("tallfile"), "testing\n").unwrap();
    run(&ctx.dir, &["git", "add", "tallfile"]);
    run(
        &ctx.dir,
        &["git", "commit", "-m", &format!("a tall commit\n\n{body}")],
    );

    ctx.config().general.diff_renderer.enabled = true;
    ctx.config().general.diff_renderer.command = [
        "awk",
        r#"/^commit /{printf "\033]1717;1;C;;;%s\033\\", $2} {print}"#,
    ]
    .map(String::from)
    .to_vec();

    let mut app = ctx.init_app_with_patch(run(&ctx.dir, &["git", "log"]));
    ctx.update(&mut app, keys(&"<space>".repeat(10)));

    let buffer = ctx.redact_buffer();
    assert!(
        buffer.contains("add initial-file"),
        "paging stalled before the end:\n{buffer}"
    );
}

/// A context line carries no change, so by default the cursor passes over it:
/// every line-level op needs something to act on.
#[test]
fn context_lines_are_not_visited_by_default() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "one\ntwo\nthree\n");
    fs::write(ctx.dir.join("firstfile"), "one\nCHANGED\nthree\n").unwrap();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys("<ctrl+j>"));

    assert_eq!(selected_hunk_line(&app), Some(1));
}

/// Reading a patch is line-by-line, and skipping the unchanged lines makes the
/// cursor jump. `visit_context_lines` stops on all of them.
#[test]
fn context_lines_are_visited_when_configured() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "one\ntwo\nthree\n");
    fs::write(ctx.dir.join("firstfile"), "one\nCHANGED\nthree\n").unwrap();
    ctx.config().general.visit_context_lines = true;

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);

    for line_i in 0..4 {
        ctx.update(&mut app, keys("<ctrl+j>"));
        assert_eq!(selected_hunk_line(&app), Some(line_i));
    }
}

/// And the renderer's rows are the same lines, so the cursor stops on the same
/// ones.
#[test]
fn rendered_context_lines_are_visited_when_configured() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "one\ntwo\nthree\n");
    fs::write(ctx.dir.join("firstfile"), "one\nCHANGED\nthree\n").unwrap();
    ctx.config().general.visit_context_lines = true;
    ctx.config().general.diff_renderer.enabled = true;
    ctx.config().general.diff_renderer.command = osc_1717_passthrough();

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);

    for line_i in 0..4 {
        ctx.update(&mut app, keys("<ctrl+j>"));
        assert_eq!(selected_hunk_line(&app), Some(line_i));
    }
}

/// A renderer that changes nothing but speaks the protocol, so its rows carry
/// the metadata that makes them content lines rather than plain text.
fn osc_1717_passthrough() -> Vec<String> {
    [
        "awk",
        r#"
        BEGIN{printf "\033]1717;1\033\\\n"}
        /^\+\+\+ /{file=substr($0,7);print;next}
        /^--- /{print;next}
        /^@@ /{o=$2;n=$3;sub(/^-/,"",o);sub(/^\+/,"",n);split(o,a,",");split(n,b,",");old=a[1];new=b[1];print;next}
        /^\+/{printf "\033]1717;1;a;%d;;%s\033\\%s\n",new++,file,$0;next}
        /^-/{printf "\033]1717;1;d;%d;%d;%s\033\\%s\n",new,old++,file,$0;next}
        /^ /{printf "\033]1717;1;c;%d;;%s\033\\%s\n",new++,file,$0;old++;next}
        {print}
        "#,
    ]
    .map(String::from)
    .to_vec()
}

fn selected_hunk_line(app: &App) -> Option<usize> {
    match app.screen().get_selected_item().data {
        crate::item_data::ItemData::HunkLine { line_i, .. } => Some(line_i),
        _ => None,
    }
}

fn offers(app: &App, op: Op) -> bool {
    let item = app.state.screens.last().unwrap().get_selected_item();
    assert!(
        matches!(item.data, crate::item_data::ItemData::Hunk { .. }),
        "expected a hunk to be selected, got {:?}",
        item.data
    );
    op.implementation().get_action(&item.data).is_some()
}

/// A re-render can lay the same patch out in fewer rows: side-by-side fuses a
/// changed pair into one. The viewport has to come back up to the content it is
/// now taller than, rather than stay where it was with blank rows below it.
#[test]
fn a_shorter_rendering_still_fills_the_screen() {
    let mut ctx = setup_clone!();
    ctx.config().general.diff_renderer.enabled = true;
    ctx.config().general.diff_renderer.features = vec!["side-by-side".into()];
    ctx.config().general.diff_renderer.command = fusing_renderer();

    // Twice the rows of the 20-row test terminal, halved by the feature: the
    // screen can be filled either way.
    let patch = (1..=100).map(|i| format!("line {i}\n")).collect::<String>();
    let mut app = ctx.init_app_with_patch(patch);
    ctx.update(&mut app, keys("G"));
    // The two rows gitu keeps below the end of the content, and no more.
    assert!(
        blank_rows_at_the_bottom(&ctx.redact_buffer()) <= 2,
        "before the re-render"
    );

    ctx.update(&mut app, keys("|<enter>"));
    let buffer = ctx.redact_buffer();
    assert!(blank_rows_at_the_bottom(&buffer) <= 2, "{buffer}");
}

/// A renderer that halves its rows once a feature is on, as a side-by-side one
/// does to a run of changed lines.
fn fusing_renderer() -> Vec<String> {
    [
        "sh",
        "-c",
        r#"if [ -n "$DELTA_FEATURES" ]; then awk 'NR%2==1'; else cat; fi"#,
    ]
    .map(String::from)
    .to_vec()
}

/// A one-hunk patch of `file`, whose content lines say which file they are
/// from, so a view can be asserted to have dropped one of two files.
fn one_hunk_patch(file: &str) -> String {
    format!(
        "diff --git a/{file} b/{file}\n\
         index 1111111..2222222 100644\n\
         --- a/{file}\n\
         +++ b/{file}\n\
         @@ -1 +1 @@\n\
         -{file} was\n\
         +{file} is\n"
    )
}

/// gitu reads all of its input before it draws anything, so input it cannot get
/// to the end of quickly has to stop somewhere. A file diff cut short is dropped
/// whole: what is left is a patch, not a fragment of one.
#[test]
fn input_past_the_limit_is_cut_back_to_whole_file_diffs() {
    let mut ctx = setup_clone!();
    let first = one_hunk_patch("a.rs");
    let patch = format!("{first}{}", one_hunk_patch("b.rs"));
    ctx.config().general.max_input_bytes = (first.len() + 60) as u64;

    let mut app = ctx.init_app_with_patch(patch);
    ctx.update(&mut app, keys("j"));

    let buffer = ctx.redact_buffer();
    assert!(!buffer.contains("b.rs"), "{buffer}");
    // Where the reading stopped, which is not where anyone starts reading.
    assert!(
        buffer.find("a.rs is") < buffer.find("input truncated at"),
        "{buffer}"
    );
}

/// A hunk missing its last lines is one git will not apply, so the hunk the
/// limit fell inside goes too.
#[test]
fn a_hunk_the_limit_cut_short_is_dropped() {
    let mut ctx = setup_clone!();
    let patch = "diff --git a/f.rs b/f.rs\n\
                 index 1111111..2222222 100644\n\
                 --- a/f.rs\n\
                 +++ b/f.rs\n\
                 @@ -1 +1 @@\n\
                 -first was\n\
                 +first is\n\
                 @@ -9 +9 @@\n\
                 -second was\n\
                 +second is\n";
    ctx.config().general.max_input_bytes = (patch.find("+second").unwrap() + 4) as u64;

    let mut app = ctx.init_app_with_patch(patch.to_owned());
    ctx.update(&mut app, keys("j"));

    let buffer = ctx.redact_buffer();
    assert!(buffer.contains("first is"), "{buffer}");
    assert!(!buffer.contains("second"), "{buffer}");
}

/// git colours what it writes to its pager, and the line's first character is
/// what says whether a file diff or a hunk starts there.
#[test]
fn a_coloured_patch_is_cut_back_at_the_same_place() {
    let mut ctx = setup_clone!();
    let first = one_hunk_patch("a.rs");
    let coloured = |patch: String| {
        patch
            .lines()
            .map(|line| format!("\x1b[1m{line}\x1b[m\n"))
            .collect::<String>()
    };
    let patch = coloured(format!("{first}{}", one_hunk_patch("b.rs")));
    ctx.config().general.max_input_bytes = (coloured(first).len() + 60) as u64;

    let _app = ctx.init_app_with_patch(patch);

    let buffer = ctx.redact_buffer();
    assert!(buffer.contains("a.rs is"), "{buffer}");
    assert!(!buffer.contains("b.rs"), "{buffer}");
}

/// A command gitu puts again can say as much as the pipe did, so what comes
/// back is read to the same limit.
#[test]
fn a_command_that_says_more_than_the_limit_is_cut_back_too() {
    let mut ctx = setup_clone!();
    two_changed_files(&ctx);
    ctx.config().general.max_input_bytes = 150;

    let mut app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.update(&mut app, keys("j"));

    let buffer = ctx.redact_buffer();
    assert!(buffer.contains("input truncated at 150 bytes"), "{buffer}");
    assert!(buffer.contains("alpha"), "{buffer}");
    assert!(!buffer.contains("beta"), "{buffer}");
    assert!(offers(&app, Op::Stage), "what is left is still a patch");
}

/// Rows of the viewport with nothing drawn on them, counted up from the last.
/// [`TestContext::redact_buffer`] ends with a `styles_hash` line, which is not
/// one of them.
fn blank_rows_at_the_bottom(buffer: &str) -> usize {
    buffer
        .lines()
        .filter(|row| row.ends_with('|'))
        .rev()
        .take_while(|row| row.trim_end_matches(['|', ' ']).is_empty())
        .count()
}

/// `--quit-if-one-screen`, as less's: a patch that fits on the terminal is
/// printed onto it, so that it is still there once gitu has exited.
#[test]
fn a_patch_that_fits_on_one_screen_is_printed() {
    let mut ctx = setup_clone!();
    commit(&ctx.dir, "firstfile", "testing\ntesttest\n");
    fs::write(ctx.dir.join("firstfile"), "changed\ntesttest\n").unwrap();

    let app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.term.clear().unwrap();
    ctx.term.queue_move_cursor(0, 0).unwrap();

    assert!(app.print_if_one_screen(&mut ctx.term).unwrap());
    insta::assert_snapshot!(ctx.redact_buffer());
}

#[test]
fn a_patch_longer_than_one_screen_is_not_printed() {
    let mut ctx = setup_clone!();
    let lines = |prefix: &str| {
        (1..=20)
            .map(|i| format!("{prefix} {i}\n"))
            .collect::<String>()
    };
    commit(&ctx.dir, "firstfile", &lines("old"));
    fs::write(ctx.dir.join("firstfile"), lines("new")).unwrap();

    let app = ctx.init_app_as_pager_of(&["git", "diff"]);
    ctx.term.clear().unwrap();
    ctx.term.queue_move_cursor(0, 0).unwrap();

    assert!(!app.print_if_one_screen(&mut ctx.term).unwrap());
    assert!(ctx.physical_screen().trim().is_empty());
}