haz-cli 0.2.0

Command-line task runner: tracks task DAGs across a workspace of projects, executes them with caching.
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
//! Pure dispatcher for the `haz init` scaffold TUI.
//!
//! [`dispatch`] maps a crossterm event and the current
//! [`TuiState`] to a [`DispatchResult`], mutating the state
//! in-place and performing no IO. Side effects the driver must
//! perform (loading children from disk, leaving the tree screen to
//! commit) are returned as enum variants, so every key binding is
//! exhaustively unit-testable without a terminal.

use std::path::Path;

use crossterm::event::{Event, KeyCode, KeyEventKind, KeyModifiers};

use crate::commands::init::model::{CycleOutcome, ExpandOutcome};
use crate::commands::init::tui::{DispatchResult, TuiFocus, TuiState};

/// Apply a single crossterm event to the TUI state and report
/// what the driver should do next.
///
/// The function clears the state's transient fields (`status`,
/// `bell_pending`) at the start of every call so each keystroke
/// produces a fresh signal. Set both inside this function when
/// the binding warrants them.
pub(super) fn dispatch(event: &Event, state: &mut TuiState) -> DispatchResult {
    state.status = None;
    state.bell_pending = false;

    let Event::Key(key) = event else {
        return DispatchResult::Continue;
    };
    if key.kind != KeyEventKind::Press {
        return DispatchResult::Continue;
    }

    // Ctrl+C aborts before any other interpretation so the user
    // can always bail out from anywhere, including the help
    // overlay.
    if key.modifiers.contains(KeyModifiers::CONTROL) && matches!(key.code, KeyCode::Char('c' | 'C'))
    {
        return DispatchResult::Abort;
    }

    // Help overlay swallows the next keystroke and closes.
    if state.help_visible {
        state.help_visible = false;
        return DispatchResult::Continue;
    }

    match key.code {
        KeyCode::Up => {
            move_focus(state, FocusDirection::Prev);
            DispatchResult::Continue
        }
        KeyCode::Down => {
            move_focus(state, FocusDirection::Next);
            DispatchResult::Continue
        }
        KeyCode::Right => expand_current(state),
        KeyCode::Left => {
            collapse_current(state);
            DispatchResult::Continue
        }
        KeyCode::Char(' ') => cycle_current(state),
        KeyCode::Enter => DispatchResult::ExitCommit,
        KeyCode::Char('h' | 'H') => {
            state.hidden_visible = !state.hidden_visible;
            state.status = Some(if state.hidden_visible {
                "hidden directories shown".to_string()
            } else {
                "hidden directories hidden".to_string()
            });
            DispatchResult::ReloadTreeForVisibility
        }
        KeyCode::Char('?') => {
            state.help_visible = true;
            DispatchResult::Continue
        }
        KeyCode::Char('q' | 'Q') | KeyCode::Esc => DispatchResult::ExitCancel,
        _ => DispatchResult::Continue,
    }
}

#[derive(Clone, Copy)]
enum FocusDirection {
    Next,
    Prev,
}

fn move_focus(state: &mut TuiState, dir: FocusDirection) {
    let visible = state.tree.visible_nodes().len();
    if visible == 0 {
        // Cannot happen with a well-formed tree (the root is
        // always visible) but stay defensive.
        return;
    }
    let total = visible + 1; // commit button is the (visible)th slot
    let current = match state.focus {
        TuiFocus::Tree => state.tree.focused_visible_index(),
        TuiFocus::CommitButton => visible,
    };
    let next = match dir {
        FocusDirection::Next => (current + 1) % total,
        FocusDirection::Prev => {
            if current == 0 {
                total - 1
            } else {
                current - 1
            }
        }
    };
    if next == visible {
        state.focus = TuiFocus::CommitButton;
    } else {
        state.focus = TuiFocus::Tree;
        state.tree.focus_at_visible_index(next);
    }
}

fn expand_current(state: &mut TuiState) -> DispatchResult {
    if state.focus != TuiFocus::Tree {
        return DispatchResult::Continue;
    }
    let outcome = state.tree.try_expand_focused();
    if matches!(outcome, ExpandOutcome::NeedsChildrenLoaded) {
        // The driver does the read and retries the expand in
        // the same keystroke so the user sees a single decisive
        // outcome per Right-arrow press.
        return DispatchResult::LoadChildrenThenRetryExpand;
    }
    apply_expand_outcome_signal(state, outcome);
    DispatchResult::Continue
}

