trail-fm 1.12.1

A terminal-first workspace for navigating, inspecting and acting on the filesystem
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
//! Integration tests for the Command Mode grammar, validation, history, and
//! completion (Phase 3).
//!
//! These tests exercise the public API of `trail::input::command_parser`
//! from outside the crate, ensuring the grammar is correct and that error
//! messages are helpful rather than cryptic.

use std::fs;

use trail::input::command_parser::{completions, parse, CommandHistory, ParseError, ParsedCommand};

// ── Grammar: valid inputs ─────────────────────────────────────────────────────

#[test]
fn mkdir_valid_simple_name() {
    let cmd = parse("mkdir new_dir", false).unwrap();
    assert_eq!(cmd, ParsedCommand::Mkdir("new_dir".to_owned()));
}

#[test]
fn touch_valid_filename() {
    let cmd = parse("touch README.md", false).unwrap();
    assert_eq!(cmd, ParsedCommand::Touch("README.md".to_owned()));
}

#[test]
fn rename_valid() {
    let cmd = parse("rename new-name.txt", false).unwrap();
    assert_eq!(cmd, ParsedCommand::Rename("new-name.txt".to_owned()));
}

#[test]
fn rename_alias_ren_works() {
    let cmd = parse("ren new-name.txt", false).unwrap();
    assert_eq!(cmd, ParsedCommand::Rename("new-name.txt".to_owned()));
}

#[test]
fn mv_accepts_relative_path() {
    let cmd = parse("mv ../sibling", false).unwrap();
    assert_eq!(cmd, ParsedCommand::Mv("../sibling".to_owned()));
}

#[test]
fn cp_accepts_path_with_extension() {
    let cmd = parse("cp backup.tar.gz", false).unwrap();
    assert_eq!(cmd, ParsedCommand::Cp("backup.tar.gz".to_owned()));
}

#[test]
fn git_valid_subcommand() {
    let cmd = parse("git status --short", false).unwrap();
    assert_eq!(cmd, ParsedCommand::Git("status --short".to_owned()));
}

#[test]
fn set_valid_key_value() {
    let cmd = parse("set text_sync_threshold_kb 500", false).unwrap();
    assert_eq!(
        cmd,
        ParsedCommand::Set {
            key: "text_sync_threshold_kb".to_owned(),
            value: "500".to_owned(),
        }
    );
}

#[test]
fn shell_command_with_bang() {
    let cmd = parse("ls -la /tmp", true).unwrap();
    assert_eq!(cmd, ParsedCommand::Shell("ls -la /tmp".to_owned()));
}

// ── Grammar: invalid / error inputs ───────────────────────────────────────────

#[test]
fn empty_buffer_returns_error() {
    let err = parse("", false).unwrap_err();
    assert!(
        matches!(err, ParseError::Empty),
        "expected Empty, got {err:?}"
    );
}

#[test]
fn unknown_verb_returns_helpful_error() {
    let err = parse("zap foo", false).unwrap_err();
    assert!(matches!(err, ParseError::UnknownVerb(_)));
    // The error message should mention the verb.
    let msg = err.to_string();
    assert!(
        msg.contains("zap"),
        "error message should name the unknown verb; got: {msg}"
    );
}

#[test]
fn mkdir_empty_arg_returns_error() {
    let err = parse("mkdir", false).unwrap_err();
    assert!(matches!(err, ParseError::MissingArgument(_)));
}

#[test]
fn mkdir_with_slash_returns_invalid_arg() {
    let err = parse("mkdir foo/bar", false).unwrap_err();
    assert!(matches!(err, ParseError::InvalidArgument(_)));
}

#[test]
fn rename_with_backslash_is_invalid_on_windows_semantics() {
    let err = parse("rename foo\\bar", false).unwrap_err();
    assert!(matches!(err, ParseError::InvalidArgument(_)));
}

#[test]
fn git_without_subcommand_is_missing_argument() {
    let err = parse("git", false).unwrap_err();
    assert!(matches!(err, ParseError::MissingArgument(_)));
}

#[test]
fn set_without_value_is_missing_argument() {
    let err = parse("set only_key", false).unwrap_err();
    assert!(matches!(err, ParseError::MissingArgument(_)));
}

