grit-lib 0.5.21

Core library for the grit Git implementation
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! Integration test for the `git://` transport: `GitDaemonTransport` +
//! `fetch::fetch_remote`.
//!
//! A source repo is built with the system `git` (two commits on `main`, a
//! second branch, and an annotated tag). A real `git daemon` is started over a
//! temp base path; an empty local repo fetches from it via the trait
//! (`GitDaemonTransport::connect` -> `fetch_remote`) using
//! `+refs/heads/*:refs/remotes/origin/*`. We assert the tracking refs landed,
//! the objects arrived, and cross-check the fetched oids against
//! `git -C <source> rev-parse`.
//!
//! The test skips gracefully (returns early) when `git daemon` is unavailable
//! or fails to bind — the happy path is otherwise real end-to-end wire I/O.

use std::net::{TcpListener, TcpStream};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::objects::odb::Odb;
use grit_lib::objects::ObjectId;
use grit_lib::porcelain::tag::{create_tag, CreateTagRequest};
use grit_lib::progress::NeverCancel;
use grit_lib::refs::resolve_ref;
use grit_lib::remote::fetch::{fetch_remote, NoProgress};
use grit_lib::remote::push::push_remote;
use grit_lib::remote::transfer::{FetchOptions, PushOptions, PushRefSpec, TagMode, UpdateMode};
use grit_lib::remote::transport::{ConnectOptions, GitDaemonTransport, Service, Transport};
use grit_lib::repo::Repository;

