delta-gitu 0.1.14

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
use super::*;
use std::path::{Path, PathBuf};

fn setup_scroll(mut ctx: TestContext) -> (TestContext, crate::app::App) {
    for file in ["file-1", "file-2", "file-3"] {
        commit(&ctx.dir, file, "");
        fs::write(
            ctx.dir.join(file),
            (1..=20).fold(String::new(), |mut acc, i| {
                use std::fmt::Write as _;

                writeln!(acc, "line {} ({})", i, file).unwrap();
                acc
            }),
        )
        .unwrap();
    }

    let mut app = ctx.init_app();
    ctx.update(&mut app, keys("jjjj<tab>k<tab>k<tab>"));
    (ctx, app)
}

#[test]
fn scroll_down() {
    let (mut ctx, mut app) = setup_scroll(setup_clone!());
    ctx.update(&mut app, keys(HALF_PAGE_DOWN));
    insta::assert_snapshot!(ctx.redact_buffer());
}

/// One key folds the whole view down to its files, and opens it again.
#[test]
fn folding_everything_and_opening_it_again() {
    let (mut ctx, mut app) = setup_scroll(setup_clone!());

    ctx.update(&mut app, keys("<backtab>"));
    let folded = ctx.redact_buffer();
    ctx.update(&mut app, keys("<backtab>"));
    let opened = ctx.redact_buffer();

    assert!(!folded.contains("line 1 (file-1)"), "still open:\n{folded}");
    assert!(folded.contains("file-1"), "{folded}");
    assert!(
        opened.contains("line 1 (file-1)"),
        "still folded:\n{opened}"
    );
}

/// The default binding is written as the keys pressed, and the help says so.
#[test]
fn folding_everything_is_bound_to_shift_tab() {
    let (mut ctx, mut app) = setup_scroll(setup_clone!());

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

    assert!(
        !ctx.redact_buffer().contains("line 1 (file-1)"),
        "shift+tab did nothing:\n{}",
        ctx.redact_buffer()
    );
    ctx.update(&mut app, keys("h"));
    assert!(
        ctx.redact_buffer().contains("shift+tab"),
        "{}",
        ctx.redact_buffer()
    );
}

/// A terminal sends shift-tab as backtab with the shift modifier still set.
/// The keycode already says shift was held, so a `backtab` binding — which is
/// what config can name — has to match it.
#[test]
fn shift_tab_reaches_a_backtab_binding() {
    let (mut ctx, mut app) = setup_scroll(setup_clone!());

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

    assert!(
        !ctx.redact_buffer().contains("line 1 (file-1)"),
        "shift-tab did nothing:\n{}",
        ctx.redact_buffer()
    );
}

/// A page is a whole viewport, which is two half pages.
#[test]
fn a_page_is_a_whole_viewport() {
    let (mut halves, mut halves_app) = setup_scroll(TestContext::setup_clone("page_in_halves"));
    halves.update(&mut halves_app, keys("<ctrl+d><ctrl+d>"));

    let (mut page, mut page_app) = setup_scroll(TestContext::setup_clone("page_at_once"));
    page.update(&mut page_app, keys("<pagedown>"));

    assert_eq!(page.redact_buffer(), halves.redact_buffer());
}

/// Space is how every pager since `more` turns the page, and what magit binds
/// it to; backspace is its other half.
#[test]
fn space_turns_the_page() {
    let (mut keys_ctx, mut keys_app) = setup_scroll(TestContext::setup_clone("page_by_key"));
    keys_ctx.update(&mut keys_app, keys("<pagedown><pagedown><pageup>"));

    let (mut space_ctx, mut space_app) = setup_scroll(TestContext::setup_clone("page_by_space"));
    space_ctx.update(&mut space_app, keys("<space><space><backspace>"));

    assert_eq!(space_ctx.redact_buffer(), keys_ctx.redact_buffer());
}

#[test]
fn a_page_down_and_a_page_up_come_back() {
    let (mut ctx, mut app) = setup_scroll(setup_clone!());
    let before = ctx.redact_buffer();

    ctx.update(&mut app, keys("<pagedown>"));
    let paged = ctx.redact_buffer();
    ctx.update(&mut app, keys("<pageup>"));

    assert_ne!(paged, before, "page down did not scroll");
    assert_eq!(ctx.redact_buffer(), before, "page up did not come back");
}

