jk 0.2.2

A log-first terminal UI for Jujutsu
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
//! Binary entry point for the `jk` terminal UI.
//!
//! This crate owns command-line parsing, terminal lifecycle, and the bridge between crossterm input
//! events and backend-neutral TUI actions. The product behavior is intentionally delegated to
//! `jk-cli` and `jk-tui` so the binary stays a thin orchestration layer.

use std::path::PathBuf;

use clap::{Parser, Subcommand};
use color_eyre::Result;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::style::force_color_output;
use jk_cli::{JjDiff, JjLog, JjLogCommand};
use jk_tui::diff_view::{DiffAction, DiffActionResult, DiffView};
use jk_tui::log_view::{ActionResult, LogView};

mod key;

use key::AppKey;

/// Command-line options for the first log-oriented `jk` surface.
#[derive(Debug, Parser)]
#[command(version, about)]
struct Args {
    /// Repository path to pass to jj.
    #[arg(short = 'R', long = "repository")]
    repository: Option<PathBuf>,

    /// Maximum number of log entries to render for the default command.
    #[arg(short = 'n', long)]
    limit: Option<usize>,

    /// View to open. If omitted, jk follows jj's configured default command.
    #[command(subcommand)]
    command: Option<Command>,
}

/// Top-level view commands supported by the binary.
#[derive(Debug, Subcommand)]
enum Command {
    /// Show the jj log view.
    Log(LogArgs),

    /// Show the jj diff view for a revision.
    Diff(DiffArgs),
}

/// Options for the explicit `jk log` command.
#[derive(Debug, Parser)]
struct LogArgs {
    /// Maximum number of log entries to render.
    #[arg(short = 'n', long)]
    limit: Option<usize>,
}

/// Options for the explicit `jk diff` command.
#[derive(Debug, Parser)]
struct DiffArgs {
    /// Revision to diff against its parent.
    #[arg(default_value = "@")]
    revision: String,
}

fn main() -> Result<()> {
    color_eyre::install()?;
    tracing_subscriber::fmt::init();
    let args = Args::parse();
    let source = log_source(&args);
    let diff_source = diff_source(&args);
    let app = if let Some(Command::Diff(diff_args)) = &args.command {
        let snapshot = diff_source.load(&diff_args.revision);
        let diff = match snapshot {
            Ok(snapshot) => DiffView::new(snapshot),
            Err(error) => DiffView::from_error(
                diff_args.revision.clone(),
                format!("jj diff -r {}", diff_args.revision),
                error.to_string(),
            ),
        };
        AppView::Diff {
            log: None,
            diff: Box::new(diff),
        }
    } else {
        let entries = source.load()?;
        AppView::Log(LogView::new(entries))
    };

    run_terminal(app, source, &diff_source)?;
    Ok(())
}

/// Builds the log source that matches the requested command-line view.
///
/// Bare `jk` intentionally starts from jj's configured default command, while `jk log` forces the
/// explicit log command. The top-level limit applies to both forms unless the subcommand provides a
/// narrower value.
fn log_source(args: &Args) -> JjLog {
    let (command, limit) = match &args.command {
        Some(Command::Log(log_args)) => (JjLogCommand::Log, log_args.limit.or(args.limit)),
        Some(Command::Diff(_)) | None => (JjLogCommand::ConfiguredDefault, args.limit),
    };

    let source = JjLog::default().with_command(command).with_limit(limit);
    if let Some(repository) = &args.repository {
        source.with_repository(repository)
    } else {
        source
    }
}

/// Builds the diff source for selected-change inspection.
fn diff_source(args: &Args) -> JjDiff {
    let source = JjDiff::default();
    if let Some(repository) = &args.repository {
        source.with_repository(repository)
    } else {
        source
    }
}

/// Active top-level application view.
#[derive(Debug)]
enum AppView {
    Log(LogView),
    Diff {
        log: Option<LogView>,
        diff: Box<DiffView>,
    },
}

