use std::collections::HashSet;
use ostrya_core::{Checksum, Ref};
use super::invalid;
use crate::error::{Error, Result};
use crate::refs::{RevKind, validate_refspec};
use crate::remote::{Expected, RefUpdate};
use crate::repo::Repo;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PushTarget {
pub(crate) dst: Ref,
pub(crate) commit: Option<Checksum>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Refspec<'a> {
src: Option<&'a str>,
dst: Option<Ref>,
}
fn fields(spec: &str) -> (&str, Option<&str>) {
let Some(last) = spec.rfind(':') else {
return (spec, None);
};
let before = &spec[..last];
let field = before.rfind(':').map_or(0, |at| at + 1);
let start = if before[field..].starts_with('@') {
field
} else {
last + 1
};
match start {
0 => (spec, None),
_ => (&spec[..start - 1], Some(&spec[start..])),
}
}
pub(super) fn is_delete(spec: &str) -> bool {
matches!(fields(spec), ("", Some(dst)) if !dst.is_empty())
}
fn split(spec: &str) -> Result<Refspec<'_>> {
if spec.is_empty() {
return Err(invalid("a refspec is empty"));
}
let (src, dst) = fields(spec);
let Some(dst) = dst 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")));
}
let dst: Ref = dst.parse()?;
if !src.is_empty()
&& let Ref::Local { name } = &dst
&& ostrya_core::is_checksum_shaped(name)
{
return Err(Error::InvalidRefspec(name.clone()));
}
Ok(Refspec {
src: (!src.is_empty()).then_some(src),
dst: Some(dst),
})
}
pub(super) fn in_collection(r: Ref, collection: Option<&str>, what: &str) -> Result<Ref> {
let Some(id) = collection else {
return Ok(r);
};
r.in_collection(id).map_err(|r| {
let Ref::Collection { id: other, .. } = &r else {
unreachable!("a refused ref is a collection ref");
};
invalid(format!(
"the {what} '{r}' names the collection '{other}', and the push names the \
collection '{id}'"
))
})
}
impl Repo {
pub(crate) async fn push_targets(
&self,
refspecs: &[String],
collection: Option<&str>,
) -> Result<Vec<PushTarget>> {
if refspecs.is_empty() {
return Err(invalid("a push needs at least one refspec"));
}
let mut specs = Vec::with_capacity(refspecs.len());
for spec in refspecs {
let Refspec { src, dst } = split(spec)?;
let dst = dst
.map(|dst| in_collection(dst, collection, "destination"))
.transpose()?;
specs.push((src, dst));
}
let mut seen = HashSet::new();
for dst in specs.iter().filter_map(|(_, dst)| dst.as_ref()) {
if !seen.insert(dst.clone()) {
return Err(named_twice(dst));
}
}
let mut targets = Vec::with_capacity(specs.len());
for (spec, (src, dst)) in refspecs.iter().zip(specs) {
let Some(src) = src else {
let dst = dst.expect("a delete names a destination");
targets.push(PushTarget { dst, commit: None });
continue;
};
let (commit, kind) = self
.resolve_rev_kind(src, false)
.await?
.ok_or_else(|| Error::RefNotFound(src.to_owned()))?;
let dst = match (dst, kind) {
(Some(dst), _) => dst,
(None, RevKind::Ref) => {
let dst = in_collection(src.parse()?, collection, "destination")?;
if !seen.insert(dst.clone()) {
return Err(named_twice(&dst));
}
dst
}
(None, RevKind::Checksum) => {
return Err(invalid(format!(
"refspec '{spec}': a checksum source needs a destination"
)));
}
};
targets.push(PushTarget {
dst,
commit: Some(commit),
});
}
Ok(targets)
}
pub async fn export_updates(
&self,
refspecs: &[String],
remote: Option<&str>,
) -> Result<Vec<RefUpdate>> {
if let Some(spec) = refspecs.iter().find(|spec| is_delete(spec)) {
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, None).await? {
let name = match (remote, target.dst) {
(Some(remote), Ref::Local { name }) => {
let name = format!("{remote}:{name}");
validate_refspec(&name)?;
name
}
(Some(_), dst) => {
return Err(invalid(format!(
"a remote ref has no collection, and the destination '{dst}' names one"
)));
}
(None, dst) => dst.to_string(),
};
updates.push(RefUpdate {
name,
expected: Expected::Any,
new: Some(target.commit.expect("a delete is refused")),
});
}
Ok(updates)
}
}
fn named_twice(dst: &Ref) -> Error {
invalid(format!("the destination '{dst}' is named twice"))
}
#[cfg(test)]
mod tests {
use super::super::test_repo::{Scratch, commit_tree};
use super::*;
use crate::Ref;
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.parse().unwrap(),
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:?}"),
}
}
fn parts<'a>(src: Option<&'a str>, dst: Option<&str>) -> Refspec<'a> {
Refspec {
src,
dst: dst.map(|dst| dst.parse().unwrap()),
}
}
#[test]
fn a_refspec_splits_before_its_last_ref() {
for (spec, src, dst) in [
("main", Some("main"), None),
("origin:main", Some("origin"), Some("main")),
("R:main:dst", Some("R:main"), Some("dst")),
("@X.y:a", Some("@X.y:a"), None),
("main:@X.y:a", Some("main"), Some("@X.y:a")),
("R:main:@X.y:a", Some("R:main"), Some("@X.y:a")),
("@X.y:a:b", Some("@X.y:a"), Some("b")),
("@X.y:a:@Y.z:b", Some("@X.y:a"), Some("@Y.z:b")),
("@X.y:main^:b", Some("@X.y:main^"), Some("b")),
(":@X.y:a", None, Some("@X.y:a")),
("a:b", Some("a"), Some("b")),
("x:y:z", Some("x:y"), Some("z")),
(":gone", None, Some("gone")),
("main^:old", Some("main^"), Some("old")),
] {
assert_eq!(split(spec).unwrap(), parts(src, dst), "{spec}");
}
assert_eq!(fields("a:@X.y"), ("a", Some("@X.y")));
assert_invalid_refspec(split("a:@X.y"), "@X.y");
}
#[test]
fn a_delete_names_its_destination_after_an_empty_source() {
for spec in [":gone", ":@X.y:a", ":a/b"] {
assert!(is_delete(spec), "{spec}");
}
for spec in [
"",
":",
"main",
"@X.y:a",
"main:gone",
"@X.y:a:b",
"a:@X.y:a",
":@X.y:a:b",
] {
assert!(!is_delete(spec), "{spec}");
}
}
#[test]
fn a_destination_never_names_a_remote_ref() {
assert_eq!(
split("main:origin:main").unwrap(),
parts(Some("main:origin"), Some("main"))
);
assert_eq!(
split("origin:main").unwrap(),
parts(Some("origin"), Some("main"))
);
assert_invalid_refspec(split("origin:main^"), "main^");
}
#[test]
fn a_collection_names_the_namespace_of_each_plain_ref() {
let x = Some("org.example.X");
assert_eq!(
in_collection(Ref::local("a"), x, "destination").unwrap(),
Ref::collection("org.example.X", "a")
);
let own = Ref::collection("org.example.X", "a");
assert_eq!(in_collection(own.clone(), x, "tag").unwrap(), own);
assert_invalid(
in_collection(Ref::collection("org.example.Y", "a"), x, "tag"),
"the tag '@org.example.Y:a' names the collection 'org.example.Y', and the push \
names the collection 'org.example.X'",
);
for r in [
Ref::local("a"),
Ref::collection("org.example.Y", "a"),
Ref::remote("o", "a"),
] {
assert_eq!(in_collection(r.clone(), None, "tag").unwrap(), r);
}
assert_eq!(
in_collection(Ref::remote("o", "a"), x, "tag").unwrap(),
Ref::remote("o", "a")
);
}
#[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(Ref::local(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(Ref::local(upper.as_str()))
);
let spec = format!("main:@org.example.X:{hex}");
assert_eq!(
split(&spec).unwrap().dst,
Some(Ref::collection("org.example.X", hex.as_str()))
);
}
#[test]
fn a_delete_of_64_lowercase_hex_characters_is_accepted() {
let hex = "ab".repeat(32);
let spec = format!(":{hex}");
assert_eq!(split(&spec).unwrap(), parts(None, Some(&hex)));
}
#[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(":^"), "^");
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^"]), None)
.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"),
]),
None,
)
.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")]), None)
.await
.unwrap();
assert_eq!(got, vec![target("dst", Some(commit))]);
assert_invalid(
repo.push_targets(&refspecs(&[short]), None).await,
"a checksum source needs a destination",
);
assert_invalid(
repo.push_targets(&refspecs(&[&hex]), None).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;
let name = if commit.to_hex().starts_with('a') {
"bbbb"
} else {
"aaaa"
};
repo.set_ref_immediate(&Ref::local(name), Some(&commit))
.await
.unwrap();
let got = repo.push_targets(&refspecs(&[name]), None).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(&[], None).await, "at least one refspec");
assert_invalid(
repo.push_targets(&refspecs(&["main:x", "other:x"]), None)
.await,
"'x' is named twice",
);
assert_invalid(
repo.push_targets(&refspecs(&["main", "other:main"]), None)
.await,
"'main' is named twice",
);
assert_invalid(
repo.push_targets(&refspecs(&["main", ":main"]), None).await,
"'main' is named twice",
);
assert_invalid(
repo.push_targets(&refspecs(&["main^"]), None).await,
"'^' suffix needs a destination",
);
assert_invalid(
repo.push_targets(&refspecs(&["absent", "main:"]), None)
.await,
"names no destination",
);
assert_invalid(
repo.push_targets(&refspecs(&["absent:x", "main:x"]), None)
.await,
"'x' is named twice",
);
assert_invalid(
repo.push_targets(&refspecs(&["main", "main"]), None).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"]), None).await,
Err(Error::RefNotFound(name)) if name == "absent"
));
assert!(matches!(
repo.push_targets(&refspecs(&["main^^:x"]), None).await,
Err(Error::NoParentCommit(c)) if c == root
));
assert!(matches!(
repo.push_targets(&refspecs(&["a/../b:x"]), None).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;
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")]), None).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"]),
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"
));
assert_invalid_refspec(
repo.export_updates(&refspecs(&[&format!("main:{hex}")]), Some("os"))
.await,
&hex,
);
});
}
#[test]
fn a_collection_applies_to_each_destination() {
ostrya_rt::block_on(async {
let scratch = Scratch::new("collection");
let repo = scratch.create(RepoMode::BareUser).await;
let main = commit_tree(&repo, &scratch, "main", None, b"one").await;
let mirror = commit_tree(&repo, &scratch, "@org.example.Y:a", None, b"two").await;
let x = Some("org.example.X");
let got = repo
.push_targets(&refspecs(&["main", "main:b", "main:@org.example.X:c"]), x)
.await
.unwrap();
assert_eq!(
got,
vec![
target("@org.example.X:main", Some(main)),
target("@org.example.X:b", Some(main)),
target("@org.example.X:c", Some(main)),
]
);
let got = repo
.push_targets(&refspecs(&["@org.example.Y:a:b"]), x)
.await
.unwrap();
assert_eq!(got, vec![target("@org.example.X:b", Some(mirror))]);
for specs in [
&["main:@org.example.Y:b"][..],
&["@org.example.Y:a"],
&[":@org.example.Y:b"],
] {
assert_invalid(
repo.push_targets(&refspecs(specs), x).await,
"names the collection 'org.example.Y', and the push names the collection \
'org.example.X'",
);
}
assert_invalid(
repo.push_targets(&refspecs(&["main", "main:@org.example.X:main"]), x)
.await,
"'@org.example.X:main' is named twice",
);
let got = repo
.push_targets(&refspecs(&["main", "main:@org.example.X:main"]), None)
.await
.unwrap();
assert_eq!(got.len(), 2);
});
}
#[test]
fn a_one_way_stream_names_collection_refs() {
ostrya_rt::block_on(async {
let scratch = Scratch::new("export-collection");
let repo = scratch.create(RepoMode::BareUser).await;
let main = commit_tree(&repo, &scratch, "main", None, b"one").await;
let mirror = commit_tree(&repo, &scratch, "@org.example.Y:a", None, b"two").await;
let got = repo
.export_updates(
&refspecs(&["main:@org.example.X:a", "@org.example.Y:a"]),
None,
)
.await
.unwrap();
assert_eq!(
got,
vec![
any("@org.example.X:a", main),
any("@org.example.Y:a", mirror)
]
);
for specs in [&["main:@org.example.X:a"][..], &["@org.example.Y:a"]] {
assert_invalid(
repo.export_updates(&refspecs(specs), Some("os")).await,
"a remote ref has no collection, and the destination '@org.example.",
);
}
let got = repo
.export_updates(&refspecs(&["@org.example.Y:a:b"]), Some("os"))
.await
.unwrap();
assert_eq!(got, vec![any("os:b", mirror)]);
assert_invalid(
repo.export_updates(&refspecs(&["main", ":@org.example.X:a"]), None)
.await,
"a one-way stream deletes no ref, and the refspec ':@org.example.X:a' is a delete",
);
});
}
#[test]
fn a_remote_that_makes_no_ref_name_is_an_invalid_refspec() {
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"),
);
});
}
}