/// Paging through a diff carries the cursor with the view, selecting whatever
/// row it lands on — a line within a hunk, when that is what is there.
#[test]
fn paging_carries_the_cursor_into_the_hunk() {
    let (mut ctx, mut app) = setup_scroll(setup_clone!());
    ctx.update(
        &mut app,
        keys(&format!("{HALF_PAGE_DOWN}{HALF_PAGE_DOWN}{HALF_PAGE_DOWN}")),
    );
    insta::assert_snapshot!(ctx.redact_buffer());
}

#[test]
fn move_prev_sibling() {
    let (mut ctx, mut app) = setup_scroll(setup_clone!());
    ctx.update(&mut app, keys("<alt+k><alt+k>"));
    insta::assert_snapshot!(ctx.redact_buffer());
}

#[test]
fn move_next_sibling() {
    let (mut ctx, mut app) = setup_scroll(setup_clone!());
    ctx.update(&mut app, keys("<alt+j>"));
    insta::assert_snapshot!(ctx.redact_buffer());
}

#[test]
fn move_next_then_parent_section() {
    let (mut ctx, mut app) = setup_scroll(setup_clone!());
    ctx.update(&mut app, keys("<alt+j><alt+h>"));
    insta::assert_snapshot!(ctx.redact_buffer());
}

#[test]
fn exit_from_picker_exits_menu() {
    snapshot!(setup_clone!(), "bb<esc>");
}

#[test]
fn re_enter_picker_from_menu() {
    snapshot!(setup_clone!(), "bb<esc>bb");
}

#[test]
fn renderer_features_offers_the_configured_ones() {
    snapshot!(setup_clone!(), "-");
}

/// Give `feature` the only key, as a user's config does: its feature keys replace
/// the default ones.
/// Make the user's config enable `features`, by delta's name, as delta tells gitu.
fn enable_by_config(ctx: &mut TestContext, features: Vec<String>) {
    ctx.config().general.diff_renderer.enabled_features =
        crate::config::EnabledFeatures::new(move |_| features.clone());
}

fn with_feature_key(ctx: &mut TestContext, feature: &str, key: char) {
    ctx.config().general.diff_renderer.feature_keys = [(feature.into(), key)].into();
}

/// The repository's own git config, given a `delta-tui` section so that it is
/// where a key set from the list is written.
fn repo_git_config(ctx: &TestContext) -> PathBuf {
    run(
        &ctx.dir,
        &["git", "config", "delta-tui.visit-context-lines", "true"],
    );
    ctx.dir.join(".git/config")
}

/// The feature keys gitu would read from the git config file at `path`.
fn saved_feature_keys(path: &Path) -> Vec<(String, char)> {
    let git_config = git2::Config::open(path).unwrap();
    crate::config::init_config_from(PathBuf::from("/nonexistent/config.toml"), Some(&git_config))
        .unwrap()
        .general
        .diff_renderer
        .feature_keys
        .into_iter()
        .collect()
}

/// A feature's key is a top-level key: it toggles the feature without `-`.
#[test]
fn a_feature_key_toggles_its_feature() {
    let mut ctx = setup_clone!();
    with_feature_key(&mut ctx, "side-by-side", 'x');
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("x"));
    assert_eq!(&*app.state.features, ["side-by-side".to_string()]);

    ctx.update(&mut app, keys("x"));
    assert!(app.state.features.is_empty());
}

/// A feature the user's own config enables is enabled from the start, and its key
/// disables it, by removing it, and enables it again.
#[test]
fn a_feature_key_turns_off_a_feature_the_users_config_turns_on() {
    let mut ctx = setup_clone!();
    with_feature_key(&mut ctx, "side-by-side", 'x');
    enable_by_config(&mut ctx, vec!["side-by-side".into()]);
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("x"));
    assert_eq!(&*app.state.features, ["-side-by-side".to_string()]);

    ctx.update(&mut app, keys("x"));
    assert!(app.state.features.is_empty());
}