#[test]
fn shell_empty_string_is_missing_argument() {
    let err = parse("   ", true).unwrap_err();
    assert!(matches!(err, ParseError::MissingArgument(_)));
}

// ── Completion ────────────────────────────────────────────────────────────────

#[test]
fn verb_completion_prefix_t_returns_touch() {
    let dir = tempfile::tempdir().unwrap();
    let candidates = completions("t", dir.path(), false);
    assert!(
        candidates.contains(&"touch ".to_owned()),
        "expected 'touch ' in: {candidates:?}"
    );
}

#[test]
fn verb_completion_mk_returns_only_mkdir() {
    let dir = tempfile::tempdir().unwrap();
    let candidates = completions("mk", dir.path(), false);
    assert_eq!(candidates, vec!["mkdir "]);
}

#[test]
fn plugin_valid_action_name() {
    let cmd = parse("plugin my_action", false).unwrap();
    assert_eq!(
        cmd,
        ParsedCommand::Plugin {
            name: "my_action".to_owned(),
            arg: "".to_owned(),
        }
    );
}

#[test]
fn plugin_with_args() {
    let cmd = parse("plugin log_note hello world", false).unwrap();
    assert_eq!(
        cmd,
        ParsedCommand::Plugin {
            name: "log_note".to_owned(),
            arg: "hello world".to_owned(),
        }
    );
}

#[test]
fn plugin_without_action_returns_error() {
    let err = parse("plugin", false).unwrap_err();
    assert!(matches!(err, ParseError::MissingArgument(_)));
}

#[test]
fn verb_completion_all_verbs_when_empty() {
    let dir = tempfile::tempdir().unwrap();
    let candidates = completions("", dir.path(), false);
    // Named rather than counted: a count tells you a verb is missing but not
    // which one, and the failure this guards against is a verb added to the
    // parser and forgotten in the completion list.
    let mut got: Vec<String> = candidates.iter().map(|c| c.trim().to_owned()).collect();
    got.sort();
    assert_eq!(
        got,
        vec![
            "bookmark", "config", "cp", "git", "jump", "mkdir", "mv", "plugin", "rename", "set",
            "sort", "term", "touch", "unmark",
        ],
        "every verb should be offered for an empty prefix"
    );
}

#[test]
fn path_completion_for_cp_matches_prefix() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("alpha.txt"), b"").unwrap();
    fs::write(dir.path().join("beta.txt"), b"").unwrap();

    let candidates = completions("cp a", dir.path(), false);
    assert!(
        candidates.contains(&"alpha.txt".to_owned()),
        "expected alpha.txt in: {candidates:?}"
    );
    assert!(
        !candidates.contains(&"beta.txt".to_owned()),
        "beta.txt should not match 'a' prefix"
    );
}

/// A destination that names a directory should be completable one step at a
/// time, which needs a trailing separator on the candidate — without it the
/// next `Tab` has nothing to walk into.
#[test]
fn path_completion_marks_a_directory_with_a_separator() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir(dir.path().join("nested")).unwrap();
    fs::write(dir.path().join("nested.txt"), b"").unwrap();

    let candidates = completions("mv nested", dir.path(), false);
    let want_dir = format!("nested{}", std::path::MAIN_SEPARATOR);
    assert!(
        candidates.contains(&want_dir),
        "the directory should carry a trailing separator: {candidates:?}"
    );
    assert!(
        candidates.contains(&"nested.txt".to_owned()),
        "the file should not: {candidates:?}"
    );
}

/// Regression: completion used to match the whole destination against the
/// names in `cwd`, so the first separator typed killed it — no route into a
/// subdirectory could ever be completed.
#[test]
fn path_completion_walks_into_a_subdirectory() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir(dir.path().join("nested")).unwrap();
    fs::write(dir.path().join("nested").join("inner.txt"), b"").unwrap();
    fs::write(dir.path().join("nested").join("other.txt"), b"").unwrap();

    let candidates = completions("mv nested/in", dir.path(), false);
    assert_eq!(
        candidates,
        vec!["nested/inner.txt".to_owned()],
        "the route must be completed against the directory it names, and the \
         candidate must carry the route back"
    );
}

