use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::Deserialize;
use crate::diagnostic::SelectionDiagnostic;
use crate::error::{Error, Result};
use crate::source::ExportPolicy;
use super::HookCommand;
use super::host::Host;
use super::{Protocol, effective_host, fill_template};
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Source {
#[serde(default)]
pub git: Option<String>,
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub digest: Option<String>,
#[serde(default)]
pub host: Option<String>,
#[serde(default)]
pub repo: Option<String>,
#[serde(default)]
pub path: Option<String>,
#[serde(default)]
pub protocol: Option<Protocol>,
pub branch: Option<String>,
pub tag: Option<String>,
pub rev: Option<String>,
pub root: Option<PathBuf>,
#[serde(default)]
pub include: Option<Vec<String>>,
#[serde(default)]
pub exclude: Option<Vec<String>>,
pub allow_symlinks: Option<bool>,
pub preserve_executable: Option<bool>,
#[serde(default)]
pub deploy: Option<DeployMode>,
#[serde(default)]
pub transitive: Option<bool>,
#[serde(default)]
pub build: Option<BuildSpec>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildSpec {
pub inputs: BuildInputs,
pub offer: Option<String>,
pub tool: BuildTool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BuildInputs {
Sources(Vec<String>),
Repo,
Root(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BuildTool {
Command {
command: HookCommand,
key: Option<HookCommand>,
},
Tool { spec: ToolSpec, argv: Vec<String> },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolSpec {
pub identity: String,
pub version: String,
}
impl std::str::FromStr for ToolSpec {
type Err = String;
fn from_str(raw: &str) -> std::result::Result<Self, String> {
match raw.rsplit_once('@') {
Some((identity, version)) if !identity.is_empty() && !version.is_empty() => Ok(Self {
identity: identity.to_owned(),
version: version.to_owned(),
}),
_ => Err(format!(
"`tool = \"{raw}\"` needs an identity and a version, as `<identity>@<version>`"
)),
}
}
}
impl std::fmt::Display for ToolSpec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}@{}", self.identity, self.version)
}
}
const SHELL_SYNTAX: &[char] = &[';', '&', '|', '$', '`', '<', '>'];
fn tool_argv(
run: Option<String>,
cmd: Option<Vec<String>>,
) -> std::result::Result<Vec<String>, String> {
let argv = match (run, cmd) {
(Some(_), Some(_)) => return Err("a tool build sets `run` or `cmd`, not both".to_owned()),
(None, None) => return Err("a tool build needs `run` or `cmd`".to_owned()),
(None, Some(cmd)) => cmd,
(Some(run), None) => {
if run.contains(SHELL_SYNTAX) {
return Err(format!(
"tool builds never run a shell; pass separate arguments instead of `{run}`"
));
}
shlex::split(&run).ok_or_else(|| format!("`run = \"{run}\"` has unbalanced quotes"))?
}
};
match argv.first() {
None => Err("a tool build's command is empty".to_owned()),
Some(program) if program.contains('/') => Err(format!(
"a tool build names the tool's executable, not a path: `{program}`"
)),
Some(_) => Ok(argv),
}
}
impl<'de> Deserialize<'de> for BuildSpec {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct BuildTable {
inputs: Option<Vec<String>>,
offer: Option<String>,
tool: Option<String>,
run: Option<String>,
shell: Option<String>,
cmd: Option<Vec<String>>,
key: Option<HookCommand>,
}
let table = BuildTable::deserialize(deserializer)?;
let tool = match table.tool {
Some(tool) => {
if table.shell.is_some() || table.key.is_some() {
return Err(serde::de::Error::custom(
"a tool build takes no `shell` or `key`: it never runs a shell, and its \
version pin is its key",
));
}
BuildTool::Tool {
spec: tool.parse().map_err(serde::de::Error::custom)?,
argv: tool_argv(table.run, table.cmd).map_err(serde::de::Error::custom)?,
}
}
None => BuildTool::Command {
command: super::hooks::validated_command(table.run, table.shell, table.cmd)?,
key: table.key,
},
};
Ok(Self {
inputs: table.inputs.map_or(BuildInputs::Repo, BuildInputs::Sources),
offer: table.offer,
tool,
})
}
}
impl BuildSpec {
#[must_use]
pub fn named_inputs(&self) -> &[String] {
match &self.inputs {
BuildInputs::Sources(names) => names,
BuildInputs::Repo | BuildInputs::Root(_) => &[],
}
}
#[must_use]
pub(crate) fn reading_repo_as(&self, repo: &str) -> Self {
let inputs = match &self.inputs {
BuildInputs::Repo => BuildInputs::Root(repo.to_owned()),
inputs => inputs.clone(),
};
Self {
inputs,
offer: self.offer.clone(),
tool: self.tool.clone(),
}
}
}
impl Source {
#[must_use]
pub fn is_transitive(&self) -> bool {
self.transitive.unwrap_or(false)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DeployMode {
Copy,
Link,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceMode {
Git,
Host,
Url,
Build,
}
#[derive(Debug, Clone)]
pub enum Remote {
Git(String),
Path(String),
Url {
url: String,
digest: Option<crate::digest::Digest>,
},
Host {
host: String,
repo: String,
protocol: Option<Protocol>,
},
Build(BuildSpec),
}
impl Remote {
#[must_use]
pub fn mode(&self) -> SourceMode {
match self {
Self::Git(_) | Self::Path(_) => SourceMode::Git,
Self::Host { .. } => SourceMode::Host,
Self::Url { .. } => SourceMode::Url,
Self::Build(_) => SourceMode::Build,
}
}
}
#[derive(Debug, Clone)]
pub struct ParsedSource {
pub remote: Remote,
pub branch: Option<String>,
pub tag: Option<String>,
pub rev: Option<String>,
pub root: Option<PathBuf>,
include: Option<Vec<String>>,
exclude: Option<Vec<String>>,
allow_symlinks: Option<bool>,
preserve_executable: Option<bool>,
deploy: Option<DeployMode>,
transitive: bool,
}
impl ParsedSource {
#[must_use]
pub fn is_transitive(&self) -> bool {
self.transitive
}
pub fn parse(name: &str, source: &Source) -> Result<Self> {
let remote = source.classify(name)?.ok_or_else(|| {
Error::Config(format!(
"source `{name}` must resolve to exactly one of a local `path`, \
a forge `host`/`repo`, a literal `git`, a `url`, or a `build`"
))
})?;
reject_bang_patterns(name, "include", source.include.as_deref())?;
reject_bang_patterns(name, "exclude", source.exclude.as_deref())?;
Ok(Self {
remote,
branch: source.branch.clone(),
tag: source.tag.clone(),
rev: source.rev.clone(),
root: source.root.clone(),
include: source.include.clone(),
exclude: source.exclude.clone(),
allow_symlinks: source.allow_symlinks,
preserve_executable: source.preserve_executable,
deploy: source.deploy,
transitive: source.is_transitive(),
})
}
#[must_use]
pub fn mode(&self) -> SourceMode {
self.remote.mode()
}
pub fn resolved_remote(
&self,
hosts: &BTreeMap<String, Host>,
protocol: Protocol,
) -> Result<String> {
match &self.remote {
Remote::Git(remote) | Remote::Path(remote) => Ok(super::expand_home(Path::new(remote))
.to_string_lossy()
.into_owned()),
Remote::Url { .. } => Ok(String::new()),
Remote::Build(_) => Ok(crate::source::BUILD_MIRROR.to_owned()),
Remote::Host { host, repo, .. } => resolve_forge(hosts, host, repo, protocol),
}
}
#[must_use]
pub fn source_url(&self) -> Option<&str> {
match &self.remote {
Remote::Url { url, .. } => Some(url),
_ => None,
}
}
#[must_use]
pub fn build(&self) -> Option<&BuildSpec> {
match &self.remote {
Remote::Build(spec) => Some(spec),
_ => None,
}
}
#[must_use]
pub fn protocol(&self) -> Option<Protocol> {
match &self.remote {
Remote::Host { protocol, .. } => *protocol,
_ => None,
}
}
#[must_use]
pub fn digest(&self) -> Option<crate::digest::Digest> {
match &self.remote {
Remote::Url { digest, .. } => *digest,
_ => None,
}
}
#[must_use]
pub fn deploy_mode(&self) -> DeployMode {
self.deploy.unwrap_or(DeployMode::Copy)
}
pub(crate) fn link_worktree(&mut self, root: &str) {
self.remote = Remote::Path(root.to_owned());
self.deploy = Some(DeployMode::Link);
self.branch = None;
self.tag = None;
self.rev = None;
}
#[must_use]
pub fn includes(&self) -> &[String] {
self.include.as_deref().unwrap_or(&[])
}
#[must_use]
pub fn excludes(&self) -> &[String] {
self.exclude.as_deref().unwrap_or(&[])
}
#[must_use]
pub fn offer(&self) -> Offer<'_> {
Offer {
includes: self.includes(),
excludes: self.excludes(),
root: self.root.as_deref(),
}
}
#[must_use]
pub fn refspec(&self) -> Refspec {
if matches!(self.remote, Remote::Url { .. } | Remote::Build(_)) {
Refspec::None
} else if let Some(rev) = &self.rev {
Refspec::Rev(rev.clone())
} else if let Some(tag) = &self.tag {
Refspec::Tag(tag.clone())
} else if let Some(branch) = &self.branch {
Refspec::Branch(branch.clone())
} else {
Refspec::Default
}
}
#[must_use]
pub fn export_policy(&self, history: bool) -> ExportPolicy {
ExportPolicy {
allow_symlinks: self.allow_symlinks.unwrap_or(history),
preserve_executable: self.preserve_executable.unwrap_or(true),
vcs_opt_in: history
|| self
.includes()
.iter()
.any(|p| p.split(['/', '\\']).any(|seg| seg == ".git")),
}
}
#[must_use]
pub fn config_digest(&self) -> String {
let mut h = blake3::Hasher::new();
for p in self.includes() {
h.update(b"inc\x00");
h.update(p.as_bytes());
}
for p in self.excludes() {
h.update(b"exc\x00");
h.update(p.as_bytes());
}
if let Some(r) = &self.root {
h.update(b"root\x00");
h.update(r.to_string_lossy().as_bytes());
}
let policy = self.export_policy(false);
h.update(&[
u8::from(policy.allow_symlinks),
u8::from(policy.preserve_executable),
]);
format!("blake3:{}", h.finalize().to_hex())
}
}
const VCS_EXCLUDES: &[&str] = &[".git/"];
#[derive(Debug, Clone, Copy)]
pub struct Offer<'a> {
includes: &'a [String],
excludes: &'a [String],
root: Option<&'a Path>,
}
impl<'a> Offer<'a> {
#[must_use]
pub fn includes(&self) -> &'a [String] {
self.includes
}
#[must_use]
pub fn excludes(&self) -> &'a [String] {
self.excludes
}
#[must_use]
pub fn is_implicit_full(&self) -> bool {
self.includes.is_empty()
}
#[must_use]
pub fn vcs_excludes(&self) -> &[&'static str] {
if self.is_implicit_full() {
VCS_EXCLUDES
} else {
&[]
}
}
#[must_use]
pub fn root(&self) -> Option<&'a Path> {
self.root
}
}
fn reject_bang_patterns(name: &str, field: &str, patterns: Option<&[String]>) -> Result<()> {
let Some(patterns) = patterns else {
return Ok(());
};
for pattern in patterns {
if pattern.starts_with('!') {
return Err(SelectionDiagnostic {
entry: pattern.clone(),
matched_against: format!("source `{name}` `{field}` patterns"),
why: "`!` negation is not supported — the offer composes `include − exclude`, \
with no gitignore ordering or re-inclusion"
.to_owned(),
did_you_mean: None,
remedy: "drop the `!` and express the exclusion via `exclude` \
(exclude wins over include)"
.to_owned(),
debug_hint: Some(format!("phora explain {name} src")),
details: Vec::new(),
}
.config());
}
}
Ok(())
}
fn resolve_forge(
hosts: &BTreeMap<String, Host>,
host_name: &str,
repo: &str,
protocol: Protocol,
) -> Result<String> {
let effective = effective_host(hosts, host_name).ok_or_else(|| {
Error::Config(format!(
"source `{repo}` references unknown host `{host_name}`"
))
})?;
let template = effective
.remote
.as_ref()
.and_then(|remote| match protocol {
Protocol::Https => remote.https_template(),
Protocol::Ssh => remote.ssh_template(),
})
.ok_or_else(|| {
let proto = match protocol {
Protocol::Https => "https",
Protocol::Ssh => "ssh",
};
Error::Config(format!("host `{host_name}` has no {proto} remote template"))
})?;
Ok(fill_template(template, repo))
}
impl Source {
#[must_use]
pub(super) fn merged_with(mut self, local: Source) -> Source {
let local_git_kind = local.git.is_some();
let local_forge_kind = local.host.is_some() || local.repo.is_some();
let local_local_kind = local.path.is_some() && !local_forge_kind;
let local_url_kind = local.url.is_some();
let local_build_kind = local.build.is_some();
let local_ref = local.branch.is_some() || local.tag.is_some() || local.rev.is_some();
if local_git_kind || local_forge_kind || local_local_kind || local_url_kind {
self.build = None;
}
if local_build_kind {
self.build = local.build;
self.git = None;
self.host = None;
self.repo = None;
self.path = None;
self.url = None;
self.digest = None;
self.branch = None;
self.tag = None;
self.rev = None;
} else if local_git_kind {
self.git = local.git;
self.host = None;
self.repo = None;
self.path = None;
self.url = None;
self.digest = None;
} else if local_forge_kind {
self.host = local.host;
self.repo = local.repo;
self.path = local.path;
self.git = None;
self.url = None;
self.digest = None;
} else if local_local_kind {
self.path = local.path;
self.host = None;
self.repo = None;
self.git = None;
self.url = None;
self.digest = None;
} else if local_url_kind {
if self.url != local.url {
self.digest = None;
}
self.url = local.url;
self.git = None;
self.host = None;
self.repo = None;
self.path = None;
self.branch = None;
self.tag = None;
self.rev = None;
self.root = None;
}
if local.digest.is_some() {
self.digest = local.digest;
}
if local.protocol.is_some() {
self.protocol = local.protocol;
}
if local_ref {
self.branch = local.branch;
self.tag = local.tag;
self.rev = local.rev;
}
if local.root.is_some() {
self.root = local.root;
}
if local.include.is_some() {
self.include = local.include;
}
if local.exclude.is_some() {
self.exclude = local.exclude;
}
if local.allow_symlinks.is_some() {
self.allow_symlinks = local.allow_symlinks;
}
if local.preserve_executable.is_some() {
self.preserve_executable = local.preserve_executable;
}
if local.deploy.is_some() {
self.deploy = local.deploy;
}
if local.transitive.is_some() {
self.transitive = local.transitive;
}
if local_local_kind && self.deploy == Some(DeployMode::Link) && !local_ref {
self.branch = None;
self.tag = None;
self.rev = None;
}
self
}
#[must_use]
fn is_forge(&self) -> bool {
self.host.is_some() || self.repo.is_some()
}
#[must_use]
fn forge_path(&self) -> Option<&str> {
self.repo.as_deref().or(self.path.as_deref())
}
#[must_use]
fn local_path(&self) -> Option<&str> {
if self.host.is_some() && self.repo.is_none() {
return None;
}
self.path.as_deref()
}
pub(super) fn classify(&self, name: &str) -> Result<Option<Remote>> {
if u8::from(self.branch.is_some())
+ u8::from(self.tag.is_some())
+ u8::from(self.rev.is_some())
> 1
{
return Err(Error::Config(format!(
"source `{name}` sets more than one of branch/tag/rev"
)));
}
let local = self.local_path();
let kinds = u8::from(self.git.is_some())
+ u8::from(self.url.is_some())
+ u8::from(self.is_forge())
+ u8::from(local.is_some())
+ u8::from(self.build.is_some());
if kinds > 1 {
return Err(Error::Config(format!(
"source `{name}` sets more than one source kind \
(local `path`, forge `host`/`repo`, literal `git`, `url`, and `build` \
are mutually exclusive)"
)));
}
if let Some(build) = &self.build {
return classify_build(name, self, build).map(Some);
}
if let Some(url) = &self.url {
if self.branch.is_some()
|| self.tag.is_some()
|| self.rev.is_some()
|| self.root.is_some()
{
return Err(Error::Config(format!(
"source `{name}`: `branch`/`tag`/`rev`/`root` are meaningless on a `url` source"
)));
}
if url.trim().is_empty() {
return Err(Error::Config(format!(
"source `{name}`: `url` must not be empty"
)));
}
let digest = self
.digest
.as_deref()
.map(|raw| {
raw.parse::<crate::digest::Digest>()
.map_err(|e| Error::Config(format!("source `{name}`: {e}")))
})
.transpose()?;
return Ok(Some(Remote::Url {
url: url.clone(),
digest,
}));
}
if let Some(git) = &self.git {
return Ok(Some(Remote::Git(git.clone())));
}
if self.is_forge() {
let host = self.host.as_deref().unwrap_or("github");
let repo = self.forge_path().ok_or_else(|| {
Error::Config(format!(
"source `{name}`: `host` set without a `repo` (incomplete forge group)"
))
})?;
return Ok(Some(Remote::Host {
host: host.to_owned(),
repo: repo.to_owned(),
protocol: self.protocol,
}));
}
if let Some(path) = local {
return Ok(Some(Remote::Path(path.to_owned())));
}
Ok(None)
}
}
fn classify_build(name: &str, source: &Source, build: &BuildSpec) -> Result<Remote> {
let field = if source.branch.is_some() {
"branch"
} else if source.tag.is_some() {
"tag"
} else if source.rev.is_some() {
"rev"
} else if source.digest.is_some() {
"digest"
} else if source.protocol.is_some() {
"protocol"
} else if source.deploy == Some(DeployMode::Link) {
"deploy = \"link\""
} else if source.transitive == Some(true) {
"transitive"
} else if source.allow_symlinks.is_some() {
"allow_symlinks"
} else {
""
};
if !field.is_empty() {
return Err(Error::Config(format!(
"source `{name}`: `{field}` is meaningless on a `build` source"
)));
}
if matches!(&build.inputs, BuildInputs::Sources(inputs) if inputs.is_empty()) {
return Err(Error::Config(format!(
"source `{name}`: `build.inputs` must name at least one source"
)));
}
if build.named_inputs().iter().any(|input| input == name) {
return Err(Error::Config(format!(
"source `{name}`: `build.inputs` cannot name the build source itself"
)));
}
Ok(Remote::Build(build.clone()))
}
#[derive(Debug, Clone)]
pub enum Refspec {
Branch(String),
Tag(String),
Rev(String),
Default,
None,
}
impl std::fmt::Display for Refspec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Branch(s) | Self::Tag(s) | Self::Rev(s) => write!(f, "{s}"),
Self::Default => write!(f, "default"),
Self::None => write!(f, ""),
}
}
}
#[cfg(test)]
mod offer_tests {
use std::path::Path;
use super::{ParsedSource, Source};
use crate::diagnostic::{MATCHED_AGAINST, REMEDY, SELECTION, TO_DEBUG};
fn git_source() -> Source {
Source {
git: Some("https://example.test/repo.git".into()),
url: None,
digest: None,
host: None,
repo: None,
path: None,
protocol: None,
branch: None,
tag: None,
rev: None,
root: None,
include: None,
exclude: None,
allow_symlinks: None,
preserve_executable: None,
deploy: None,
transitive: None,
build: None,
}
}
fn parsed(source: &Source) -> ParsedSource {
ParsedSource::parse("dotfiles", source).expect("fixture source must parse")
}
#[test]
fn absent_include_is_an_implicit_full_offer() {
let parsed = parsed(&git_source());
let offer = parsed.offer();
assert!(
offer.is_implicit_full(),
"a source with no `include` must expose the OCaml `no .mli = public` implicit full offer"
);
}
#[test]
fn an_include_makes_the_offer_explicit_not_full() {
let mut source = git_source();
source.include = Some(vec!["skills/**".into()]);
let parsed = parsed(&source);
let offer = parsed.offer();
assert!(
!offer.is_implicit_full(),
"a declared `include` is an explicit `.mli`; the offer is no longer the implicit full offer"
);
assert_eq!(
offer.includes(),
["skills/**"],
"the offer must carry the declared include patterns verbatim"
);
}
#[test]
fn implicit_full_offer_excludes_vcs_metadata() {
let parsed = parsed(&git_source());
let offer = parsed.offer();
assert!(
offer
.vcs_excludes()
.iter()
.any(|pattern| pattern.contains(".git")),
"the implicit full offer must bound `everything` by pruning `.git/`/VCS metadata (M5); \
got vcs excludes: {:?}",
offer.vcs_excludes()
);
}
#[test]
fn offer_carries_both_include_and_exclude_for_set_composition() {
let mut source = git_source();
source.include = Some(vec!["skills/**".into()]);
source.exclude = Some(vec!["skills/private/**".into()]);
let parsed = parsed(&source);
let offer = parsed.offer();
assert_eq!(
offer.includes(),
["skills/**"],
"the offer must expose include patterns for `include − exclude` composition"
);
assert_eq!(
offer.excludes(),
["skills/private/**"],
"the offer must expose exclude patterns; exclude-wins composition is resolved at SMR-020"
);
}
#[test]
fn dotfiles_are_not_opted_out_of_the_offer_surface() {
let mut source = git_source();
source.include = Some(vec![".config/**".into()]);
let parsed = parsed(&source);
let offer = parsed.offer();
assert!(
offer
.vcs_excludes()
.iter()
.all(|pattern| pattern.contains(".git")),
"the only dotted thing the offer surface prunes is VCS metadata; no blanket dotfile \
opt-out may appear (D4/RQ-3 — dotfiles MATCH, 100% gitignore); got: {:?}",
offer.vcs_excludes()
);
assert!(
offer.includes().iter().any(|p| p.starts_with('.')),
"a dotted include pattern must survive into the offer unchanged"
);
}
#[test]
fn offer_exposes_root_for_re_anchoring() {
let mut source = git_source();
source.root = Some("nested/here".into());
let parsed = parsed(&source);
let offer = parsed.offer();
assert_eq!(
offer.root(),
Some(Path::new("nested/here")),
"the offer must expose `root` so SMR-020 re-anchors gitignore matching and publishes \
a root-relative namespace (D20)"
);
}
#[test]
fn absent_root_anchors_at_the_source_top() {
let parsed = parsed(&git_source());
let offer = parsed.offer();
assert_eq!(
offer.root(),
None,
"no `root` means the offer anchors at the source top; the namespace is the full source"
);
}
#[test]
fn bang_negation_in_include_is_rejected_with_a_selection_diagnostic() {
let mut source = git_source();
source.include = Some(vec!["!skills/private/**".into()]);
let err = ParsedSource::parse("dotfiles", &source)
.expect_err("a `!`-prefixed include must be rejected — no gitignore ordering/negation");
let rendered = err.to_string();
for phrase in [SELECTION, MATCHED_AGAINST, REMEDY, TO_DEBUG] {
assert!(
rendered.contains(phrase),
"the `!`-rejection must render the named selection-diagnostic phrase `{phrase}`; \
got:\n{rendered}"
);
}
assert!(
rendered.contains('!'),
"the diagnostic must surface the offending `!` pattern; got:\n{rendered}"
);
}
#[test]
fn bang_negation_in_exclude_is_rejected() {
let mut source = git_source();
source.exclude = Some(vec!["!skills/keep/**".into()]);
let err = ParsedSource::parse("dotfiles", &source)
.expect_err("a `!`-prefixed exclude must be rejected — exclude-wins, no re-inclusion");
let rendered = err.to_string();
assert!(
rendered.contains(SELECTION) && rendered.contains(REMEDY),
"the exclude `!`-rejection must render a structured selection diagnostic; got:\n{rendered}"
);
}
}
#[cfg(test)]
mod merge_url_digest_tests {
use super::Source;
const OLD_DIGEST: &str =
"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const NEW_DIGEST: &str =
"sha256:fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210";
fn bare() -> Source {
Source {
git: None,
url: None,
digest: None,
host: None,
repo: None,
path: None,
protocol: None,
branch: None,
tag: None,
rev: None,
root: None,
include: None,
exclude: None,
allow_symlinks: None,
preserve_executable: None,
deploy: None,
transitive: None,
build: None,
}
}
fn url_source(url: &str, digest: Option<&str>) -> Source {
Source {
url: Some(url.to_owned()),
digest: digest.map(str::to_owned),
..bare()
}
}
#[test]
fn url_override_changing_url_without_digest_drops_the_stale_base_pin() {
let base = url_source("https://example.com/old.tar.gz", Some(OLD_DIGEST));
let local = url_source("https://example.com/new.tar.gz", None);
let merged = base.merged_with(local);
assert_eq!(
merged.url.as_deref(),
Some("https://example.com/new.tar.gz"),
"the override url must win"
);
assert!(
merged.digest.is_none(),
"changing the url without restating a digest must drop the stale base pin so the \
next sync does not fail a spurious digest mismatch; got {:?}",
merged.digest
);
}
#[test]
fn url_override_restating_url_and_digest_keeps_the_new_pin() {
let base = url_source("https://example.com/old.tar.gz", Some(OLD_DIGEST));
let local = url_source("https://example.com/new.tar.gz", Some(NEW_DIGEST));
let merged = base.merged_with(local);
assert_eq!(
merged.digest.as_deref(),
Some(NEW_DIGEST),
"restating a digest alongside the new url must pin to the override digest"
);
}
#[test]
fn url_override_restating_same_url_without_digest_keeps_the_base_pin() {
let base = url_source("https://example.com/pkg.tar.gz", Some(OLD_DIGEST));
let local = url_source("https://example.com/pkg.tar.gz", None);
let merged = base.merged_with(local);
assert_eq!(
merged.digest.as_deref(),
Some(OLD_DIGEST),
"restating the same url without a digest must keep the valid base pin, not drop it"
);
}
}