/// Every feature key toggles its feature the same way, whatever the name: a builtin switch
/// feature, a builtin style feature, the user's own feature, or a builtin name the user also has
/// a section for (delta treats that section as part of the builtin). The first press enables the
/// feature (`+name`), or disables it (`+-name`) if the user's config enables it; the second press
/// returns to the user's config. The test reads what delta is given in `DELTA_FEATURES` each time
/// it runs.
#[test]
fn every_feature_key_toggles_its_feature_the_same_way() {
    let mut failures = vec![];
    for name in ["side-by-side", "raw", "mine"] {
        for enabled_by_config in [false, true] {
            let mut ctx = TestContext::setup_clone(&format!(
                "every_feature_key_toggles_{name}_{enabled_by_config}"
            ));
            let log = ctx.dir.join(".git").join("delta-features");
            ctx.config().general.diff_renderer.command = super::pager::annotating_renderer()
                .into_iter()
                .map(|arg| {
                    arg.replacen(
                        "BEGIN{",
                        &format!(
                            r#"BEGIN{{print ENVIRON["DELTA_FEATURES"] >> "{}";"#,
                            log.display()
                        ),
                        1,
                    )
                })
                .collect();
            ctx.config().general.diff_renderer.features = vec![name.into()];
            if enabled_by_config {
                enable_by_config(&mut ctx, vec![name.into()]);
            }
            with_feature_key(&mut ctx, name, 'x');
            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("x"));
            ctx.update(&mut app, keys("x"));

            let toggled = if enabled_by_config {
                format!("+-{name}")
            } else {
                format!("+{name}")
            };
            let expected = format!("\n{toggled}\n\n");
            let actual = fs::read_to_string(&log).unwrap_or_default();
            if actual != expected {
                failures.push(format!(
                    "{name}, enabled by config: {enabled_by_config}: delta was given {actual:?}, not {expected:?}"
                ));
            }
        }
    }
    assert!(failures.is_empty(), "\n{}", failures.join("\n"));
}

/// Whether the user's config enables a feature is asked when a key is pressed, so a change to
/// the user's git config during the session counts.
#[test]
fn a_feature_key_follows_a_change_to_the_users_config_during_the_session() {
    let mut ctx = setup_clone!();
    with_feature_key(&mut ctx, "side-by-side", 'x');
    let enabled = ctx.dir.join(".git").join("enabled-features");
    let asked = enabled.clone();
    ctx.config().general.diff_renderer.enabled_features =
        crate::config::EnabledFeatures::new(move |_| {
            fs::read_to_string(&asked)
                .unwrap_or_default()
                .split_whitespace()
                .map(String::from)
                .collect()
        });
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("x"));
    assert_eq!(&*app.state.features, ["side-by-side".to_string()]);
    ctx.update(&mut app, keys("x"));
    assert!(app.state.features.is_empty());

    // The user turns side-by-side on in their git config.
    fs::write(&enabled, "side-by-side").unwrap();
    ctx.update(&mut app, keys("x"));
    assert_eq!(&*app.state.features, ["-side-by-side".to_string()]);
    ctx.update(&mut app, keys("x"));
    assert!(app.state.features.is_empty());
}

/// delta calls the +/- markers `keep-plus-minus-markers`.
#[test]
fn plus_turns_off_the_plus_minus_markers_the_users_config_turns_on() {
    let mut ctx = setup_clone!();
    enable_by_config(&mut ctx, vec!["keep-plus-minus-markers".into()]);
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("+"));
    assert_eq!(&*app.state.features, ["-plus-minus-markers".to_string()]);
}

/// The feature list marks as on a feature the user's own config turns on, until
/// it is turned off.
#[test]
fn the_feature_list_marks_the_features_the_users_config_turns_on() {
    let mut ctx = setup_clone!();
    enable_by_config(&mut ctx, vec!["line-numbers".into()]);
    let mut app = ctx.init_app();
    ctx.update(&mut app, keys("-"));
    assert!(ctx.redact_buffer().contains("● L line-numbers"));

    let mut app = ctx.init_app();
    ctx.update(&mut app, keys("L-"));
    assert!(ctx.redact_buffer().contains("  L line-numbers"));
}