fn git(dir: &Path, args: &[&str]) -> String {
    let out = Command::new("git")
        .current_dir(dir)
        .args(args)
        .env("GIT_AUTHOR_NAME", "T")
        .env("GIT_AUTHOR_EMAIL", "t@example.com")
        .env("GIT_AUTHOR_DATE", "2005-04-07T22:13:13 +0200")
        .env("GIT_COMMITTER_NAME", "T")
        .env("GIT_COMMITTER_EMAIL", "t@example.com")
        .env("GIT_COMMITTER_DATE", "2005-04-07T22:13:13 +0200")
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .output()
        .expect("run git");
    assert!(
        out.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8(out.stdout).expect("utf8 git output")
}

fn rev_parse(dir: &Path, rev: &str) -> ObjectId {
    ObjectId::from_hex(git(dir, &["rev-parse", rev]).trim()).expect("valid oid")
}

fn open_odb(git_dir: &Path) -> Odb {
    Odb::new(&git_dir.join("objects")).with_config_git_dir(git_dir.to_path_buf())
}

/// Build a source repo: two commits on `main`, a `topic` branch, an annotated tag.
fn build_source(dir: &Path) {
    git(dir, &["init", "-q", "-b", "main", "."]);
    std::fs::write(dir.join("a.txt"), "one\n").unwrap();
    git(dir, &["add", "a.txt"]);
    git(dir, &["commit", "-q", "-m", "c1"]);
    std::fs::write(dir.join("b.txt"), "two\n").unwrap();
    git(dir, &["add", "b.txt"]);
    git(dir, &["commit", "-q", "-m", "c2"]);
    git(dir, &["tag", "-a", "v1", "-m", "release one"]);
    git(dir, &["branch", "topic"]);
}

/// Pick a currently-free localhost port by binding then dropping a listener.
fn free_port() -> Option<u16> {
    // Dedup port handout per process so a concurrent caller never accepts a
    // port another test already reserved (closes the bind-before-spawn TOCTOU
    // that let two servers share a port under high test parallelism).
    static USED: std::sync::Mutex<Vec<u16>> = std::sync::Mutex::new(Vec::new());
    let mut used = USED.lock().unwrap_or_else(|e| e.into_inner());
    for _ in 0..200 {
        let l = TcpListener::bind(("127.0.0.1", 0)).ok()?;
        let p = l.local_addr().ok()?.port();
        drop(l);
        if !used.contains(&p) {
            used.push(p);
            return Some(p);
        }
    }
    None
}

/// Spawn `git daemon` over `base_path` on `port`. Returns the child handle, or
/// `None` if the binary is missing.
fn spawn_daemon(base_path: &Path, port: u16) -> Option<Child> {
    Command::new("git")
        .arg("daemon")
        .arg("--listen=127.0.0.1")
        .arg(format!("--port={port}"))
        .arg("--reuseaddr")
        .arg("--export-all")
        .arg(format!("--base-path={}", base_path.display()))
        .arg(base_path)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .ok()
}

/// Wait until the daemon answers a TCP connect on `port`, or time out.
fn wait_ready(port: u16) -> bool {
    let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
    let deadline = Instant::now() + Duration::from_secs(5);
    while Instant::now() < deadline {
        if TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok() {
            return true;
        }
        std::thread::sleep(Duration::from_millis(50));
    }
    false
}

struct DaemonGuard(Child);
impl Drop for DaemonGuard {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

#[test]
fn fetch_over_git_daemon_lands_refs_and_objects() {
    // Build a source repo, then mirror it into a bare repo under the daemon
    // base path (a bare repo is served directly at `/repo.git`).
    let tmp = tempfile::tempdir().expect("tempdir");
    let work = tmp.path().join("work");
    std::fs::create_dir_all(&work).unwrap();
    build_source(&work);

    let base = tmp.path().join("srv");
    std::fs::create_dir_all(&base).unwrap();
    let source = base.join("repo.git");
    git(
        &work,
        &[
            "clone",
            "-q",
            "--bare",
            ".",
            source.to_str().expect("utf8 path"),
        ],
    );
    // Mirror the annotated tag and topic branch (a plain --bare clone copies all
    // refs already, but ensure HEAD points at main for the symref check).
    git(&source, &["symbolic-ref", "HEAD", "refs/heads/main"]);

    let main_oid = rev_parse(&source, "refs/heads/main");
    let topic_oid = rev_parse(&source, "refs/heads/topic");
    let c1_oid = rev_parse(&work, "HEAD~1");

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Some(child) = spawn_daemon(&base, port) else {
        eprintln!("SKIP: `git daemon` is unavailable");
        return;
    };
    let _guard = DaemonGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: git daemon did not become ready on port {port}");
        return;
    }

    // The daemon serves repos relative to base; the bare repo lives at
    // `<base>/repo.git`.
    let url = format!("git://127.0.0.1:{port}/repo.git");

    // Empty local repo.
    let local = tmp.path().join("local");
    std::fs::create_dir_all(&local).unwrap();
    git(&local, &["init", "-q", "-b", "main", "."]);
    let local_git = local.join(".git");

    // Connect + fetch via the trait.
    let transport = GitDaemonTransport::new();
    let mut conn = match transport.connect(&url, Service::UploadPack, &ConnectOptions::default()) {
        Ok(c) => c,
        Err(e) => {
            // Some environments forbid the daemon protocol entirely; treat a
            // connect failure as a skip rather than a hard failure.
            eprintln!("SKIP: could not connect to git daemon: {e}");
            return;
        }
    };

    // The advertisement should carry the source's heads.
    assert!(
        conn.advertised_refs()
            .iter()
            .any(|(n, o)| n == "refs/heads/main" && *o == main_oid),
        "advertisement missing refs/heads/main = {}",
        main_oid.to_hex()
    );

    let mut opts = FetchOptions {
        refspecs: vec!["+refs/heads/*:refs/remotes/origin/*".to_owned()],
        tags: TagMode::All,
        ..Default::default()
    };
    let outcome = fetch_remote(
        &local_git,
        &mut *conn,
        &mut opts,
        &mut NoProgress,
        &NeverCancel,
    )
    .expect("fetch_remote over git daemon");

    // Tracking refs written.
    let got_main = resolve_ref(&local_git, "refs/remotes/origin/main").expect("origin/main");
    let got_topic = resolve_ref(&local_git, "refs/remotes/origin/topic").expect("origin/topic");
    assert_eq!(got_main, main_oid, "origin/main oid mismatch vs source");
    assert_eq!(got_topic, topic_oid, "origin/topic oid mismatch vs source");

    // The annotated tag arrived (TagMode::All).
    let tag_oid = rev_parse(&source, "refs/tags/v1");
    let got_tag = resolve_ref(&local_git, "refs/tags/v1").expect("tag v1 written");
    assert_eq!(got_tag, tag_oid, "tag v1 oid mismatch vs source");

    // Objects landed in the local odb: tips and an interior commit.
    let local_odb = open_odb(&local_git);
    for oid in [main_oid, topic_oid, c1_oid, tag_oid] {
        assert!(
            local_odb.exists(&oid),
            "object {} missing from local odb after fetch",
            oid.to_hex()
        );
        // And it must be readable (a real object, not a stub).
        local_odb
            .read(&oid)
            .unwrap_or_else(|e| panic!("read {}: {e}", oid.to_hex()));
    }

    // Per-ref update modes: both heads are New.
    let main_update = outcome
        .updates
        .iter()
        .find(|u| u.remote_ref == "refs/heads/main")
        .expect("update for main");
    assert_eq!(main_update.mode, UpdateMode::New);
    assert_eq!(main_update.new_oid, Some(main_oid));

    // Default branch resolved from the server's HEAD symref.
    assert_eq!(outcome.default_branch.as_deref(), Some("main"));

    // Cross-check that the fetched main tip equals git's view of the source.
    assert_eq!(
        got_main.to_hex(),
        git(&source, &["rev-parse", "refs/heads/main"]).trim()
    );

    // Sanity: the fetched pack re-indexes / fsck's clean in the local repo.
    let fsck = Command::new("git")
        .current_dir(&local)
        .args(["fsck", "--no-dangling"])
        .output()
        .expect("run git fsck");
    assert!(
        fsck.status.success(),
        "git fsck failed after fetch: {}",
        String::from_utf8_lossy(&fsck.stderr)
    );
}

/// Issue #933: a lightweight tag at the same commit as a side branch tip must not
/// suppress the branch `want`, leaving `origin/<branch>` dangling after clone/fetch.
#[test]
fn fetch_following_lightweight_tag_at_branch_tip_downloads_branch() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let work = tmp.path().join("work");
    std::fs::create_dir_all(&work).unwrap();
    git(&work, &["init", "-q", "-b", "main", "."]);
    std::fs::write(work.join("a"), "a\n").unwrap();
    git(&work, &["add", "a"]);
    git(&work, &["commit", "-q", "-m", "a"]);
    git(&work, &["checkout", "-q", "-b", "rel"]);
    std::fs::write(work.join("r"), "r\n").unwrap();
    git(&work, &["add", "r"]);
    git(&work, &["commit", "-q", "-m", "rel"]);
    git(&work, &["tag", "light"]);
    git(&work, &["tag", "-a", "-m", "rel1", "rel-1.0"]);
    git(&work, &["checkout", "-q", "main"]);
    std::fs::write(work.join("b"), "b\n").unwrap();
    git(&work, &["add", "b"]);
    git(&work, &["commit", "-q", "-m", "b"]);

    let base = tmp.path().join("srv");
    std::fs::create_dir_all(&base).unwrap();
    let source = base.join("repo.git");
    git(
        &work,
        &[
            "clone",
            "-q",
            "--bare",
            ".",
            source.to_str().expect("utf8 path"),
        ],
    );
    git(&source, &["symbolic-ref", "HEAD", "refs/heads/main"]);

    let main_oid = rev_parse(&source, "refs/heads/main");
    let rel_oid = rev_parse(&source, "refs/heads/rel");
    let light_oid = rev_parse(&source, "refs/tags/light");
    let rel10_oid = rev_parse(&source, "refs/tags/rel-1.0");
    assert_eq!(light_oid, rel_oid, "fixture: lightweight tag at rel tip");

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Some(child) = spawn_daemon(&base, port) else {
        eprintln!("SKIP: `git daemon` is unavailable");
        return;
    };
    let _guard = DaemonGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: git daemon did not become ready on port {port}");
        return;
    }

    let url = format!("git://127.0.0.1:{port}/repo.git");
    let local = tmp.path().join("local");
    std::fs::create_dir_all(&local).unwrap();
    git(&local, &["init", "-q", "-b", "main", "."]);
    let local_git = local.join(".git");

    let transport = GitDaemonTransport::new();
    let mut conn = match transport.connect(&url, Service::UploadPack, &ConnectOptions::default()) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("SKIP: could not connect to git daemon: {e}");
            return;
        }
    };

    let mut opts = FetchOptions {
        refspecs: vec!["+refs/heads/*:refs/remotes/origin/*".to_owned()],
        tags: TagMode::Following,
        ..Default::default()
    };
    fetch_remote(
        &local_git,
        &mut *conn,
        &mut opts,
        &mut NoProgress,
        &NeverCancel,
    )
    .expect("fetch with TagMode::Following");

    let got_rel = resolve_ref(&local_git, "refs/remotes/origin/rel").expect("origin/rel");
    assert_eq!(got_rel, rel_oid);
    assert_eq!(
        resolve_ref(&local_git, "refs/tags/light").expect("light tag"),
        light_oid
    );
    assert_eq!(
        resolve_ref(&local_git, "refs/tags/rel-1.0").expect("annotated tag"),
        rel10_oid
    );

    let local_odb = open_odb(&local_git);
    for oid in [main_oid, rel_oid, light_oid, rel10_oid] {
        assert!(
            local_odb.exists(&oid),
            "object {} missing after fetch",
            oid.to_hex()
        );
    }

    let fsck = Command::new("git")
        .current_dir(&local)
        .args(["fsck", "--no-dangling"])
        .output()
        .expect("run git fsck");
    assert!(
        fsck.status.success(),
        "git fsck failed (issue #933): {}",
        String::from_utf8_lossy(&fsck.stderr)
    );
}