/// Owns the terminal event loop for the current log-first application.
///
/// The view remains responsible for state transitions and rendering. This loop only translates
/// terminal events, performs I/O requested by the view, and redraws when input or terminal resize
/// events can change the screen.
fn run_terminal(mut app: AppView, mut source: JjLog, diff_source: &JjDiff) -> Result<()> {
    // jj should keep configured colors even when the parent process was run by an agent or tool
    // that exports NO_COLOR.
    force_color_output(true);
    let mut terminal = ratatui::try_init().inspect_err(|_| ratatui::restore())?;
    let _terminal_restore = TerminalRestore;
    let mut needs_redraw = true;
    let mut input_mode = InputMode::Normal;

    loop {
        if needs_redraw {
            terminal.draw(|frame| match &mut app {
                AppView::Log(log) => log.render(frame),
                AppView::Diff { diff, .. } => match &input_mode {
                    InputMode::Normal => diff.render(frame),
                    InputMode::DiffSearch { query } => {
                        let status = format!("/{query}");
                        diff.render_with_status(frame, &status);
                    }
                },
            })?;
            needs_redraw = false;
        }

        match event::read()? {
            Event::Key(key) => {
                if handle_input_mode(&mut app, &mut input_mode, key) == InputModeResult::Handled {
                    needs_redraw = true;
                    continue;
                }

                let AppKey::Action(action) = AppKey::from_crossterm(key) else {
                    match AppKey::from_crossterm(key) {
                        AppKey::StartSearch if matches!(app, AppView::Diff { .. }) => {
                            input_mode = InputMode::DiffSearch {
                                query: String::new(),
                            };
                            needs_redraw = true;
                        }
                        AppKey::SearchNext => {
                            apply_diff_search_action(&mut app, DiffAction::SearchNext);
                            needs_redraw = true;
                        }
                        AppKey::SearchPrevious => {
                            apply_diff_search_action(&mut app, DiffAction::SearchPrevious);
                            needs_redraw = true;
                        }
                        _ => {}
                    }
                    continue;
                };

                if apply_action(&mut app, &mut source, diff_source, action) == AppLoop::Quit {
                    break;
                }
                needs_redraw = true;
            }
            Event::Resize(_, _) => {
                needs_redraw = true;
            }
            _ => {}
        }
    }

    Ok(())
}

/// Transient input modes owned by the terminal loop.
#[derive(Clone, Debug, Eq, PartialEq)]
enum InputMode {
    Normal,
    DiffSearch { query: String },
}

/// Whether an input-mode handler consumed a key event.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum InputModeResult {
    Handled,
    Unhandled,
}

/// Handles key input while a prompt-like mode is active.
fn handle_input_mode(
    app: &mut AppView,
    input_mode: &mut InputMode,
    key: KeyEvent,
) -> InputModeResult {
    let InputMode::DiffSearch { query } = input_mode else {
        return InputModeResult::Unhandled;
    };

    match key {
        KeyEvent {
            code: KeyCode::Esc, ..
        } => {
            *input_mode = InputMode::Normal;
            InputModeResult::Handled
        }
        KeyEvent {
            code: KeyCode::Enter,
            ..
        } => {
            apply_diff_search_action(app, DiffAction::Search(query.clone()));
            *input_mode = InputMode::Normal;
            InputModeResult::Handled
        }
        KeyEvent {
            code: KeyCode::Backspace,
            ..
        } => {
            query.pop();
            InputModeResult::Handled
        }
        KeyEvent {
            code: KeyCode::Char(character),
            modifiers,
            ..
        } if !modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) => {
            query.push(character);
            InputModeResult::Handled
        }
        _ => InputModeResult::Handled,
    }
}

/// Applies a search-only diff action when the active view supports it.
fn apply_diff_search_action(app: &mut AppView, action: DiffAction) {
    if let AppView::Diff { diff, .. } = app {
        let _ = diff.apply(action);
    }
}

/// Applies an action to the active view and performs any requested I/O.
fn apply_action(
    app: &mut AppView,
    source: &mut JjLog,
    diff_source: &JjDiff,
    action: jk_tui::log_view::LogAction,
) -> AppLoop {
    let transition = match app {
        AppView::Log(log) => apply_log_action(log, source, diff_source, action),
        AppView::Diff { diff, .. } => apply_diff_action(diff, diff_source, action),
    };

    match transition {
        AppTransition::Continue => AppLoop::Continue,
        AppTransition::OpenDiff(diff) => {
            let previous = std::mem::replace(app, AppView::Log(LogView::default()));
            if let AppView::Log(log) = previous {
                *app = AppView::Diff {
                    log: Some(log),
                    diff,
                };
            }
            AppLoop::Continue
        }
        AppTransition::ReturnToLog => {
            let previous = std::mem::replace(app, AppView::Log(LogView::default()));
            if let AppView::Diff { log, diff } = previous {
                if let Some(log) = log {
                    *app = AppView::Log(log);
                } else {
                    *app = AppView::Diff { log: None, diff };
                }
            }
            AppLoop::Continue
        }
        AppTransition::Quit => AppLoop::Quit,
    }
}