/// The help menu lists feature keys with the other top-level keys.
#[test]
fn the_help_menu_lists_feature_keys() {
    let mut ctx = setup_clone!();
    with_feature_key(&mut ctx, "side-by-side", 'x');
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("?"));
    let buffer = ctx.redact_buffer();
    assert!(
        regex::Regex::new(r"\bx +side-by-side")
            .unwrap()
            .is_match(&buffer),
        "{buffer}"
    );
}

#[test]
fn the_help_menu_sets_feature_keys_apart_from_submenus() {
    let mut ctx = setup_clone!();
    with_feature_key(&mut ctx, "side-by-side", 'x');
    snapshot!(ctx, "?");
}

/// A key that does something already keeps doing it.
#[test]
fn a_configured_feature_key_that_is_already_bound_is_a_config_error() {
    let dir = temp_dir::TempDir::new().unwrap();
    let path = dir.path().join("gitconfig");
    fs::write(
        &path,
        "[delta-tui \"general.diff-renderer.feature-keys\"]\n\tside-by-side = s\n",
    )
    .unwrap();
    let git_config = git2::Config::open(&path).unwrap();

    assert!(
        crate::config::init_config_from(dir.path().join("config.toml"), Some(&git_config)).is_err()
    );
}

/// The list is moved through, not searched: letters are keys.
#[test]
fn the_feature_list_is_moved_through_with_the_arrows() {
    let mut ctx = setup_clone!();
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("<-><down><enter>"));
    assert_eq!(&*app.state.features, ["line-numbers".to_string()]);
}

/// Each feature's key is written beside it.
#[test]
fn the_feature_list_shows_feature_keys() {
    let mut ctx = setup_clone!();
    with_feature_key(&mut ctx, "line-numbers", 'x');
    snapshot!(ctx, "-");
}

/// In the list, a letter becomes the selected feature's key. It works at once,
/// and is saved to the user's git config beside what was already there.
#[test]
fn a_letter_in_the_feature_list_sets_the_selected_features_key() {
    let mut ctx = setup_clone!();
    let path = repo_git_config(&ctx);
    let mine = fs::read_to_string(&path).unwrap();
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("-x<esc>"));
    assert!(
        app.state.features.is_empty(),
        "setting a key toggles nothing"
    );

    ctx.update(&mut app, keys("x"));
    assert_eq!(&*app.state.features, ["side-by-side".to_string()]);

    assert!(fs::read_to_string(&path).unwrap().starts_with(&mine));
    assert_eq!(
        saved_feature_keys(&path),
        [
            ("line-numbers".into(), 'L'),
            ("plus-minus-markers".into(), '+'),
            ("side-by-side".into(), 'x')
        ]
    );
}

#[test]
fn the_same_letter_again_unsets_the_key() {
    let mut ctx = setup_clone!();
    let path = repo_git_config(&ctx);
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("-xx<esc>x"));
    assert!(app.state.features.is_empty());
    assert_eq!(
        saved_feature_keys(&path),
        [
            ("line-numbers".into(), 'L'),
            ("plus-minus-markers".into(), '+')
        ]
    );
}

#[test]
fn another_letter_replaces_the_key() {
    let mut ctx = setup_clone!();
    let path = repo_git_config(&ctx);
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("-xw<esc>x"));
    assert!(app.state.features.is_empty());

    ctx.update(&mut app, keys("w"));
    assert_eq!(&*app.state.features, ["side-by-side".to_string()]);
    assert_eq!(
        saved_feature_keys(&path),
        [
            ("line-numbers".into(), 'L'),
            ("plus-minus-markers".into(), '+'),
            ("side-by-side".into(), 'w')
        ]
    );
}

#[test]
fn a_key_set_for_one_feature_is_taken_from_another() {
    let mut ctx = setup_clone!();
    let path = repo_git_config(&ctx);
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("-x<down>x<esc>x"));
    assert_eq!(&*app.state.features, ["line-numbers".to_string()]);
    assert_eq!(
        saved_feature_keys(&path),
        [
            ("line-numbers".into(), 'x'),
            ("plus-minus-markers".into(), '+')
        ]
    );
}