/// The separator the user typed is the one the candidate comes back with, so a
/// route does not end up spelled two ways at once.
#[test]
#[cfg(windows)]
fn path_completion_accepts_a_backslash_route() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir(dir.path().join("nested")).unwrap();
    fs::write(dir.path().join("nested").join("inner.txt"), b"").unwrap();

    let candidates = completions(r"mv nested\in", dir.path(), false);
    assert_eq!(candidates, vec![r"nested\inner.txt".to_owned()]);
}

/// An absolute destination — what you get by pasting a path in — completes
/// against the directory it names, not against `cwd`.
#[test]
fn path_completion_accepts_an_absolute_route() {
    let dir = tempfile::tempdir().unwrap();
    let elsewhere = dir.path().join("elsewhere");
    fs::create_dir(&elsewhere).unwrap();
    fs::write(elsewhere.join("target.txt"), b"").unwrap();
    let cwd = dir.path().join("cwd");
    fs::create_dir(&cwd).unwrap();

    let route = format!("{}{}", elsewhere.display(), std::path::MAIN_SEPARATOR);
    let candidates = completions(&format!("mv {route}"), &cwd, false);
    assert_eq!(candidates, vec![format!("{route}target.txt")]);
}

#[test]
fn no_completion_for_rename_arg() {
    // rename takes a simple name, not a path — no path completion.
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("foo.txt"), b"").unwrap();
    let candidates = completions("rename f", dir.path(), false);
    assert!(
        candidates.is_empty(),
        "rename should not have path completion; got {candidates:?}"
    );
}

#[test]
fn shell_mode_returns_no_completions() {
    let dir = tempfile::tempdir().unwrap();
    let candidates = completions("ls", dir.path(), true);
    assert!(
        candidates.is_empty(),
        "shell mode should not complete verbs; got {candidates:?}"
    );
}

// ── History ───────────────────────────────────────────────────────────────────

#[test]
fn history_push_retains_commands_in_order() {
    let mut h = CommandHistory::new();
    h.push("mkdir alpha".to_owned());
    h.push("touch beta.txt".to_owned());
    h.push("rename gamma.txt".to_owned());
    assert_eq!(h.prev(0), Some("rename gamma.txt"));
    assert_eq!(h.prev(1), Some("touch beta.txt"));
    assert_eq!(h.prev(2), Some("mkdir alpha"));
}

#[test]
fn history_deduplicates_consecutive_entries() {
    let mut h = CommandHistory::new();
    h.push("mkdir foo".to_owned());
    h.push("mkdir foo".to_owned());
    assert_eq!(h.len(), 1);
}

#[test]
fn history_persists_to_file_and_reloads() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("history.txt");

    {
        let mut h = CommandHistory::with_path(path.clone());
        h.push("mkdir a".to_owned());
        h.push("touch b.txt".to_owned());
    }

    let h2 = CommandHistory::with_path(path);
    assert_eq!(h2.len(), 2);
    assert_eq!(h2.prev(0), Some("touch b.txt"));
    assert_eq!(h2.prev(1), Some("mkdir a"));
}

#[test]
fn history_prev_out_of_range_returns_none() {
    let mut h = CommandHistory::new();
    h.push("mkdir foo".to_owned());
    assert!(h.prev(999).is_none());
}

// ── Action integration: ExecuteCommand via AppState ───────────────────────────

#[test]
fn execute_mkdir_creates_dir_and_refreshes() {
    let dir = tempfile::tempdir().unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();
    let before = state.visible_count();

    trail::actions::apply(
        trail::actions::Action::ExecuteCommand(ParsedCommand::Mkdir("new_subdir".to_owned())),
        &mut state,
    )
    .unwrap();

    assert!(
        state.error_text().is_none(),
        "no error expected; got {:?}",
        state.error_text()
    );
    assert_eq!(
        state.visible_count(),
        before + 1,
        "listing should contain the new directory"
    );
}

