mkit-cli 0.4.2

The mkit command-line tool: a content-addressed VCS with native attestation support
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
//! `mkit rebase -i` — interactive rebase: reorder / drop / reword / squash
//! / fixup.
//!
//! Drives the command with a stub `$EDITOR` that transforms the todo file
//! (and, for reword/squash, writes the new/combined commit message on the
//! later editor invocation), keyed by the `$OP`/`$MSG` env vars.

#![cfg(unix)]
#![allow(clippy::unwrap_used)] // unwrap is the assertion in test helpers

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::{Command, Output};

fn mkit_bin() -> &'static str {
    env!("CARGO_BIN_EXE_mkit")
}

/// A stub editor that branches on the file it is handed:
/// - a rebase todo (detected by the `# Rebase` header) → apply `$OP`
/// - anything else (a reword message seed) → overwrite with `$MSG`
///
/// `$OP` values operate on commits whose subjects are single letters
/// `A`/`B`/`C` (the fixtures below), so the transformations are portable
/// shell with no `tac`/`sed -i`.
fn editor_script() -> (tempfile::TempDir, std::path::PathBuf) {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("todo-editor.sh");
    let script = r#"#!/bin/sh
f="$1"
if grep -q '^# Rebase' "$f"; then
    a=$(grep ' A$' "$f")
    b=$(grep ' B$' "$f")
    c=$(grep ' C$' "$f")
    case "$OP" in
        noop) : ;;
        reverse)
            { printf '%s\n' "$c"; printf '%s\n' "$b"; printf '%s\n' "$a"; } > "$f" ;;
        drop_b)
            grep -v ' B$' "$f" > "$f.tmp" && mv "$f.tmp" "$f" ;;
        reword_b)
            { printf '%s\n' "$a"; printf '%s\n' "$b" | sed 's/^pick/reword/'; printf '%s\n' "$c"; } > "$f" ;;
        squash_b)
            { printf '%s\n' "$a"; printf '%s\n' "$b" | sed 's/^pick/squash/'; printf '%s\n' "$c"; } > "$f" ;;
        fixup_b)
            { printf '%s\n' "$a"; printf '%s\n' "$b" | sed 's/^pick/fixup/'; printf '%s\n' "$c"; } > "$f" ;;
        squash_first)
            { printf '%s\n' "$a" | sed 's/^pick/squash/'; printf '%s\n' "$b"; printf '%s\n' "$c"; } > "$f" ;;
        drop_all)
            : > "$f" ;;
    esac
else
    printf '%s' "${MSG:-edited}" > "$f"
fi
"#;
    fs::write(&path, script).unwrap();
    let mut perms = fs::metadata(&path).unwrap().permissions();
    perms.set_mode(0o755);
    fs::set_permissions(&path, perms).unwrap();
    (dir, path)
}

struct Repo {
    _td: tempfile::TempDir,
    _xdg: tempfile::TempDir,
    path: std::path::PathBuf,
    xdg: std::path::PathBuf,
}

fn run(repo: &Repo, args: &[&str]) -> Output {
    Command::new(mkit_bin())
        .args(args)
        .current_dir(&repo.path)
        .env("XDG_CONFIG_HOME", &repo.xdg)
        .output()
        .expect("spawn mkit")
}

fn ok(repo: &Repo, args: &[&str]) -> Output {
    let out = run(repo, args);
    assert!(
        out.status.success(),
        "mkit {:?} failed: {}",
        args,
        String::from_utf8_lossy(&out.stderr)
    );
    out
}

/// `mkit rebase -i <onto>` driven by the stub editor under operation `op`
/// (and reword message `msg`).
fn rebase_i(repo: &Repo, onto: &str, script: &Path, op: &str, msg: &str) -> Output {
    Command::new(mkit_bin())
        .args(["rebase", "-i", onto])
        .current_dir(&repo.path)
        .env("XDG_CONFIG_HOME", &repo.xdg)
        .env("EDITOR", script)
        .env_remove("GIT_EDITOR")
        .env_remove("VISUAL")
        .env("OP", op)
        .env("MSG", msg)
        .output()
        .expect("spawn mkit rebase -i")
}

/// `mkit rebase --continue` with the stub editor wired up (the squash
/// combined-message editor runs during continue).
fn rebase_continue(repo: &Repo, script: &Path, msg: &str) -> Output {
    Command::new(mkit_bin())
        .args(["rebase", "--continue"])
        .current_dir(&repo.path)
        .env("XDG_CONFIG_HOME", &repo.xdg)
        .env("EDITOR", script)
        .env_remove("GIT_EDITOR")
        .env_remove("VISUAL")
        .env("MSG", msg)
        .output()
        .expect("spawn mkit rebase --continue")
}

