xtask: compare pinned repositories as Cargo does

`git_source` writes an IPv6 host in the compressed form Cargo writes,
so `https://[0:0:0:0:0:0:0:1]/r` pins as `https://[::1]/r`.

`check_commits` compares a source's repository with the rule's URL by
Cargo's repository identity: a trailing `/` and `.git` are removed, and
a `github.com` URL is compared over https with a lowercase path. A
dependency spelled `craft-libs.git` is now grouped with `craft-libs`,
and `craft-libs-extra` stays out of the group. A scheme containing `+`
keeps its `.git` suffix and path case.
This commit is contained in:
dotCooCoo committed 2026-11-29 04:29:28 -08:00
1 parent 5513a98548
commit ea8e588730
1 file changed
+245 -9
+245 -9
View File
@@ -62,7 +62,8 @@ pub fn git_source(url: &str, rev: &str) -> String {
}
/// `url` as Cargo writes it in a `source`: the scheme in lowercase, the `.` and `..` segments of the
/// path resolved, and, for `http` and `https`, the host in lowercase, a port of digits written as its
/// path resolved, and, for `http` and `https`, the host in lowercase (an IPv6 host compressed as
/// [`ipv6_text`] writes it), a port of digits written as its
/// number, an empty port or the scheme's default port (80 or 443) left out, and `/` for an empty
/// path. Other URLs keep their authority as
/// written.
@@ -91,7 +92,14 @@ fn cargo_url(url: &str) -> String {
out.push_str(user);
out.push('@');
}
out.push_str(&host.to_ascii_lowercase());
match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).and_then(|h| h.parse::<std::net::Ipv6Addr>().ok()) {
Some(addr) => {
out.push('[');
out.push_str(&ipv6_text(&addr));
out.push(']');
}
None => out.push_str(&host.to_ascii_lowercase()),
}
// A port of digits is written as its number, so `0443` is the default port 443.
let port = port.filter(|port| !port.is_empty()).map(|port| match port.parse::<u16>() {
Ok(number) if port.bytes().all(|b| b.is_ascii_digit()) => (number != default_port).then(|| number.to_string()),
@@ -109,6 +117,70 @@ fn cargo_url(url: &str) -> String {
out
}
/// `addr` as Cargo's URL parser writes an IPv6 host: eight groups in lowercase hex without leading
/// zeros, with the first longest run of two or more zero groups written as `::`.
fn ipv6_text(addr: &std::net::Ipv6Addr) -> String {
let groups = addr.segments();
let (mut best, mut run) = ((0, 0), (0, 0));
for (i, &group) in groups.iter().enumerate() {
if group == 0 {
if run.1 == 0 {
run.0 = i;
}
run.1 += 1;
if run.1 > best.1 {
best = run;
}
} else {
run.1 = 0;
}
}
let hex = |groups: &[u16]| groups.iter().map(|g| format!("{g:x}")).collect::<Vec<_>>().join(":");
if best.1 < 2 {
return hex(&groups);
}
format!("{}::{}", hex(&groups[..best.0]), hex(&groups[best.0 + best.1..]))
}
/// A repository URL as Cargo compares repositories. When the scheme contains no `+`, a URL on
/// `github.com` gets the `https` scheme and a lowercase path. One trailing `/` is removed from a path
/// longer than `/`, then, when the scheme contains no `+`, one trailing `.git` is removed. Removing
/// `.git` writes each `%` in the last segment as `%25`, and a last segment left as `.` or `..` is
/// dropped, keeping at least `/` as the path. The host, query and fragment are unchanged.
fn repo_identity(url: &str) -> String {
let (repo, tail) = url.split_at(url.find(['?', '#']).unwrap_or(url.len()));
let host_start = repo.find("://").map_or(0, |i| i + 3);
let path_start = repo[host_start..].find('/').map_or(repo.len(), |i| host_start + i);
let authority = repo[host_start..path_start].rsplit('@').next().unwrap_or("");
let host = authority.split(':').next().unwrap_or("");
let scheme = repo.split_once("://").map_or("", |(scheme, _)| scheme);
let plus = scheme.contains('+');
let github = !plus && host.eq_ignore_ascii_case("github.com");
let lowercase_path;
let path = if github {
lowercase_path = repo[path_start..].to_ascii_lowercase();
lowercase_path.as_str()
} else {
&repo[path_start..]
};
let prefix = if github {
let authority = &repo[host_start..path_start];
format!("https://{}", authority.strip_suffix(":443").unwrap_or(authority))
} else {
repo[..path_start].to_string()
};
let path = if path.len() > 1 { path.strip_suffix('/').unwrap_or(path) } else { path };
let stripped = if plus { None } else { path.strip_suffix(".git") };
let Some(path) = stripped else { return format!("{prefix}{path}{tail}") };
let (head, last) = path.rsplit_once('/').unwrap_or(("", path));
let path = if matches!(last, "." | "..") {
if head.is_empty() { "/".to_string() } else { head.to_string() }
} else {
format!("{head}/{}", last.replace('%', "%25"))
};
format!("{prefix}{path}{tail}")
}
/// `path`, which starts with `/`, with its `.` and `..` segments resolved as Cargo's URL parser
/// resolves them: `.` is dropped, `..` drops the segment before it, and either one as the last segment
/// leaves the path ending in `/`. `%2e` counts as a `.`, in either case.
@@ -493,15 +565,24 @@ pub fn check_commits(metadata_json: &[u8], rules: &[OneCommit<'_>], limits: &Lim
Ok(())
}
/// The commit of a `source` from the git repository at `url` (as [`cargo_url`] writes it): the text
/// after its last `#`. `None` for a source from anywhere else.
/// Returns the text after the last `#` of a git `source` from the repository at `url`, as
/// [`cargo_url`] writes it. After removing the commit fragment, normalizes both URLs once with
/// [`repo_identity`]. The source identity must equal the rule identity or continue with `?rev=`,
/// `?branch=` or `?tag=`. Reference values may contain `?`, and repository URLs may contain queries.
/// Returns `None` for another repository and an error for a matching source without a commit.
fn git_commit<'s>(source: &'s str, url: &str) -> Result<Option<&'s str>, Error> {
let Some(rest) = source.strip_prefix("git+").and_then(|s| s.strip_prefix(url)) else { return Ok(None) };
if !rest.is_empty() && !rest.starts_with(['?', '#']) {
let Some(source_url) = source.strip_prefix("git+") else { return Ok(None) };
let (repo, commit) = source_url.rsplit_once('#').map_or((source_url, None), |(repo, commit)| (repo, Some(commit)));
let identity = repo_identity(url);
let source_identity = repo_identity(repo);
let matches = source_identity
.strip_prefix(&identity)
.is_some_and(|rest| rest.is_empty() || ["?rev=", "?branch=", "?tag="].into_iter().any(|key| rest.starts_with(key)));
if !matches {
return Ok(None);
}
match rest.rsplit_once('#') {
Some((_, commit)) if !commit.is_empty() => Ok(Some(commit)),
match commit {
Some(commit) if !commit.is_empty() => Ok(Some(commit)),
_ => Err(invalid(format!("source {source} names no commit"))),
}
}
@@ -893,7 +974,7 @@ fn stop(child: &mut Child) {
mod tests {
use super::{
CRATES_IO, Error, Extra, FeatureRule, Forbidden, Limits, Name, OneCommit, Pin, Policy, Scope, Violation, check, check_commits,
check_target_features, git_source,
check_target_features, git_commit, git_source, repo_identity,
};
use serde_json::{Value, json};
@@ -992,6 +1073,15 @@ mod tests {
assert_eq!(git_source("https://host/o/.../r.", "abc"), "git+https://host/o/.../r.?rev=abc#abc");
}
#[test]
fn git_sources_compress_an_ipv6_host_as_cargo_does() {
assert_eq!(git_source("https://[0:0:0:0:0:0:0:1]/r", "abc"), "git+https://[::1]/r?rev=abc#abc");
assert_eq!(git_source("https://[2001:DB8:0:0:1:0:0:1]:443/r", "abc"), "git+https://[2001:db8::1:0:0:1]/r?rev=abc#abc");
assert_eq!(git_source("https://[2001:db8:0:1:1:1:1:1]/r", "abc"), "git+https://[2001:db8:0:1:1:1:1:1]/r?rev=abc#abc");
assert_eq!(git_source("https://[0:0:0:0:0:0:0:0]:8443/r", "abc"), "git+https://[::]:8443/r?rev=abc#abc");
assert_eq!(git_source("https://[0001:00:0:0:1::]/r", "abc"), "git+https://[1::1:0:0:0]/r?rev=abc#abc");
}
#[test]
fn target_features_without_any_enabled_match_an_empty_list() {
assert!(check_target_features("krilla v0.8.2|\n", "krilla", &[]).is_ok());
@@ -1115,6 +1205,152 @@ mod tests {
}
}
#[test]
fn a_rule_url_with_an_expanded_ipv6_host_matches_the_compressed_source() {
let m = libs_metadata(&[("craft-xml", "git+https://[::1]/r?rev=aaa#aaa"), ("craft-zip", "git+https://[::1]/r?rev=bbb#bbb")]);
let rule = OneCommit { url: "https://[0:0:0:0:0:0:0:1]/r", extra: &[] };
assert!(matches!(violation(check_commits(&bytes(&m), &[rule], &Limits::default())), Violation::Commits { .. }));
}
#[test]
fn a_git_suffix_or_trailing_slash_names_the_same_repository() {
let m = libs_metadata(&[
("craft-xml", &git_source(LIBS, "aaa")),
("craft-zip", &git_source(&format!("{LIBS}.git"), "bbb")),
("craft-io", &git_source(&format!("{LIBS}/"), "ccc")),
("other", &git_source("https://github.com/storytold/craft-libs-extra.git", "ddd")),
]);
let expected =
vec![("aaa".into(), vec!["craft-xml".into()]), ("bbb".into(), vec!["craft-zip".into()]), ("ccc".into(), vec!["craft-io".into()])];
for url in [LIBS, "https://github.com/storytold/craft-libs.git", "https://github.com/storytold/craft-libs/"] {
match violation(check_commits(&bytes(&m), &[OneCommit { url, extra: &[] }], &Limits::default())) {
Violation::Commits { commits, .. } => assert_eq!(commits, expected, "rule url {url}"),
other => panic!("expected a commits violation, got {other:?}"),
}
}
let m = libs_metadata(&[
("craft-xml", &git_source(LIBS, "aaa")),
("other", &git_source("https://github.com/storytold/craft-libs-extra.git", "bbb")),
]);
assert!(check_libs(&m, &[]).is_ok());
}
#[test]
fn a_git_suffix_is_left_out_of_the_path_only() {
let m = libs_metadata(&[("a", "git+https://mirror.example/?rev=aaa#aaa"), ("b", "git+https://mirror.example.git/?rev=bbb#bbb")]);
assert!(check_commits(&bytes(&m), &[OneCommit { url: "https://mirror.example/", extra: &[] }], &Limits::default()).is_ok());
let m = libs_metadata(&[("a", "git+https://host/r?rev=aaa#aaa"), ("b", "git+https://host/r.git/?rev=bbb#bbb")]);
assert!(check_commits(&bytes(&m), &[OneCommit { url: "https://host/r", extra: &[] }], &Limits::default()).is_err());
}
#[test]
fn a_rule_url_with_a_query_matches_sources_with_that_query() {
let m = libs_metadata(&[("a", "git+https://host/r?x=1?rev=aaa#aaa"), ("b", "git+https://host/r?x=1?rev=bbb#bbb")]);
assert!(check_commits(&bytes(&m), &[OneCommit { url: "https://host/r?x=1", extra: &[] }], &Limits::default()).is_err());
assert!(check_commits(&bytes(&m), &[OneCommit { url: "https://host/r?y=1", extra: &[] }], &Limits::default()).is_ok());
assert!(check_commits(&bytes(&m), &[OneCommit { url: "https://host/r", extra: &[] }], &Limits::default()).is_ok());
assert!(check_commits(&bytes(&m), &[OneCommit { url: "https://host/r?x=1&y=2", extra: &[] }], &Limits::default()).is_ok());
let m = libs_metadata(&[("a", "git+https://host/r?branch=stable?rev=aaa#aaa"), ("b", "git+https://host/r?branch=stable-next?rev=bbb#bbb")]);
assert!(check_commits(&bytes(&m), &[OneCommit { url: "https://host/r?branch=stable", extra: &[] }], &Limits::default()).is_ok());
}
#[test]
fn github_paths_are_lowercased_before_removing_the_git_suffix() {
for host in ["github.com", "GitHub.com"] {
let source = format!("git+https://{host}/StoryTold/craft-libs.GIT?rev=main#aaa");
let url = format!("https://{host}/storytold/craft-libs");
assert_eq!(git_commit(&source, &url).unwrap(), Some("aaa"));
}
assert_eq!(git_commit("git+https://host/StoryTold/craft-libs.GIT?rev=main#aaa", "https://host/storytold/craft-libs").unwrap(), None);
assert_eq!(repo_identity("https://github.com/StoryTold/R.GIT/?Branch=Main#Part"), "https://github.com/storytold/r?Branch=Main#Part");
}
#[test]
fn removing_a_git_suffix_resolves_a_remaining_dot_segment() {
for (path, expected) in [("/team/..git", "/team"), ("/a/team/...git", "/a/team"), ("/...git", "/")] {
let url = format!("https://host{expected}?x=1");
assert_eq!(repo_identity(&format!("https://host{path}?x=1")), url);
let source = format!("git+https://host{path}/?x=1?branch=fix?parser#aaa");
assert_eq!(git_commit(&source, &url).unwrap(), Some("aaa"));
}
}
#[test]
fn a_source_matches_before_a_reference_query() {
for reference in ["rev=main", "branch=main", "tag=v1"] {
let source = format!("git+https://host/r.git/?x=1?{reference}#aaa");
assert_eq!(git_commit(&source, "https://host/r?x=1").unwrap(), Some("aaa"));
assert_eq!(git_commit(&source, "https://host/r?x=1&y=2").unwrap(), None);
}
assert_eq!(git_commit("git+https://host/r?x=1#aaa", "https://host/r?x=1").unwrap(), Some("aaa"));
assert_eq!(git_commit("git+https://host/r?x=1&y=2?rev=bbb#bbb", "https://host/r?x=1").unwrap(), None);
assert_eq!(git_commit("git+https://host/r?x=1?other=main#aaa", "https://host/r?x=1").unwrap(), None);
assert_eq!(git_commit("git+https://host/r?x=1?rev=main#part#aaa", "https://host/r?x=1").unwrap(), Some("aaa"));
}
#[test]
fn a_reference_value_can_contain_question_marks() {
for reference in ["rev=HEAD^{/fix[ ]?parser}", "branch=fix?parser", "tag=fix?parser"] {
let source = format!("git+https://host/r?{reference}#aaa");
assert_eq!(git_commit(&source, "https://host/r").unwrap(), Some("aaa"));
}
}
#[test]
fn a_reference_query_can_also_be_a_repository_query() {
let source = "git+https://host/r?branch=stable#aaa";
assert_eq!(git_commit(source, "https://host/r?branch=stable").unwrap(), Some("aaa"));
assert_eq!(git_commit(source, "https://host/r").unwrap(), Some("aaa"));
}
#[test]
fn a_reference_query_keeps_repository_names_distinct() {
let source = "git+https://host/craft-libs-extra?rev=HEAD^{/fix[ ]?parser}#aaa";
assert_eq!(git_commit(source, "https://host/craft-libs").unwrap(), None);
assert_eq!(git_commit(source, "https://host/craft-libs-extra").unwrap(), Some("aaa"));
}
#[test]
fn github_http_and_https_sources_name_the_same_repository() {
let m = libs_metadata(&[("a", "git+https://github.com/storytold/r?rev=aaa#aaa"), ("b", "git+http://github.com/storytold/r?rev=bbb#bbb")]);
assert!(check_commits(&bytes(&m), &[OneCommit { url: "https://github.com/storytold/r", extra: &[] }], &Limits::default()).is_err());
assert_eq!(git_commit("git+http://host/r?rev=aaa#aaa", "https://host/r").unwrap(), None);
assert_eq!(git_commit("git+ssh://github.com:443/storytold/r?rev=aaa#aaa", "https://github.com/storytold/r").unwrap(), Some("aaa"));
}
#[test]
fn github_paths_keep_their_case_when_the_scheme_contains_a_plus() {
assert_eq!(repo_identity("git+ssh://github.com/Team/Repo"), "git+ssh://github.com/Team/Repo");
assert_eq!(git_commit("git+git+ssh://github.com/Team/Repo?rev=aaa#aaa", "git+ssh://github.com/team/repo").unwrap(), None);
}
#[test]
fn a_git_suffix_is_kept_when_the_scheme_contains_a_plus() {
assert_eq!(repo_identity("git+ssh://host/r.git/"), "git+ssh://host/r.git");
assert_eq!(git_commit("git+git+ssh://host/r.git?rev=aaa#aaa", "git+ssh://host/r").unwrap(), None);
assert_eq!(git_commit("git+git+ssh://host/r.git?rev=aaa#aaa", "git+ssh://host/r.git/").unwrap(), Some("aaa"));
assert_eq!(git_commit("git+ssh://host/r.git?rev=aaa#aaa", "ssh://host/r").unwrap(), Some("aaa"));
}
#[test]
fn a_root_path_is_kept_when_removing_a_slash_or_git_suffix() {
assert_eq!(repo_identity("https://host/"), "https://host/");
assert_eq!(repo_identity("https://host/.git"), "https://host/");
assert_eq!(repo_identity("https://host/.git/?x=1"), "https://host/?x=1");
let m = libs_metadata(&[("a", "git+https://host/?rev=aaa#aaa"), ("b", "git+https://host/.git?rev=bbb#bbb")]);
for url in ["https://host/", "https://host/.git"] {
assert!(matches!(violation(check_commits(&bytes(&m), &[OneCommit { url, extra: &[] }], &Limits::default())), Violation::Commits { .. }));
}
}
#[test]
fn a_git_suffix_on_an_encoded_segment_names_another_repository() {
let m = libs_metadata(&[("a", "git+https://host/my%20repo?rev=aaa#aaa"), ("b", "git+https://host/my%20repo.git?rev=bbb#bbb")]);
assert!(check_commits(&bytes(&m), &[OneCommit { url: "https://host/my%20repo", extra: &[] }], &Limits::default()).is_ok());
let m = libs_metadata(&[("a", "git+https://host/my%2520repo?rev=aaa#aaa"), ("b", "git+https://host/my%20repo.git?rev=bbb#bbb")]);
assert!(check_commits(&bytes(&m), &[OneCommit { url: "https://host/my%2520repo", extra: &[] }], &Limits::default()).is_err());
}
#[test]
fn rejects_features_that_are_not_strings() {
let m = json!({