/// Translate an `ExpandOutcome` into the user-visible signal.
/// `Expanded` and `AlreadyExpanded` are silent (success or
/// no-op); `RefusedNoSubdirs` rings the bell and shows a status
/// message; `NeedsChildrenLoaded` is treated as a no-op here
/// because the driver only calls this helper after a load.
pub(super) fn apply_expand_outcome_signal(state: &mut TuiState, outcome: ExpandOutcome) {
    match outcome {
        ExpandOutcome::Expanded
        | ExpandOutcome::AlreadyExpanded
        | ExpandOutcome::NeedsChildrenLoaded => {}
        ExpandOutcome::RefusedNoSubdirs => {
            let path_display = display_workspace_path(&state.tree.focused().path);
            state.bell_pending = true;
            state.status = Some(format!("cannot expand `{path_display}`: no subdirectories"));
        }
    }
}

fn collapse_current(state: &mut TuiState) {
    if state.focus != TuiFocus::Tree {
        return;
    }
    state.tree.collapse_focused();
}

fn cycle_current(state: &mut TuiState) -> DispatchResult {
    if state.focus != TuiFocus::Tree {
        return DispatchResult::Continue;
    }
    let outcome = state.tree.cycle_focused();
    if matches!(outcome, CycleOutcome::NeedsChildrenLoaded) {
        // The driver does the disk read and retries the cycle in
        // the same keystroke so the user sees a single, decisive
        // transition per Space press.
        return DispatchResult::LoadChildrenThenRetryCycle;
    }
    apply_cycle_outcome_signal(state, outcome);
    DispatchResult::Continue
}

/// Translate a `CycleOutcome` into the user-visible signal:
/// terminal bell and status message for the two refusal cases,
/// no-op for `Advanced`. `NeedsChildrenLoaded` is treated as a
/// no-op here because the driver only calls this helper after a
/// load (where the outcome cannot be `NeedsChildrenLoaded`
/// again).
pub(super) fn apply_cycle_outcome_signal(state: &mut TuiState, outcome: CycleOutcome) {
    match outcome {
        CycleOutcome::Advanced(_) | CycleOutcome::NeedsChildrenLoaded => {}
        CycleOutcome::RefusedEmptyGlob => {
            let path_display = display_workspace_path(&state.tree.focused().path);
            state.bell_pending = true;
            state.status = Some(format!(
                "skipped projects-parent for `{path_display}`: no subdirectories",
            ));
        }
        CycleOutcome::RefusedSubtreeLock => {
            let path_display = display_workspace_path(&state.tree.focused().path);
            state.bell_pending = true;
            state.status = Some(format!(
                "cannot cycle `{path_display}`: under a projects-parent directory",
            ));
        }
    }
}

fn display_workspace_path(p: &Path) -> String {
    p.to_string_lossy().into_owned()
}

#[cfg(test)]
mod tests {
    use std::ffi::OsString;
    use std::path::{Path, PathBuf};

