rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
//! Git actions with pinned inputs and durable recovery refs. No shell commands are built.

use std::fs::{self, File, OpenOptions};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use super::{forge, git, source};

#[derive(Clone, Debug)]
pub struct Commit {
    pub id: String,
    pub subject: String,
}

#[derive(Clone, Debug)]
pub struct Snapshot {
    pub root: PathBuf,
    pub branch: String,
    pub head: String,
    pub dirty: usize,
    pub branches: Vec<String>,
    pub remote_branches: Vec<String>,
    pub commits: Vec<Commit>,
    pub recovery: Option<Move>,
    pub undo: Option<Move>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Move {
    pub source: String,
    pub destination: String,
    pub old: String,
    pub base: String,
    pub backup: String,
    pub count: usize,
}

#[derive(Clone, Debug, PartialEq)]
pub enum Action {
    Track { reference: String, expected: String },
    Switch { branch: String, expected: String },
    Create { branch: String, expected: String },
    Move(Move),
    Undo(Move),
    Publish { movement: Move, remote: String, expected: String, desired: String, destination_exists: bool },
}

fn head(root: &Path) -> Result<String, String> {
    git::commit_id(root, "HEAD").ok_or("No commits yet".into())
}

fn branch(root: &Path) -> Result<String, String> {
    git::line(root, &["symbolic-ref", "--quiet", "--short", "HEAD"])
        .map_err(|_| "Detached HEAD: switch to a branch first".into())
}

fn state_dir(root: &Path) -> Result<PathBuf, String> {
    git::line(root, &["rev-parse", "--path-format=absolute", "--git-common-dir"])
        .map(|p| PathBuf::from(p).join("rustimal"))
}

fn lock(root: &Path) -> Result<File, String> {
    let dir = state_dir(root)?;
    fs::create_dir_all(&dir).map_err(|e| format!("Recovery storage: {e}"))?;
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(dir.join("operation.lock"))
        .map_err(|e| format!("Git operation lock: {e}"))?;
    file.try_lock().map_err(|_| "Another rustimal Git action is running".to_string())?;
    Ok(file)
}

fn clean(root: &Path) -> Result<(), String> {
    if !git::output(root, &["status", "--porcelain=v1", "--untracked-files=normal", "--ignore-submodules=none"])?
        .is_empty()
    {
        return Err("Commit or stash your changes first".into());
    }
    for marker in
        ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply", "sequencer", "BISECT_LOG"]
    {
        let path = git::line(root, &["rev-parse", "--path-format=absolute", "--git-path", marker])?;
        if Path::new(&path).exists() {
            return Err("Finish or abort the current Git operation first".into());
        }
    }
    Ok(())
}

fn valid_branch(root: &Path, name: &str) -> Result<(), String> {
    if name.is_empty() || name.starts_with('-') || name == "HEAD" || name.chars().any(char::is_control) {
        return Err("Choose a valid branch name".into());
    }
    git::output(root, &["check-ref-format", &format!("refs/heads/{name}")]).map(|_| ())
}

fn pinned(root: &Path, expected: &str) -> Result<(), String> {
    if head(root)? != expected {
        return Err("HEAD changed. Refresh and try again".into());
    }
    clean(root)
}

fn validate_move(root: &Path, m: &Move) -> Result<(), String> {
    valid_branch(root, &m.source)?;
    valid_branch(root, &m.destination)?;
    let oid = |s: &str| matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit());
    if m.source == m.destination
        || !oid(&m.old)
        || !oid(&m.base)
        || !m.backup.starts_with("refs/rustimal/undo/")
        || m.backup.contains("..")
    {
        return Err("Invalid recovery record".into());
    }
    git::output(root, &["check-ref-format", &m.backup])?;
    Ok(())
}