/// side-by-side, line numbers and +/- markers have keys without the user
/// setting any.
#[test]
fn the_default_features_have_keys_by_default() {
    let dir = temp_dir::TempDir::new().unwrap();
    let path = dir.path().join("gitconfig");
    fs::write(&path, "").unwrap();
    assert_eq!(
        saved_feature_keys(&path),
        [
            ("line-numbers".into(), 'L'),
            ("plus-minus-markers".into(), '+'),
            ("side-by-side".into(), 'S')
        ]
    );
}

#[test]
fn plus_toggles_the_plus_minus_markers_by_default() {
    let mut ctx = setup_clone!();
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("+"));
    assert_eq!(&*app.state.features, ["plus-minus-markers".to_string()]);
}

/// The feature keys a user's config gives are all of them, as are those the
/// list saves.
#[test]
fn a_users_feature_keys_replace_the_default_ones() {
    let dir = temp_dir::TempDir::new().unwrap();
    let path = dir.path().join("gitconfig");
    fs::write(
        &path,
        "[delta-tui \"general.diff-renderer.feature-keys\"]\n\tside-by-side = x\n",
    )
    .unwrap();

    assert_eq!(saved_feature_keys(&path), [("side-by-side".into(), 'x')]);
}

#[test]
fn a_default_key_unset_in_the_list_stays_unset() {
    let mut ctx = setup_clone!();
    let path = repo_git_config(&ctx);
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("-S<esc>"));
    assert_eq!(
        saved_feature_keys(&path),
        [
            ("line-numbers".into(), 'L'),
            ("plus-minus-markers".into(), '+')
        ]
    );
}

/// A letter that already does something at the top level stays as it is.
#[test]
fn a_letter_bound_at_the_top_level_is_refused() {
    let mut ctx = setup_clone!();
    let path = repo_git_config(&ctx);
    let mine = fs::read_to_string(&path).unwrap();
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("-s<esc>"));
    assert!(!app.state.feature_keys.values().any(|key| *key == 's'));
    assert_eq!(fs::read_to_string(&path).unwrap(), mine);
}

/// q leaves the feature list, as it leaves theme mode, rather than being a
/// letter to set as a key.
#[test]
fn q_leaves_the_feature_list() {
    let mut ctx = setup_clone!();
    let path = repo_git_config(&ctx);
    let mine = fs::read_to_string(&path).unwrap();
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("-q"));
    assert!(app.state.picker.is_none(), "the feature list is gone");
    assert!(!ctx.redact_buffer().contains("bound already"));
    assert_eq!(fs::read_to_string(&path).unwrap(), mine);
}

/// The features the user defined for themselves are theirs to choose from too,
/// by a pattern rather than one by one.
#[test]
fn renderer_features_offers_those_in_git_config_a_pattern_matches() {
    let mut ctx = setup_clone!();
    ctx.config().general.diff_renderer.features = vec!["*".into()];
    run(
        &ctx.dir,
        &["git", "config", "delta.my-theme.syntax-theme", "Nord"],
    );
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("<-><enter>"));
    assert_eq!(&*app.state.features, ["my-theme".to_string()]);
}

#[test]
fn choosing_a_renderer_feature_marks_it() {
    // Picking `side-by-side` enables it; re-opening shows it marked, and
    // picking it again disables it.
    let ctx = setup_clone!();
    let mut ctx = ctx;
    let mut app = ctx.init_app();

    ctx.update(&mut app, keys("<-><enter>"));
    assert_eq!(&*app.state.features, ["side-by-side".to_string()]);

    ctx.update(&mut app, keys("<-><enter>"));
    assert!(
        app.state.features.is_empty(),
        "picking it again turns it off"
    );
}

/// ctrl+z stops gitu as a terminal's job control stops any program. In raw
/// mode the terminal sends it as a key, so gitu has to be bound to it.
#[test]
fn suspending_is_bound_to_ctrl_z() {
    let mut ctx = setup_clone!();
    let ctrl_z = [(
        crossterm::event::KeyModifiers::CONTROL,
        crossterm::event::KeyCode::Char('z'),
    )];

    let ops: Vec<&str> = ctx
        .config()
        .bindings
        .match_bindings(&crate::menu::Menu::Root, &ctrl_z)
        .map(|binding| binding.op.as_ref())
        .collect();

    assert_eq!(ops, ["suspend"]);
}