mnml-rs 0.2.14

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
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
//! `git log --all` reader + a lane layout for an ASCII commit DAG (the data
//! behind [`crate::git::graph::GitGraphPane`]). Shells out to `git`; degrades to
//! an empty graph when `git` is missing or this isn't a repo.
//!
//! The layout is single-row-per-commit: each commit sits in one lane (column),
//! pass-through lanes draw `│`, the commit's node is `●`. Branch/merge points use
//! corner glyphs (`╮ ╭ ╯ ╰`) toward the commit's lane — approximate (no diagonal
//! crossings), but readable; fancier connectors are a follow-up.

use std::path::Path;
use std::process::Command;

/// What kind of ref points at a commit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefKind {
    /// `HEAD` (the symbolic ref itself — drawn on whatever commit is checked out).
    Head,
    LocalBranch,
    RemoteBranch,
    Tag,
}

#[derive(Debug, Clone)]
pub struct RefLabel {
    pub kind: RefKind,
    /// Short name — `main`, `origin/main`, `v1.2.0`, `HEAD`.
    pub name: String,
}

/// One graph cell — a character to draw plus a lane-colour index (`0..N`, cycled
/// through a small palette by the renderer).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GraphCell {
    pub ch: char,
    pub color: u8,
}

impl GraphCell {
    const BLANK: GraphCell = GraphCell { ch: ' ', color: 0 };
}

#[derive(Debug, Clone)]
pub struct Commit {
    pub hash: String,
    /// First 9 chars of `hash` (what's shown).
    pub short: String,
    pub parents: Vec<String>,
    pub author: String,
    /// Author time, unix seconds.
    pub time: i64,
    pub subject: String,
    pub refs: Vec<RefLabel>,
    /// The rendered graph columns for this row (left → right).
    pub graph: Vec<GraphCell>,
    /// The lane this commit's node sits in (index into `graph`).
    pub lane: usize,
}

/// Load up to `limit` commits across all refs, with a lane layout computed.
/// Convenience wrapper for the default no-filter path.
pub fn load(workspace: &Path, limit: usize) -> Vec<Commit> {
    load_filtered(workspace, limit, &LogFilter::default())
}

/// Filter knobs applied to the commit listing in `load_filtered`.
/// `branch = None` ⇒ `git log --all` (every ref); `branch = Some("foo")`
/// ⇒ `git log foo` (commits reachable from `foo`). `since` / `until` are
/// passed through as `--since=…` / `--until=…` so any git-recognized
/// date spec works ("1 week ago", "2026-01-01", `1736294400`, …).
#[derive(Debug, Clone, Default)]
pub struct LogFilter {
    pub branch: Option<String>,
    pub since: Option<String>,
    pub until: Option<String>,
    /// `--author=<pattern>` — fixed-string or regex; git treats it as
    /// a regex but a plain name still matches (`John` finds "John Doe").
    pub author: Option<String>,
    /// `--grep=<pattern>` against commit messages.
    pub grep: Option<String>,
}

/// Load up to `limit` commits honoring `filter`. The lane layout
/// recomputes against whatever commit subset comes back, so the graph
/// stays connected for branch-scoped views.
pub fn load_filtered(workspace: &Path, limit: usize, filter: &LogFilter) -> Vec<Commit> {
    let refs = load_refs(workspace);
    let head = head_hash(workspace);

    // `%x1f` (unit separator) between fields — safe inside commit subjects.
    let fmt = "%H%x1f%P%x1f%an%x1f%at%x1f%s";
    let mut args: Vec<String> = vec!["log".into()];
    match &filter.branch {
        Some(b) if !b.is_empty() => args.push(b.clone()),
        _ => args.push("--all".into()),
    }
    args.push("--date-order".into());
    args.push(format!("-n{limit}"));
    args.push(format!("--pretty=format:{fmt}"));
    if let Some(s) = &filter.since {
        args.push(format!("--since={s}"));
    }
    if let Some(u) = &filter.until {
        args.push(format!("--until={u}"));
    }
    if let Some(a) = &filter.author {
        args.push(format!("--author={a}"));
    }
    if let Some(g) = &filter.grep {
        args.push(format!("--grep={g}"));
        args.push("--regexp-ignore-case".into());
    }
    let out = match Command::new("git")
        .args(&args)
        .current_dir(workspace)
        .output()
    {
        Ok(o) if o.status.success() => o,
        _ => return Vec::new(),
    };

    let mut commits: Vec<Commit> = String::from_utf8_lossy(&out.stdout)
        .lines()
        .filter_map(|line| {
            let mut f = line.split('\u{1f}');
            let hash = f.next()?.to_string();
            let parents: Vec<String> = f.next()?.split_whitespace().map(str::to_string).collect();
            let author = f.next().unwrap_or("").to_string();
            let time = f.next().unwrap_or("0").parse().unwrap_or(0);
            let subject = f.next().unwrap_or("").to_string();
            let short: String = hash.chars().take(9).collect();
            let mut refs: Vec<RefLabel> = refs
                .iter()
                .filter(|(h, _)| *h == hash)
                .map(|(_, r)| r.clone())
                .collect();
            if head.as_deref() == Some(hash.as_str()) {
                refs.insert(
                    0,
                    RefLabel {
                        kind: RefKind::Head,
                        name: "HEAD".to_string(),
                    },
                );
            }
            Some(Commit {
                hash,
                short,
                parents,
                author,
                time,
                subject,
                refs,
                graph: Vec::new(),
                lane: 0,
            })
        })
        .collect();

    layout(&mut commits);
    commits
}