/// After both sides already have `main`, a newly advertised annotated tag on the
/// existing tip must be imported over git:// (Git `fetch` creates `refs/tags/*`).
#[test]
fn fetch_remote_following_imports_annotated_tag_on_existing_tip() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let base = tmp.path().join("base");
    std::fs::create_dir_all(&base).unwrap();
    let source = base.join("repo.git");
    std::fs::create_dir_all(&source).unwrap();
    git(&source, &["init", "-q", "-b", "main", "."]);
    std::fs::write(source.join("README"), b"paired tip\n").unwrap();
    git(&source, &["add", "README"]);
    git(&source, &["commit", "-q", "-m", "init"]);

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Some(child) = spawn_daemon(&base, port) else {
        eprintln!("SKIP: `git daemon` is unavailable");
        return;
    };
    let _guard = DaemonGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: git daemon did not become ready on port {port}");
        return;
    }

    let url = format!("git://127.0.0.1:{port}/repo.git");
    let local = tmp.path().join("local");
    std::fs::create_dir_all(&local).unwrap();
    git(&local, &["init", "-q", "-b", "main", "."]);
    let local_git = local.join(".git");

    let transport = GitDaemonTransport::new();
    let mut conn = match transport.connect(&url, Service::UploadPack, &ConnectOptions::default()) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("SKIP: could not connect to git daemon: {e}");
            return;
        }
    };

    let mut opts = FetchOptions {
        refspecs: vec!["+refs/heads/main:refs/remotes/origin/main".to_owned()],
        tags: TagMode::Following,
        ..Default::default()
    };
    fetch_remote(
        &local_git,
        &mut *conn,
        &mut opts,
        &mut NoProgress,
        &NeverCancel,
    )
    .expect("initial fetch");

    git(
        &source,
        &["tag", "-a", "annotated-paired", "-m", "on existing tip"],
    );

    let mut conn = transport
        .connect(&url, Service::UploadPack, &ConnectOptions::default())
        .expect("reconnect");
    let outcome = fetch_remote(
        &local_git,
        &mut *conn,
        &mut opts,
        &mut NoProgress,
        &NeverCancel,
    )
    .expect("incremental fetch with new annotated tag");

    let tag_update = outcome
        .updates
        .iter()
        .find(|u| u.remote_ref == "refs/tags/annotated-paired")
        .expect("annotated tag update");
    assert_eq!(tag_update.mode, UpdateMode::New);

    let tag_oid = rev_parse(&source, "refs/tags/annotated-paired");
    assert_eq!(
        resolve_ref(&local_git, "refs/tags/annotated-paired").expect("tag ref"),
        tag_oid
    );
    assert!(
        open_odb(&local_git).exists(&tag_oid),
        "annotated tag object must be present locally"
    );
}