/// Applies an action while the log view is active.
fn apply_log_action(
    log: &mut LogView,
    source: &mut JjLog,
    diff_source: &JjDiff,
    action: jk_tui::log_view::LogAction,
) -> AppTransition {
    match log.apply(action) {
        ActionResult::Refresh => refresh_log(log, source),
        ActionResult::SwitchHome => {
            switch_log_command(log, source, JjLogCommand::ConfiguredDefault);
        }
        ActionResult::SwitchLog => switch_log_command(log, source, JjLogCommand::Log),
        ActionResult::Quit => return AppTransition::Quit,
        _ => {}
    }

    if action == jk_tui::log_view::LogAction::OpenDiff {
        let Some(change_id) = log.selected_change_id().map(ToOwned::to_owned) else {
            return AppTransition::Continue;
        };

        match diff_source.load(&change_id) {
            Ok(snapshot) => {
                let diff = DiffView::new(snapshot);
                return AppTransition::OpenDiff(Box::new(diff));
            }
            Err(error) => log.show_error(error.to_string()),
        }
    }

    AppTransition::Continue
}

/// Applies an action while the diff view is active.
fn apply_diff_action(
    diff: &mut DiffView,
    diff_source: &JjDiff,
    action: jk_tui::log_view::LogAction,
) -> AppTransition {
    let diff_action = match action {
        jk_tui::log_view::LogAction::Previous => DiffAction::ScrollPrevious,
        jk_tui::log_view::LogAction::Next => DiffAction::ScrollNext,
        jk_tui::log_view::LogAction::PagePrevious => DiffAction::PagePrevious,
        jk_tui::log_view::LogAction::PageNext => DiffAction::PageNext,
        jk_tui::log_view::LogAction::First => DiffAction::First,
        jk_tui::log_view::LogAction::Last => DiffAction::Last,
        jk_tui::log_view::LogAction::PreviousFile => DiffAction::PreviousFile,
        jk_tui::log_view::LogAction::NextFile => DiffAction::NextFile,
        jk_tui::log_view::LogAction::PreviousHunk => DiffAction::PreviousHunk,
        jk_tui::log_view::LogAction::NextHunk => DiffAction::NextHunk,
        jk_tui::log_view::LogAction::FoldHunk => DiffAction::FoldHunk,
        jk_tui::log_view::LogAction::UnfoldHunk => DiffAction::UnfoldHunk,
        jk_tui::log_view::LogAction::HorizontalPrevious => DiffAction::ScrollLeft,
        jk_tui::log_view::LogAction::HorizontalNext => DiffAction::ScrollRight,
        jk_tui::log_view::LogAction::ToggleHelp => DiffAction::ToggleHelp,
        jk_tui::log_view::LogAction::ToggleExpanded => DiffAction::UnfoldFile,
        jk_tui::log_view::LogAction::CollapseExpanded => DiffAction::FoldFile,
        jk_tui::log_view::LogAction::FoldAll => DiffAction::FoldAll,
        jk_tui::log_view::LogAction::UnfoldAll => DiffAction::UnfoldAll,
        jk_tui::log_view::LogAction::Refresh => DiffAction::Refresh,
        jk_tui::log_view::LogAction::OpenDiff => DiffAction::Ignore,
        jk_tui::log_view::LogAction::Quit => DiffAction::Quit,
        _ => DiffAction::ReturnToLog,
    };

    match diff.apply(diff_action) {
        DiffActionResult::Refresh => refresh_diff(diff, diff_source),
        DiffActionResult::ReturnToLog => return AppTransition::ReturnToLog,
        DiffActionResult::Quit => return AppTransition::Quit,
        _ => {}
    }

    AppTransition::Continue
}

/// Whether the terminal event loop should continue running.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum AppLoop {
    Continue,
    Quit,
}

/// View transition requested after an action is applied.
#[derive(Debug)]
enum AppTransition {
    Continue,
    OpenDiff(Box<DiffView>),
    ReturnToLog,
    Quit,
}

/// Reloads the current command without replacing the view on failure.
fn refresh_log(app: &mut LogView, source: &JjLog) {
    match source.load() {
        Ok(snapshot) => app.refresh(snapshot),
        Err(error) => app.show_error(error.to_string()),
    }
}

/// Reloads the active diff without replacing the view on failure.
fn refresh_diff(app: &mut DiffView, source: &JjDiff) {
    let change_id = app.change_id().to_owned();
    match source.load(&change_id) {
        Ok(snapshot) => app.refresh(snapshot),
        Err(error) => app.show_error(error.to_string()),
    }
}

/// Switches the command context only after the replacement log loads.
fn switch_log_command(app: &mut LogView, source: &mut JjLog, command: JjLogCommand) {
    let next_source = source.clone().with_command(command);
    match next_source.load() {
        Ok(snapshot) => {
            *source = next_source;
            app.refresh(snapshot);
        }
        Err(error) => app.show_error(error.to_string()),
    }
}

/// Restores terminal mode even when the event loop returns through an error.
struct TerminalRestore;

impl Drop for TerminalRestore {
    fn drop(&mut self) {
        ratatui::restore();
    }
}