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}
265
266/// How a run treats the lock.
267#[derive(Debug, Clone, PartialEq, Eq)]
268pub enum Mode {
269    /// Replay compatible lock entries, otherwise the newest compatible.
270    Sync,
271    /// The lock replays exactly, or the run fails.
272    Frozen,
273    /// Ignore the lock for `targets` (every name when empty).
274    Upgrade { targets: BTreeSet<String> },
275}
276
277#[derive(Debug, Clone, Default)]
278pub struct Bounds {
279    pub packages: Option<usize>,
280    pub bytes: Option<u64>,
281}
282
283pub struct Request {
284    pub root: Vec<Dependency>,
285    /// A package's preparation replaced, its source still answered.
286    pub supplied: BTreeMap<String, Arc<Prepared>>,
287    /// Local overrides by name: the path that replaces the source of every entry of that name.
288    pub overrides: BTreeMap<String, String>,
289    pub locked: BTreeMap<String, LockedDependency>,
290    pub mode: Mode,
291    pub engine: Engine,
292    pub bounds: Bounds,
293}
294
295/// A package's resolved version: the tag it was selected at (`version` and `tag`), or a pinned
296/// ref (`tag` only), or neither for a default branch or a path.
297#[derive(Debug, Clone, PartialEq, Eq)]
298pub struct Ref {
299    pub version: Option<Version>,
300    pub tag: Option<String>,
301    pub commit: Option<String>,
302    pub origin: Origin,
303}
304
305#[derive(Clone)]
306pub struct Node {
307    pub name: String,
308    pub declared: SourceId,
309    pub id: SourceId,
310    /// The URL the source was fetched with, as the entry spelled it; `None` for a path.
311    pub fetch_url: Option<String>,
312    pub resolved: Ref,
313    /// Where the package's files are: the marketplace's own checkout for a local plugin, the
314    /// plugin's repository for a remote one.
315    pub rooted: Rooted,
316    pub plugin: Option<PluginRoot>,
317    pub prepared: Arc<Prepared>,
318    /// What normalizing the tree reported before the package was split out, by file.
319    pub normalized: BTreeMap<String, Vec<SchemaDiagnostic>>,
320}
321
322/// The `mars.lock` row of a dependency resolved at `commit` (under `tag`, when it has one).
323pub fn locked_dependency(
324    id: &SourceId,
325    tag: Option<&str>,
326    commit: Option<&str>,
327    plugin: Option<&PluginRoot>,
328) -> LockedDependency {
329    let (url, path, subpath) = match id {
330        SourceId::Git { url, subpath, .. } => (Some(url.clone()), None, subpath.clone()),
331        SourceId::Path {
332            canonical, subpath, ..
333        } => (None, Some(canonical.clone()), subpath.clone()),
334    };
335    LockedDependency {
336        url,
337        path,
338        subpath,
339        version: tag.map(str::to_owned),
340        commit: commit.map(str::to_owned),
341        plugin: plugin.and_then(|plugin| plugin.locked_name().map(str::to_owned)),
342        content: plugin.and_then(|plugin| plugin.locked_content().cloned()),
343    }
344}
345
346#[derive(Debug, Clone, PartialEq, Eq)]
347pub struct EngineFallbackSkipped {
348    pub version: String,
349    pub failures: Vec<EngineFailure>,
350}
351
352/// A source that took an older version because a newer one needs a newer engine.
353#[derive(Debug, Clone, PartialEq, Eq)]
354pub struct EngineFallback {
355    pub source: String,
356    pub skipped: Vec<EngineFallbackSkipped>,
357    pub selected_version: String,
358}
359
360#[derive(Debug, Clone, Copy, PartialEq, Eq)]
361pub enum Level {
362    /// The user loses something: the sync fell short of the state it wanted.
363    Warning,
364    /// A warning that does not imply it did.
365    Advisory,
366    Info,
367}
368
369#[derive(Debug, Clone, PartialEq, Eq)]
370pub enum Diagnostic {
371    Note {
372        level: Level,
373        code: String,
374        message: String,
375        /// Reported once however many passes or packages repeat it.
376        once: bool,
377    },
378    /// The package was registered here: what preparing its files found belongs at this point, and
379    /// is read from the node's `prepared` and `normalized`, which the consumer frames.
380    Registered { package: String },
381}
382
383pub struct Resolved {
384    /// In the order the final pass registered them.
385    pub nodes: IndexMap<String, Node>,
386    /// Every requester's constraint on each name.
387    pub constraints: BTreeMap<String, Vec<(String, Constraint)>>,
388    pub engine_fallbacks: Vec<EngineFallback>,
389    pub diagnostics: Vec<Diagnostic>,
390}
391
392pub struct Failed {
393    pub failure: Failure,
394    pub diagnostics: Vec<Diagnostic>,
395}
396
397pub enum Outcome {
398    /// Answers still needed, every one on the frontier.
399    Needs(Vec<Need>),
400    Resolved(Resolved),
401    /// The first failure; one found after an open need waits for the needs before it.
402    Failed(Failed),
403}
404
405/// Resolve `request`, asking `answers`.
406pub fn resolve(request: &Request, answers: &dyn Answers) -> Outcome {
407    package::Run::new(request, answers).run()
408}
409
410#[cfg(test)]
411mod tests;