diffler 0.20.0

Standalone magit-style git TUI and code reviewer, on its own or with your coding agent
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
use std::path::Path;

use clap::{Parser, Subcommand};
use diffler::app::{self, App, CiRequest, Flow};
use diffler::event::AppEvent;
use diffler::workspace::{self, Workspace, WsEvent};
use diffler::{ci, clipboard, config, editor, event, mcp, ui};
use diffler_core::review::Review;
use ratatui::DefaultTerminal;
use tokio::sync::mpsc;

/// Standalone magit-style git TUI and code reviewer, on its own or with your coding agent.
#[derive(Parser, Debug)]
#[command(version, about)]
struct Cli {
    /// Path to the repository to review (defaults to the current directory)
    #[arg(default_value = ".")]
    path: String,

    /// MCP server port (overrides config key `mcp.port`)
    #[arg(long, global = true)]
    port: Option<u16>,

    /// Disable the MCP server (overrides config key `mcp.enabled`)
    #[arg(long, global = true)]
    no_mcp: bool,

    /// UI theme name (overrides `ui.theme`)
    #[arg(long, global = true)]
    theme: Option<String>,

    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Inspect configuration
    Config {
        /// Print the merged effective config with per-key origins
        #[arg(long)]
        dump: bool,
    },
}

#[tokio::main]
async fn main() -> color_eyre::Result<()> {
    color_eyre::install()?;
    let cli = Cli::parse();
    let repo = diffler_core::repo::discover(std::path::Path::new(&cli.path));

    let overrides = config::CliOverrides {
        port: cli.port,
        mcp_enabled: cli.no_mcp.then_some(false),
        theme: cli.theme.clone(),
    };
    let loaded = config::load(repo.as_deref().ok(), &overrides)?;

    match cli.command {
        Some(Command::Config { dump: true }) => print_config_dump(&loaded),
        Some(Command::Config { dump: false }) => Err(color_eyre::eyre::eyre!(
            "nothing to do: try `diffler config --dump`"
        )),
        None => {
            // fail before touching the terminal so the error stays readable
            let root = match repo {
                Ok(root) => root,
                Err(err) => exit_without_repo(&err, &cli.path),
            };
            let review = Review::open_with_settings(&root, &loaded.config.diff_settings())?;
            let app = App::new(review, loaded);
            let terminal = ratatui::init();
            set_mouse_capture(true);
            install_mouse_panic_hook();
            // the App lives in this future, and clippy's large_futures wants it on the heap
            let result = Box::pin(run(terminal, app, overrides)).await;
            set_mouse_capture(false);
            ratatui::restore();
            result
        }
    }
}

/// Focus reporting rides along so the CI poll can idle while nobody looks.
fn set_mouse_capture(on: bool) {
    use crossterm::event::{DisableFocusChange, EnableFocusChange};
    use std::io::Write as _;
    let mut out = std::io::stdout();
    // clicks (1000), drags (1002) and SGR coordinates (1006): the set every multiplexer forwards
    let _ = if on {
        out.write_all(MOUSE_ON.as_bytes())
            .and_then(|()| crossterm::execute!(out, EnableFocusChange))
    } else {
        out.write_all(MOUSE_OFF.as_bytes())
            .and_then(|()| crossterm::execute!(out, DisableFocusChange))
    };
    let _ = out.flush();
}

const MOUSE_ON: &str = "\x1b[?1000h\x1b[?1002h\x1b[?1006h";
const MOUSE_OFF: &str = "\x1b[?1006l\x1b[?1002l\x1b[?1000l";

/// So a crash leaves no terminal emitting mouse escape codes.
fn install_mouse_panic_hook() {
    let previous = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        set_mouse_capture(false);
        previous(info);
    }));
}