#[test]
fn execute_touch_creates_file_and_refreshes() {
    let dir = tempfile::tempdir().unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();
    let before = state.visible_count();

    trail::actions::apply(
        trail::actions::Action::ExecuteCommand(ParsedCommand::Touch("new_file.txt".to_owned())),
        &mut state,
    )
    .unwrap();

    assert!(state.error_text().is_none());
    assert_eq!(state.visible_count(), before + 1);
}

#[test]
fn execute_rename_renames_selected_entry() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("old.txt"), b"").unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();
    // Select old.txt (it's the only file; selection index 0).
    assert_eq!(
        state.selected_entry().map(|e| e.file_name.as_str()),
        Some("old.txt")
    );

    trail::actions::apply(
        trail::actions::Action::ExecuteCommand(ParsedCommand::Rename("new.txt".to_owned())),
        &mut state,
    )
    .unwrap();

    assert!(state.error_text().is_none());
    assert!(
        state.visible_entries().any(|e| e.file_name == "new.txt"),
        "new.txt should appear in listing"
    );
}

#[test]
fn execute_mkdir_duplicate_surfaces_error_message() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir(dir.path().join("existing")).unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();

    trail::actions::apply(
        trail::actions::Action::ExecuteCommand(ParsedCommand::Mkdir("existing".to_owned())),
        &mut state,
    )
    .unwrap();

    assert!(
        state.error_text().is_some(),
        "an error message should be set for duplicate mkdir"
    );
}

// ── Delete confirmation flow ──────────────────────────────────────────────────

#[test]
fn begin_delete_sets_pending_delete() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("to_delete.txt"), b"").unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();

    trail::actions::apply(trail::actions::Action::BeginDelete, &mut state).unwrap();
    assert!(state.pending_delete);
}

#[test]
fn confirm_delete_removes_file() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("to_delete.txt"), b"").unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();
    // Permanent on purpose: the shipped default is the recycle bin, and a test
    // suite must not fill the machine's bin with its own fixtures.
    state.config.set_value("delete_mode", "permanent").unwrap();

    trail::actions::apply(trail::actions::Action::BeginDelete, &mut state).unwrap();
    trail::actions::apply(trail::actions::Action::ConfirmDelete, &mut state).unwrap();

    assert!(!state.pending_delete);
    assert!(
        !state
            .visible_entries()
            .any(|e| e.file_name == "to_delete.txt"),
        "to_delete.txt should be gone after ConfirmDelete"
    );
    let notice = state
        .notice
        .as_ref()
        .expect("a delete should report itself");
    assert_eq!(notice.level, trail::app::state::NoticeLevel::Info);
    assert!(
        notice.text.starts_with("deleted:"),
        "a permanent delete must not claim to be recoverable; got: {}",
        notice.text
    );
}

/// `dd` goes to the recycle bin unless the config says otherwise, and the
/// confirmation prompt says which of the two is about to happen — one can be
/// undone from the desktop and the other cannot.
#[test]
fn the_shipped_default_sends_a_delete_to_the_recycle_bin() {
    let config = trail::config::load(None).unwrap();
    assert_eq!(config.general.delete_mode, "trash");
}

/// The tab is titled by directory unless the config says otherwise, and
/// `:set` takes only the three forms the title knows.
#[test]
fn terminal_title_defaults_to_the_directory_and_rejects_other_forms() {
    let mut config = trail::config::load(None).unwrap();
    assert_eq!(config.general.terminal_title, "dir");

    config.set_value("terminal_title", " Path ").unwrap();
    assert_eq!(config.general.terminal_title, "path");
    let err = config.set_value("terminal_title", "name").unwrap_err();
    assert!(err.to_string().contains("off, dir or path"), "{err}");
    assert_eq!(
        config.general.terminal_title, "path",
        "a rejected value changes nothing"
    );
}

#[test]
fn cancel_delete_clears_pending_without_deleting() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("safe.txt"), b"").unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();

    trail::actions::apply(trail::actions::Action::BeginDelete, &mut state).unwrap();
    trail::actions::apply(trail::actions::Action::CancelDelete, &mut state).unwrap();

    assert!(!state.pending_delete);
    assert!(
        state.visible_entries().any(|e| e.file_name == "safe.txt"),
        "safe.txt must still exist after CancelDelete"
    );
}