/// After `main` is already on the remote, pushing a new annotated tag on that tip
/// must send the tag object over git:// receive-pack (issue #1020).
#[test]
fn push_annotated_tag_on_existing_commit_over_git_daemon() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let base = tmp.path().join("srv");
    std::fs::create_dir_all(&base).unwrap();
    let bare = base.join("repo.git");
    std::fs::create_dir_all(&bare).unwrap();
    git(&bare, &["init", "-q", "--bare", "-b", "main"]);
    git(&bare, &["config", "daemon.receivepack", "true"]);
    std::fs::write(bare.join("git-daemon-export-ok"), b"").unwrap();

    let seed = tmp.path().join("seed");
    std::fs::create_dir_all(&seed).unwrap();
    git(&seed, &["init", "-q", "-b", "main"]);
    std::fs::write(seed.join("f"), "x\n").unwrap();
    git(&seed, &["add", "f"]);
    git(&seed, &["commit", "-q", "-m", "one"]);
    git(
        &seed,
        &["push", "-q", bare.to_str().expect("utf8 path"), "HEAD:main"],
    );

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Some(child) = spawn_daemon(&base, port) else {
        eprintln!("SKIP: `git daemon` is unavailable");
        return;
    };
    let _guard = DaemonGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: git daemon did not become ready on port {port}");
        return;
    }

    let url = format!("git://127.0.0.1:{port}/repo.git");
    let local = tmp.path().join("local");
    std::fs::create_dir_all(&local).unwrap();
    git(&local, &["init", "-q", "-b", "main"]);
    let local_git = local.join(".git");

    let transport = GitDaemonTransport::new();
    let mut conn = match transport.connect(&url, Service::UploadPack, &ConnectOptions::default()) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("SKIP: could not connect to git daemon: {e}");
            return;
        }
    };
    let mut fetch_opts = FetchOptions {
        refspecs: vec!["+refs/heads/main:refs/remotes/origin/main".to_owned()],
        tags: TagMode::None,
        ..Default::default()
    };
    fetch_remote(
        &local_git,
        &mut *conn,
        &mut fetch_opts,
        &mut NoProgress,
        &NeverCancel,
    )
    .expect("fetch main");

    let repo = Repository::open(&local_git, &RepositoryOptions::empty()).expect("open local repo");
    let head = resolve_ref(&local_git, "refs/remotes/origin/main").expect("origin/main");
    let tag_outcome = create_tag(
        &repo,
        &CreateTagRequest {
            name: "v1-ann".to_owned(),
            target: head,
            message: Some("release".to_owned()),
            tagger: Some("T <t@example.com> 946684800 +0000".to_owned()),
            sign: None,
            signing_key: None,
            tree_sha256: None,
            force: false,
            dry_run: false,
        },
    )
    .expect("annotated tag");

    match transport.connect(&url, Service::ReceivePack, &ConnectOptions::default()) {
        Ok(_) => {}
        Err(e) => {
            eprintln!("SKIP: git daemon refuses receive-pack: {e}");
            return;
        }
    }

    let mut conn = transport
        .connect(&url, Service::ReceivePack, &ConnectOptions::default())
        .expect("receive-pack connect");
    push_remote(
        &local_git,
        &mut *conn,
        &[PushRefSpec {
            src: Some(tag_outcome.oid),
            src_ref: None,
            dst: "refs/tags/v1-ann".to_owned(),
            force: false,
            delete: false,
            expected_old: None,
            expect_absent: false,
            ..Default::default()
        }],
        &PushOptions::default(),
        &mut NoProgress,
        &grit_lib::progress::NeverCancel,
    )
    .expect("push annotated tag");

    assert_eq!(
        resolve_ref(&bare, "refs/tags/v1-ann").expect("tag ref on remote"),
        tag_outcome.oid
    );
    let cat_type = git(&bare, &["cat-file", "-t", "v1-ann"]);
    assert_eq!(
        cat_type.trim(),
        "tag",
        "remote must store annotated tag object"
    );
}