fn commit(repo: &Repo, file: &str, content: &str, msg: &str) {
    fs::write(repo.path.join(file), content).unwrap();
    ok(repo, &["add", "."]);
    ok(repo, &["commit", "-m", msg]);
}

/// Subjects of the current branch's log, newest-first.
fn log_subjects(repo: &Repo) -> Vec<String> {
    let out = ok(repo, &["log", "--oneline"]);
    String::from_utf8(out.stdout)
        .unwrap()
        .lines()
        .map(|l| {
            l.split_once(' ')
                .map_or(String::new(), |(_, s)| s.to_string())
        })
        .collect()
}

/// main = base (c0); feature = base -> A -> B -> C, checked out.
fn setup() -> Repo {
    let td = tempfile::tempdir().unwrap();
    let xdg = tempfile::tempdir().unwrap();
    let repo = Repo {
        path: td.path().to_path_buf(),
        xdg: xdg.path().to_path_buf(),
        _td: td,
        _xdg: xdg,
    };
    ok(&repo, &["init"]);
    ok(&repo, &["keygen"]);
    commit(&repo, "base.txt", "base", "base");
    ok(&repo, &["branch", "feature"]);
    ok(&repo, &["checkout", "feature"]);
    commit(&repo, "a.txt", "A", "A");
    commit(&repo, "b.txt", "B", "B");
    commit(&repo, "c.txt", "C", "C");
    repo
}