// a missing repository is user error, so we print a plain line and a hint
#[allow(clippy::print_stderr)]
fn exit_without_repo(err: &diffler_core::repo::RepoError, path: &str) -> ! {
    let shown = std::fs::canonicalize(path)
        .map_or_else(|_| path.to_owned(), |full| full.display().to_string());
    match err {
        diffler_core::repo::RepoError::NotFound(_) => {
            eprintln!("diffler: no git repository at {shown} or any parent");
            eprintln!(
                "start one with `git init`, or point diffler at a repository: diffler <path>"
            );
        }
        diffler_core::repo::RepoError::Bare(_) => {
            eprintln!("diffler: {shown} is a bare repository, which has nothing to review");
            eprintln!("open a clone with a working tree instead");
        }
        git @ diffler_core::repo::RepoError::Git(_) => eprintln!("diffler: {git}"),
    }
    std::process::exit(1)
}

// the TUI never starts on this path, so stdout is safe
#[allow(clippy::print_stdout)]
fn print_config_dump(loaded: &config::LoadedConfig) -> color_eyre::Result<()> {
    print!("{}", config::render_dump(loaded)?);
    Ok(())
}

async fn run(
    mut terminal: DefaultTerminal,
    mut app: App,
    overrides: config::CliOverrides,
) -> color_eyre::Result<()> {
    // the query reads the terminal's answer from stdin, so it runs before the event pump
    if let Ok(picker) = ratatui_image::picker::Picker::from_query_stdio() {
        app.image_picker = picker;
    }
    let (tx, mut rx) = mpsc::unbounded_channel();
    let mut events = spawn_input(&tx);
    let mut workspace = Workspace::new(app, tx.clone(), overrides);
    let mcp = start_mcp(&mut workspace, &tx);
    let mut needs_draw = true;
    loop {
        if needs_draw {
            workspace.sync_strip();
            // drawing and handling block, so we free the worker or a slow repo
            // stalls the MCP server and the watcher
            tokio::task::block_in_place(|| {
                terminal.draw(|frame| ui::draw(frame, workspace.active_mut()))
            })?;
            needs_draw = false;
        }
        if let Some(text) = workspace.take_clipboard() {
            // OSC52 goes out raw right after the draw so it never interleaves
            // with one; the native copy covers terminals without OSC52
            use std::io::Write as _;
            let mut out = std::io::stdout();
            out.write_all(clipboard::osc52(&text).as_bytes())?;
            out.flush()?;
            tokio::task::spawn_blocking(move || clipboard::native_copy(&text));
        }
        if let Some((tab, request)) = workspace.take_editor() {
            // the event pump releases the tty first, or both read the same keystrokes
            events.abort();
            let _ = (&mut events).await;
            set_mouse_capture(false);
            ratatui::restore();
            let editor::EditorRequest { cmd, purpose } = request;
            let outcome = tokio::task::spawn_blocking(move || editor::run(&cmd))
                .await
                .map_err(|err| err.to_string())
                .and_then(|result| result.map_err(|err| err.to_string()));
            terminal = ratatui::init();
            set_mouse_capture(true);
            terminal.clear()?;
            events = spawn_input(&tx);
            workspace.editor_finished(tab, purpose, outcome);
            needs_draw = true;
            continue;
        }
        for tab in workspace.tabs_mut() {
            dispatch_tab(tab);
        }
        let Some(event) = rx.recv().await else { break };
        match tokio::task::block_in_place(|| workspace.handle(event)) {
            Flow::Quit => break,
            Flow::Continue => needs_draw = true,
            Flow::Idle => {}
        }
        // we drain the queue so one draw covers a burst of held keys or watcher events
        let mut quit = false;
        while let Ok(event) = rx.try_recv() {
            match tokio::task::block_in_place(|| workspace.handle(event)) {
                Flow::Quit => {
                    quit = true;
                    break;
                }
                Flow::Continue => needs_draw = true,
                Flow::Idle => {}
            }
            if workspace.has_pending() {
                break;
            }
        }
        if quit {
            break;
        }
    }
    events.abort();
    if let Some(mcp) = mcp {
        mcp.handle.abort();
        workspace.clear_endpoints();
    }
    Ok(())
}

