rootle 0.8.4

Modal TUI for browsing remote source-control systems (GitHub in-tree, any forge via stdio providers) from the terminal
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
//! Worker spawners + result styling for `App`: every provider call
//! runs on a dedicated thread and reports back over the event channel
//! (PLAN.md §6). Same `impl App` as `mod.rs` — a file split, not a
//! design split.

use super::{App, trace};
use crate::components::global_search::SearchKind;
use crate::event::AppEvent;
use crate::provider::{ErrorKind, ProviderError, ProviderResult};

/// Blobs over 1 MiB never enter the app, whatever the provider: the
/// preview pane rejects them anyway, and no backend (in-tree or stdio)
/// should be able to push a giant payload through the pipe. The
/// uniform guarantee lives here, at the boundary, not in each provider
/// (plans/0009 R1).
const BLOB_CAP: usize = 1024 * 1024;

/// fetch_blob with the uniform cap; every blob path in the app goes
/// through this.
fn fetch_blob_capped(
    provider: &dyn crate::provider::Provider,
    repo: &str,
    sha: &str,
) -> ProviderResult<Vec<u8>> {
    let bytes = provider.fetch_blob(repo, sha)?;
    if bytes.len() > BLOB_CAP {
        return Err(ProviderError::new(
            ErrorKind::Provider,
            format!(
                "blob {sha} is {} KiB — over the 1 MiB preview cap",
                bytes.len() / 1024
            ),
        ));
    }
    Ok(bytes)
}

impl App {
    /// Style raw hits at the UI boundary: syntect highlight + grep
    /// match chips (plans/0002 §5). Runs on mock and real hits alike.
    pub(super) fn finish_hits(
        &self,
        hits: Vec<crate::components::global_search::SearchHit>,
        kind: SearchKind,
        query: &str,
    ) -> Vec<crate::components::global_search::SearchHit> {
        let mut hits: Vec<_> = hits
            .into_iter()
            .map(|hit| {
                let lines = self.highlighter.highlight(&hit.path, &hit.preview_text());
                hit.with_highlighted(lines)
            })
            .collect();
        if kind == SearchKind::Grep {
            crate::components::global_search::highlight_matches(
                &mut hits,
                query,
                self.theme.semantic.search_match,
                self.theme.semantic.crust,
            );
        }
        hits
    }