/// Assign lanes + build each row's `graph` cells. `commits` is newest-first.
fn layout(commits: &mut [Commit]) {
    // `lanes[i]` = the hash that lane `i` is "waiting for" (its next commit going
    // older), or `None` if free. A stable colour is `lane_index` cycled.
    let mut lanes: Vec<Option<String>> = Vec::new();
    // qa-fix 2026-06-30 — cooldown per lane. When a lane is freed
    // (merged in), it becomes eligible for reuse only after
    // COOLDOWN rows so the graph stays compact but freshly-emptied
    // slots aren't repurposed for unrelated branches (which would
    // stack unrelated ● dots in the same visual column with no
    // vertical connection).
    let mut lane_cooldown: Vec<u16> = Vec::new();
    const COOLDOWN: u16 = 5;

    for c in commits.iter_mut() {
        // Decrement cooldowns each row so freed slots become
        // reusable after COOLDOWN rows.
        for cd in lane_cooldown.iter_mut() {
            *cd = cd.saturating_sub(1);
        }
        // Which lane is this commit's? (the first lane already waiting for it).
        let my_lane = match lanes
            .iter()
            .position(|l| l.as_deref() == Some(c.hash.as_str()))
        {
            Some(i) => i,
            None => {
                lanes.push(None);
                lane_cooldown.push(0);
                lanes.len() - 1
            }
        };
        // Other lanes also waiting for this commit ⇒ branches merging in here.
        let merging: Vec<usize> = lanes
            .iter()
            .enumerate()
            .filter(|(i, l)| *i != my_lane && l.as_deref() == Some(c.hash.as_str()))
            .map(|(i, _)| i)
            .collect();

        // Reserve lanes for extra parents (the first parent stays in `my_lane`).
        // qa-fix 2026-06-30 — allow reuse of mid-graph free slots
        // ONLY when they've cooled down (>= COOLDOWN rows since
        // last freed). Prevents "3 unrelated ● in one column"
        // while keeping the graph narrow in typical histories.
        let mut branch_to: Vec<usize> = Vec::new();
        for p in c.parents.iter().skip(1) {
            if lanes.iter().any(|l| l.as_deref() == Some(p.as_str())) {
                continue; // a lane already heads there — it'll merge later
            }
            let free = lanes
                .iter()
                .enumerate()
                .find(|(i, l)| {
                    *i != my_lane && l.is_none() && lane_cooldown.get(*i).copied().unwrap_or(0) == 0
                })
                .map(|(i, _)| i);
            let slot = match free {
                Some(free) => free,
                None => {
                    lanes.push(None);
                    lane_cooldown.push(0);
                    lanes.len() - 1
                }
            };
            lanes[slot] = Some(p.clone());
            branch_to.push(slot);
        }

        // Build this row's cells.
        let width = lanes.len();
        let mut cells = vec![GraphCell::BLANK; width];
        for (i, l) in lanes.iter().enumerate() {
            let color = (i % LANE_COLORS) as u8;
            if i == my_lane {
                cells[i] = GraphCell { ch: '', color };
            } else if merging.contains(&i) {
                cells[i] = GraphCell {
                    ch: if i < my_lane { '' } else { '' },
                    color,
                };
            } else if branch_to.contains(&i) {
                cells[i] = GraphCell {
                    ch: if i < my_lane { '' } else { '' },
                    color,
                };
            } else if l.is_some() {
                cells[i] = GraphCell { ch: '', color };
            }
        }
        // A horizontal stretch across the gap between `my_lane` and the furthest
        // merge/branch lane, so the corners actually connect.
        let mut endpoints: Vec<usize> = merging.iter().chain(branch_to.iter()).copied().collect();
        if let (Some(&lo), Some(&hi)) = (
            endpoints.iter().chain(std::iter::once(&my_lane)).min(),
            endpoints.iter().chain(std::iter::once(&my_lane)).max(),
        ) {
            for cell in cells.iter_mut().take(hi).skip(lo + 1) {
                if cell.ch == ' ' {
                    *cell = GraphCell {
                        ch: '',
                        color: (my_lane % LANE_COLORS) as u8,
                    };
                } else if cell.ch == '' {
                    *cell = GraphCell {
                        ch: '',
                        color: cell.color,
                    };
                }
            }
        }
        endpoints.clear();

        c.graph = cells;
        c.lane = my_lane;

        // Advance lanes for the next (older) row: `my_lane` now waits for the
        // first parent (or frees up); merged-in lanes are absorbed (freed).
        for i in &merging {
            lanes[*i] = None;
            if let Some(cd) = lane_cooldown.get_mut(*i) {
                *cd = COOLDOWN;
            }
        }
        lanes[my_lane] = c.parents.first().cloned();
        if lanes[my_lane].is_none()
            && let Some(cd) = lane_cooldown.get_mut(my_lane)
        {
            *cd = COOLDOWN;
        }
        // Trim trailing free lanes so the graph doesn't drift wide forever.
        while matches!(lanes.last(), Some(None)) {
            lanes.pop();
            lane_cooldown.pop();
        }
    }
}