fn spawn_input(tx: &mpsc::UnboundedSender<WsEvent>) -> tokio::task::JoinHandle<()> {
    let (input_tx, _) = workspace::forward(tx, WsEvent::Input);
    event::spawn_event_loop(input_tx)
}

/// Each worker answers on the tab's own channel.
fn dispatch_tab(tab: &mut workspace::Tab) {
    if let Some(app::GitOp { label, argv }) = tab.app.pending_git.take() {
        let repo_root = tab.app.review.repo_root.clone();
        let tx = tab.tx.clone();
        tokio::task::spawn_blocking(move || {
            let _ = tx.send(run_git(&label, &argv, &repo_root));
        });
    }
    dispatch_workers(&mut tab.app, &tab.tx);
    if let Some(request) = tab.app.pending_ci.take() {
        dispatch_ci(&tab.app, request, &tab.tx);
    }
}

/// A startup failure disables MCP for the session.
fn start_mcp(
    workspace: &mut Workspace,
    tx: &mpsc::UnboundedSender<WsEvent>,
) -> Option<mcp::McpHandle> {
    let config = &workspace.active().config;
    if !config.mcp.enabled {
        return None;
    }
    let port = config.mcp.port;
    let (mcp_tx, _) = workspace::forward(tx, WsEvent::Mcp);
    match mcp::spawn_mcp(mcp_tx, workspace.feedback_rx(), port) {
        Ok(handle) => {
            workspace.set_mcp_port(handle.port);
            Some(handle)
        }
        Err(err) => {
            workspace
                .active_mut()
                .error(format!("mcp server failed to start: {err}"));
            None
        }
    }
}

fn dispatch_refresh(app: &mut App, tx: &mpsc::UnboundedSender<AppEvent>) {
    if app.refresh_state != app::RefreshState::Queued {
        return;
    }
    app.refresh_state = app::RefreshState::Running;
    let root = app.review.repo_root.clone();
    let settings = app.config.diff_settings();
    let against = app.against_rev().map(str::to_owned);
    let limits = app.commit_limits();
    let tx = tx.clone();
    tokio::task::spawn_blocking(move || {
        let result = diffler_core::review::Review::compute_refresh(
            &root,
            &settings,
            against.as_deref(),
            None,
            limits,
        )
        .map_err(|err| err.to_string());
        let _ = tx.send(AppEvent::RefreshDone(Box::new(result)));
    });
}

/// Highlights on the same worker so the screen opens fully rendered.
fn dispatch_file(app: &mut App, tx: &mpsc::UnboundedSender<AppEvent>) {
    let Some(request) = app.pending_file.take() else {
        return;
    };
    let tx = tx.clone();
    let root = app.review.repo_root.clone();
    let highlighter = std::sync::Arc::clone(&app.highlighter);
    tokio::task::spawn_blocking(move || {
        let result = diffler_core::review::Review::compute_file(&root, &request.path)
            .map_err(|err| format!("{}: {err}", request.path))
            .map(|snapshot| {
                let highlights = highlighter.highlight(&snapshot.path, &snapshot.content);
                app::file::FileView::new(
                    snapshot.path,
                    &snapshot.content,
                    highlights,
                    snapshot.blame,
                    request.blame,
                )
            });
        let _ = tx.send(AppEvent::FileLoaded {
            result: Box::new(result),
            span: request.span,
            reload: request.reload,
            token: request.token,
        });
    });
}

fn dispatch_declared(app: &mut App, tx: &mpsc::UnboundedSender<AppEvent>) {
    let Some(request) = app.pending_declared.take() else {
        return;
    };
    let tx = tx.clone();
    let root = app.review.repo_root.clone();
    tokio::task::spawn_blocking(move || {
        let kinds = diffler_core::review::Review::compute_declared(&root, &request.paths)
            .unwrap_or_default();
        let _ = tx.send(AppEvent::DeclaredKinds {
            kinds,
            token: request.token,
        });
    });
}