// ── Clipboard actions ─────────────────────────────────────────────────────────

#[test]
fn copy_abs_path_stores_in_last_yank() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("file.txt"), b"").unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();

    // Select file.txt (index 0 in a single-file dir).
    trail::actions::apply(trail::actions::Action::CopyAbsPath, &mut state).unwrap();
    let yank = state.last_yank.as_deref().expect("last_yank should be set");
    assert!(
        yank.contains("file.txt"),
        "yanked absolute path should contain the filename; got: {yank}"
    );
}

/// Regression: `ya` yanked whatever `canonicalize` produced, which on Windows
/// is `\\?\C:\…`. A yank exists to be pasted into a shell or another program,
/// and the verbatim prefix is not something either wants to be handed.
#[test]
fn copy_abs_path_yanks_a_path_without_a_verbatim_prefix() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("file.txt"), b"").unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();

    trail::actions::apply(trail::actions::Action::CopyAbsPath, &mut state).unwrap();
    let yank = state.last_yank.as_deref().expect("last_yank should be set");
    assert!(
        !yank.contains(r"\\?\"),
        "yank leaked an extended-length prefix: {yank}"
    );
    // Still a usable absolute path, not just a prefix-free string.
    assert!(
        std::path::Path::new(yank).exists(),
        "the yanked path must still resolve: {yank}"
    );
}

#[test]
fn copy_filename_stores_just_name() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("unique_name.rs"), b"").unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();

    trail::actions::apply(trail::actions::Action::CopyFilename, &mut state).unwrap();
    assert_eq!(
        state.last_yank.as_deref(),
        Some("unique_name.rs"),
        "CopyFilename should store only the filename"
    );
}

#[test]
fn copy_rel_path_is_relative_to_the_launch_dir() {
    let dir = tempfile::tempdir().unwrap();
    let launched_from = dir.path().join("launched");
    let browsing = dir.path().join("browsing");
    fs::create_dir(&launched_from).unwrap();
    fs::create_dir(&browsing).unwrap();
    fs::write(browsing.join("rel.txt"), b"").unwrap();

    let mut state = trail::app::state::AppState::new(browsing).unwrap();
    state.launch_dir = trail::pathfmt::canonicalize(&launched_from).unwrap();

    trail::actions::apply(trail::actions::Action::CopyRelPath, &mut state).unwrap();
    let yank = state.last_yank.as_deref().expect("last_yank should be set");
    // Relative to the launch directory, climbing out of it as needed — this is
    // what makes the yank pasteable in the shell Trail was started from.
    assert_eq!(yank.replace('\\', "/"), "../browsing/rel.txt");
}

#[test]
fn copy_rel_path_and_copy_filename_yank_different_strings() {
    // Regression: `yr` used to resolve against `cwd`, where every entry's
    // relative path is its own file name — making it a duplicate of `yn`.
    let dir = tempfile::tempdir().unwrap();
    let browsing = dir.path().join("browsing");
    fs::create_dir(&browsing).unwrap();
    fs::write(browsing.join("rel.txt"), b"").unwrap();

    let mut state = trail::app::state::AppState::new(browsing).unwrap();
    state.launch_dir = trail::pathfmt::canonicalize(dir.path()).unwrap();

    trail::actions::apply(trail::actions::Action::CopyRelPath, &mut state).unwrap();
    let relative = state.last_yank.clone().expect("last_yank should be set");

    trail::actions::apply(trail::actions::Action::CopyFilename, &mut state).unwrap();
    let filename = state.last_yank.clone().expect("last_yank should be set");

    assert_eq!(relative.replace('\\', "/"), "browsing/rel.txt");
    assert_eq!(filename, "rel.txt");
    assert_ne!(relative, filename);
}

#[test]
fn copy_content_yanks_file_text() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("notes.txt"), b"first\nsecond\n").unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();

    trail::actions::apply(trail::actions::Action::CopyContent, &mut state).unwrap();
    assert_eq!(state.last_yank.as_deref(), Some("first\nsecond\n"));
}