pub fn snapshot(cwd: &Path) -> Result<Snapshot, String> {
    let root = source::repository(cwd)?;
    let branch = branch(&root).unwrap_or_else(|_| "(detached)".into());
    let head = head(&root).unwrap_or_default();
    let dirty = git::output(&root, &["status", "--porcelain=v1"])?.lines().count();
    let branches =
        git::output(&root, &["for-each-ref", "--sort=-committerdate", "--format=%(refname:strip=2)", "refs/heads/"])?
            .lines()
            .map(str::to_string)
            .collect();
    let commits = git::output(&root, &["log", "--first-parent", "-n", "100", "--format=%H%x1f%s", "HEAD", "--"])
        .unwrap_or_default()
        .lines()
        .filter_map(|l| l.split_once('\x1f'))
        .map(|(id, subject)| Commit { id: id.into(), subject: subject.into() })
        .collect();
    let remote_branches = git::output(
        &root,
        &["for-each-ref", "--sort=-committerdate", "--format=%(refname:strip=2)%1f%(symref)", "refs/remotes/"],
    )?
    .lines()
    .filter_map(|line| line.split_once('\x1f'))
    .filter(|(_, symref)| symref.is_empty())
    .map(|(name, _)| name.to_string())
    .collect();
    let recoveries = matching_recoveries(&root, &branch).unwrap_or_default();
    let recovery = recoveries.first().cloned();
    let undo = recoveries.iter().find(|m| m.base == head).cloned();
    Ok(Snapshot { root, branch, head, dirty, branches, remote_branches, commits, recovery, undo })
}

fn matching_recoveries(root: &Path, source: &str) -> Option<Vec<Move>> {
    let current = head(root).ok()?;
    let mut files: Vec<_> = fs::read_dir(state_dir(root).ok()?)
        .ok()?
        .filter_map(Result::ok)
        .filter(|e| e.path().extension().is_some_and(|e| e == "json"))
        .collect();
    files.sort_by_key(|e| std::cmp::Reverse(e.file_name()));
    let eligible: Vec<_> = files
        .into_iter()
        .take(100)
        .filter_map(|e| {
            let m: Move = serde_json::from_slice(&fs::read(e.path()).ok()?).ok()?;
            if m.source != source && source != "(detached)" {
                return None;
            }
            let source_id = git::commit_id(root, &format!("refs/heads/{}", m.source));
            let matches = if source == "(detached)" {
                current == m.base && source_id.as_deref().is_some_and(|id| id == m.base || id == m.old)
            } else {
                source_id.as_deref() == Some(&current)
                    && (current == m.base || (current == m.old && e.path().with_extension("done").exists()))
            };
            ((m.source == source || source == "(detached)")
                && matches
                && validate_move(root, &m).is_ok()
                && git::commit_id(root, &m.backup).as_deref() == Some(&m.old))
            .then_some(m)
        })
        .collect();
    if source == "(detached)" && eligible.len() != 1 { None } else { Some(eligible) }
}

fn completed(root: &Path, m: &Move) -> Result<(), String> {
    let name = m.backup.rsplit('/').next().ok_or("Invalid recovery name")?;
    let file = File::create(state_dir(root)?.join(format!("{name}.done")))
        .map_err(|e| format!("History updated, but recovery marker failed: {e}"))?;
    file.sync_all().map_err(|e| format!("History updated, but recovery marker failed: {e}"))
}

