grit-lib 0.5.22

Core library for the grit Git implementation
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
//! Round-trip `grit reset` with system `git fsck` / `git status`.

mod support;

use std::path::Path;

use grit_lib::error::Error;
use grit_lib::index::write_tree::{write_tree_update_index, WriteTreeFlags};
use grit_lib::objects::ObjectId;
use grit_lib::porcelain::reset::{reset_to_commit, ResetMode, ResetOptions};
use grit_lib::repo::{InitOptions, Repository};
use grit_lib::revwalk::rev_parse::resolve_revision_as_commit_without_index_dwim;
use grit_lib::{objects, refs, RefStorageFormat};
use grit_test_support::git_cmd;
use support::{
    assert_porcelain_v2_matches_git, git_status_porcelain_v2_lines, grit_status_porcelain_v2_lines,
    open_grit_repo,
};
use tempfile::TempDir;

fn identity() -> grit_lib::ident::Signature {
    support::parse_reflog_signature("T <t@t> 0 +0000")
}

fn commit_file(
    repo: &Repository,
    path: &str,
    contents: &str,
    parent: Option<ObjectId>,
) -> ObjectId {
    let wt = repo.work_tree().expect("wt");
    std::fs::write(wt.join(path), contents).expect("write");
    let mut index = repo.index_handle().load().expect("index");
    let oid = repo
        .odb()
        .write(objects::ObjectKind::Blob, contents.as_bytes())
        .expect("blob");
    let entry = grit_lib::index::entry_from_stat(
        &wt.join(path),
        path.as_bytes(),
        oid,
        grit_lib::index::MODE_REGULAR,
    )
    .expect("entry");
    index.add_or_replace(entry);
    index.sort();
    let tree = write_tree_update_index(repo.odb(), &mut index, "", WriteTreeFlags::silent())
        .expect("tree");
    repo.index_handle().write(&mut index).expect("write index");
    let commit = objects::CommitData {
        tree,
        parents: parent.into_iter().collect(),
        author: "T <t@t> 0 +0000".into(),
        committer: "T <t@t> 0 +0000".into(),
        author_raw: vec![],
        committer_raw: vec![],
        encoding: None,
        message: "c\n".into(),
        raw_message: None,
        extra_headers: Vec::new(),
    };
    let co = repo
        .odb()
        .write(
            objects::ObjectKind::Commit,
            &objects::serialize_commit(&commit),
        )
        .expect("commit");
    refs::write_ref(repo.git_dir(), "refs/heads/main", &co).expect("branch");
    refs::write_symbolic_ref(repo.git_dir(), "HEAD", "refs/heads/main").expect("symhead");
    co
}