fn dispatch_stats(app: &mut App, tx: &mpsc::UnboundedSender<AppEvent>) {
    let Some(request) = app.pending_stats.take() else {
        return;
    };
    let tx = tx.clone();
    let root = app.review.repo_root.clone();
    // we count untracked files too, so a new file counts like the rest
    let untracked: Vec<String> = app
        .review
        .status
        .untracked
        .files
        .iter()
        .map(|file| file.path.clone())
        .collect();
    let rules = app.config.classify.rules();
    tokio::task::spawn_blocking(move || {
        let stats = diffler_core::stats::scan_repo(&root, &untracked, &rules).unwrap_or_default();
        let _ = tx.send(AppEvent::RepoStats {
            stats: Box::new(stats),
            token: request.token,
        });
    });
}

/// Reads the copy `read_first` names, the pinned revision or the worktree,
/// and falls back to the other.
fn dispatch_walkthrough(app: &mut App, tx: &mpsc::UnboundedSender<AppEvent>) {
    let Some(request) = app.pending_walkthrough.take() else {
        return;
    };
    let tx = tx.clone();
    let root = app.review.repo_root.clone();
    tokio::task::spawn_blocking(move || {
        let read = diffler_core::review::Review::compute_walkthrough_files(
            &root,
            request.read_rev.as_deref(),
            request.read_first,
            &request.files,
        );
        let _ = tx.send(AppEvent::WalkthroughAnchors {
            contents: read.contents,
            pin_broken: read.pin_broken,
            token: request.token,
        });
    });
}

fn dispatch_image(app: &mut App, tx: &mpsc::UnboundedSender<AppEvent>) {
    let Some(request) = app.pending_image.take() else {
        return;
    };
    let tx = tx.clone();
    let root = app.review.repo_root.clone();
    let picker = app.image_picker.clone();
    tokio::task::spawn_blocking(move || {
        let key = &request.key;
        let sides = diffler_core::review::Review::compute_binary_sides(
            &root,
            &key.path,
            &key.blobs,
            key.deleted,
        );
        let preview = app::image::build_preview(&picker, &request, sides);
        let _ = tx.send(AppEvent::ImagePreview {
            token: request.token,
            preview: Box::new(preview),
        });
    });
}

fn dispatch_lens(app: &mut App, tx: &mpsc::UnboundedSender<AppEvent>) {
    let Some(request) = app.pending_lens.take() else {
        return;
    };
    let tx = tx.clone();
    let highlighter = std::sync::Arc::clone(&app.highlighter);
    tokio::task::spawn_blocking(move || {
        let lens = app::compute_lens(&highlighter, &request);
        let _ = tx.send(AppEvent::Lens {
            token: request.token,
            lens: Box::new(lens),
        });
    });
}

fn dispatch_workers(app: &mut App, tx: &mpsc::UnboundedSender<AppEvent>) {
    dispatch_enrich(app, tx);
    dispatch_lens(app, tx);
    dispatch_image(app, tx);
    dispatch_walkthrough(app, tx);
    dispatch_file(app, tx);
    dispatch_declared(app, tx);
    dispatch_stats(app, tx);
    dispatch_pr_posts(app, tx);
    dispatch_refresh(app, tx);
    dispatch_rediff(app, tx);
}

/// The re-diff holds the refresh slot, so it never runs beside a refresh and
/// whichever finishes last carries the newest snapshot.
fn dispatch_rediff(app: &mut App, tx: &mpsc::UnboundedSender<AppEvent>) {
    let Some(request) = app.start_rediff() else {
        return;
    };
    let root = app.review.repo_root.clone();
    let settings = app.config.diff_settings();
    let tx = tx.clone();
    tokio::task::spawn_blocking(move || {
        let result = request.run(&root, &settings);
        let _ = tx.send(AppEvent::RediffDone {
            result: Box::new(result),
            request,
        });
    });
}

fn provider_for(
    remote: &diffler::app::CiRemote,
    repo_root: &Path,
    branch: Option<&str>,
    yaml_cache: ci::YamlCache,
    etags: ci::EtagCache,
) -> Box<dyn ci::ForgeProvider + Send> {
    ci::build_provider(
        &remote.detected,
        repo_root,
        branch,
        remote.url.as_deref(),
        yaml_cache,
        etags,
    )
}

