Skip to main content

mars_schema/resolve/
mod.rs

1//! Which version of which source, for a whole dependency graph.
2//!
3//! [`resolve`] is a pure function over [`Answers`]: it asks for the tags of a repository, what a
4//! ref points at, the files of a commit, and never fetches. `mars sync` answers each question as
5//! it is asked (so no question stays open and the order of work is the CLI's); Flow answers from
6//! a map and gets back the questions still open ([`Outcome::Needs`]).
7//!
8//! A pass walks the graph from the root; a constraint that changes a version already chosen
9//! restarts the walk with that choice fixed, and diagnostics belong to the last pass only.
10//! Selection of items, hooks and installation are not here: the caller runs them on the graph
11//! this returns.
12
13mod engine;
14mod failure;
15mod lock;
16mod package;
17mod plugin;
18mod version;
19pub mod wire;
20
21use std::collections::{BTreeMap, BTreeSet};
22use std::fmt;
23use std::rc::Rc;
24use std::sync::Arc;
25
26use indexmap::IndexMap;
27use semver::Version;
28
29use crate::dependency::{Entry, Source};
30use crate::diagnostic::SchemaDiagnostic;
31use crate::dialect::Dialect;
32use crate::names::SourceSubpath;
33use crate::prepare::Prepared;
34use crate::tree::TreeSource;
35use crate::version::Constraint;
36
37pub use engine::{BadVersion, Engine, EngineFailure};
38pub use failure::{BoundsLimit, Failure, Identity, PluginDetail, Requester, Step, SubpathDetail};
39pub use lock::{LockedContent, LockedDependency, PluginRoot};
40pub use package::sort_tags;
41
42/// A tag of a repository and the commit it points at, peeled for an annotated tag.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct Tag {
45    pub tag: String,
46    pub commit: String,
47}
48
49/// A tag that is a version.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct TagVersion {
52    pub version: Version,
53    pub tag: String,
54    pub commit: String,
55}
56
57/// What a lookup found. `Missing` is a commit or ref that does not exist, and the only answer
58/// that drops a lock; `Failed` is any other error and always stops resolution.
59#[derive(Debug, Clone)]
60pub enum Answer<T> {
61    Found(T),
62    Missing,
63    Failed(FailedFetch),
64}
65
66/// Why a lookup failed.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub enum FailedFetch {
69    /// The fetch itself failed (network, auth, a limit, an unreadable file): its text.
70    Fetch(String),
71    /// A tree lookup below a repository's root found no folder there, or no folder that stays
72    /// inside it: the dependency's `subpath` is wrong. Only a tree (or path) lookup fails this way.
73    Subpath(SubpathDetail),
74}
75
76impl fmt::Display for FailedFetch {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        match self {
79            Self::Fetch(reason) => f.write_str(reason),
80            Self::Subpath(detail) => write!(f, "the folder {}", detail.reason()),
81        }
82    }
83}
84
85/// A path dependency asked for: `path` as written (relative to `declared_in`'s root, or absolute),
86/// narrowed to `subpath`.
87#[derive(Debug, Clone)]
88pub struct PathRequest<'a> {
89    pub name: &'a str,
90    pub path: &'a str,
91    pub subpath: Option<&'a str>,
92    pub declared_in: Option<&'a Rooted>,
93}
94
95/// An answered path dependency: its canonical directory, and a tree rooted at `subpath` below it.
96#[derive(Clone)]
97pub struct PathSource {
98    pub canonical: String,
99    pub tree: Rc<dyn TreeSource>,
100}
101
102/// Every lookup the resolver makes. A tree is read on demand and rooted at `path` (`None` is the
103/// whole repository); a lookup with no answer yet is an open need ([`Outcome::Needs`]).
104pub trait Answers {
105    fn tags(&self, url: &str) -> Option<Answer<Vec<Tag>>>;
106    fn reference(&self, url: &str, name: &str) -> Option<Answer<String>>;
107    fn tree(
108        &self,
109        url: &str,
110        commit: &str,
111        path: Option<&str>,
112    ) -> Option<Answer<Rc<dyn TreeSource>>>;
113    fn path(&self, request: &PathRequest<'_>) -> Answer<PathSource>;
114    /// The first error a tree met reading a file since the last call: a tree has no error type, so
115    /// an answerer that can fail to read latches it.
116    fn take_read_error(&self) -> Option<String> {
117        None
118    }
119}
120
121/// An answer the resolver is waiting for.
122#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
123pub enum Need {
124    Tags {
125        url: String,
126    },
127    Ref {
128        url: String,
129        name: String,
130    },
131    Tree {
132        url: String,
133        commit: String,
134        path: Option<String>,
135    },
136}
137
138impl fmt::Display for Need {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        match self {
141            Self::Tags { url } => write!(f, "tags of {url}"),
142            Self::Ref { url, name } => write!(f, "ref `{name}` of {url}"),
143            Self::Tree { url, commit, path } => match path {
144                Some(path) => write!(f, "files of {url} at {commit} under {path}"),
145                None => write!(f, "files of {url} at {commit}"),
146            },
147        }
148    }
149}
150
151/// Where a package's files are.
152#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
153pub enum Origin {
154    Git { url: String, commit: String },
155    Path { dir: String },
156}
157
158/// A package root: `subpath` below a checkout.
159#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
160pub struct Rooted {
161    pub checkout: Origin,
162    pub subpath: Option<String>,
163}
164
165/// The identity of a source: the same one under two names, or one name for two, is refused.
166#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
167pub enum SourceId {
168    Git {
169        url: String,
170        subpath: Option<SourceSubpath>,
171        plugin: Option<String>,
172    },
173    Path {
174        canonical: String,
175        subpath: Option<SourceSubpath>,
176        plugin: Option<String>,
177    },
178}
179
180impl SourceId {
181    pub fn plugin(&self) -> Option<&str> {
182        match self {
183            Self::Git { plugin, .. } | Self::Path { plugin, .. } => plugin.as_deref(),
184        }
185    }
186}
187
188impl fmt::Display for SourceId {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        let (subpath, plugin) = match self {
191            Self::Git {
192                url,
193                subpath,
194                plugin,
195            } => {
196                write!(f, "git:{url}")?;
197                (subpath, plugin)
198            }
199            Self::Path {
200                canonical,
201                subpath,
202                plugin,
203            } => {
204                write!(f, "path:{canonical}")?;
205                (subpath, plugin)
206            }
207        };
208        if let Some(subpath) = subpath {
209            write!(f, "@{subpath}")?;
210        }
211        if let Some(plugin) = plugin {
212            write!(f, " (plugin {plugin})")?;
213        }
214        Ok(())
215    }
216}
217
218/// Where a dependency's package comes from, as an entry spells it.
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub enum Spec {
221    Git {
222        url: String,
223        version: Option<String>,
224    },
225    Path(String),
226}
227
228impl Spec {
229    /// The source an entry spells.
230    pub fn of(entry: &Entry) -> Self {
231        match &entry.source {
232            Source::Git { url } => Self::Git {
233                url: url.clone(),
234                version: entry.version.clone(),
235            },
236            Source::Path { path } => Self::Path(path.to_string_lossy().into_owned()),
237        }
238    }
239
240    pub fn constraint(&self) -> Constraint {
241        match self {
242            Self::Git { version, .. } => crate::version::parse_constraint(version.as_deref()),
243            Self::Path(_) => Constraint::Latest,
244        }
245    }
246}
247
248/// One request for a source by name.
249#[derive(Debug, Clone)]
250pub struct Dependency {
251    pub name: String,
252    /// The source the entry declares, before a local override.
253    pub declared: Spec,
254    /// The source fetched: `declared`, or an override's path.
255    pub spec: Spec,
256    pub subpath: Option<SourceSubpath>,
257    pub plugin: Option<String>,
258    pub constraint: Constraint,
259    pub required_by: String,
260    /// The package whose manifest declares this entry; `None` for the root's own.
261    pub declared_in: Option<Rooted>,
262    /// The inbound dialect the root's entry sets; read for the root's entries only.
263    pub dialect: Option<Dialect>,
264    /// Set on a root entry that brings in another root's graph whole (the user level's
265    /// `_user-<name>`), never read from a manifest: every dependency its packages declare is
266    /// named with this prefix and inherits it, so the subgraph never merges with this root's own
267    /// packages, and each of its names replays its `locked` row exactly, as `--frozen` does,
268    /// whatever `mode` says.
269    pub namespace: Option<String>,
270}
271
272/// How a run treats the lock.
273#[derive(Debug, Clone, PartialEq, Eq)]
274pub enum Mode {
275    /// Replay compatible lock entries, otherwise the newest compatible.
276    Sync,
277    /// The lock replays exactly, or the run fails.
278    Frozen,
279    /// Ignore the lock for `targets` (every name when empty).
280    Upgrade { targets: BTreeSet<String> },
281}
282
283#[derive(Debug, Clone, Default)]
284pub struct Bounds {
285    pub packages: Option<usize>,
286    pub bytes: Option<u64>,
287}
288
289pub struct Request {
290    pub root: Vec<Dependency>,
291    /// A package's preparation replaced, its source still answered.
292    pub supplied: BTreeMap<String, Arc<Prepared>>,
293    /// Local overrides by name: the path that replaces the source of every entry of that name.
294    pub overrides: BTreeMap<String, String>,
295    pub locked: BTreeMap<String, LockedDependency>,
296    pub mode: Mode,
297    pub engine: Engine,
298    pub bounds: Bounds,
299}
300
301/// A package's resolved version: the tag it was selected at (`version` and `tag`), or a pinned
302/// ref (`tag` only), or neither for a default branch or a path.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct Ref {
305    pub version: Option<Version>,
306    pub tag: Option<String>,
307    pub commit: Option<String>,
308    pub origin: Origin,
309}
310
311#[derive(Clone)]
312pub struct Node {
313    pub name: String,
314    pub declared: SourceId,
315    pub id: SourceId,
316    /// The URL the source was fetched with, as the entry spelled it; `None` for a path.
317    pub fetch_url: Option<String>,
318    pub resolved: Ref,
319    /// Where the package's files are: the marketplace's own checkout for a local plugin, the
320    /// plugin's repository for a remote one.
321    pub rooted: Rooted,
322    pub plugin: Option<PluginRoot>,
323    pub prepared: Arc<Prepared>,
324    /// What normalizing the tree reported before the package was split out, by file.
325    pub normalized: BTreeMap<String, Vec<SchemaDiagnostic>>,
326}
327
328/// The `mars.lock` row of a dependency resolved at `commit` (under `tag`, when it has one).
329pub fn locked_dependency(
330    id: &SourceId,
331    tag: Option<&str>,
332    commit: Option<&str>,
333    plugin: Option<&PluginRoot>,
334) -> LockedDependency {
335    let (url, path, subpath) = match id {
336        SourceId::Git { url, subpath, .. } => (Some(url.clone()), None, subpath.clone()),
337        SourceId::Path {
338            canonical, subpath, ..
339        } => (None, Some(canonical.clone()), subpath.clone()),
340    };
341    LockedDependency {
342        url,
343        path,
344        subpath,
345        version: tag.map(str::to_owned),
346        commit: commit.map(str::to_owned),
347        plugin: plugin.and_then(|plugin| plugin.locked_name().map(str::to_owned)),
348        content: plugin.and_then(|plugin| plugin.locked_content().cloned()),
349    }
350}
351
352#[derive(Debug, Clone, PartialEq, Eq)]
353pub struct EngineFallbackSkipped {
354    pub version: String,
355    pub failures: Vec<EngineFailure>,
356}
357
358/// A source that took an older version because a newer one needs a newer engine.
359#[derive(Debug, Clone, PartialEq, Eq)]
360pub struct EngineFallback {
361    pub source: String,
362    pub skipped: Vec<EngineFallbackSkipped>,
363    pub selected_version: String,
364}
365
366#[derive(Debug, Clone, Copy, PartialEq, Eq)]
367pub enum Level {
368    /// The user loses something: the sync fell short of the state it wanted.
369    Warning,
370    /// A warning that does not imply it did.
371    Advisory,
372    Info,
373}
374
375#[derive(Debug, Clone, PartialEq, Eq)]
376pub enum Diagnostic {
377    Note {
378        level: Level,
379        code: String,
380        message: String,
381        /// Reported once however many passes or packages repeat it.
382        once: bool,
383    },
384    /// The package was registered here: what preparing its files found belongs at this point, and
385    /// is read from the node's `prepared` and `normalized`, which the consumer frames.
386    Registered { package: String },
387}
388
389pub struct Resolved {
390    /// In the order the final pass registered them.
391    pub nodes: IndexMap<String, Node>,
392    /// Every requester's constraint on each name.
393    pub constraints: BTreeMap<String, Vec<(String, Constraint)>>,
394    pub engine_fallbacks: Vec<EngineFallback>,
395    pub diagnostics: Vec<Diagnostic>,
396}
397
398pub struct Failed {
399    pub failure: Failure,
400    pub diagnostics: Vec<Diagnostic>,
401}
402
403pub enum Outcome {
404    /// Answers still needed, every one on the frontier.
405    Needs(Vec<Need>),
406    Resolved(Resolved),
407    /// The first failure; one found after an open need waits for the needs before it.
408    Failed(Failed),
409}
410
411/// Resolve `request`, asking `answers`.
412pub fn resolve(request: &Request, answers: &dyn Answers) -> Outcome {
413    package::Run::new(request, answers).run()
414}
415
416#[cfg(test)]
417mod tests;