#[test]
fn copy_content_yanks_directory_listing() {
    let dir = tempfile::tempdir().unwrap();
    // Directories sort first, so `sub` is the selection at index 0.
    fs::create_dir(dir.path().join("sub")).unwrap();
    fs::write(dir.path().join("sub").join("inner.txt"), b"").unwrap();
    fs::create_dir(dir.path().join("sub").join("deeper")).unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();

    trail::actions::apply(trail::actions::Action::CopyContent, &mut state).unwrap();
    assert_eq!(state.last_yank.as_deref(), Some("deeper/\ninner.txt"));
}

#[test]
fn copy_content_of_a_binary_file_reports_an_error() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("blob.bin"), [0u8, 1, 0, 2]).unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();

    trail::actions::apply(trail::actions::Action::CopyContent, &mut state).unwrap();
    assert!(
        state.last_yank.is_none(),
        "nothing should be yanked for a binary file"
    );
    let err = state
        .error_text()
        .expect("a binary yank should surface an error");
    assert!(
        err.contains("binary"),
        "error should name the cause; got: {err}"
    );
}

// ── Notices ───────────────────────────────────────────────────────────────────

/// The bug this guards: the success branch of `:bookmark` set the error field,
/// so a bookmark that saved correctly was announced as
/// `Error: bookmark added: name`.
#[test]
fn a_saved_bookmark_is_reported_as_an_outcome_not_an_error() {
    let dir = tempfile::tempdir().unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();

    trail::actions::apply(
        trail::actions::Action::ExecuteCommand(ParsedCommand::Bookmark("work".to_owned())),
        &mut state,
    )
    .unwrap();

    assert!(
        state.error_text().is_none(),
        "saving a bookmark is not a failure"
    );
    let notice = state.notice.as_ref().expect("the outcome should be shown");
    assert_eq!(notice.level, trail::app::state::NoticeLevel::Info);
    assert!(
        notice.text.contains("bookmark added: work"),
        "the notice should name the bookmark; got: {}",
        notice.text
    );
}

/// A yank reports itself through the notice channel, summarized: `yc` puts
/// whole files on the clipboard and the status bar holds one line.
#[test]
fn a_yank_posts_a_summarized_notice() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("long.txt"), "first line\nsecond line\n").unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();

    trail::actions::apply(trail::actions::Action::CopyContent, &mut state).unwrap();

    // The clipboard itself may be unreachable (headless CI), which is reported
    // as an error rather than an outcome — but either way the notice must be
    // one line and must not carry the whole file.
    let notice = state.notice.as_ref().expect("a yank should report itself");
    assert!(
        !notice.text.contains('\n'),
        "a notice is one line; got: {:?}",
        notice.text
    );
    if notice.level == trail::app::state::NoticeLevel::Info {
        assert!(
            notice.text.starts_with("yanked: first line"),
            "the notice should summarize the yank; got: {}",
            notice.text
        );
        assert!(
            notice.text.ends_with('…'),
            "the elision should be marked; got: {}",
            notice.text
        );
    }
}

// ── Wildcards in :mv / :cp ────────────────────────────────────────────────────

/// The reported gap: `:mv *.md docs/` resolved a destination literally named
/// `*.md docs/`. A wildcard in the first token now means "several files, then a
/// destination".
#[test]
fn mv_with_a_wildcard_parses_as_a_pattern_and_a_destination() {
    assert_eq!(
        parse("mv *.md notes", false).unwrap(),
        ParsedCommand::MvMatching {
            pattern: "*.md".to_owned(),
            dest: "notes".to_owned(),
        }
    );
    assert_eq!(
        parse("cp note?.txt ../backup", false).unwrap(),
        ParsedCommand::CpMatching {
            pattern: "note?.txt".to_owned(),
            dest: "../backup".to_owned(),
        }
    );
}

/// The one-argument form has to keep working, including for a destination with a
/// space in it — that is what makes the wildcard the only signal.
#[test]
fn mv_without_a_wildcard_is_still_one_destination() {
    assert_eq!(
        parse("mv ../sibling", false).unwrap(),
        ParsedCommand::Mv("../sibling".to_owned())
    );
    assert_eq!(
        parse("mv my folder", false).unwrap(),
        ParsedCommand::Mv("my folder".to_owned())
    );
}