#[test]
fn mixed_reset_readable_by_git() {
    let dir = TempDir::new().expect("tempdir");
    let repo = Repository::init(
        dir.path(),
        &InitOptions::new()
            .with_initial_branch("main".to_owned())
            .with_ref_storage(RefStorageFormat::Files),
    )
    .expect("init");
    let c1 = commit_file(&repo, "f", "1\n", None);
    commit_file(&repo, "f", "2\n", Some(c1));

    reset_to_commit(
        &repo,
        &ResetOptions::new(c1, ResetMode::Mixed, identity(), "reset"),
        &mut grit_lib::progress::NullProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("reset");

    git_cmd(&["fsck"]).in_dir(dir.path()).suc();
    git_cmd(&["status", "--porcelain"]).in_dir(dir.path()).suc();
}

fn init_git_repo(root: &Path) {
    git_cmd(&["init", "-b", "main"]).in_dir(root).suc();
    git_cmd(&["config", "user.email", "t@t.com"])
        .in_dir(root)
        .suc();
    git_cmd(&["config", "user.name", "T"]).in_dir(root).suc();
}

fn two_commit_history(root: &Path) -> ObjectId {
    std::fs::write(root.join("a"), "v1\n").expect("write");
    git_cmd(&["add", "a"]).in_dir(root).suc();
    git_cmd(&["commit", "-m", "c1"]).in_dir(root).suc();
    let c1_hex = git_cmd(&["rev-parse", "HEAD"])
        .in_dir(root)
        .suc()
        .stdout
        .trim()
        .to_owned();
    std::fs::write(root.join("a"), "v2\n").expect("write");
    git_cmd(&["commit", "-am", "c2"]).in_dir(root).suc();
    ObjectId::from_hex(&c1_hex).expect("c1 oid")
}

#[test]
fn reset_keep_preserves_unrelated_local_changes_like_git() {
    let dir = TempDir::new().expect("tempdir");
    init_git_repo(dir.path());
    two_commit_history(dir.path());
    std::fs::write(dir.path().join("b"), "local\n").expect("local b");
    git_cmd(&["reset", "--keep", "HEAD~1"])
        .in_dir(dir.path())
        .suc();
    let git_lines = git_status_porcelain_v2_lines(dir.path());

    let dir2 = TempDir::new().expect("tempdir2");
    init_git_repo(dir2.path());
    two_commit_history(dir2.path());
    std::fs::write(dir2.path().join("b"), "local\n").expect("local b");
    let repo = open_grit_repo(dir2.path());
    let parent = resolve_revision_as_commit_without_index_dwim(&repo, "HEAD~1").expect("parent");
    reset_to_commit(
        &repo,
        &ResetOptions::new(
            parent,
            ResetMode::Keep,
            support::parse_reflog_signature("T <t@t.com> 0 +0000"),
            "reset",
        ),
        &mut grit_lib::progress::NullProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("keep reset");
    assert_porcelain_v2_matches_git(dir2.path(), &repo);
    let grit_lines = grit_status_porcelain_v2_lines(&repo);
    assert_eq!(grit_lines, git_lines);
}

#[test]
fn reset_keep_refuses_when_changed_file_has_local_edits() {
    let dir = TempDir::new().expect("tempdir");
    init_git_repo(dir.path());
    two_commit_history(dir.path());
    std::fs::write(dir.path().join("a"), "edited\n").expect("edit a");
    git_cmd(&["reset", "--keep", "HEAD~1"])
        .in_dir(dir.path())
        .with_status(128);

    let dir2 = TempDir::new().expect("tempdir2");
    init_git_repo(dir2.path());
    two_commit_history(dir2.path());
    std::fs::write(dir2.path().join("a"), "edited\n").expect("edit a");
    let repo = open_grit_repo(dir2.path());
    let head_before = refs::resolve_ref(repo.git_dir(), "HEAD").expect("head");
    let parent = resolve_revision_as_commit_without_index_dwim(&repo, "HEAD~1").expect("parent");
    let err = reset_to_commit(
        &repo,
        &ResetOptions::new(
            parent,
            ResetMode::Keep,
            support::parse_reflog_signature("T <t@t.com> 0 +0000"),
            "reset",
        ),
        &mut grit_lib::progress::NullProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect_err("grit should refuse");
    assert!(
        matches!(err, Error::WouldOverwrite { .. }),
        "expected WouldOverwrite, got {err:?}"
    );
    assert_eq!(
        refs::resolve_ref(repo.git_dir(), "HEAD").expect("head"),
        head_before
    );
    let git_lines = git_status_porcelain_v2_lines(dir.path());
    let grit_lines = grit_status_porcelain_v2_lines(&repo);
    assert_eq!(grit_lines, git_lines);
}

#[test]
fn reset_dry_run_hard_lists_overwritten_paths_and_changes_nothing() {
    let dir = TempDir::new().expect("tempdir");
    let repo = Repository::init(
        dir.path(),
        &InitOptions::new()
            .with_initial_branch("main".to_owned())
            .with_ref_storage(RefStorageFormat::Files),
    )
    .expect("init");
    let c1 = {
        commit_file(&repo, "a", "1\n", None);
        refs::resolve_ref(repo.git_dir(), "HEAD").expect("head")
    };
    commit_file(&repo, "a", "2\n", Some(c1));
    let head_before = refs::resolve_ref(repo.git_dir(), "HEAD").expect("head");
    let wt = repo.work_tree().expect("wt");
    std::fs::write(wt.join("a"), "dirty\n").expect("dirty");

    let mut opts = ResetOptions::new(
        c1,
        ResetMode::Hard,
        support::parse_reflog_signature("T <t@t.com> 0 +0000"),
        "reset",
    );
    opts.dry_run = true;
    let outcome = reset_to_commit(
        &repo,
        &opts,
        &mut grit_lib::progress::NullProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("dry-run");
    assert!(outcome.dry_run);
    assert!(outcome.would_overwrite.iter().any(|p| p == "a"));
    assert_eq!(
        refs::resolve_ref(repo.git_dir(), "HEAD").expect("head"),
        head_before
    );
    assert_eq!(std::fs::read(wt.join("a")).expect("disk"), b"dirty\n");
}

#[test]
fn reset_orphaned_commits_main_only_git_init() {
    let dir = TempDir::new().expect("tempdir");
    init_git_repo(dir.path());
    std::fs::write(dir.path().join("f.txt"), "1").expect("write");
    git_cmd(&["add", "-A"]).in_dir(dir.path()).suc();
    git_cmd(&["commit", "-m", "c1"]).in_dir(dir.path()).suc();
    let c1_hex = git_cmd(&["rev-parse", "HEAD"])
        .in_dir(dir.path())
        .suc()
        .stdout
        .trim()
        .to_owned();
    for v in ["2", "3"] {
        std::fs::write(dir.path().join("f.txt"), v).expect("write");
        git_cmd(&["add", "-A"]).in_dir(dir.path()).suc();
        git_cmd(&["commit", "-m", &format!("c{v}")])
            .in_dir(dir.path())
            .suc();
    }
    let c2_hex = git_cmd(&["rev-parse", "HEAD~1"])
        .in_dir(dir.path())
        .suc()
        .stdout
        .trim()
        .to_owned();
    let c3_hex = git_cmd(&["rev-parse", "HEAD"])
        .in_dir(dir.path())
        .suc()
        .stdout
        .trim()
        .to_owned();

    let repo = open_grit_repo(dir.path());
    let c1 = resolve_revision_as_commit_without_index_dwim(&repo, "HEAD~2").expect("c1");
    assert_eq!(c1, ObjectId::from_hex(&c1_hex).expect("c1 hex"));

    let mut opts = ResetOptions::new(
        c1,
        ResetMode::Hard,
        support::parse_reflog_signature("T <t@t.com> 0 +0000"),
        "reset",
    );
    opts.dry_run = true;
    let preview = reset_to_commit(
        &repo,
        &opts,
        &mut grit_lib::progress::NullProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("dry-run reset");
    assert_eq!(preview.orphaned_total, 2, "c2 and c3 should orphan");
    assert_eq!(preview.orphaned_commits.len(), 2);
    assert_eq!(
        preview.orphaned_commits[0].oid,
        ObjectId::from_hex(&c3_hex).expect("c3")
    );
    assert_eq!(
        preview.orphaned_commits[1].oid,
        ObjectId::from_hex(&c2_hex).expect("c2")
    );
    assert_eq!(preview.orphaned_commits[0].subject, "c3");
    assert_eq!(preview.orphaned_commits[1].subject, "c2");
}

#[test]
fn reset_orphaned_commits_excludes_commits_held_by_other_refs() {
    let dir = TempDir::new().expect("tempdir");
    let repo = Repository::init(
        dir.path(),
        &InitOptions::new()
            .with_initial_branch("main".to_owned())
            .with_ref_storage(RefStorageFormat::Files),
    )
    .expect("init");
    let c1 = commit_file(&repo, "f", "1\n", None);
    let c2 = commit_file(&repo, "f", "2\n", Some(c1));
    let c3 = commit_file(&repo, "f", "3\n", Some(c2));
    refs::write_ref(repo.git_dir(), "refs/heads/keep", &c2).expect("branch keep");

    let outcome = reset_to_commit(
        &repo,
        &ResetOptions::new(
            c1,
            ResetMode::Mixed,
            support::parse_reflog_signature("T <t@t.com> 0 +0000"),
            "reset",
        ),
        &mut grit_lib::progress::NullProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("reset");
    assert_eq!(outcome.orphaned_total, 1);
    assert_eq!(outcome.orphaned_commits.len(), 1);
    assert_eq!(outcome.orphaned_commits[0].oid, c3);
    let _ = c2;
}

#[test]
fn reset_orphan_zero_when_other_ref_holds_old_tip() {
    let dir = TempDir::new().expect("tempdir");
    let repo = Repository::init(
        dir.path(),
        &InitOptions::new()
            .with_initial_branch("main".to_owned())
            .with_ref_storage(RefStorageFormat::Files),
    )
    .expect("init");
    let c1 = commit_file(&repo, "f", "1\n", None);
    let c2 = commit_file(&repo, "f", "2\n", Some(c1));
    let c3 = commit_file(&repo, "f", "3\n", Some(c2));
    refs::write_ref(repo.git_dir(), "refs/heads/hold", &c3).expect("hold");

    let outcome = reset_to_commit(
        &repo,
        &ResetOptions::new(
            c1,
            ResetMode::Mixed,
            support::parse_reflog_signature("T <t@t.com> 0 +0000"),
            "reset",
        ),
        &mut grit_lib::progress::NullProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("reset");
    assert_eq!(outcome.orphaned_total, 0);
}

#[test]
fn reset_keep_rejects_unmerged_index_like_git() {
    let dir = TempDir::new().expect("tempdir");
    init_git_repo(dir.path());
    two_commit_history(dir.path());
    let tip = git_cmd(&["rev-parse", "HEAD"])
        .in_dir(dir.path())
        .suc()
        .stdout
        .trim()
        .to_owned();
    git_cmd(&["checkout", "-b", "side", "HEAD~1"])
        .in_dir(dir.path())
        .suc();
    std::fs::write(dir.path().join("a"), "side\n").expect("side");
    git_cmd(&["commit", "-am", "side"]).in_dir(dir.path()).suc();
    git_cmd(&["checkout", "main"]).in_dir(dir.path()).suc();
    std::fs::write(dir.path().join("a"), "main\n").expect("main");
    git_cmd(&["commit", "-am", "main"]).in_dir(dir.path()).suc();
    git_cmd(&["merge", "side", "--no-commit", "--no-ff"])
        .in_dir(dir.path())
        .with_status(1);

    let _ = git_cmd(&["reset", "--keep", "HEAD"])
        .in_dir(dir.path())
        .with_status(128);

    let repo = open_grit_repo(dir.path());
    let head = refs::resolve_ref(repo.git_dir(), "HEAD").expect("head");
    let err = reset_to_commit(
        &repo,
        &ResetOptions::new(
            head,
            ResetMode::Keep,
            support::parse_reflog_signature("T <t@t.com> 0 +0000"),
            "reset",
        ),
        &mut grit_lib::progress::NullProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect_err("grit keep should refuse unmerged index");
    assert!(matches!(err, Error::IndexUnmerged));
    let _ = tip;
}

#[test]
fn reset_forward_has_no_orphan_walk() {
    let dir = TempDir::new().expect("tempdir");
    let repo = Repository::init(
        dir.path(),
        &InitOptions::new()
            .with_initial_branch("main".to_owned())
            .with_ref_storage(RefStorageFormat::Files),
    )
    .expect("init");
    let c1 = commit_file(&repo, "f", "1\n", None);
    let c2 = commit_file(&repo, "f", "2\n", Some(c1));
    let outcome = reset_to_commit(
        &repo,
        &ResetOptions::new(
            c2,
            ResetMode::Mixed,
            support::parse_reflog_signature("T <t@t.com> 0 +0000"),
            "reset",
        ),
        &mut grit_lib::progress::NullProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("reset");
    assert_eq!(outcome.orphaned_total, 0);
    assert!(outcome.orphaned_commits.is_empty());
}

#[test]
fn reset_reflog_identity_includes_signature_timestamp_and_git_reads_it() {
    use grit_lib::ident::Signature;
    use time::{OffsetDateTime, UtcOffset};

    let dir = TempDir::new().expect("tempdir");
    let repo = Repository::init(
        dir.path(),
        &InitOptions::new()
            .with_initial_branch("main".to_owned())
            .with_ref_storage(RefStorageFormat::Files),
    )
    .expect("init");
    repo.config_handle()
        .set_local("user.name", "Solo Dev")
        .expect("name");
    repo.config_handle()
        .set_local("user.email", "solo@example.com")
        .expect("email");
    let repo = Repository::open(
        repo.git_dir(),
        &grit_lib::config::environment::RepositoryOptions::empty().with_work_tree(dir.path()),
    )
    .expect("reopen");
    let c1 = commit_file(&repo, "a.txt", "v0\n", None);
    commit_file(&repo, "a.txt", "v1\n", Some(c1));
    let time = OffsetDateTime::from_unix_timestamp(1_700_000_000)
        .expect("time")
        .to_offset(UtcOffset::UTC);
    let sig = Signature::new("Solo Dev", "solo@example.com", time).expect("sig");
    reset_to_commit(
        &repo,
        &ResetOptions::new(c1, ResetMode::Soft, sig.clone(), "reset: test"),
        &mut grit_lib::progress::NullProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("reset");
    let log = std::fs::read_to_string(repo.git_dir().join("logs/HEAD")).expect("log");
    assert!(
        log.contains(&format!("{}", time.unix_timestamp())),
        "reflog line should include signature epoch: {log}"
    );
    let out = git_cmd(&["log", "-g", "-1", "--format=%gn <%ge>"])
        .in_dir(dir.path())
        .suc()
        .stdout;
    assert!(
        out.contains("Solo Dev") && out.contains("solo@example.com"),
        "git log -g should read identity: {out}"
    );
}

#[test]
fn append_reflog_rejects_malformed_identity() {
    let dir = TempDir::new().expect("tempdir");
    let repo = Repository::init(
        dir.path(),
        &InitOptions::new().with_initial_branch("main".to_owned()),
    )
    .expect("init");
    let zero = ObjectId::zero();
    let tip = commit_file(&repo, "f.txt", "x\n", None);
    for bad in ["garbage", "Evil <a@b> 1 +0000\nfoo"] {
        let err = refs::append_reflog(
            repo.git_dir(),
            "refs/heads/main",
            &zero,
            &tip,
            bad,
            "reset: test",
            true,
        )
        .unwrap_err();
        assert!(
            matches!(err, Error::InvalidSignature(_)),
            "expected InvalidSignature for {bad:?}, got {err:?}"
        );
    }
}