/// Detach before changing a branch ref, then update that exact ref with compare-and-swap.
/// Every interruption leaves the commits on named refs; ignored files are never replaced.
fn rewind(root: &Path, m: &Move, undo: bool) -> Result<(), String> {
    let (expected, target) = if undo { (&m.base, &m.old) } else { (&m.old, &m.base) };
    let source_ref = format!("refs/heads/{}", m.source);
    let current = branch(root).ok();
    if current.as_deref().is_some_and(|b| b != m.source) {
        return Err("Branch changed. Refresh first".into());
    }
    if !undo && current.is_none() {
        return Err("Branch changed. Refresh first".into());
    }
    if git::commit_id(root, &source_ref).as_deref() != Some(expected) {
        // A crash before the ref update left the original branch intact. Reattach safely.
        if undo && current.is_none() && git::commit_id(root, &source_ref).as_deref() == Some(&m.old) {
            git::output(root, &["switch", "--no-guess", "--no-overwrite-ignore", "--", &m.source])?;
            return Ok(());
        }
        return Err("Source branch changed since the preview".into());
    }
    git::output(root, &["switch", "--detach", "--no-overwrite-ignore", target])?;
    if branch(root).is_ok() || head(root)? != *target {
        return Err("HEAD changed during checkout. Recovery refs kept".into());
    }
    clean(root)?;
    let worktrees = git::output(root, &["worktree", "list", "--porcelain", "-z"])?;
    if worktrees.split('\0').any(|part| part == format!("branch {source_ref}")) {
        return Err("Source branch is now checked out in another worktree. Recovery refs kept".into());
    }
    git::output(root, &["update-ref", "-m", "rustimal recovery", &source_ref, target, expected])
        .map_err(|e| format!("{e}. Detached at {}. Recovery: {}", &target[..8], m.backup))?;
    if branch(root).is_ok() || head(root)? != *target {
        return Err("HEAD changed. Branch updated; recovery refs kept".into());
    }
    git::output(root, &["switch", "--no-guess", "--no-overwrite-ignore", "--", &m.source])?;
    Ok(())
}

pub fn prepare_move(snapshot: &Snapshot, oldest: usize, destination: &str) -> Result<Move, String> {
    let root = &snapshot.root;
    pinned(root, &snapshot.head)?;
    if branch(root)? != snapshot.branch {
        return Err("Branch changed. Refresh first".into());
    }
    valid_branch(root, destination)?;
    if git::commit_id(root, &format!("refs/heads/{destination}")).is_some() {
        return Err("That branch already exists".into());
    }
    let last = snapshot.commits.get(oldest).ok_or("Select commits first")?;
    let range = git::output(root, &["rev-list", "--parents", &format!("{}^..{}", last.id, snapshot.head), "--"])?;
    let rows: Vec<Vec<&str>> = range.lines().map(|l| l.split_whitespace().collect()).collect();
    if rows.len() != oldest + 1 || rows.iter().any(|r| r.len() != 2) {
        return Err("Select a linear block of latest commits; merges are not supported".into());
    }
    let base = git::commit_id(root, &format!("{}^", last.id)).ok_or("Cannot move the root commit")?;
    let id = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos();
    Ok(Move {
        source: snapshot.branch.clone(),
        destination: destination.into(),
        old: snapshot.head.clone(),
        base,
        backup: format!("refs/rustimal/undo/{id:030}-{}", std::process::id()),
        count: oldest + 1,
    })
}