fn dispatch_pr_posts(app: &mut App, tx: &mpsc::UnboundedSender<AppEvent>) {
    if app.pending_pr_posts.is_empty() {
        return;
    }
    let Some(remote) = app.ci_remotes().first().cloned() else {
        app.drop_pending_pr_posts();
        return;
    };
    let repo_root = app.review.repo_root.clone();
    let branch = app.head.branch.clone();
    let yaml_cache = app.ci_yaml_cache.clone();
    let etags = app.ci_etags.clone();
    for post in std::mem::take(&mut app.pending_pr_posts) {
        let tx = tx.clone();
        let repo_root = repo_root.clone();
        let branch = branch.clone();
        let yaml_cache = yaml_cache.clone();
        let etags = etags.clone();
        let remote = remote.clone();
        tokio::spawn(async move {
            let provider = provider_for(&remote, &repo_root, branch.as_deref(), yaml_cache, etags);
            let result = match &post {
                app::pr::PrPost::Review { review, .. } => {
                    provider.submit_pr_review(review).await.map(|()| None)
                }
                app::pr::PrPost::Reply {
                    number,
                    parent_remote_id,
                    body,
                    ..
                } => provider
                    .reply_pr_comment(*number, parent_remote_id, body)
                    .await
                    .map(Some),
                app::pr::PrPost::Resolve {
                    number,
                    thread_id,
                    resolved,
                    ..
                } => provider
                    .resolve_pr_thread(*number, thread_id, *resolved)
                    .await
                    .map(|()| None),
                app::pr::PrPost::Edit {
                    number,
                    remote_id,
                    body,
                    ..
                } => provider
                    .update_pr_comment(*number, remote_id, body)
                    .await
                    .map(|()| None),
                app::pr::PrPost::Delete {
                    number, remote_id, ..
                } => provider
                    .delete_pr_comment(*number, remote_id)
                    .await
                    .map(|()| None),
            };
            let _ = tx.send(AppEvent::PrPosted {
                post: Box::new(post),
                result: result.map_err(|err| err.to_string()),
            });
        });
    }
}

fn dispatch_enrich(app: &mut App, tx: &mpsc::UnboundedSender<AppEvent>) {
    for job in app.pending_enrich.drain(..) {
        let tx = tx.clone();
        let highlighter = std::sync::Arc::clone(&app.highlighter);
        tokio::task::spawn_blocking(move || {
            let outcome = app::enrich::run_enrich(&highlighter, job);
            let _ = tx.send(AppEvent::Enriched(Box::new(outcome)));
        });
    }
}

/// `Runs` merges every remote, tagging runs when there are several;
/// detail, log and extras go to the open run's remote, the rest to the primary.
fn dispatch_ci(app: &App, request: CiRequest, tx: &mpsc::UnboundedSender<AppEvent>) {
    let remotes = app.ci_remotes();
    if remotes.is_empty() {
        return;
    }
    let repo_root = app.review.repo_root.clone();
    let branch = app.head.branch.clone();
    let yaml_cache = app.ci_yaml_cache.clone();
    let etags = app.ci_etags.clone();
    let tx = tx.clone();
    if matches!(request, CiRequest::Runs) {
        let multi = remotes.len() > 1;
        tokio::spawn(async move {
            let mut all = Vec::new();
            for remote in &remotes {
                let provider = provider_for(
                    remote,
                    &repo_root,
                    branch.as_deref(),
                    yaml_cache.clone(),
                    etags.clone(),
                );
                if let Ok(mut runs) = provider.list_runs(30).await {
                    if multi {
                        for run in &mut runs {
                            run.remote = Some(remote.name.clone());
                        }
                    }
                    all.extend(runs);
                }
            }
            all.sort_by_key(|run| std::cmp::Reverse(run.created));
            let _ = tx.send(AppEvent::CiRuns(all));
        });
        return;
    }
    let remote = match &request {
        CiRequest::Detail(_) | CiRequest::Extras(_) | CiRequest::Log { .. } => {
            app.ci_remote_for_open_run()
        }
        _ => remotes.first().cloned(),
    };
    if let Some(remote) = remote {
        let provider = provider_for(&remote, &repo_root, branch.as_deref(), yaml_cache, etags);
        tokio::spawn(async move {
            let _ = tx.send(run_ci_request(provider, request).await);
        });
    }
}

