ostrya 0.7.0

Pure-Rust async reimplementation of the ostree repository library
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
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
//! The refspecs of a push.
//!
//! `RepoPushOptions::refspecs` states the syntax of a refspec, `SRC[:DST]`,
//! split at its last `:`.

use std::collections::HashSet;

use ostrya_core::Checksum;

use super::invalid;
use crate::error::{Error, Result};
use crate::refs::{RevKind, validate_refspec};
use crate::remote::{Expected, RefUpdate};
use crate::repo::Repo;

/// One ref update of a push.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PushTarget {
    /// The ref of the server.
    pub(crate) dst: String,
    /// The local commit that the ref takes, or `None` for a delete of the ref.
    pub(crate) commit: Option<Checksum>,
}

/// A refspec split into its parts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Refspec<'a> {
    /// The local revision, or `None` for a delete.
    src: Option<&'a str>,
    /// The ref of the server, if the refspec names one.
    dst: Option<&'a str>,
}

/// Splits `spec` at its last `:`.
///
/// These forms give [`Error::Remote`] with
/// [`InvalidInput`](crate::remote::Error::InvalidInput):
///
/// - An empty refspec.
/// - The refspec `:` and each other refspec with an empty `DST`.
/// - A `SRC` with a `^` suffix and no `DST`.
///
/// These forms of `DST` give [`Error::InvalidRefspec`] with the `DST`:
///
/// - A `DST` that [`validate_refspec`] refuses.
/// - A `DST` that [`is_checksum_shaped`](ostrya_core::is_checksum_shaped)
///   marks, after a non-empty `SRC`.
///
/// A delete (`:DST`) of a checksum-shaped `DST` passes.
fn split(spec: &str) -> Result<Refspec<'_>> {
    if spec.is_empty() {
        return Err(invalid("a refspec is empty"));
    }
    let Some((src, dst)) = spec.rsplit_once(':') else {
        if spec.ends_with('^') {
            return Err(invalid(format!(
                "refspec '{spec}': a source with a '^' suffix needs a destination"
            )));
        }
        return Ok(Refspec {
            src: Some(spec),
            dst: None,
        });
    };
    if dst.is_empty() {
        return Err(invalid(format!("refspec '{spec}' names no destination")));
    }
    validate_refspec(dst)?;
    // A revision reads 64 lowercase hex characters as a checksum, so a push
    // writes no commit to such a ref. A delete of it passes.
    if !src.is_empty() && ostrya_core::is_checksum_shaped(dst) {
        return Err(Error::InvalidRefspec(dst.to_owned()));
    }
    Ok(Refspec {
        src: (!src.is_empty()).then_some(src),
        dst: Some(dst),
    })
}

impl Repo {
    /// Returns the ref updates of the push `refspecs`, in the order of the
    /// refspecs.
    ///
    /// Each `SRC` resolves as [`resolve_rev`](Repo::resolve_rev) resolves it.
    /// If `SRC` resolves as a ref with no `^` suffix, `DST` defaults to
    /// `SRC`. A `SRC` that resolves as a full or an abbreviated
    /// checksum needs a `DST`. A `SRC` with a `^` suffix also needs a `DST`.
    ///
    /// The split of each refspec comes before any resolution. The check of
    /// the `DST` names that the refspecs spell also comes before any
    /// resolution.
    ///
    /// # Errors
    ///
    /// - The error of [`split`] if it refuses a refspec.
    /// - [`Error::Remote`] with [`InvalidInput`](crate::remote::Error::InvalidInput)
    ///   for an empty list, a checksum `SRC` with no `DST`, and a `DST` that
    ///   two refspecs name.
    /// - [`Error::RefNotFound`] with the `SRC` if `SRC` resolves to no commit.
    /// - The errors of [`resolve_rev`](Repo::resolve_rev) for a `SRC`.
    pub(crate) async fn push_targets(&self, refspecs: &[String]) -> Result<Vec<PushTarget>> {
        if refspecs.is_empty() {
            return Err(invalid("a push needs at least one refspec"));
        }
        let specs = refspecs
            .iter()
            .map(|spec| split(spec))
            .collect::<Result<Vec<_>>>()?;
        let mut seen = HashSet::new();
        for dst in specs.iter().filter_map(|parts| parts.dst) {
            if !seen.insert(dst) {
                return Err(named_twice(dst));
            }
        }
        let mut targets = Vec::with_capacity(specs.len());
        for (spec, parts) in refspecs.iter().zip(specs) {
            let Some(src) = parts.src else {
                let dst = parts.dst.expect("a delete names a destination");
                targets.push(PushTarget {
                    dst: dst.to_owned(),
                    commit: None,
                });
                continue;
            };
            let (commit, kind) = self
                .resolve_rev_kind(src, false)
                .await?
                .ok_or_else(|| Error::RefNotFound(src.to_owned()))?;
            let dst = match (parts.dst, kind) {
                (Some(dst), _) => dst,
                (None, RevKind::Ref) => {
                    // A `DST` that defaults to `SRC` is known only now.
                    if !seen.insert(src) {
                        return Err(named_twice(src));
                    }
                    src
                }
                (None, RevKind::Checksum) => {
                    return Err(invalid(format!(
                        "refspec '{spec}': a checksum source needs a destination"
                    )));
                }
            };
            targets.push(PushTarget {
                dst: dst.to_owned(),
                commit: Some(commit),
            });
        }
        Ok(targets)
    }