/// How many colours the lane palette cycles through (the renderer maps `0..N`).
pub const LANE_COLORS: usize = 6;

fn head_hash(workspace: &Path) -> Option<String> {
    let out = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(workspace)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let h = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (!h.is_empty()).then_some(h)
}

/// `(commit-hash, label)` for every branch / remote-branch / tag tip.
fn load_refs(workspace: &Path) -> Vec<(String, RefLabel)> {
    let out = match Command::new("git")
        .args([
            "for-each-ref",
            "--format=%(objectname) %(refname)",
            "refs/heads",
            "refs/remotes",
            "refs/tags",
        ])
        .current_dir(workspace)
        .output()
    {
        Ok(o) if o.status.success() => o,
        _ => return Vec::new(),
    };
    String::from_utf8_lossy(&out.stdout)
        .lines()
        .filter_map(|line| {
            let (hash, refname) = line.split_once(' ')?;
            let (kind, name) = if let Some(n) = refname.strip_prefix("refs/heads/") {
                (RefKind::LocalBranch, n.to_string())
            } else if let Some(n) = refname.strip_prefix("refs/remotes/") {
                if n.ends_with("/HEAD") {
                    return None; // the `origin/HEAD -> origin/main` alias — skip
                }
                (RefKind::RemoteBranch, n.to_string())
            } else {
                let n = refname.strip_prefix("refs/tags/")?;
                (RefKind::Tag, n.to_string())
            };
            Some((hash.to_string(), RefLabel { kind, name }))
        })
        .collect()
}

/// `git show -s --format=%B <hash>` — the full commit message body.
pub fn full_message(workspace: &Path, hash: &str) -> String {
    Command::new("git")
        .args(["show", "-s", "--format=%B", hash])
        .current_dir(workspace)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim_end().to_string())
        .unwrap_or_default()
}

/// `git show <hash>:<rel_path>` — the file's contents at that commit.
/// Returns `None` when git can't find the path at that revision (e.g.
/// the file was added in this commit but the user picked the wrong
/// short hash, or the path is a rename target that doesn't exist
/// under the same name at the parent commit). Lossy UTF-8 — non-UTF-8
/// bytes get the standard replacement character.
#[allow(dead_code)]
pub fn file_at_commit(workspace: &Path, hash: &str, rel_path: &str) -> Option<String> {
    let spec = format!("{hash}:{rel_path}");
    let out = Command::new("git")
        .args(["show", &spec])
        .current_dir(workspace)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&out.stdout).into_owned())
}

/// Compact commit entry for the per-file history picker — just enough
/// to render a fuzzy-pickable row and open the commit's diff.
#[derive(Debug, Clone)]
pub struct FileCommit {
    pub hash: String,
    pub short: String,
    pub author: String,
    pub time: i64,
    pub subject: String,
}