#[test]
fn rebase_i_noop_preserves_order() {
    let repo = setup();
    let (_d, script) = editor_script();
    let out = rebase_i(&repo, "main", &script, "noop", "");
    assert!(
        out.status.success(),
        "noop rebase -i failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(log_subjects(&repo), vec!["C", "B", "A", "base"]);
}

#[test]
fn rebase_i_reorder_reverses_commits() {
    let repo = setup();
    let (_d, script) = editor_script();
    // Apply order C, B, A → HEAD is A, newest-first log: A, B, C.
    let out = rebase_i(&repo, "main", &script, "reverse", "");
    assert!(out.status.success());
    assert_eq!(log_subjects(&repo), vec!["A", "B", "C", "base"]);
    // All three files still present (reordering disjoint changes).
    for f in ["a.txt", "b.txt", "c.txt"] {
        assert!(repo.path.join(f).exists(), "{f} missing after reorder");
    }
}

#[test]
fn rebase_i_drop_removes_commit() {
    let repo = setup();
    let (_d, script) = editor_script();
    let out = rebase_i(&repo, "main", &script, "drop_b", "");
    assert!(out.status.success());
    assert_eq!(log_subjects(&repo), vec!["C", "A", "base"]);
    assert!(
        !repo.path.join("b.txt").exists(),
        "dropped commit's file should be gone"
    );
}

#[test]
fn rebase_i_reword_changes_message() {
    let repo = setup();
    let (_d, script) = editor_script();
    let out = rebase_i(&repo, "main", &script, "reword_b", "B-reworded");
    assert!(
        out.status.success(),
        "reword rebase -i failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(log_subjects(&repo), vec!["C", "B-reworded", "A", "base"]);
    // Content is untouched by a reword.
    assert!(repo.path.join("b.txt").exists());
}

#[test]
fn rebase_i_squash_folds_into_previous_and_combines_message() {
    let repo = setup();
    let (_d, script) = editor_script();
    // pick A, squash B into A, pick C. The squash opens the combined-message
    // editor; the stub writes MSG. Result: base -> AB(squashed) -> C.
    let out = rebase_i(&repo, "main", &script, "squash_b", "A and B squashed");
    assert!(
        out.status.success(),
        "squash rebase -i failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(
        log_subjects(&repo),
        vec!["C", "A and B squashed", "base"],
        "B should be folded into A with a combined message"
    );
    // The squashed commit still carries B's changes.
    assert!(
        repo.path.join("a.txt").exists(),
        "a.txt missing after squash"
    );
    assert!(
        repo.path.join("b.txt").exists(),
        "b.txt missing after squash"
    );
    assert!(repo.path.join("c.txt").exists());
}

#[test]
fn rebase_i_fixup_folds_into_previous_keeping_message() {
    let repo = setup();
    let (_d, script) = editor_script();
    // pick A, fixup B into A, pick C. Fixup keeps A's message and opens no
    // editor. Result: base -> A(+B's changes) -> C.
    let out = rebase_i(&repo, "main", &script, "fixup_b", "");
    assert!(
        out.status.success(),
        "fixup rebase -i failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(
        log_subjects(&repo),
        vec!["C", "A", "base"],
        "fixup should keep A's message and discard B's"
    );
    assert!(
        repo.path.join("b.txt").exists(),
        "b.txt missing after fixup"
    );
}

/// The danger-zone path: a `squash` whose replay conflicts must pause, and
/// `--continue` must build the *folded* commit (parent = the kept commit's
/// parent = `onto`, combined message) from the resolved tree — not a plain
/// child of HEAD. Scenario: `A` touches a different file (clean pick onto
/// `main`), then `B` edits `f.txt` where `main` also edited it, so only the
/// `squash B` step collides.
#[test]
fn rebase_i_squash_with_conflict_then_continue() {
    let td = tempfile::tempdir().unwrap();
    let xdg = tempfile::tempdir().unwrap();
    let repo = Repo {
        path: td.path().to_path_buf(),
        xdg: xdg.path().to_path_buf(),
        _td: td,
        _xdg: xdg,
    };
    ok(&repo, &["init"]);
    ok(&repo, &["keygen"]);
    commit(&repo, "f.txt", "x\ny\n", "base");
    ok(&repo, &["branch", "feature"]);
    ok(&repo, &["checkout", "feature"]);
    commit(&repo, "a.txt", "from A\n", "A"); // different file → clean pick
    commit(&repo, "f.txt", "B-line\ny\n", "B"); // edits f.txt line 1
    ok(&repo, &["checkout", "main"]);
    commit(&repo, "f.txt", "MAIN-line\ny\n", "M"); // also edits f.txt line 1
    ok(&repo, &["checkout", "feature"]);

    let (_d, script) = editor_script();
    // pick A (other file, clean onto M) then squash B (f.txt line 1 collides).
    let out = rebase_i(&repo, "main", &script, "squash_b", "A+B squashed");
    assert!(
        !out.status.success(),
        "squash should pause on the line-1 conflict"
    );
    assert!(
        repo.path.join(".mkit/rebase-apply").exists(),
        "a paused rebase should leave in-progress state"
    );

    // Resolve and continue. The squash's combined-message editor runs here.
    fs::write(repo.path.join("f.txt"), "RESOLVED\nfrom main+B\n").unwrap();
    ok(&repo, &["add", "f.txt"]);
    let cont = rebase_continue(&repo, &script, "A+B squashed");
    assert!(
        cont.status.success(),
        "rebase --continue after squash conflict failed: {}",
        String::from_utf8_lossy(&cont.stderr)
    );

    // feature = base -> M -> (A+B squashed); the fold's parent is `onto` (M),
    // not the throwaway picked-A commit.
    assert_eq!(log_subjects(&repo), vec!["A+B squashed", "M", "base"]);
    assert_eq!(
        fs::read_to_string(repo.path.join("f.txt")).unwrap(),
        "RESOLVED\nfrom main+B\n",
        "the resolved tree should be committed"
    );
    // A's file survives the fold (it was part of the kept commit).
    assert!(
        repo.path.join("a.txt").exists(),
        "a.txt lost in the squash fold"
    );
    assert!(!repo.path.join(".mkit/rebase-apply").exists());
}

#[test]
fn rebase_i_squash_as_first_line_is_rejected_without_mutating() {
    let repo = setup();
    let before = log_subjects(&repo);
    let (_d, script) = editor_script();
    // Marking the first line `squash` has nothing to fold into.
    let out = rebase_i(&repo, "main", &script, "squash_first", "");
    assert!(!out.status.success(), "a leading squash must be rejected");
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("first commit"),
        "expected a 'first commit' rejection, got: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    // Rejected before any mutation.
    assert_eq!(log_subjects(&repo), before);
    assert!(!repo.path.join(".mkit/rebase-apply").exists());
}

/// `rebase -i <onto>` when the current branch is *behind* `onto` (an
/// ancestor of it) must fast-forward the branch to `onto`, like
/// non-interactive rebase — not early-return as a noop.
#[test]
fn rebase_i_fast_forwards_when_behind() {
    let td = tempfile::tempdir().unwrap();
    let xdg = tempfile::tempdir().unwrap();
    let repo = Repo {
        path: td.path().to_path_buf(),
        xdg: xdg.path().to_path_buf(),
        _td: td,
        _xdg: xdg,
    };
    ok(&repo, &["init"]);
    ok(&repo, &["keygen"]);
    // main = base -> A; feature branches at base (one commit behind main).
    commit(&repo, "base.txt", "base", "base");
    ok(&repo, &["branch", "feature"]);
    commit(&repo, "a.txt", "A", "A"); // advances main to A
    ok(&repo, &["checkout", "feature"]);
    assert_eq!(log_subjects(&repo), vec!["base"]);

    let (_d, script) = editor_script();
    let out = rebase_i(&repo, "main", &script, "noop", "");
    assert!(
        out.status.success(),
        "rebase -i when behind failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    // feature fast-forwarded to main (base -> A).
    assert_eq!(log_subjects(&repo), vec!["A", "base"]);
    assert!(repo.path.join("a.txt").exists());
}

#[test]
fn rebase_i_drop_all_resets_to_base() {
    let repo = setup();
    let (_d, script) = editor_script();
    let out = rebase_i(&repo, "main", &script, "drop_all", "");
    assert!(
        out.status.success(),
        "drop-all rebase -i failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    // Dropping every commit resets feature to the base.
    assert_eq!(log_subjects(&repo), vec!["base"]);
    for f in ["a.txt", "b.txt", "c.txt"] {
        assert!(!repo.path.join(f).exists(), "{f} should be gone");
    }
}

// ---------- revspec targets (the onto argument is resolved through the
// shared revspec resolver, not a literal ref read) ------------------------

/// Non-interactive `rebase HEAD~n` works: the positional argument
/// accepts any revspec, not just a branch name. (Regression: this used
/// to fail with `read ref: invalid ref name 'HEAD~3'`.)
#[test]
fn rebase_accepts_head_relative_revspec() {
    let repo = setup();
    // On feature (base -> A -> B -> C): HEAD~3 == base == main.
    let out = run(&repo, &["rebase", "HEAD~3"]);
    assert!(
        out.status.success(),
        "rebase HEAD~3 failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("Successfully rebased"),
        "expected a 3-commit replay, got: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(log_subjects(&repo), vec!["C", "B", "A", "base"]);
}

/// Non-interactive `rebase <short-hash>` works.
#[test]
fn rebase_accepts_short_hash_revspec() {
    let repo = setup();
    let main_hash = fs::read_to_string(repo.path.join(".mkit/refs/heads/main")).unwrap();
    let short = &main_hash.trim()[..12];
    let out = run(&repo, &["rebase", short]);
    assert!(
        out.status.success(),
        "rebase {short} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("Successfully rebased"),
        "expected a 3-commit replay, got: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(log_subjects(&repo), vec!["C", "B", "A", "base"]);
}

/// `rebase -i HEAD~n` works (the interactive flag goes through the same
/// resolution).
#[test]
fn rebase_i_accepts_head_relative_revspec() {
    let repo = setup();
    let (_d, script) = editor_script();
    // HEAD~2 == A; replay B and C onto it unchanged.
    let out = rebase_i(&repo, "HEAD~2", &script, "noop", "");
    assert!(
        out.status.success(),
        "rebase -i HEAD~2 failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("Successfully rebased"),
        "expected a 2-commit replay, got: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(log_subjects(&repo), vec!["C", "B", "A", "base"]);
}

/// An unknown revspec is still rejected before any mutation.
#[test]
fn rebase_rejects_unknown_revspec() {
    let repo = setup();
    let before = log_subjects(&repo);
    let out = run(&repo, &["rebase", "nosuchref~2"]);
    assert!(!out.status.success(), "unknown revspec should fail");
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("no such commit"),
        "expected a resolver error, got: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(log_subjects(&repo), before);
    assert!(!repo.path.join(".mkit/rebase-apply").exists());
}

#[test]
fn rebase_i_skip_rejects_newly_leading_squash() {
    // feature: base -> A(a.txt) -> B(b.txt) -> C(c.txt). `main` diverges on
    // a.txt so replaying A conflicts. Todo: pick A / squash B / pick C. Skip
    // the conflicted A → `squash B` becomes the first APPLIED step, which must
    // be rejected (a runtime leading-fold guard), not silently folded into
    // onto's parent.
    let repo = setup();
    ok(&repo, &["checkout", "main"]);
    commit(&repo, "a.txt", "main-A", "main diverge"); // conflicts with feature's A
    ok(&repo, &["checkout", "feature"]);
    let (_d, script) = editor_script();

    let out = rebase_i(&repo, "main", &script, "squash_b", "BB");
    assert!(
        !out.status.success(),
        "rebase should pause on A's conflict, not finish: {}",
        String::from_utf8_lossy(&out.stdout)
    );

    // Skip the conflicted A; the now-leading `squash B` must be rejected.
    let skip = run(&repo, &["rebase", "--skip"]);
    assert!(
        !skip.status.success(),
        "skip must reject a newly-leading squash, not fold B into onto"
    );
    assert!(
        String::from_utf8_lossy(&skip.stderr).contains("cannot 'squash' as the first commit"),
        "stderr: {}",
        String::from_utf8_lossy(&skip.stderr)
    );

    // The rebase is still in progress and can be aborted cleanly.
    assert!(run(&repo, &["rebase", "--abort"]).status.success());
    assert_eq!(log_subjects(&repo), vec!["C", "B", "A", "base"]);
}