#[test]
fn a_pattern_without_a_destination_is_an_error() {
    let err = parse("mv *.md", false).unwrap_err();
    assert!(matches!(err, ParseError::MissingArgument(_)));
    assert!(
        err.to_string().contains("destination"),
        "the message should say what is missing; got: {err}"
    );
}

#[test]
fn mv_with_a_wildcard_moves_every_match_into_the_destination() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("one.md"), b"1").unwrap();
    fs::write(dir.path().join("two.md"), b"2").unwrap();
    fs::write(dir.path().join("keep.txt"), b"k").unwrap();
    fs::create_dir(dir.path().join("notes")).unwrap();

    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();
    trail::actions::apply(
        trail::actions::Action::ExecuteCommand(ParsedCommand::MvMatching {
            pattern: "*.md".to_owned(),
            dest: "notes".to_owned(),
        }),
        &mut state,
    )
    .unwrap();

    assert!(
        state.error_text().is_none(),
        "the move should succeed; got {:?}",
        state.error_text()
    );
    assert!(dir.path().join("notes/one.md").exists());
    assert!(dir.path().join("notes/two.md").exists());
    assert!(
        dir.path().join("keep.txt").exists(),
        "a non-matching file must be left alone"
    );
    let notice = state.notice.as_ref().expect("the count should be reported");
    assert!(
        notice.text.contains('2'),
        "the notice should say how many moved; got: {}",
        notice.text
    );
}

/// Several files cannot be moved onto one path, so a destination that is not a
/// directory is refused before anything is touched.
#[test]
fn a_pattern_needs_a_directory_to_move_into() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("one.md"), b"1").unwrap();
    fs::write(dir.path().join("two.md"), b"2").unwrap();

    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();
    trail::actions::apply(
        trail::actions::Action::ExecuteCommand(ParsedCommand::MvMatching {
            pattern: "*.md".to_owned(),
            dest: "collected.md".to_owned(),
        }),
        &mut state,
    )
    .unwrap();

    let err = state.error_text().expect("this must be refused");
    assert!(
        err.contains("not a directory"),
        "the error should say why; got: {err}"
    );
    assert!(
        dir.path().join("one.md").exists() && dir.path().join("two.md").exists(),
        "nothing may have moved"
    );
}

#[test]
fn a_pattern_that_matches_nothing_says_so() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir(dir.path().join("notes")).unwrap();
    let mut state = trail::app::state::AppState::new(dir.path().to_owned()).unwrap();

    trail::actions::apply(
        trail::actions::Action::ExecuteCommand(ParsedCommand::MvMatching {
            pattern: "*.md".to_owned(),
            dest: "notes".to_owned(),
        }),
        &mut state,
    )
    .unwrap();

    let err = state.error_text().expect("an empty match is an error");
    assert!(err.contains("nothing matches"), "got: {err}");
}

// ── :term ─────────────────────────────────────────────────────────────────────

#[test]
fn term_commands_parse() {
    use trail::terminal::TermCommand;

    let term = |text: &str| parse(text, false);
    assert_eq!(term("term"), Ok(ParsedCommand::Term(TermCommand::Toggle)));
    assert_eq!(
        term("term new"),
        Ok(ParsedCommand::Term(TermCommand::New(None)))
    );
    assert_eq!(
        term("term new gitbash"),
        Ok(ParsedCommand::Term(TermCommand::New(Some(
            "gitbash".to_owned()
        ))))
    );
    assert_eq!(
        term("term close"),
        Ok(ParsedCommand::Term(TermCommand::Close))
    );
    assert_eq!(term("term max"), Ok(ParsedCommand::Term(TermCommand::Max)));
    assert_eq!(
        term("term 2"),
        Ok(ParsedCommand::Term(TermCommand::Select(2)))
    );
}

#[test]
fn term_rejects_what_it_cannot_do() {
    for bad in ["term 0", "term split", "term new a b", "term close now"] {
        assert!(
            matches!(parse(bad, false), Err(ParseError::InvalidArgument(_))),
            "{bad}"
        );
    }
}