/// `git log --follow --pretty=… -- <path>` — commits that touched `rel`
/// (workspace-relative). `--follow` traces renames. Newest first. Capped
/// at 200 — past that, the picker becomes a wall of noise.
pub fn commits_for_file(workspace: &Path, rel: &str) -> Vec<FileCommit> {
    let fmt = "%H%x1f%an%x1f%at%x1f%s";
    let out = match Command::new("git")
        .args([
            "log",
            "--follow",
            "-n200",
            &format!("--pretty=format:{fmt}"),
            "--",
            rel,
        ])
        .current_dir(workspace)
        .output()
    {
        Ok(o) if o.status.success() => o,
        _ => return Vec::new(),
    };
    String::from_utf8_lossy(&out.stdout)
        .lines()
        .filter_map(|line| {
            let mut f = line.split('\u{1f}');
            let hash = f.next()?.to_string();
            let author = f.next().unwrap_or("").to_string();
            let time = f.next().unwrap_or("0").parse().unwrap_or(0);
            let subject = f.next().unwrap_or("").to_string();
            let short: String = hash.chars().take(9).collect();
            Some(FileCommit {
                hash,
                short,
                author,
                time,
                subject,
            })
        })
        .collect()
}

/// `git show --name-status --format= <hash>` — `(status, path)` per changed file.
/// `status` is the porcelain letter (`M`/`A`/`D`/`R…`/`C…`).
pub fn changed_files(workspace: &Path, hash: &str) -> Vec<(String, String)> {
    let out = match Command::new("git")
        .args(["show", "--name-status", "--format=", hash])
        .current_dir(workspace)
        .output()
    {
        Ok(o) if o.status.success() => o,
        _ => return Vec::new(),
    };
    String::from_utf8_lossy(&out.stdout)
        .lines()
        .filter(|l| !l.trim().is_empty())
        .filter_map(|l| {
            let mut it = l.split('\t');
            let status = it.next()?.to_string();
            // For renames/copies the line is `R100\told\tnew` — take the new path.
            let path = it.next_back()?.to_string();
            Some((status, path))
        })
        .collect()
}

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

    #[test]
    fn empty_on_non_repo() {
        let d = tempfile::tempdir().unwrap();
        assert!(load(d.path(), 100).is_empty());
    }

    #[test]
    fn lays_out_a_linear_history() {
        // C <- B <- A (newest first), all in lane 0.
        let mut commits = vec![
            Commit {
                hash: "c".into(),
                short: "c".into(),
                parents: vec!["b".into()],
                author: "x".into(),
                time: 3,
                subject: "third".into(),
                refs: vec![],
                graph: vec![],
                lane: 9,
            },
            Commit {
                hash: "b".into(),
                short: "b".into(),
                parents: vec!["a".into()],
                author: "x".into(),
                time: 2,
                subject: "second".into(),
                refs: vec![],
                graph: vec![],
                lane: 9,
            },
            Commit {
                hash: "a".into(),
                short: "a".into(),
                parents: vec![],
                author: "x".into(),
                time: 1,
                subject: "first".into(),
                refs: vec![],
                graph: vec![],
                lane: 9,
            },
        ];
        layout(&mut commits);
        for c in &commits {
            assert_eq!(c.lane, 0);
            assert_eq!(c.graph.len(), 1);
            assert_eq!(c.graph[0].ch, '');
        }
    }

    #[test]
    fn merge_uses_two_lanes() {
        // M (parents P1, P2) <- P1 <- (root), P2 <- (root). Newest first: M, P1, P2.
        let mut commits = vec![
            Commit {
                hash: "m".into(),
                short: "m".into(),
                parents: vec!["p1".into(), "p2".into()],
                author: "x".into(),
                time: 4,
                subject: "merge".into(),
                refs: vec![],
                graph: vec![],
                lane: 9,
            },
            Commit {
                hash: "p1".into(),
                short: "p1".into(),
                parents: vec![],
                author: "x".into(),
                time: 3,
                subject: "p1".into(),
                refs: vec![],
                graph: vec![],
                lane: 9,
            },
            Commit {
                hash: "p2".into(),
                short: "p2".into(),
                parents: vec![],
                author: "x".into(),
                time: 2,
                subject: "p2".into(),
                refs: vec![],
                graph: vec![],
                lane: 9,
            },
        ];
        layout(&mut commits);
        assert_eq!(commits[0].lane, 0);
        // The merge row spans two lanes (a branch-out corner in lane 1).
        assert!(commits[0].graph.len() >= 2);
        assert_eq!(commits[1].lane, 0); // p1 stays in lane 0
        assert_eq!(commits[2].lane, 1); // p2 in the second lane
    }
}