pub fn execute(root: &Path, action: &Action) -> Result<String, String> {
    let _lock = lock(root)?;
    match action {
        Action::Track { reference, expected } => {
            pinned(root, expected)?;
            if !reference.starts_with("refs/remotes/") || git::commit_id(root, reference).is_none() {
                return Err("Remote branch is missing. Fetch first".into());
            }
            git::output(root, &["check-ref-format", reference])?;
            git::output(root, &["switch", "--no-guess", "--no-overwrite-ignore", "--track", "--", reference])?;
            Ok(format!("On {}", branch(root)?))
        }
        Action::Switch { branch: target, expected } | Action::Create { branch: target, expected } => {
            pinned(root, expected)?;
            valid_branch(root, target)?;
            if matches!(action, Action::Create { .. }) {
                git::output(root, &["switch", "--no-guess", "--no-overwrite-ignore", "-c", target])?;
            } else {
                git::output(root, &["switch", "--no-guess", "--no-overwrite-ignore", "--", target])?;
            }
            Ok(format!("On {target}"))
        }
        Action::Move(m) => {
            validate_move(root, m)?;
            pinned(root, &m.old)?;
            if branch(root)? != m.source {
                return Err("Branch changed. Refresh first".into());
            }
            // Rebuild from the pinned history, rather than trusting a stale or edited preview.
            let s = snapshot(root)?;
            let checked = prepare_move(&s, m.count.checked_sub(1).ok_or("Invalid commit count")?, &m.destination)?;
            if checked.old != m.old || checked.base != m.base {
                return Err("History changed. Refresh first".into());
            }
            let name = m.backup.rsplit('/').next().ok_or("Invalid recovery name")?;
            let bytes = serde_json::to_vec(m).map_err(|e| e.to_string())?;
            use std::io::Write;
            let mut record = OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(state_dir(root)?.join(format!("{name}.json")))
                .map_err(|e| format!("Could not save recovery: {e}"))?;
            record
                .write_all(&bytes)
                .and_then(|_| record.sync_all())
                .map_err(|e| format!("Could not save recovery: {e}"))?;
            git::output(root, &["update-ref", &m.backup, &m.old, ""])?;
            git::output(root, &["branch", "--no-track", &m.destination, &m.old])?;
            if let Err(e) = rewind(root, m, false) {
                return Err(format!("{e}. Commits are safe on {} and {}", m.destination, m.backup));
            }
            completed(root, m)?;
            Ok(format!("Moved {} commits to {}. Undo: u", m.count, m.destination))
        }
        Action::Undo(m) => {
            validate_move(root, m)?;
            pinned(root, &m.base)?;
            if branch(root).ok().as_deref().is_some_and(|b| b != m.source)
                || git::commit_id(root, &m.backup).as_deref() != Some(&m.old)
            {
                return Err("Recovery no longer matches this branch".into());
            }
            rewind(root, m, true)?;
            completed(root, m)?;
            Ok(format!("Restored {}. {} kept", m.source, m.destination))
        }
        Action::Publish { movement: m, remote, expected, desired, destination_exists } => {
            validate_move(root, m)?;
            pinned(root, desired)?;
            if branch(root)? != m.source
                || git::commit_id(root, &m.backup).as_deref() != Some(&m.old)
                || !((expected == &m.old && desired == &m.base) || (expected == &m.base && desired == &m.old))
            {
                return Err("Publication no longer matches this recovery".into());
            }
            // Pin the server URL too; configuration changing after the preview must not redirect the push.
            let (configured, _) = forge::remote(root)?;
            let url = git::line(root, &["remote", "get-url", "--push", &configured])?;
            if remote != &url {
                return Err("Remote changed. Preview again".into());
            }
            if git::commit_id(root, &format!("refs/heads/{}", m.destination)).as_deref() != Some(&m.old) {
                return Err("Destination branch changed".into());
            }
            let source_ref = format!("refs/heads/{}", m.source);
            let destination_ref = format!("refs/heads/{}", m.destination);
            let live = git::output(root, &["ls-remote", "--refs", "--", remote, &source_ref, &destination_ref])?;
            let remote_id = |r: &str| {
                live.lines().filter_map(|l| l.split_once('\t')).find(|(_, name)| *name == r).map(|(id, _)| id)
            };
            if remote_id(&source_ref) != Some(expected)
                || remote_id(&destination_ref) != if *destination_exists { Some(m.old.as_str()) } else { None }
            {
                return Err("Remote changed since the preview. Preview again".into());
            }
            let source_lease = format!("--force-with-lease={source_ref}:{expected}");
            let dest_lease =
                format!("--force-with-lease={destination_ref}:{}", if *destination_exists { &m.old } else { "" });
            git::output(
                root,
                &[
                    "push",
                    "--porcelain",
                    "--atomic",
                    "--no-follow-tags",
                    "--recurse-submodules=no",
                    &source_lease,
                    &dest_lease,
                    "--",
                    remote,
                    &format!("{desired}:{source_ref}"),
                    &format!("{}:{destination_ref}", m.old),
                ],
            )?;
            Ok(format!("Published {} and {}", m.source, m.destination))
        }
    }
}

pub fn fetch(root: &Path) -> Result<(), String> {
    let _lock = lock(root)?;
    let (remote, _) = forge::remote(root)?;
    git::output(root, &["fetch", "--prune", "--", &remote]).map(|_| ())
}

