Skip to main content

mars_schema/resolve/
wire.rs

1//! `resolve` as Flow calls it: JSON in, JSON out, answers from a list.
2//!
3//! [`run`] turns the answers in an [`Input`] into a map-backed [`Answers`] (a lookup with no
4//! answer is an open need) and [`Output`] is the outcome in the shape `npm/@meridian-flow/mars-schema`
5//! documents. Flow keeps no state between calls: every call replays the resolution from the full
6//! list of answers.
7
8use std::cell::RefCell;
9use std::collections::{BTreeMap, BTreeSet};
10use std::rc::Rc;
11
12use semver::Version;
13use serde::{Deserialize, Deserializer, Serialize};
14use serde_bytes::ByteBuf;
15
16use super::{
17    Answer, Answers, Bounds, BoundsLimit, Dependency, Diagnostic, Engine, EngineFailure,
18    FailedFetch, Failure, Identity, Level, LockedDependency, Mode, Need, Outcome, PathRequest,
19    PathSource, PluginDetail, Request, Spec, SubpathDetail, Tag, locked_dependency,
20};
21use crate::dependency::Dependencies;
22use crate::diagnostic::SchemaDiagnostic;
23use crate::names::SourceSubpath;
24use crate::tree::{FileTree, TreeSource};
25use crate::version::Constraint;
26
27/// The root's name for itself in `required_by`; the core says `mars.toml`.
28const ROOT_CORE: &str = "mars.toml";
29const ROOT: &str = "root";
30
31/// An argument that is not the shape `resolve` documents.
32#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
33#[error("{0}")]
34pub struct InputError(String);
35
36impl InputError {
37    pub fn code(&self) -> &'static str {
38        "input.invalid"
39    }
40}
41
42#[derive(Debug, Deserialize)]
43#[serde(deny_unknown_fields)]
44pub struct Input {
45    root: RootInput,
46    /// A package's preparation replaced by an edited manifest. Not supported yet: a non-empty
47    /// map is refused.
48    #[serde(default)]
49    supplied: BTreeMap<String, SuppliedInput>,
50    #[serde(default)]
51    locked: BTreeMap<String, LockedDependency>,
52    #[serde(default)]
53    refresh: Refresh,
54    engine: EngineInput,
55    #[serde(default)]
56    bounds: BoundsInput,
57    answers: Vec<AnswerInput>,
58}
59
60#[derive(Debug, Deserialize)]
61#[serde(deny_unknown_fields)]
62struct RootInput {
63    manifest: String,
64}
65
66#[derive(Debug, Deserialize)]
67#[serde(deny_unknown_fields)]
68struct SuppliedInput {
69    #[allow(dead_code)]
70    manifest: String,
71}
72
73#[derive(Debug, Default, Deserialize)]
74#[serde(untagged)]
75enum Refresh {
76    #[default]
77    None,
78    All(RefreshAll),
79    Names(Vec<String>),
80}
81
82#[derive(Debug, Deserialize)]
83enum RefreshAll {
84    #[serde(rename = "all")]
85    All,
86}
87
88#[derive(Debug, Deserialize)]
89#[serde(deny_unknown_fields)]
90struct EngineInput {
91    mars: String,
92    #[serde(default)]
93    meridian: Option<String>,
94}
95
96#[derive(Debug, Default, Deserialize)]
97#[serde(deny_unknown_fields)]
98struct BoundsInput {
99    #[serde(default)]
100    packages: Option<usize>,
101    #[serde(default)]
102    bytes: Option<u64>,
103}
104
105/// A fetch asked for, or one answered.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(tag = "kind", rename_all = "lowercase")]
108pub enum NeedWire {
109    Tags {
110        url: String,
111    },
112    Ref {
113        url: String,
114        #[serde(rename = "ref")]
115        name: String,
116    },
117    Tree {
118        url: String,
119        commit: String,
120        path: Option<String>,
121    },
122}
123
124impl From<Need> for NeedWire {
125    fn from(need: Need) -> Self {
126        match need {
127            Need::Tags { url } => Self::Tags { url },
128            Need::Ref { url, name } => Self::Ref { url, name },
129            Need::Tree { url, commit, path } => Self::Tree { url, commit, path },
130        }
131    }
132}
133
134#[derive(Debug, Deserialize)]
135struct TagInput {
136    tag: String,
137    commit: String,
138}
139
140/// One answer, in whichever of the five spellings: tags, a ref's commit, a tree's files, or a
141/// need that is `missing` or `failed`.
142#[derive(Debug, Deserialize)]
143struct AnswerInput {
144    need: Option<NeedWire>,
145    tags: Option<Vec<TagInput>>,
146    commit: Option<String>,
147    url: Option<String>,
148    #[serde(default, deserialize_with = "present")]
149    path: Option<Option<String>>,
150    files: Option<BTreeMap<String, ByteBuf>>,
151    missing: Option<bool>,
152    failed: Option<String>,
153}
154
155/// A key that is there, `null` included, apart from one that is not.
156fn present<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Option<String>>, D::Error> {
157    Option::<String>::deserialize(deserializer).map(Some)
158}
159
160/// What `resolve` returned.
161#[derive(Debug, Serialize)]
162#[serde(untagged)]
163pub enum Output {
164    Needs {
165        needs: Vec<NeedWire>,
166    },
167    Resolved {
168        resolved: ResolvedOutput,
169        diagnostics: Vec<DiagnosticOutput>,
170    },
171    Failed {
172        failed: FailureOutput,
173        diagnostics: Vec<DiagnosticOutput>,
174    },
175}
176
177#[derive(Debug, Serialize)]
178pub struct ResolvedOutput {
179    lock: BTreeMap<String, LockedDependency>,
180    dependencies: BTreeMap<String, DependencyOutput>,
181}
182
183#[derive(Debug, Serialize)]
184struct DependencyOutput {
185    url: String,
186    commit: String,
187    subpath: Option<SourceSubpath>,
188    version: Option<String>,
189    #[serde(skip_serializing_if = "Option::is_none")]
190    content: Option<ContentOutput>,
191    required_by: Vec<RequesterOutput>,
192}
193
194/// Where a plugin's files are, with every field spelled, unlike the lock's row.
195#[derive(Debug, Serialize)]
196struct ContentOutput {
197    url: String,
198    subpath: Option<SourceSubpath>,
199    commit: String,
200}
201
202#[derive(Debug, Serialize)]
203struct RequesterOutput {
204    by: String,
205    constraint: Option<String>,
206}
207
208#[derive(Debug, Serialize)]
209pub struct DiagnosticOutput {
210    level: &'static str,
211    code: String,
212    message: String,
213}
214
215#[derive(Debug, Serialize)]
216pub struct FailureOutput {
217    #[serde(flatten)]
218    body: FailureBody,
219    message: String,
220}
221
222#[derive(Debug, Serialize)]
223struct ExcludedOutput {
224    version: String,
225    requirement: String,
226    engine: &'static str,
227}
228
229#[derive(Debug, Serialize)]
230struct StepOutput {
231    version: Option<String>,
232    commit: Option<String>,
233}
234
235#[derive(Debug, Serialize)]
236#[serde(tag = "kind", rename_all = "kebab-case")]
237enum FailureBody {
238    Conflict {
239        name: String,
240        requesters: Vec<RequesterOutput>,
241    },
242    Identity {
243        detail: &'static str,
244        names: Vec<String>,
245        source: String,
246        /// For `one-name-two-sources`: the source the name had first.
247        #[serde(skip_serializing_if = "Option::is_none")]
248        existing: Option<String>,
249    },
250    EngineIncompatible {
251        name: String,
252        requirement: Option<String>,
253        engine: Option<&'static str>,
254    },
255    EngineUnsatisfiable {
256        name: String,
257        excluded: Vec<ExcludedOutput>,
258    },
259    EngineRequirementInvalid {
260        name: String,
261        requirement: String,
262        engine: String,
263    },
264    EngineVersionInvalid {
265        engine: String,
266        version: String,
267    },
268    Plugin {
269        name: String,
270        detail: &'static str,
271        #[serde(skip_serializing_if = "Option::is_none")]
272        plugin: Option<String>,
273    },
274    Subpath {
275        name: String,
276        subpath: String,
277        detail: &'static str,
278    },
279    Unreadable {
280        name: String,
281        diagnostics: Vec<SchemaDiagnostic>,
282    },
283    Path {
284        name: String,
285        declared_in: String,
286    },
287    Unavailable {
288        need: NeedWire,
289        reason: String,
290    },
291    Bounds {
292        limit: &'static str,
293        at: String,
294    },
295    Oscillation {
296        name: String,
297        steps: Vec<StepOutput>,
298    },
299    /// Only `--frozen` produces it, which `resolve` never runs.
300    Frozen,
301}
302
303/// An answer to one kind of lookup, or why there is none.
304enum Reply<T> {
305    Found(T),
306    Missing,
307    Failed(String),
308}
309
310/// A tree answer's key: the repository, the commit and the folder it covers (`None`: everything).
311type TreeKey = (String, String, Option<String>);
312
313/// The tree below a folder of an answer, or why the folder is not one.
314type View = Result<Rc<FileTree>, SubpathDetail>;
315
316/// The answers of an input as a map, which the resolver looks its lookups up in. Every kind keeps
317/// one answer per key, and the later one in the list replaces the earlier: the lookup never
318/// depends on the order the answers arrive in, only on which one is last for its key.
319struct MapAnswers {
320    tags: BTreeMap<String, Reply<Vec<Tag>>>,
321    refs: BTreeMap<(String, String), Reply<String>>,
322    trees: BTreeMap<TreeKey, Reply<Rc<FileTree>>>,
323    /// Trees rooted below a repository's root, built once per lookup.
324    views: RefCell<BTreeMap<(TreeKey, String), View>>,
325}
326
327fn invalid(message: impl Into<String>) -> InputError {
328    InputError(message.into())
329}
330
331impl MapAnswers {
332    fn new(answers: Vec<AnswerInput>) -> Result<Self, InputError> {
333        let mut map = Self {
334            tags: BTreeMap::new(),
335            refs: BTreeMap::new(),
336            trees: BTreeMap::new(),
337            views: RefCell::default(),
338        };
339        for (index, answer) in answers.into_iter().enumerate() {
340            map.add(answer)
341                .map_err(|error| invalid(format!("answers[{index}]: {error}")))?;
342        }
343        Ok(map)
344    }
345
346    fn add(&mut self, answer: AnswerInput) -> Result<(), InputError> {
347        if let Some(files) = answer.files {
348            if answer.need.is_some()
349                || answer.tags.is_some()
350                || answer.missing.is_some()
351                || answer.failed.is_some()
352            {
353                return Err(invalid(
354                    "a tree answer carries only url, commit, path and files",
355                ));
356            }
357            let (Some(url), Some(commit), Some(path)) = (answer.url, answer.commit, answer.path)
358            else {
359                return Err(invalid("a tree answer needs url, commit and path"));
360            };
361            let tree = FileTree::from_files(
362                files
363                    .into_iter()
364                    .map(|(path, bytes)| (path, bytes.into_vec())),
365            )
366            .map_err(|error| invalid(error.to_string()))?;
367            self.trees
368                .insert((url, commit, path), Reply::Found(Rc::new(tree)));
369            return Ok(());
370        }
371        let Some(need) = answer.need else {
372            return Err(invalid(
373                "an answer names its `need`, or carries a tree's `files`",
374            ));
375        };
376        let missing = answer.missing == Some(true);
377        let given = [
378            answer.tags.is_some(),
379            answer.commit.is_some(),
380            missing,
381            answer.failed.is_some(),
382        ]
383        .into_iter()
384        .filter(|given| *given)
385        .count();
386        if given != 1 || answer.missing == Some(false) {
387            return Err(invalid(
388                "an answer carries exactly one of `tags`, `commit`, `missing: true` or `failed`",
389            ));
390        }
391        match need {
392            NeedWire::Tags { url } => {
393                let reply = match (answer.tags, answer.failed) {
394                    (Some(tags), _) => Reply::Found(
395                        tags.into_iter()
396                            .map(|tag| Tag {
397                                tag: tag.tag,
398                                commit: tag.commit,
399                            })
400                            .collect(),
401                    ),
402                    (None, Some(reason)) => Reply::Failed(reason),
403                    _ if missing => Reply::Missing,
404                    _ => return Err(invalid("a tags need is answered with `tags`")),
405                };
406                self.tags.insert(url, reply);
407            }
408            NeedWire::Ref { url, name } => {
409                let reply = match (answer.commit, answer.failed) {
410                    (Some(commit), _) => Reply::Found(commit),
411                    (None, Some(reason)) => Reply::Failed(reason),
412                    _ if missing => Reply::Missing,
413                    _ => return Err(invalid("a ref need is answered with a `commit`")),
414                };
415                self.refs.insert((url, name), reply);
416            }
417            NeedWire::Tree { url, commit, path } => {
418                let reply = match answer.failed {
419                    Some(reason) => Reply::Failed(reason),
420                    None if missing => Reply::Missing,
421                    None => {
422                        return Err(invalid(
423                            "a tree need is answered with `files`, `missing` or `failed`",
424                        ));
425                    }
426                };
427                self.trees.insert((url, commit, path), reply);
428            }
429        }
430        Ok(())
431    }
432
433    /// The answer for a tree need: the one for its own key, else the one for the nearest folder
434    /// above it, else the whole repository's. A narrower answer, found or not, is about the need
435    /// itself, so it outranks a broader one that failed.
436    fn covering(
437        &self,
438        url: &str,
439        commit: &str,
440        path: Option<&str>,
441    ) -> Option<(&TreeKey, &Reply<Rc<FileTree>>)> {
442        let mut at = path.map(str::to_string);
443        loop {
444            let key = (url.to_string(), commit.to_string(), at.clone());
445            if let Some(found) = self.trees.get_key_value(&key) {
446                return Some(found);
447            }
448            at = at?.rsplit_once('/').map(|(parent, _)| parent.to_string());
449        }
450    }
451
452    /// The files of the answer `key` under `path`, as a tree rooted there.
453    fn view(&self, key: &TreeKey, tree: &FileTree, path: &str) -> View {
454        let cached = (key.clone(), path.to_string());
455        if let Some(view) = self.views.borrow().get(&cached) {
456            return view.clone();
457        }
458        let prefix = format!("{path}/");
459        let view = if tree.is_file(path) {
460            Err(SubpathDetail::NotADirectory)
461        } else if !tree.is_dir(path) {
462            Err(SubpathDetail::Missing)
463        } else {
464            let files = tree.files().iter().filter_map(|(file, bytes)| {
465                file.strip_prefix(&prefix)
466                    .map(|relative| (relative.to_string(), bytes.clone()))
467            });
468            Ok(Rc::new(
469                FileTree::from_files(files).expect("paths of a tree stay valid below a folder"),
470            ))
471        };
472        self.views.borrow_mut().insert(cached, view.clone());
473        view
474    }
475}
476
477impl<T: Clone> Reply<T> {
478    fn answer(&self) -> Answer<T> {
479        match self {
480            Self::Found(value) => Answer::Found(value.clone()),
481            Self::Missing => Answer::Missing,
482            Self::Failed(reason) => Answer::Failed(FailedFetch::Fetch(reason.clone())),
483        }
484    }
485}
486
487impl Answers for MapAnswers {
488    fn tags(&self, url: &str) -> Option<Answer<Vec<Tag>>> {
489        self.tags.get(url).map(Reply::answer)
490    }
491
492    fn reference(&self, url: &str, name: &str) -> Option<Answer<String>> {
493        self.refs
494            .get(&(url.to_string(), name.to_string()))
495            .map(Reply::answer)
496    }
497
498    fn tree(
499        &self,
500        url: &str,
501        commit: &str,
502        path: Option<&str>,
503    ) -> Option<Answer<Rc<dyn TreeSource>>> {
504        let (key, reply) = self.covering(url, commit, path)?;
505        Some(match (reply, path) {
506            (Reply::Found(tree), None) => Answer::Found(Rc::clone(tree) as Rc<dyn TreeSource>),
507            (Reply::Found(tree), Some(path)) => match self.view(key, tree, path) {
508                Ok(view) => Answer::Found(view as Rc<dyn TreeSource>),
509                Err(detail) => Answer::Failed(FailedFetch::Subpath(detail)),
510            },
511            (Reply::Missing, _) => Answer::Missing,
512            (Reply::Failed(reason), _) => Answer::Failed(FailedFetch::Fetch(reason.clone())),
513        })
514    }
515
516    /// A fetched package's path names its author's disk.
517    fn path(&self, _request: &PathRequest<'_>) -> Answer<PathSource> {
518        Answer::Failed(FailedFetch::Fetch("path refused".to_string()))
519    }
520}
521
522fn root_dependencies(manifest: &str) -> Result<Vec<Dependency>, InputError> {
523    let document = manifest
524        .parse::<toml_edit::DocumentMut>()
525        .map_err(|error| invalid(format!("root.manifest is not TOML: {error}")))?;
526    let mut diagnostics = Vec::new();
527    let dependencies = Dependencies::read(&document, &mut diagnostics);
528    if let Some(error) = diagnostics.iter().find(|diagnostic| diagnostic.is_error()) {
529        return Err(invalid(format!("root.manifest: {}", error.message)));
530    }
531    Ok(dependencies
532        .dependencies
533        .into_iter()
534        .map(|(name, entry)| {
535            let spec = Spec::of(&entry);
536            Dependency {
537                name,
538                constraint: spec.constraint(),
539                declared: spec.clone(),
540                spec,
541                subpath: entry.subpath,
542                plugin: entry.plugin,
543                required_by: ROOT_CORE.to_string(),
544                declared_in: None,
545                dialect: entry.dialect,
546            }
547        })
548        .collect())
549}
550
551/// Resolve what `input` answers, or say what it still needs.
552pub fn run(input: Input) -> Result<Output, InputError> {
553    if !input.supplied.is_empty() {
554        return Err(invalid(
555            "`supplied` is not supported yet: resolve prepares every package from its fetched tree",
556        ));
557    }
558    let root = root_dependencies(&input.root.manifest)?;
559    let answers = MapAnswers::new(input.answers)?;
560    let mars = match Version::parse(&input.engine.mars) {
561        Ok(mars) => mars,
562        Err(error) => {
563            let failure = Failure::EngineVersionInvalid {
564                engine: "mars".to_string(),
565                version: input.engine.mars,
566                message: error.to_string(),
567            };
568            return Ok(failed(failure, &[]));
569        }
570    };
571    let request = Request {
572        root,
573        supplied: BTreeMap::new(),
574        overrides: BTreeMap::new(),
575        locked: input.locked,
576        mode: match input.refresh {
577            Refresh::None => Mode::Sync,
578            Refresh::All(_) => Mode::Upgrade {
579                targets: BTreeSet::new(),
580            },
581            Refresh::Names(names) if names.is_empty() => Mode::Sync,
582            Refresh::Names(names) => Mode::Upgrade {
583                targets: names.into_iter().collect(),
584            },
585        },
586        engine: Engine {
587            mars,
588            meridian: input.engine.meridian.map(|version| {
589                Version::parse(&version).map_err(|error| super::BadVersion {
590                    version,
591                    message: error.to_string(),
592                })
593            }),
594            ignore_requires_mars: false,
595            ignore_requires_meridian: false,
596        },
597        bounds: Bounds {
598            packages: input.bounds.packages,
599            bytes: input.bounds.bytes,
600        },
601    };
602    Ok(match super::resolve(&request, &answers) {
603        Outcome::Needs(needs) => Output::Needs {
604            needs: needs.into_iter().map(NeedWire::from).collect(),
605        },
606        Outcome::Failed(error) => failed(error.failure, &error.diagnostics),
607        Outcome::Resolved(resolved) => Output::Resolved {
608            resolved: ResolvedOutput {
609                lock: resolved
610                    .nodes
611                    .iter()
612                    .map(|(name, node)| {
613                        (
614                            name.clone(),
615                            locked_dependency(
616                                &node.id,
617                                node.resolved.tag.as_deref(),
618                                node.resolved.commit.as_deref(),
619                                node.plugin.as_ref(),
620                            ),
621                        )
622                    })
623                    .collect(),
624                dependencies: dependencies(&resolved),
625            },
626            diagnostics: diagnostics(&resolved.diagnostics),
627        },
628    })
629}
630
631fn dependencies(resolved: &super::Resolved) -> BTreeMap<String, DependencyOutput> {
632    resolved
633        .nodes
634        .iter()
635        .filter_map(|(name, node)| {
636            let lock = locked_dependency(
637                &node.id,
638                node.resolved.tag.as_deref(),
639                node.resolved.commit.as_deref(),
640                node.plugin.as_ref(),
641            );
642            // Path sources are refused, so a resolved node is a git one.
643            let (url, commit) = (lock.url?, lock.commit?);
644            let required_by = resolved
645                .constraints
646                .get(name)
647                .into_iter()
648                .flatten()
649                .map(|(by, constraint)| RequesterOutput {
650                    by: requester(by),
651                    constraint: constraint_text(constraint),
652                })
653                .collect();
654            Some((
655                name.clone(),
656                DependencyOutput {
657                    url,
658                    commit,
659                    subpath: lock.subpath,
660                    version: node.resolved.version.as_ref().and(lock.version),
661                    content: lock.content.and_then(|content| {
662                        Some(ContentOutput {
663                            url: content.url?,
664                            subpath: content.subpath,
665                            commit: content.commit?,
666                        })
667                    }),
668                    required_by,
669                },
670            ))
671        })
672        .collect()
673}
674
675fn requester(by: &str) -> String {
676    if by == ROOT_CORE { ROOT } else { by }.to_string()
677}
678
679fn constraint_text(constraint: &Constraint) -> Option<String> {
680    match constraint {
681        Constraint::Latest => None,
682        other => Some(other.to_string()),
683    }
684}
685
686fn diagnostics(notes: &[Diagnostic]) -> Vec<DiagnosticOutput> {
687    let mut seen = BTreeSet::new();
688    notes
689        .iter()
690        .filter_map(|note| {
691            let Diagnostic::Note {
692                level,
693                code,
694                message,
695                once,
696            } = note
697            else {
698                return None;
699            };
700            if *once && !seen.insert((code.clone(), message.clone())) {
701                return None;
702            }
703            Some(DiagnosticOutput {
704                level: match level {
705                    Level::Warning => "warning",
706                    Level::Advisory => "advisory",
707                    Level::Info => "info",
708                },
709                code: code.clone(),
710                message: message.clone(),
711            })
712        })
713        .collect()
714}
715
716fn failed(failure: Failure, notes: &[Diagnostic]) -> Output {
717    let message = failure.message();
718    let body = match failure {
719        Failure::Conflict {
720            name, requesters, ..
721        } => FailureBody::Conflict {
722            name,
723            requesters: requesters
724                .into_iter()
725                .map(|found| RequesterOutput {
726                    by: requester(&found.by),
727                    constraint: (found.constraint != "latest").then_some(found.constraint),
728                })
729                .collect(),
730        },
731        Failure::Identity(Identity::OneSourceTwoNames {
732            existing,
733            duplicate,
734            source,
735        }) => FailureBody::Identity {
736            detail: "one-source-two-names",
737            names: vec![existing, duplicate],
738            source,
739            existing: None,
740        },
741        Failure::Identity(Identity::OneNameTwoSources {
742            name,
743            existing,
744            incoming,
745        }) => FailureBody::Identity {
746            detail: "one-name-two-sources",
747            names: vec![name],
748            source: incoming,
749            existing: Some(existing),
750        },
751        Failure::EngineIncompatible { name, failures, .. } => {
752            let first = failures.first();
753            FailureBody::EngineIncompatible {
754                name,
755                requirement: first.map(|failure| failure.requirement.clone()),
756                engine: first.map(|failure| failure.engine),
757            }
758        }
759        Failure::EngineUnsatisfiable { name, excluded } => FailureBody::EngineUnsatisfiable {
760            name,
761            excluded: excluded
762                .into_iter()
763                .flat_map(|(version, failures)| {
764                    failures.into_iter().map(
765                        move |EngineFailure {
766                                  engine,
767                                  requirement,
768                                  ..
769                              }| ExcludedOutput {
770                            version: version.to_string(),
771                            requirement,
772                            engine,
773                        },
774                    )
775                })
776                .collect(),
777        },
778        Failure::EngineRequirementInvalid {
779            name,
780            engine,
781            requirement,
782            ..
783        } => FailureBody::EngineRequirementInvalid {
784            name,
785            requirement,
786            engine,
787        },
788        Failure::EngineVersionInvalid {
789            engine, version, ..
790        } => FailureBody::EngineVersionInvalid { engine, version },
791        Failure::Plugin {
792            name,
793            detail,
794            plugin,
795            ..
796        } => FailureBody::Plugin {
797            name,
798            detail: match detail {
799                PluginDetail::NotAMarketplace => "not-a-marketplace",
800                PluginDetail::NotListed => "not-listed",
801                PluginDetail::Refused => "refused",
802                PluginDetail::ChoiceNeeded => "choice-needed",
803                PluginDetail::NotOnePackage => "not-one-package",
804                PluginDetail::UnusablePath => "unusable-path",
805            },
806            plugin,
807        },
808        Failure::Subpath {
809            name,
810            subpath,
811            detail,
812        } => FailureBody::Subpath {
813            name,
814            subpath,
815            detail: subpath_detail(detail),
816        },
817        Failure::Unreadable {
818            name, diagnostics, ..
819        } => FailureBody::Unreadable { name, diagnostics },
820        Failure::Path { name, declared_in } => FailureBody::Path {
821            name,
822            declared_in: requester(&declared_in),
823        },
824        Failure::Unavailable { need, reason, .. } => FailureBody::Unavailable {
825            need: need.into(),
826            reason,
827        },
828        Failure::Bounds { limit, at } => FailureBody::Bounds {
829            limit: match limit {
830                BoundsLimit::Packages => "packages",
831                BoundsLimit::Bytes => "bytes",
832            },
833            at,
834        },
835        Failure::Oscillation { name, steps } => FailureBody::Oscillation {
836            name,
837            steps: steps
838                .into_iter()
839                .map(|step| StepOutput {
840                    version: step.version,
841                    commit: step.commit,
842                })
843                .collect(),
844        },
845        Failure::Frozen { .. } => FailureBody::Frozen,
846    };
847    Output::Failed {
848        failed: FailureOutput { body, message },
849        diagnostics: diagnostics(notes),
850    }
851}
852
853fn subpath_detail(detail: SubpathDetail) -> &'static str {
854    match detail {
855        SubpathDetail::Missing => "missing",
856        SubpathDetail::NotADirectory => "not-a-directory",
857        SubpathDetail::Traversal => "traversal",
858    }
859}