async fn run_ci_request(
    provider: Box<dyn crate::ci::ForgeProvider + Send>,
    request: CiRequest,
) -> AppEvent {
    match request {
        CiRequest::Runs => match provider.list_runs(30).await {
            Ok(runs) => AppEvent::CiRuns(runs),
            Err(err) => AppEvent::CiError(err.to_string()),
        },
        CiRequest::Pr => AppEvent::CiPr(provider.current_pr().await.unwrap_or(None)),
        CiRequest::CreatePr(new) => AppEvent::PrCreated(Box::new(
            provider
                .create_pr(&new)
                .await
                .map_err(|err| err.to_string()),
        )),
        CiRequest::Prs => match provider.list_prs().await {
            Ok(prs) => AppEvent::CiPrs(prs),
            Err(err) => AppEvent::CiPrsError(err.to_string()),
        },
        CiRequest::PrComments(number) => match provider.pr_comments(number).await {
            Ok(comments) => AppEvent::PrComments {
                number,
                comments,
                // best-effort: a failed lookup only skips force-push detection
                pr: provider.pr(number).await.ok(),
            },
            Err(err) => AppEvent::CiError(err.to_string()),
        },
        CiRequest::Detail(id) => match provider.run_detail(&id).await {
            Ok(detail) => AppEvent::CiRunDetail(detail),
            Err(err) => AppEvent::CiError(err.to_string()),
        },
        CiRequest::Extras(id) => match provider.run_extras(&id).await {
            Ok(extras) => AppEvent::CiExtras(extras),
            Err(err) => AppEvent::CiError(err.to_string()),
        },
        CiRequest::Log { run, job, offset } => match provider.job_log(&run, &job, offset).await {
            Ok(chunk) => AppEvent::CiLog {
                text: chunk.text,
                steps: chunk.steps,
                next_offset: chunk.next_offset,
                done: chunk.done,
            },
            Err(err) => AppEvent::CiError(err.to_string()),
        },
    }
}

/// We shell out to the user's `git` so credentials stay out of diffler.
fn run_git(label: &str, argv: &[String], repo_root: &Path) -> AppEvent {
    let Some((program, rest)) = argv.split_first() else {
        return AppEvent::GitDone {
            label: label.to_owned(),
            ok: false,
            output: "empty command".to_owned(),
        };
    };
    match std::process::Command::new(program)
        .args(rest)
        .current_dir(repo_root)
        .stdin(std::process::Stdio::null())
        .envs(diffler::proc::NO_PROMPT)
        .output()
    {
        Ok(out) => {
            let mut output = String::from_utf8_lossy(&out.stderr).into_owned();
            output.push_str(&String::from_utf8_lossy(&out.stdout));
            AppEvent::GitDone {
                label: label.to_owned(),
                ok: out.status.success(),
                output,
            }
        }
        Err(err) => AppEvent::GitDone {
            label: label.to_owned(),
            ok: false,
            output: format!("cannot run {program}: {err}"),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_git_child_cannot_ask_the_user_anything() {
        let argv = [
            "sh",
            "-c",
            "printf %s \"$GIT_TERMINAL_PROMPT$GH_PROMPT_DISABLED\"",
        ]
        .map(str::to_owned)
        .to_vec();
        let AppEvent::GitDone { ok, output, .. } = run_git("probe", &argv, Path::new(".")) else {
            panic!("a git op answers with GitDone");
        };
        assert!(ok, "{output}");
        assert_eq!(output, "01");
    }
}