ud 0.1.0

UpDate! — A fast, universal dependency updater.
Documentation
use crate::core::model::*;
use async_trait::async_trait;
use std::cmp::Ordering;
use std::path::Path;
use std::sync::Arc;

pub trait Manifest: Send + Sync {
    /// Stable id for logs/errors: "cargo-toml", "package-json", "deno-json".
    fn id(&self) -> &'static str;
    /// Discovery table: exact file names the kernel probes for in a directory.
    /// Order matters: first existing name wins for THIS handler (deno.json beats deno.jsonc).
    fn file_names(&self) -> &'static [&'static str];
    /// Claim a specific path. Default: file_name() ∈ file_names().
    fn detect(&self, path: &Path) -> bool {
        path.file_name()
            .and_then(|n| n.to_str())
            .map_or(false, |name| self.file_names().contains(&name))
    }
    /// Parse raw text into dependencies. Must set `source` where syntax declares it,
    /// `span` on every returned dep, and silently skip unsupported forms.
    fn read(&self, raw: &str) -> Result<Vec<Dependency>, UdError>;
    /// Apply all edits, return the full new file content. Must be lossless outside
    /// edited spans and idempotent (applying the same edits twice = same bytes).
    fn write_batch(&self, raw: &str, edits: &[Edit]) -> Result<String, UdError>;
}

#[async_trait]
pub trait Registry: Send + Sync {
    fn id(&self) -> RegistryId; // "crates" | "npm" | "jsr"
    /// Full Dependency (decision 1.A from alignment): registries may use
    /// coordinate, constraint, or section. 404 / not-in-namespace ⇒ Ok(empty), never Err.
    async fn versions(&self, dep: &Dependency) -> Result<Availability, UdError>;
}

pub trait Scheme: Send + Sync {
    /// Total order over version strings. Unparseable versions sort BELOW parseable,
    /// ties broken lexically — totality is the impl's problem, not the caller's.
    fn cmp(&self, a: &Version, b: &Version) -> Ordering;
    fn is_prerelease(&self, v: &Version) -> bool;
    fn satisfies(&self, v: &Version, c: &Constraint) -> bool;
    /// The minimum version the constraint declares, if extractable.
    /// None ⇒ resolve cannot judge "already newer" and reports conservatively.
    fn declared_floor(&self, c: &Constraint) -> Option<Version>;
    /// Would moving to `target` be a real upgrade over what's declared?
    fn is_upgrade(&self, c: &Constraint, target: &Version) -> bool {
        self.declared_floor(c)
            .map_or(true, |floor| self.cmp(target, &floor) == Ordering::Greater)
    }
    /// Produce the new constraint text for `target`, or None if this constraint
    /// shape must not be rewritten (complex ranges — D7). THE operator-preservation policy.
    fn rewrite(&self, c: &Constraint, target: &Version) -> Option<Constraint>;
}

pub struct Ecosystem {
    pub name: &'static str,
    pub manifests: Vec<Arc<dyn Manifest>>,
    pub registries: Vec<Arc<dyn Registry>>,
    pub scheme: Arc<dyn Scheme>,
}

impl Ecosystem {
    /// The ONLY registry-routing logic in the codebase.
    pub async fn availability(&self, dep: &Dependency) -> Result<Availability, UdError> {
        if let Some(ref source_id) = dep.source {
            let registry = self.registries.iter().find(|r| r.id() == *source_id);
            match registry {
                Some(r) => r.versions(dep).await,
                None => Err(UdError::UnknownRegistry {
                    id: source_id.clone(),
                    ecosystem: self.name.to_string(),
                }),
            }
        } else {
            // Fan-out to all registries concurrently (D3)
            let mut futures = Vec::new();
            for r in &self.registries {
                futures.push(r.versions(dep));
            }
            let results = futures::future::join_all(futures).await;

            let mut merged_versions = Vec::<VersionMeta>::new();
            let mut errors = Vec::new();

            for res in results {
                match res {
                    Ok(avail) => {
                        for v in avail.versions {
                            if let Some(existing) =
                                merged_versions.iter_mut().find(|x| x.version == v.version)
                            {
                                existing.yanked = existing.yanked || v.yanked;
                            } else {
                                merged_versions.push(v);
                            }
                        }
                    }
                    Err(e) => {
                        errors.push(e);
                    }
                }
            }

            if !merged_versions.is_empty() {
                Ok(Availability {
                    versions: merged_versions,
                })
            } else if !errors.is_empty() {
                let joined_msgs: Vec<String> = errors.iter().map(|e| e.to_string()).collect();
                Err(UdError::Http(joined_msgs.join("; ")))
            } else {
                Ok(Availability::default())
            }
        }
    }
}