#[test]
fn fetch_remote_dry_run_explicit_fast_forward_classifies_without_writing() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let work = tmp.path().join("work");
    std::fs::create_dir_all(&work).unwrap();
    git(&work, &["init", "-q", "-b", "main", "."]);
    std::fs::write(work.join("a.txt"), "one\n").unwrap();
    git(&work, &["add", "a.txt"]);
    git(&work, &["commit", "-q", "-m", "c1"]);
    let c1_oid = rev_parse(&work, "HEAD");
    std::fs::write(work.join("b.txt"), "two\n").unwrap();
    git(&work, &["add", "b.txt"]);
    git(&work, &["commit", "-q", "-m", "c2"]);

    let base = tmp.path().join("srv");
    std::fs::create_dir_all(&base).unwrap();
    let bare = base.join("repo.git");
    git(
        &work,
        &[
            "clone",
            "-q",
            "--bare",
            ".",
            bare.to_str().expect("utf8 path"),
        ],
    );
    git(&bare, &["symbolic-ref", "HEAD", "refs/heads/main"]);

    let Some(port) = free_port() else {
        eprintln!("SKIP: could not allocate a free port");
        return;
    };
    let Some(child) = spawn_daemon(&base, port) else {
        eprintln!("SKIP: `git daemon` is unavailable");
        return;
    };
    let _guard = DaemonGuard(child);
    if !wait_ready(port) {
        eprintln!("SKIP: git daemon did not become ready on port {port}");
        return;
    }

    let url = format!("git://127.0.0.1:{port}/repo.git");
    let local = tmp.path().join("local");
    std::fs::create_dir_all(&local).unwrap();
    git(&local, &["init", "-q", "-b", "main", "."]);
    let local_git = local.join(".git");

    let transport = GitDaemonTransport::new();
    let mut conn = match transport.connect(&url, Service::UploadPack, &ConnectOptions::default()) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("SKIP: could not connect to git daemon: {e}");
            return;
        }
    };
    let mut seed_opts = FetchOptions {
        refspecs: vec!["+refs/heads/*:refs/remotes/origin/*".to_owned()],
        tags: TagMode::None,
        ..Default::default()
    };
    fetch_remote(
        &local_git,
        &mut *conn,
        &mut seed_opts,
        &mut NoProgress,
        &NeverCancel,
    )
    .expect("seed fetch");

    git(&local, &["branch", "probe", &c1_oid.to_hex()]);
    let probe_before = resolve_ref(&local_git, "refs/heads/probe").expect("probe");

    std::fs::write(work.join("c.txt"), "three\n").unwrap();
    git(&work, &["add", "c.txt"]);
    git(&work, &["commit", "-q", "-m", "c3"]);
    git(
        &work,
        &["push", "-q", bare.to_str().expect("utf8 path"), "HEAD:main"],
    );

    let mut conn = transport
        .connect(&url, Service::UploadPack, &ConnectOptions::default())
        .expect("reconnect");
    let mut dry_run_opts = FetchOptions {
        refspecs: vec!["refs/heads/main:refs/heads/probe".to_owned()],
        configured_refspecs: vec!["+refs/heads/*:refs/remotes/origin/*".to_owned()],
        remote_name: Some("origin".to_owned()),
        dry_run: true,
        tags: TagMode::None,
        ..Default::default()
    };
    let outcome = fetch_remote(
        &local_git,
        &mut *conn,
        &mut dry_run_opts,
        &mut NoProgress,
        &NeverCancel,
    )
    .expect("dry-run fetch");

    let probe_update = outcome
        .updates
        .iter()
        .find(|u| u.local_ref.as_deref() == Some("refs/heads/probe"))
        .expect("probe update");
    assert_eq!(
        probe_update.mode,
        UpdateMode::FastForward,
        "probe update: {:?}",
        outcome.updates
    );
    assert_eq!(
        resolve_ref(&local_git, "refs/heads/probe").expect("probe after dry-run"),
        probe_before
    );
}