pub fn prepare_publish(root: &Path, m: &Move) -> Result<Action, String> {
    validate_move(root, m)?;
    clean(root)?;
    let desired = head(root)?;
    let expected = if desired == m.base {
        &m.old
    } else if desired == m.old {
        &m.base
    } else {
        return Err("Branch changed since the move".into());
    };
    let (name, _) = forge::remote(root)?;
    let remote = git::line(root, &["remote", "get-url", "--push", &name])?;
    let source_ref = format!("refs/heads/{}", m.source);
    let destination_ref = format!("refs/heads/{}", m.destination);
    let refs = git::output(root, &["ls-remote", "--refs", "--", &remote, &source_ref, &destination_ref])?;
    let find = |r: &str| refs.lines().filter_map(|l| l.split_once('\t')).find(|(_, name)| *name == r).map(|(id, _)| id);
    if find(&source_ref) != Some(expected) {
        return Err("Remote branch changed or is missing. Fetch and inspect it first".into());
    }
    if find(&destination_ref).is_some_and(|id| id != m.old) {
        return Err("The remote destination branch already has other commits".into());
    }
    Ok(Action::Publish {
        movement: m.clone(),
        remote,
        expected: expected.clone(),
        desired,
        destination_exists: find(&destination_ref).is_some(),
    })
}