    /// Returns the ref updates of a one-way stream for `refspecs`, in the
    /// order of the refspecs.
    ///
    /// A refspec is `SRC[:DST]`, and the rules of
    /// [`RepoPushOptions::refspecs`](crate::RepoPushOptions::refspecs) apply.
    /// The split is at the last `:`. Each `SRC` resolves in this repository.
    /// If `SRC` is a ref with no `^` suffix, `DST` defaults to `SRC`. A `SRC`
    /// that is a checksum, or that has a `^` suffix, needs a `DST`.
    ///
    /// A one-way stream deletes no ref, so the call refuses a delete, `:DST`.
    /// The call refuses a `DST` of 64 lowercase hex characters after a `SRC`.
    /// Without `remote`, the reason is that a revision reads such a name as
    /// a commit checksum. With `remote`, the call refuses it by the refspec
    /// rule of [`push`](Repo::push).
    ///
    /// Without `remote`, the name of each update is `DST`. With `remote`, it is
    /// `REMOTE:DST`, and the receiver writes a remote ref. The call checks
    /// each name with [`validate_refspec`], so each name that it returns
    /// passes the ref-name checks of [`export_stream`](Repo::export_stream).
    ///
    /// The call does not check the ref binding of a commit. If the commit of
    /// a `SRC` has a non-empty `ostree.ref-binding` list that does not hold
    /// `DST`, `export_stream` refuses the update with [`Error::Remote`] and
    /// [`BindingMismatch`](crate::remote::Error::BindingMismatch) before it
    /// writes a byte. A commit of `ostrya commit -b BRANCH` is bound to
    /// `BRANCH`.
    ///
    /// Each update expects [`Any`](Expected::Any) and sets the commit of its
    /// `SRC`. So the receiver applies its own rules to the state of the ref.
    /// The updates go in
    /// [`ExportStreamOptions::updates`](crate::ExportStreamOptions::updates).
    ///
    /// The call takes no lock. `export_stream` takes the repository lock.
    ///
    /// # Errors
    ///
    /// - [`Error::Remote`] with
    ///   [`InvalidInput`](crate::remote::Error::InvalidInput) if a refspec is
    ///   a delete. This check comes before each other check.
    /// - [`Error::Remote`] with
    ///   [`InvalidInput`](crate::remote::Error::InvalidInput) for an empty
    ///   list, an empty refspec, a refspec with an empty `DST`, a `SRC` with
    ///   a `^` suffix and no `DST`, a checksum `SRC` with no `DST`, and a
    ///   `DST` that two refspecs name.
    /// - [`Error::InvalidRefspec`] with the `DST` if the ref-name rule
    ///   refuses the `DST`, or if the `DST` after a `SRC` is 64 lowercase
    ///   hex characters.
    /// - [`Error::RefNotFound`] with the `SRC` if `SRC` resolves to no commit.
    /// - The errors of [`resolve_rev`](Repo::resolve_rev) for a `SRC`.
    /// - [`Error::InvalidRefspec`] with `REMOTE:DST` if [`validate_refspec`]
    ///   refuses the name of an update.
    ///
    /// # Examples
    ///
    /// Write a one-way stream of the refs `main` and `stable` to a file. The
    /// receiver writes the refs `origin:main` and `origin:stable`. Each `DST`
    /// is its `SRC`, so a commit bound to its branch passes the binding
    /// check:
    ///
    /// ```no_run
    /// use ostrya::{ExportStreamOptions, Repo};
    ///
    /// # async fn run() -> ostrya::Result<()> {
    /// let repo = Repo::open("/srv/repo".as_ref()).await?;
    /// let refspecs = ["main".to_owned(), "stable".to_owned()];
    /// let updates = repo.export_updates(&refspecs, Some("origin")).await?;
    /// let output = ostrya_rt::File::from(std::fs::File::create("stream")?);
    /// let opts = ExportStreamOptions {
    ///     updates,
    ///     ..ExportStreamOptions::default()
    /// };
    /// repo.export_stream(output, opts).await?;
    /// # Ok(()) }
    /// ```
    pub async fn export_updates(
        &self,
        refspecs: &[String],
        remote: Option<&str>,
    ) -> Result<Vec<RefUpdate>> {
        if let Some(spec) = refspecs.iter().find(|spec| {
            spec.rsplit_once(':')
                .is_some_and(|(src, dst)| src.is_empty() && !dst.is_empty())
        }) {
            return Err(invalid(format!(
                "a one-way stream deletes no ref, and the refspec '{spec}' is a delete"
            )));
        }
        let mut updates = Vec::with_capacity(refspecs.len());
        for target in self.push_targets(refspecs).await? {
            let name = match remote {
                Some(remote) => format!("{remote}:{}", target.dst),
                None => target.dst,
            };
            validate_refspec(&name)?;
            updates.push(RefUpdate {
                name,
                expected: Expected::Any,
                new: Some(target.commit.expect("a delete is refused")),
            });
        }
        Ok(updates)
    }
}