    use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};

    use crate::commands::init::model::{Node, SelectionState, Tree};
    use crate::commands::init::tui::gitignore::GitignoreMatcher;
    use crate::commands::init::tui::{DispatchResult, TuiFocus, TuiState};

    use super::dispatch;

    fn press(code: KeyCode) -> Event {
        press_with(code, KeyModifiers::NONE)
    }

    fn press_with(code: KeyCode, mods: KeyModifiers) -> Event {
        Event::Key(KeyEvent {
            code,
            modifiers: mods,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        })
    }

    fn release(code: KeyCode) -> Event {
        Event::Key(KeyEvent {
            code,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Release,
            state: KeyEventState::NONE,
        })
    }

    fn dir(name: &str, path: &str) -> Node {
        Node::new(OsString::from(name), PathBuf::from(path))
    }

    fn loaded_dir(name: &str, path: &str, children: Vec<Node>) -> Node {
        let mut node = dir(name, path);
        node.children = children;
        node.children_loaded = true;
        node
    }

    fn loaded_empty(name: &str, path: &str) -> Node {
        loaded_dir(name, path, Vec::new())
    }

    fn build_state(root: Node) -> TuiState {
        let mut state = TuiState {
            tree: Tree::new(root),
            focus: TuiFocus::Tree,
            cwd_host: PathBuf::from("/host"),
            gitignore: GitignoreMatcher::new(Path::new("/host")),
            hidden_visible: false,
            status: None,
            help_visible: false,
            bell_pending: false,
        };
        // Make sure we are starting in a known clean state.
        let _ = dispatch(&release(KeyCode::Esc), &mut state);
        state.status = None;
        state.bell_pending = false;
        state
    }

    // --- key release events are no-ops -------------------------

    #[test]
    fn release_events_do_not_mutate_state() {
        let mut root = loaded_dir("root", "/", vec![loaded_empty("a", "/a")]);
        root.expanded = true;
        let mut state = build_state(root);
        let before_focus = state.focus;
        let result = dispatch(&release(KeyCode::Down), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert_eq!(state.focus, before_focus);
    }

    // --- Ctrl+C aborts regardless of overlay state -------------

    #[test]
    fn ctrl_c_returns_abort() {
        let mut state = build_state(loaded_empty("root", "/"));
        let result = dispatch(
            &press_with(KeyCode::Char('c'), KeyModifiers::CONTROL),
            &mut state,
        );
        assert_eq!(result, DispatchResult::Abort);
    }

    #[test]
    fn ctrl_c_aborts_even_when_help_overlay_is_open() {
        let mut state = build_state(loaded_empty("root", "/"));
        dispatch(&press(KeyCode::Char('?')), &mut state);
        assert!(state.help_visible);
        let result = dispatch(
            &press_with(KeyCode::Char('c'), KeyModifiers::CONTROL),
            &mut state,
        );
        assert_eq!(result, DispatchResult::Abort);
    }

    // --- help overlay swallows the next keystroke --------------

    #[test]
    fn help_overlay_closes_on_next_keystroke() {
        let mut state = build_state(loaded_empty("root", "/"));
        dispatch(&press(KeyCode::Char('?')), &mut state);
        assert!(state.help_visible);
        let result = dispatch(&press(KeyCode::Char('q')), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert!(!state.help_visible);
    }

    // --- navigation wraps via the commit button ----------------

    #[test]
    fn down_at_last_visible_tree_row_moves_to_commit_button() {
        let mut root = loaded_dir(
            "root",
            "/",
            vec![loaded_empty("a", "/a"), loaded_empty("b", "/b")],
        );
        root.expanded = true;
        let mut state = build_state(root);
        // root -> a
        dispatch(&press(KeyCode::Down), &mut state);
        // a -> b
        dispatch(&press(KeyCode::Down), &mut state);
        assert_eq!(state.focus, TuiFocus::Tree);
        // b -> commit button
        dispatch(&press(KeyCode::Down), &mut state);
        assert_eq!(state.focus, TuiFocus::CommitButton);
        // commit button -> root (wrap)
        dispatch(&press(KeyCode::Down), &mut state);
        assert_eq!(state.focus, TuiFocus::Tree);
        assert_eq!(state.tree.focused().path, PathBuf::from("/"));
    }

    #[test]
    fn up_from_root_wraps_to_commit_button() {
        let mut state = build_state(loaded_empty("root", "/"));
        // Root only, one visible row -> Up wraps to commit button.
        let result = dispatch(&press(KeyCode::Up), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert_eq!(state.focus, TuiFocus::CommitButton);
    }

    // --- Space cycle (AUX-003) ---------------------------------

    #[test]
    fn space_advances_state_when_focused_on_tree_row() {
        let mut state = build_state(loaded_empty("root", "/"));
        dispatch(&press(KeyCode::Char(' ')), &mut state);
        assert_eq!(state.tree.focused().state, SelectionState::Project);
    }

    #[test]
    fn space_on_commit_button_is_noop() {
        let mut state = build_state(loaded_empty("root", "/"));
        // Move focus to commit button.
        dispatch(&press(KeyCode::Down), &mut state);
        assert_eq!(state.focus, TuiFocus::CommitButton);
        dispatch(&press(KeyCode::Char(' ')), &mut state);
        assert_eq!(state.tree.focused().state, SelectionState::None);
    }

    // --- Space on an unloaded directory requests the load and retry ---

    #[test]
    fn space_on_unloaded_directory_at_project_state_requests_load_then_retry() {
        // children_loaded=false. From Project state the next
        // cycle step is ProjectsParent, which the model cannot
        // evaluate without knowing whether subdirs exist. The
        // dispatcher signals the driver to load and re-issue
        // the cycle so the user sees a single decisive
        // transition per Space press.
        let mut root = Node::new(OsString::from("root"), PathBuf::from("/"));
        root.state = SelectionState::Project;
        let mut state = build_state(root);
        let result = dispatch(&press(KeyCode::Char(' ')), &mut state);
        assert_eq!(result, DispatchResult::LoadChildrenThenRetryCycle);
        // State unchanged at this point; the driver does the
        // load + retry, which the dispatcher unit test cannot
        // exercise.
        assert_eq!(state.tree.focused().state, SelectionState::Project);
    }

    // --- AUX-004 rule 1: empty-glob refusal --------------------

    #[test]
    fn space_refusal_when_no_subdirs_skips_to_none_and_signals() {
        // On a leaf, ProjectsParent is unreachable: the cycle
        // moves past it to None, AND the refusal channels (bell
        // + status message) still fire so the user perceives
        // why ProjectsParent didn't take.
        let mut state = build_state(loaded_empty("root", "/"));
        dispatch(&press(KeyCode::Char(' ')), &mut state); // -> Project
        let result = dispatch(&press(KeyCode::Char(' ')), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert_eq!(state.tree.focused().state, SelectionState::None);
        assert!(state.bell_pending, "AUX-004 refusal must ring the bell");
        let status = state.status.as_deref().unwrap_or("");
        assert!(
            status.contains("no subdirectories"),
            "status message should explain the refusal: {status}",
        );
    }

    // --- AUX-004 rule 2: sub-tree lockout ----------------------

    #[test]
    fn space_refusal_under_locked_subtree_sets_status_and_bell() {
        let mut src = loaded_empty("src", "/lib/src");
        let mut lib = loaded_dir("lib", "/lib", vec![src.clone()]);
        lib.state = SelectionState::ProjectsParent;
        lib.expanded = true;
        let mut root = loaded_dir("root", "/", vec![lib]);
        root.expanded = true;
        // Tweak src state to verify it stays put under lockout.
        src.state = SelectionState::None;
        let mut state = build_state(root);
        // Move focus down to lib/src (root -> lib -> lib/src).
        dispatch(&press(KeyCode::Down), &mut state);
        dispatch(&press(KeyCode::Down), &mut state);
        assert_eq!(state.tree.focused().path, PathBuf::from("/lib/src"));
        let result = dispatch(&press(KeyCode::Char(' ')), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert!(state.bell_pending, "lockout refusal must ring the bell");
        let status = state.status.as_deref().unwrap_or("");
        assert!(
            status.contains("projects-parent"),
            "lockout status should explain the cause: {status}",
        );
        assert_eq!(state.tree.focused().state, SelectionState::None);
    }

    // --- right-arrow expansion ---------------------------------

    #[test]
    fn right_arrow_expands_focused_directory_with_subdirectories() {
        let root = loaded_dir("root", "/", vec![loaded_empty("a", "/a")]);
        let mut state = build_state(root);
        assert!(!state.tree.focused().expanded);
        let result = dispatch(&press(KeyCode::Right), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert!(state.tree.focused().expanded);
    }

    #[test]
    fn right_arrow_on_loaded_leaf_refuses_with_bell_and_status() {
        // No subdirectories: expansion would reveal nothing, so
        // it is refused. `expanded` MUST stay false; the user
        // gets the bell + status message.
        let mut state = build_state(loaded_empty("root", "/"));
        let result = dispatch(&press(KeyCode::Right), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert!(!state.tree.focused().expanded);
        assert!(state.bell_pending);
        let status = state.status.as_deref().unwrap_or("");
        assert!(
            status.contains("no subdirectories"),
            "refusal status should explain the reason: {status}",
        );
    }

    #[test]
    fn right_arrow_on_unloaded_directory_requests_load_then_retry() {
        let root = Node::new(OsString::from("root"), PathBuf::from("/"));
        // children_loaded is false by default.
        let mut state = build_state(root);
        let result = dispatch(&press(KeyCode::Right), &mut state);
        assert_eq!(result, DispatchResult::LoadChildrenThenRetryExpand);
        // expanded MUST stay false until the driver loads and
        // retries: the empty-vs-non-empty decision is not made
        // until after the load.
        assert!(!state.tree.focused().expanded);
    }

    #[test]
    fn right_arrow_on_commit_button_is_noop() {
        let mut state = build_state(loaded_empty("root", "/"));
        dispatch(&press(KeyCode::Down), &mut state); // focus button
        let result = dispatch(&press(KeyCode::Right), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert_eq!(state.focus, TuiFocus::CommitButton);
    }

    // --- left-arrow collapse -----------------------------------

    #[test]
    fn left_arrow_collapses_focused_directory() {
        let mut root = loaded_dir("root", "/", vec![loaded_empty("a", "/a")]);
        root.expanded = true;
        let mut state = build_state(root);
        assert!(state.tree.focused().expanded);
        let result = dispatch(&press(KeyCode::Left), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert!(!state.tree.focused().expanded);
    }

    // --- Enter always commits ----------------------------------

    #[test]
    fn enter_on_tree_row_returns_exit_commit() {
        let mut state = build_state(loaded_empty("root", "/"));
        let result = dispatch(&press(KeyCode::Enter), &mut state);
        assert_eq!(result, DispatchResult::ExitCommit);
    }

    #[test]
    fn enter_on_commit_button_returns_exit_commit() {
        let mut state = build_state(loaded_empty("root", "/"));
        dispatch(&press(KeyCode::Down), &mut state);
        assert_eq!(state.focus, TuiFocus::CommitButton);
        let result = dispatch(&press(KeyCode::Enter), &mut state);
        assert_eq!(result, DispatchResult::ExitCommit);
    }

    // --- H toggle ----------------------------------------------

    #[test]
    fn h_toggles_hidden_visibility_and_requests_reload() {
        let mut state = build_state(loaded_empty("root", "/"));
        assert!(!state.hidden_visible);
        let result = dispatch(&press(KeyCode::Char('h')), &mut state);
        assert!(state.hidden_visible);
        assert_eq!(result, DispatchResult::ReloadTreeForVisibility);
        assert!(state.status.as_deref().unwrap_or("").contains("shown"));
        let result = dispatch(&press(KeyCode::Char('h')), &mut state);
        assert!(!state.hidden_visible);
        assert_eq!(result, DispatchResult::ReloadTreeForVisibility);
        assert!(state.status.as_deref().unwrap_or("").contains("hidden"));
    }

    #[test]
    fn capital_h_also_toggles_hidden() {
        let mut state = build_state(loaded_empty("root", "/"));
        let result = dispatch(&press(KeyCode::Char('H')), &mut state);
        assert!(state.hidden_visible);
        assert_eq!(result, DispatchResult::ReloadTreeForVisibility);
    }

    // --- q / Esc cancel ----------------------------------------

    #[test]
    fn q_returns_exit_cancel() {
        let mut state = build_state(loaded_empty("root", "/"));
        let result = dispatch(&press(KeyCode::Char('q')), &mut state);
        assert_eq!(result, DispatchResult::ExitCancel);
    }

    #[test]
    fn esc_returns_exit_cancel() {
        let mut state = build_state(loaded_empty("root", "/"));
        let result = dispatch(&press(KeyCode::Esc), &mut state);
        assert_eq!(result, DispatchResult::ExitCancel);
    }

    // --- transient state cleared on every dispatch -------------

    #[test]
    fn status_cleared_on_each_dispatch_unless_set_by_handler() {
        let mut state = build_state(loaded_empty("root", "/"));
        // Set status via H toggle.
        dispatch(&press(KeyCode::Char('h')), &mut state);
        assert!(state.status.is_some());
        // An unrelated keystroke (Up) clears it.
        dispatch(&press(KeyCode::Up), &mut state);
        assert!(state.status.is_none());
    }
}