/// Open an existing PR for this branch; if none exists, open the host's creation page.
pub fn remote_label(remote: &str) -> String {
    forge::parse_remote(remote)
        .map(|at| format!("{}/{}", at.host, at.path))
        .unwrap_or_else(|| if Path::new(remote).is_absolute() { remote.into() } else { "Configured remote".into() })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::review::git::testing::{commit, init, run};
    use crate::review::testutil::Scratch;

    fn repo(name: &str) -> Scratch {
        let s = Scratch::new(name);
        init(&s.0);
        for n in 0..4 {
            fs::write(s.0.join("file"), format!("{n}\n")).unwrap();
            commit(&s.0, &format!("commit {n}"));
        }
        s
    }

    #[test]
    fn moving_and_undoing_preserves_commits_and_the_working_tree() {
        let s = repo("git-move");
        let before = snapshot(&s.0).unwrap();
        let m = prepare_move(&before, 1, "feature/fix").unwrap();
        execute(&s.0, &Action::Move(m.clone())).unwrap();
        assert_eq!(head(&s.0).unwrap(), m.base);
        assert_eq!(fs::read_to_string(s.0.join("file")).unwrap(), "1\n");
        assert_eq!(git::commit_id(&s.0, "refs/heads/feature/fix"), Some(before.head.clone()));
        assert_eq!(git::commit_id(&s.0, &m.backup), Some(before.head.clone()));
        assert_eq!(snapshot(&s.0).unwrap().recovery, Some(m.clone()));
        execute(&s.0, &Action::Undo(m.clone())).unwrap();
        assert_eq!(head(&s.0).unwrap(), before.head);
        assert_eq!(fs::read_to_string(s.0.join("file")).unwrap(), "3\n");
        assert!(git::commit_id(&s.0, "refs/heads/feature/fix").is_some());
        assert!(git::output(&s.0, &["status", "--porcelain"]).unwrap().is_empty());
        assert!(execute(&s.0, &Action::Undo(m)).is_err());
    }

    #[test]
    fn dirty_stale_merged_and_invalid_moves_leave_history_alone() {
        let s = repo("git-guards");
        let before = snapshot(&s.0).unwrap();
        let m = prepare_move(&before, 0, "feature").unwrap();
        fs::write(s.0.join("untracked"), "keep me").unwrap();
        assert!(execute(&s.0, &Action::Move(m.clone())).unwrap_err().contains("stash"));
        assert_eq!(head(&s.0).unwrap(), before.head);
        assert!(git::commit_id(&s.0, "refs/heads/feature").is_none());
        commit(&s.0, "new work");
        assert!(execute(&s.0, &Action::Move(m)).unwrap_err().contains("HEAD changed"));
        for name in ["--force", "a..b", "HEAD", "x\ny", ""] {
            assert!(prepare_move(&snapshot(&s.0).unwrap(), 0, name).is_err(), "{name}");
        }
        assert!(prepare_move(&snapshot(&s.0).unwrap(), 4, "root").is_err());
        run(&s.0, &["switch", "-c", "other", "HEAD~2"]);
        fs::write(s.0.join("other"), "branch").unwrap();
        commit(&s.0, "other");
        run(&s.0, &["switch", "main"]);
        run(&s.0, &["merge", "--no-ff", "other", "-m", "merge"]);
        assert!(prepare_move(&snapshot(&s.0).unwrap(), 0, "merged").is_err());
    }

    #[test]
    fn checkout_create_and_operation_locks() {
        let s = repo("git-switch");
        let before = snapshot(&s.0).unwrap();
        execute(&s.0, &Action::Create { branch: "feature".into(), expected: before.head.clone() }).unwrap();
        assert_eq!(branch(&s.0).unwrap(), "feature");
        execute(&s.0, &Action::Switch { branch: "main".into(), expected: before.head.clone() }).unwrap();
        let _lock = lock(&s.0).unwrap();
        assert!(
            execute(&s.0, &Action::Switch { branch: "feature".into(), expected: before.head })
                .unwrap_err()
                .contains("running")
        );
    }

    #[test]
    fn failed_later_move_does_not_hide_an_earlier_undo() {
        let s = repo("git-failed-recovery");
        fs::write(s.0.join("data"), "tracked").unwrap();
        commit(&s.0, "track data");
        fs::remove_file(s.0.join("data")).unwrap();
        fs::write(s.0.join(".gitignore"), "data\n").unwrap();
        commit(&s.0, "ignore data");
        fs::write(s.0.join("extra"), "extra").unwrap();
        commit(&s.0, "extra");
        let first = prepare_move(&snapshot(&s.0).unwrap(), 0, "first").unwrap();
        execute(&s.0, &Action::Move(first.clone())).unwrap();
        fs::write(s.0.join("data"), "USER CONTENT").unwrap();
        let later = prepare_move(&snapshot(&s.0).unwrap(), 0, "later").unwrap();
        assert!(execute(&s.0, &Action::Move(later)).is_err());
        assert_eq!(snapshot(&s.0).unwrap().recovery, Some(first.clone()));
        execute(&s.0, &Action::Undo(first)).unwrap();
        assert_eq!(fs::read_to_string(s.0.join("data")).unwrap(), "USER CONTENT");
    }

    #[test]
    fn consecutive_moves_can_be_undone_in_order() {
        let s = repo("git-chain-undo");
        let original = head(&s.0).unwrap();
        let first = prepare_move(&snapshot(&s.0).unwrap(), 0, "first").unwrap();
        execute(&s.0, &Action::Move(first.clone())).unwrap();
        let second = prepare_move(&snapshot(&s.0).unwrap(), 0, "second").unwrap();
        execute(&s.0, &Action::Move(second.clone())).unwrap();
        execute(&s.0, &Action::Undo(snapshot(&s.0).unwrap().undo.unwrap())).unwrap();
        let after = snapshot(&s.0).unwrap();
        assert_eq!(after.recovery, Some(second));
        assert_eq!(after.undo, Some(first));
        execute(&s.0, &Action::Undo(after.undo.unwrap())).unwrap();
        assert_eq!(head(&s.0).unwrap(), original);
    }

    #[test]
    fn fetch_and_checkout_remote_tracking_branch() {
        let s = repo("git-tracking");
        let remote = Scratch::new("git-tracking-bare");
        run(&remote.0, &["init", "--bare", "--quiet"]);
        run(&s.0, &["remote", "add", "origin", remote.0.to_str().unwrap()]);
        run(&s.0, &["push", "--quiet", "origin", "HEAD:refs/heads/feature/settings"]);
        fetch(&s.0).unwrap();
        let s0 = snapshot(&s.0).unwrap();
        assert!(s0.remote_branches.contains(&"origin/feature/settings".into()));
        execute(&s.0, &Action::Track { reference: "refs/remotes/origin/feature/settings".into(), expected: s0.head })
            .unwrap();
        assert_eq!(branch(&s.0).unwrap(), "feature/settings");
        assert_eq!(git::line(&s.0, &["rev-parse", "--abbrev-ref", "@{upstream}"]).unwrap(), "origin/feature/settings");
    }

    #[test]
    fn ignored_files_are_not_overwritten_by_move_or_checkout() {
        let s = repo("git-ignored");
        fs::write(s.0.join("data"), "tracked").unwrap();
        commit(&s.0, "track data");
        fs::remove_file(s.0.join("data")).unwrap();
        fs::write(s.0.join(".gitignore"), "data\n").unwrap();
        commit(&s.0, "ignore data");
        fs::write(s.0.join("data"), "USER CONTENT").unwrap();
        let before = snapshot(&s.0).unwrap();
        assert_eq!(before.dirty, 0);
        let m = prepare_move(&before, 0, "saved").unwrap();
        assert!(execute(&s.0, &Action::Move(m)).is_err());
        assert_eq!(fs::read_to_string(s.0.join("data")).unwrap(), "USER CONTENT");
        assert_eq!(head(&s.0).unwrap(), before.head);
    }

    #[test]
    fn interrupted_detached_move_can_be_recovered_without_rewriting_new_work() {
        let s = repo("git-interrupted");
        let m = prepare_move(&snapshot(&s.0).unwrap(), 0, "saved").unwrap();
        execute(&s.0, &Action::Move(m.clone())).unwrap();
        run(&s.0, &["switch", "--detach", &m.base]);
        assert_eq!(snapshot(&s.0).unwrap().recovery, Some(m.clone()));
        execute(&s.0, &Action::Undo(m.clone())).unwrap();
        assert_eq!(branch(&s.0).unwrap(), "main");
        assert_eq!(head(&s.0).unwrap(), m.old);
        // A second process committing on the source makes a stale recovery refuse.
        fs::write(s.0.join("new"), "keep").unwrap();
        commit(&s.0, "later work");
        let later = head(&s.0).unwrap();
        run(&s.0, &["switch", "--detach", &m.base]);
        assert!(execute(&s.0, &Action::Undo(m)).is_err());
        assert_eq!(git::commit_id(&s.0, "refs/heads/main"), Some(later));
    }

    #[test]
    fn atomic_publication_leases_and_remote_undo() {
        let s = repo("git-publish");
        let remote = Scratch::new("git-bare");
        run(&remote.0, &["init", "--bare", "--quiet"]);
        run(&s.0, &["remote", "add", "origin", remote.0.to_str().unwrap()]);
        run(&s.0, &["push", "--quiet", "origin", "main"]);
        let m = prepare_move(&snapshot(&s.0).unwrap(), 0, "rescued").unwrap();
        execute(&s.0, &Action::Move(m.clone())).unwrap();
        let push = prepare_publish(&s.0, &m).unwrap();
        // A concurrent remote update makes the exact lease fail; neither ref moves.
        run(&remote.0, &["update-ref", "refs/heads/main", &m.base]);
        assert!(execute(&s.0, &push).is_err());
        assert!(git::commit_id(&remote.0, "refs/heads/rescued").is_none());
        run(&remote.0, &["update-ref", "refs/heads/main", &m.old]);
        execute(&s.0, &push).unwrap();
        assert_eq!(git::commit_id(&remote.0, "refs/heads/main"), Some(m.base.clone()));
        assert_eq!(git::commit_id(&remote.0, "refs/heads/rescued"), Some(m.old.clone()));
        execute(&s.0, &Action::Undo(m.clone())).unwrap();
        execute(&s.0, &prepare_publish(&s.0, &m).unwrap()).unwrap();
        assert_eq!(git::commit_id(&remote.0, "refs/heads/main"), Some(m.old));
    }
}