/// Returns the error for a `DST` that two refspecs name.
fn named_twice(dst: &str) -> Error {
    invalid(format!("the destination '{dst}' is named twice"))
}

#[cfg(test)]
mod tests {
    use super::super::test_repo::{Scratch, commit_tree};
    use super::*;
    use ostrya_core::RepoMode;

    fn refspecs(specs: &[&str]) -> Vec<String> {
        specs.iter().map(|s| (*s).to_owned()).collect()
    }

    fn target(dst: &str, commit: Option<Checksum>) -> PushTarget {
        PushTarget {
            dst: dst.to_owned(),
            commit,
        }
    }

    fn assert_invalid<T: std::fmt::Debug>(result: Result<T>, needle: &str) {
        match result {
            Err(Error::Remote(crate::remote::Error::InvalidInput(msg))) => {
                assert!(msg.contains(needle), "{msg:?} lacks {needle:?}")
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }

    fn assert_invalid_refspec<T: std::fmt::Debug>(result: Result<T>, dst: &str) {
        match result {
            Err(Error::InvalidRefspec(name)) => assert_eq!(name, dst),
            other => panic!("expected InvalidRefspec, got {other:?}"),
        }
    }

    #[test]
    fn a_refspec_splits_at_its_last_colon() {
        assert_eq!(
            split("main").unwrap(),
            Refspec {
                src: Some("main"),
                dst: None
            }
        );
        assert_eq!(
            split("a:b").unwrap(),
            Refspec {
                src: Some("a"),
                dst: Some("b")
            }
        );
        assert_eq!(
            split("origin:main:dst").unwrap(),
            Refspec {
                src: Some("origin:main"),
                dst: Some("dst")
            }
        );
        assert_eq!(
            split("x:y:z").unwrap(),
            Refspec {
                src: Some("x:y"),
                dst: Some("z")
            }
        );
        assert_eq!(
            split(":gone").unwrap(),
            Refspec {
                src: None,
                dst: Some("gone")
            }
        );
        assert_eq!(
            split("main^:old").unwrap(),
            Refspec {
                src: Some("main^"),
                dst: Some("old")
            }
        );
    }

    #[test]
    fn a_destination_never_names_a_remote_ref() {
        // What reads as a remote ref after the first `:` is the source.
        let parts = split("main:origin:main").unwrap();
        assert_eq!(parts.src, Some("main:origin"));
        assert_eq!(parts.dst, Some("main"));
        let parts = split("origin:main").unwrap();
        assert_eq!(parts.src, Some("origin"));
        assert_eq!(parts.dst, Some("main"));
        // The refspec `origin:main^` is the source `origin` and the
        // destination `main^`. The split refuses this destination.
        assert_invalid_refspec(split("origin:main^"), "main^");
    }

    #[test]
    fn the_forms_that_name_no_update_are_refused() {
        assert_invalid(split(""), "empty");
        assert_invalid(split(":"), "names no destination");
        assert_invalid(split("main:"), "names no destination");
        assert_invalid(split("a:b:"), "names no destination");
        assert_invalid(split("main^"), "'^' suffix needs a destination");
        assert_invalid(split("main^^"), "'^' suffix needs a destination");
    }

    #[test]
    fn a_destination_that_is_no_ref_name_is_an_invalid_refspec() {
        assert_invalid_refspec(split("main:a/../b"), "a/../b");
        assert_invalid_refspec(split("main:/b"), "/b");
    }

    #[test]
    fn a_destination_outside_the_ref_name_rule_is_an_invalid_refspec() {
        for dst in ["a b", "a*", "-a", "a/.b", "a~b"] {
            assert_invalid_refspec(split(&format!("main:{dst}")), dst);
            assert_invalid_refspec(split(&format!(":{dst}")), dst);
        }
        for dst in ["a.", "_a", "1a", "é"] {
            assert_eq!(split(&format!("main:{dst}")).unwrap().dst, Some(dst));
        }
    }

    #[test]
    fn a_destination_of_64_lowercase_hex_characters_is_an_invalid_refspec() {
        let hex = "ab".repeat(32);
        assert_invalid_refspec(split(&format!("main:{hex}")), &hex);
        assert_invalid_refspec(split(&format!("origin:main:{hex}")), &hex);
        let upper = hex.to_uppercase();
        assert_eq!(
            split(&format!("main:{upper}")).unwrap().dst,
            Some(upper.as_str())
        );
    }

    #[test]
    fn a_delete_of_64_lowercase_hex_characters_is_accepted() {
        let hex = "ab".repeat(32);
        let spec = format!(":{hex}");
        let parts = split(&spec).unwrap();
        assert_eq!(parts.src, None);
        assert_eq!(parts.dst, Some(hex.as_str()));
    }

    #[test]
    fn a_destination_with_a_caret_is_an_invalid_refspec() {
        assert_invalid_refspec(split("main:dst^"), "dst^");
        assert_invalid_refspec(split("main:a^b"), "a^b");
        assert_invalid_refspec(split(":^"), "^");
        // The refusal comes before any resolution.
        ostrya_rt::block_on(async {
            let scratch = Scratch::new("caret-dst");
            let repo = scratch.create(RepoMode::BareUser).await;
            commit_tree(&repo, &scratch, "main", None, b"one").await;
            assert_invalid_refspec(
                repo.push_targets(&refspecs(&["absent", "main:dst^"])).await,
                "dst^",
            );
        });
    }

    #[test]
    fn refspecs_resolve_against_the_repository() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new("refspecs");
            let repo = scratch.create(RepoMode::BareUser).await;
            let first = commit_tree(&repo, &scratch, "main", None, b"one").await;
            let second = commit_tree(&repo, &scratch, "main", Some(first), b"two").await;
            let other = commit_tree(&repo, &scratch, "origin:main", None, b"three").await;

            let got = repo
                .push_targets(&refspecs(&[
                    "main",
                    "main^:old",
                    "origin:main:mirror",
                    ":gone",
                    &format!("{second}:full"),
                ]))
                .await
                .unwrap();
            assert_eq!(
                got,
                vec![
                    target("main", Some(second)),
                    target("old", Some(first)),
                    target("mirror", Some(other)),
                    target("gone", None),
                    target("full", Some(second)),
                ]
            );
        });
    }

    #[test]
    fn an_abbreviated_checksum_source_is_a_checksum() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new("abbrev");
            let repo = scratch.create(RepoMode::BareUser).await;
            let commit = commit_tree(&repo, &scratch, "main", None, b"one").await;
            let hex = commit.to_hex();
            let short = &hex[..10];

            let got = repo
                .push_targets(&refspecs(&[&format!("{short}:dst")]))
                .await
                .unwrap();
            assert_eq!(got, vec![target("dst", Some(commit))]);

            assert_invalid(
                repo.push_targets(&refspecs(&[short])).await,
                "a checksum source needs a destination",
            );
            assert_invalid(
                repo.push_targets(&refspecs(&[&hex])).await,
                "a checksum source needs a destination",
            );
        });
    }

    #[test]
    fn a_hex_ref_name_that_no_commit_prefixes_is_a_ref() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new("hex-ref");
            let repo = scratch.create(RepoMode::BareUser).await;
            let commit = commit_tree(&repo, &scratch, "main", None, b"one").await;
            // A name of lowercase hex that is not a prefix of the checksum
            // of the one commit.
            let name = if commit.to_hex().starts_with('a') {
                "bbbb"
            } else {
                "aaaa"
            };
            repo.set_ref_immediate(name, Some(&commit)).await.unwrap();

            let got = repo.push_targets(&refspecs(&[name])).await.unwrap();
            assert_eq!(got, vec![target(name, Some(commit))]);
        });
    }

    #[test]
    fn refused_refspecs_name_the_reason() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new("refused");
            let repo = scratch.create(RepoMode::BareUser).await;
            commit_tree(&repo, &scratch, "main", None, b"one").await;
            commit_tree(&repo, &scratch, "other", None, b"two").await;

            assert_invalid(repo.push_targets(&[]).await, "at least one refspec");
            assert_invalid(
                repo.push_targets(&refspecs(&["main:x", "other:x"])).await,
                "'x' is named twice",
            );
            assert_invalid(
                repo.push_targets(&refspecs(&["main", "other:main"])).await,
                "'main' is named twice",
            );
            assert_invalid(
                repo.push_targets(&refspecs(&["main", ":main"])).await,
                "'main' is named twice",
            );
            assert_invalid(
                repo.push_targets(&refspecs(&["main^"])).await,
                "'^' suffix needs a destination",
            );
            // A syntax refusal comes before any resolution.
            assert_invalid(
                repo.push_targets(&refspecs(&["absent", "main:"])).await,
                "names no destination",
            );
            // A destination that two refspecs spell also gives an error
            // before any resolution.
            assert_invalid(
                repo.push_targets(&refspecs(&["absent:x", "main:x"])).await,
                "'x' is named twice",
            );
            // The check of a destination that defaults to its source comes
            // when the source resolves as a ref.
            assert_invalid(
                repo.push_targets(&refspecs(&["main", "main"])).await,
                "'main' is named twice",
            );
        });
    }

    #[test]
    fn resolution_errors_keep_their_kinds() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new("resolve-errors");
            let repo = scratch.create(RepoMode::BareUser).await;
            let root = commit_tree(&repo, &scratch, "main", None, b"one").await;

            assert!(matches!(
                repo.push_targets(&refspecs(&["absent"])).await,
                Err(Error::RefNotFound(name)) if name == "absent"
            ));
            assert!(matches!(
                repo.push_targets(&refspecs(&["main^^:x"])).await,
                Err(Error::NoParentCommit(c)) if c == root
            ));
            assert!(matches!(
                repo.push_targets(&refspecs(&["a/../b:x"])).await,
                Err(Error::InvalidRefspec(_))
            ));
        });
    }

    #[test]
    fn an_ambiguous_abbreviated_checksum_is_refused() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new("ambiguous");
            let repo = scratch.create(RepoMode::BareUser).await;
            // Of 17 commits, at least two have checksums that start with the
            // same hex digit.
            let mut firsts = HashSet::new();
            let mut shared = None;
            for i in 0..17u8 {
                let commit = commit_tree(&repo, &scratch, "main", None, &[i]).await;
                let first = commit.to_hex()[..1].to_owned();
                if !firsts.insert(first.clone()) {
                    shared = Some(first);
                }
            }
            let shared = shared.expect("two commits share a first digit");
            assert!(matches!(
                repo.push_targets(&refspecs(&[&format!("{shared}:x")])).await,
                Err(Error::AmbiguousRefspec(rev)) if rev == shared
            ));
        });
    }

    fn any(name: &str, commit: Checksum) -> RefUpdate {
        RefUpdate {
            name: name.to_owned(),
            expected: Expected::Any,
            new: Some(commit),
        }
    }

    #[test]
    fn the_updates_of_a_one_way_stream_expect_any_state() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new("export-updates");
            let repo = scratch.create(RepoMode::BareUser).await;
            let first = commit_tree(&repo, &scratch, "main", None, b"one").await;
            let second = commit_tree(&repo, &scratch, "main", Some(first), b"two").await;
            let other = commit_tree(&repo, &scratch, "origin:main", None, b"three").await;
            let full = format!("{second}:full");

            let got = repo
                .export_updates(
                    &refspecs(&["main", "main^:old", "origin:main:mirror", &full]),
                    None,
                )
                .await
                .unwrap();
            assert_eq!(
                got,
                vec![
                    any("main", second),
                    any("old", first),
                    any("mirror", other),
                    any("full", second),
                ]
            );

            let got = repo
                .export_updates(&refspecs(&["main", "main^:old"]), Some("os"))
                .await
                .unwrap();
            assert_eq!(got, vec![any("os:main", second), any("os:old", first)]);
        });
    }

    #[test]
    fn a_one_way_stream_refuses_a_delete() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new("export-delete");
            let repo = scratch.create(RepoMode::BareUser).await;
            commit_tree(&repo, &scratch, "main", None, b"one").await;
            let hex = "ab".repeat(32);

            for specs in [
                refspecs(&[":gone"]),
                refspecs(&[&format!(":{hex}")]),
                refspecs(&["main", ":gone"]),
                // The refusal comes before any resolution.
                refspecs(&["absent", ":gone"]),
            ] {
                assert_invalid(
                    repo.export_updates(&specs, None).await,
                    "a one-way stream deletes no ref, and the refspec ':",
                );
            }
        });
    }

    #[test]
    fn the_updates_of_a_one_way_stream_keep_the_push_rules() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new("export-rules");
            let repo = scratch.create(RepoMode::BareUser).await;
            commit_tree(&repo, &scratch, "main", None, b"one").await;
            let hex = "ab".repeat(32);

            assert_invalid(repo.export_updates(&[], None).await, "at least one refspec");
            assert!(matches!(
                repo.export_updates(&refspecs(&["absent"]), None).await,
                Err(Error::RefNotFound(name)) if name == "absent"
            ));
            // A checksum-shaped `DST` is refused, also with a remote.
            assert_invalid_refspec(
                repo.export_updates(&refspecs(&[&format!("main:{hex}")]), Some("os"))
                    .await,
                &hex,
            );
        });
    }

    #[test]
    fn a_remote_that_makes_no_ref_name_is_an_invalid_refspec() {
        // The remote name rule accepts the character, and the ref-name rule
        // refuses it.
        let remote = "\u{1f130}";
        assert!(crate::valid_remote_name(remote));
        ostrya_rt::block_on(async {
            let scratch = Scratch::new("export-remote");
            let repo = scratch.create(RepoMode::BareUser).await;
            commit_tree(&repo, &scratch, "main", None, b"one").await;
            assert_invalid_refspec(
                repo.export_updates(&refspecs(&["main"]), Some(remote))
                    .await,
                &format!("{remote}:main"),
            );
        });
    }
}