    pub(super) fn spawn_view_search(
        &self,
        gen_id: u64,
        kind: SearchKind,
        query: String,
        scope: String,
        extension: String,
    ) {
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            trace(&format!(
                "view search start gen={gen_id} q={query:?} scope={scope}"
            ));
            // Streamed batches go straight to the event loop as they
            // arrive (v1.3, plans/0011) — the worker stays blocked in
            // the provider call until the final metadata reply. The
            // sender is not Sync, so the sink holds it through a mutex
            // (one lock per batch).
            let sink_tx = std::sync::Mutex::new(tx.clone());
            let on_hits = move |hits: Vec<crate::components::global_search::RawHit>| {
                if let Ok(tx) = sink_tx.lock() {
                    let _ = tx.send(AppEvent::GlobalSearchDelta { gen_id, hits });
                }
            };
            let event = match crate::components::global_search::run_view_search(
                provider.as_ref(),
                kind,
                &query,
                &scope,
                &extension,
                &on_hits,
            ) {
                Ok(outcome) => {
                    trace(&format!(
                        "view search ok gen={gen_id} clipped={} index={:?}",
                        outcome.clipped, outcome.index_as_of
                    ));
                    AppEvent::GlobalSearchResults {
                        gen_id,
                        hits: Vec::new(),
                        clipped: outcome.clipped,
                        index: outcome.index_as_of,
                        client_filtered: outcome.client_filtered,
                        unfiltered: outcome.unfiltered,
                    }
                }
                Err(error) => {
                    trace(&format!("view search ERR gen={gen_id} {error}"));
                    AppEvent::GlobalSearchFailed { gen_id, error }
                }
            };
            let _ = tx.send(event);
        });
    }

    /// Expand org marks to their repos off the UI thread, then the
    /// wizard opens with the combined list. v1.4: expanded repos keep
    /// their listing metadata; direct selections stay bare names.
    pub(super) fn spawn_expand_clone(&self, repos: Vec<String>, orgs: Vec<String>) {
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            let mut repos: Vec<crate::provider::RepoInfo> = repos
                .into_iter()
                .map(crate::provider::RepoInfo::bare)
                .collect();
            let mut errors = Vec::new();
            for org in orgs {
                match provider.org_repos(&org) {
                    Ok(metas) => {
                        for m in metas {
                            let full = format!("{org}/{}", m.name);
                            let meta = crate::provider::RepoInfo {
                                name: full.clone(),
                                ..m
                            };
                            // The listing copy carries metadata — it
                            // wins over a bare selection of the same
                            // repo.
                            match repos.iter_mut().find(|r| r.name == full) {
                                Some(slot) => *slot = meta,
                                None => repos.push(meta),
                            }
                        }
                    }
                    Err(e) => errors.push(format!("{org}: {e}")),
                }
            }
            let _ = tx.send(AppEvent::CloneExpanded { repos, errors });
        });
    }

    /// Startup update check (0017 M3): 24h-cached, one network call a
    /// day at most; failures are silent by design. The once-a-day
    /// toast quota (0018 M2) is consumed here, cache-file side —
    /// never on the UI thread.
    pub(super) fn spawn_update_check(&self) {
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            if let Some(tag) = crate::update::latest_known()
                && crate::update::is_newer(&tag)
            {
                let toast = crate::update::take_toast(&tag);
                let _ = tx.send(AppEvent::UpdateAvailable { tag, toast });
            }
        });
    }

    /// 0019 M2: the consent-approved install — the same verified
    /// flow as the CLI, through a recorder Ui (no stderr writes
    /// inside the TUI), honoring the config's tag and sha pins.
    pub(super) fn spawn_declared_install(&self, decl: crate::provider::Declaration) {
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            let r = crate::provider::manager::Ref {
                repo: decl.repo.clone(),
                name: decl.name.clone(),
                tag: decl.tag.clone(),
                tarball: None,
            };
            let event = match crate::provider::manager::Manager::new().and_then(|m| {
                let (ui, _log) = crate::provider::ui::Ui::recorder();
                m.install_inner(&r, true, &ui, decl.sha.as_deref())
            }) {
                Ok(_) => crate::event::AppEvent::DeclarationInstalled {
                    name: decl.name.clone(),
                },
                Err(e) => crate::event::AppEvent::DeclarationFailed {
                    name: decl.name.clone(),
                    error: e.to_string(),
                },
            };
            let _ = tx.send(event);
        });
    }

    /// 0019 polish: the preview band's last-commit fetch — one
    /// `log(path, limit=1)` call, only for log-capable providers.
    /// Ambient: no status noise, silent on failure.
    pub(super) fn spawn_last_commit(&self, repo: String, path: String, ref_: Option<String>) {
        if !self.provider.capabilities().log {
            return;
        }
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            let entry = provider
                .log(&repo, Some(&path), ref_.as_deref(), Some(1))
                .ok()
                .and_then(|(entries, _)| entries.into_iter().next());
            let _ = tx.send(AppEvent::LastCommitLoaded { repo, path, entry });
        });
    }

    /// Revision fetches (v1.5, plans/0016 M1): one worker per lens;
    /// landings are identity-checked by the UI.
    pub(super) fn spawn_refs(&self, repo: String) {
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            let event = match provider.refs(&repo) {
                Ok(refs) => AppEvent::RefsLoaded { repo, refs },
                Err(error) => AppEvent::RefsFailed { repo, error },
            };
            let _ = tx.send(event);
        });
    }

    pub(super) fn spawn_log(&self, repo: String, path: String, ref_: Option<String>) {
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            // The lens' render budget, per the bounded-compute
            // contract: past it, `truncated` tells the user to narrow.
            let limit = Some(crate::provider::RENDER_BUDGET);
            let event = match provider.log(&repo, Some(&path), ref_.as_deref(), limit) {
                Ok((entries, truncated)) => AppEvent::LogLoaded {
                    path,
                    entries,
                    truncated,
                },
                Err(error) => AppEvent::LogFailed { path, error },
            };
            let _ = tx.send(event);
        });
    }

    pub(super) fn spawn_blame(&self, repo: String, path: String, ref_: Option<String>) {
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            let event = match provider.blame(&repo, &path, ref_.as_deref()) {
                Ok(ranges) => AppEvent::BlameLoaded { path, ranges },
                Err(error) => AppEvent::BlameFailed { path, error },
            };
            let _ = tx.send(event);
        });
    }

    /// Open-at-commit from the history lens; the band context rides
    /// along so the header can dress the commit view.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn spawn_blob_at(
        &self,
        repo: String,
        path: String,
        ref_: String,
        subject: String,
        author: String,
        date: String,
    ) {
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            let event = match provider.blob_at(&repo, &path, Some(&ref_)) {
                Ok((bytes, sha)) => AppEvent::BlobAtLoaded {
                    path,
                    ref_,
                    sha,
                    bytes,
                    subject,
                    author,
                    date,
                },
                Err(error) => AppEvent::BlobAtFailed { path, error },
            };
            let _ = tx.send(event);
        });
    }

    /// Sequential clones on one worker: git is bandwidth-bound anyway,
    /// and per-repo outcomes aggregate into one CloneDone toast.
    pub(super) fn spawn_clones(&self, repos: Vec<String>, dest: std::path::PathBuf) {
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            let mut ok = Vec::new();
            let mut failed = Vec::new();
            for repo in repos {
                trace(&format!("clone start {repo}"));
                let outcome = provider
                    .clone_url(&repo)
                    .map_err(|e| e.to_string())
                    .and_then(|url| {
                        // dest/org/repo — the org level avoids collisions.
                        let target = dest.join(&repo);
                        if target.exists() {
                            return Err("destination exists".into());
                        }
                        std::fs::create_dir_all(target.parent().unwrap_or(&dest))
                            .map_err(|e| e.to_string())?;
                        std::process::Command::new("git")
                            .args(["clone", &url])
                            .arg(&target)
                            .stdout(std::process::Stdio::null())
                            .stderr(std::process::Stdio::null())
                            .status()
                            .map_err(|e| e.to_string())
                            .and_then(|s| {
                                if s.success() {
                                    Ok(())
                                } else {
                                    Err("git clone failed".into())
                                }
                            })
                    });
                match outcome {
                    Ok(()) => {
                        trace(&format!("clone ok {repo}"));
                        ok.push(repo);
                    }
                    Err(e) => {
                        trace(&format!("clone ERR {repo} {e}"));
                        failed.push((repo, e));
                    }
                }
            }
            let _ = tx.send(AppEvent::CloneDone { ok, failed });
        });
    }

    pub(super) fn spawn_blob(&self, sha: String, name: String) {
        let Some((owner, repo)) = self.browser.repo_coords() else {
            return;
        };
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            trace(&format!("blob start {sha}"));
            let event = match fetch_blob_capped(provider.as_ref(), &format!("{owner}/{repo}"), &sha)
            {
                Ok(bytes) => {
                    trace(&format!("blob ok {sha} {} bytes", bytes.len()));
                    AppEvent::BlobLoaded { sha, name, bytes }
                }
                Err(error) => {
                    trace(&format!("blob ERR {sha} {error}"));
                    AppEvent::BlobFailed { sha, error }
                }
            };
            let _ = tx.send(event);
        });
    }

    pub(super) fn spawn_search(&self, gen_id: u64) {
        let Some(popup) = &self.popup else { return };
        let query = popup.input.value();
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            trace(&format!("search start gen={gen_id} q={query:?}"));
            let event = match provider.search(&query) {
                Ok(items) => {
                    trace(&format!("search ok gen={gen_id} items={}", items.len()));
                    AppEvent::SearchResults { gen_id, items }
                }
                Err(error) => {
                    trace(&format!("search ERR gen={gen_id} {error}"));
                    AppEvent::SearchFailed { gen_id, error }
                }
            };
            let _ = tx.send(event);
            trace(&format!("search sent gen={gen_id}"));
        });
    }

    /// Lazy per-hit context (plans/0006 §1): fetch the selected bare
    /// hit's blob and locate the query's context. Cache-first, so the
    /// second visit of a hit is free.
    pub(super) fn spawn_hit_context(
        &self,
        gen_id: u64,
        hit: crate::components::global_search::SearchHit,
        query: String,
    ) {
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            let sha = hit.sha.clone();
            trace(&format!(
                "hit ctx start gen={gen_id} {} sha={sha}",
                hit.path
            ));
            let event = match fetch_blob_capped(provider.as_ref(), &hit.repo, &sha) {
                Ok(bytes) => {
                    let needles: Vec<String> =
                        query.split_whitespace().map(str::to_string).collect();
                    let located =
                        crate::components::global_search::locate_in_blob(&bytes, &needles);
                    match located {
                        Some((line, preview, count)) => {
                            trace(&format!("hit ctx ok gen={gen_id} {sha}"));
                            AppEvent::HitContextLoaded {
                                gen_id,
                                repo: hit.repo,
                                path: hit.path,
                                sha,
                                line,
                                preview,
                                match_count: count,
                                query,
                            }
                        }
                        None => {
                            // Blob fetched but nothing matched — the hit
                            // is unlocatable, not just pending (§4).
                            trace(&format!("hit ctx none gen={gen_id} {sha}"));
                            AppEvent::HitContextMissing { gen_id, sha }
                        }
                    }
                }
                Err(error) => {
                    trace(&format!("hit ctx ERR gen={gen_id} {sha} {error}"));
                    // Auth/throttle surface a status line; other kinds
                    // stay quiet (plans/0008 §2).
                    AppEvent::HitContextFailed { gen_id, sha, error }
                }
            };
            let _ = tx.send(event);
        });
    }

    /// The expanded file pane (plans/0012 M2): fetch the hit's whole
    /// blob. Cache-first — the lazy context fetch usually warmed the
    /// exact (repo, sha), so expanding a located hit is free.
    pub(super) fn spawn_hit_file(
        &self,
        gen_id: u64,
        hit: crate::components::global_search::SearchHit,
    ) {
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            let sha = hit.sha.clone();
            trace(&format!(
                "hit file start gen={gen_id} {} sha={sha}",
                hit.path
            ));
            let event = match fetch_blob_capped(provider.as_ref(), &hit.repo, &sha) {
                Ok(bytes) => {
                    trace(&format!(
                        "hit file ok gen={gen_id} {sha} {} bytes",
                        bytes.len()
                    ));
                    AppEvent::HitFileLoaded {
                        gen_id,
                        repo: hit.repo,
                        path: hit.path,
                        sha,
                        bytes,
                    }
                }
                Err(error) => {
                    trace(&format!("hit file ERR gen={gen_id} {sha} {error}"));
                    AppEvent::HitFileFailed { gen_id, sha, error }
                }
            };
            let _ = tx.send(event);
        });
    }

    pub(super) fn spawn_org_repos(&self, org: String) {
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            let event = match provider.org_repos(&org) {
                Ok(repos) => AppEvent::OrgReposLoaded { org, repos },
                Err(error) => AppEvent::OrgReposFailed { org, error },
            };
            let _ = tx.send(event);
        });
    }

    pub(super) fn spawn_tree(&self, owner: String, name: String) {
        let provider = self.provider.clone();
        let tx = self.tx.clone();
        // v1.5: the browsed revision, if the switcher set one.
        let ref_ = self.browser.current_ref().map(str::to_string);
        std::thread::spawn(move || {
            trace(&format!("tree start {owner}/{name}"));
            let event = match provider.fetch_tree(&format!("{owner}/{name}"), ref_.as_deref()) {
                Ok(tree) => {
                    trace(&format!(
                        "tree ok {owner}/{name} entries={} truncated={}",
                        tree.entries.len(),
                        tree.truncated
                    ));
                    AppEvent::TreeLoaded {
                        owner,
                        name,
                        entries: tree.entries,
                        truncated: tree.truncated,
                        branch: tree.branch,
                    }
                }
                Err(error) => {
                    trace(&format!("tree ERR {owner}/{name} {error}"));
                    AppEvent::TreeFailed { owner, name, error }
                }
            };
            let _ = tx.send(event);
        });
    }

    /// Clone candidates (plans/0004 §2): (immediate repos, orgs to
    /// expand on a worker — the UI thread never calls the provider).
    /// Repo marks stay verbatim, file/dir marks fold up to the open
    /// repo, org marks fan out to ALL the org's repos.
    pub(super) fn clone_candidates(&self) -> (Vec<String>, Vec<String>) {
        let mut repos: Vec<String> = Vec::new();
        let mut orgs: Vec<String> = Vec::new();
        let marks = self.browser.visual_marks();
        if !marks.is_empty() {
            for mark in marks {
                let (title, name) = mark.split_once('/').unwrap_or(("", &mark));
                match title {
                    "orgs" => orgs.push(name.to_string()),
                    _ if Some(title) == self.browser.selected_org().as_deref() => {
                        if !repos.contains(&mark) {
                            repos.push(mark.clone());
                        }
                    }
                    _ => {
                        if let Some((owner, repo)) = self.browser.repo_coords() {
                            let full = format!("{owner}/{repo}");
                            if !repos.contains(&full) {
                                repos.push(full);
                            }
                        }
                    }
                }
            }
        } else {
            // No marks: everything in the org's repos level.
            for full in self.browser.org_repo_full_names() {
                if !repos.contains(&full) {
                    repos.push(full);
                }
            }
        }
        repos.sort();
        repos.dedup();
        orgs.sort();
        orgs.dedup();
        (repos, orgs)
    }
}