Skip to main content

mars_schema/
dependency.rs

1//! One `[dependencies]` or `[local-dependencies]` entry, as a package manifest or a consumer
2//! `mars.toml` writes it: its source, selectors and filter, and the rules that hold wherever it is
3//! read. The consumer's configuration, a package's manifest reading and `mars add` all read an
4//! entry through [`Entry::read`], which holds every rule and says, by [`Strictness`], which of them
5//! refuse and which only warn.
6
7use std::collections::BTreeMap;
8use std::path::PathBuf;
9
10use indexmap::IndexMap;
11use serde::{Deserialize, Serialize};
12
13use crate::diagnostic::{SchemaDiagnostic, Severity, child_path};
14use crate::dialect::Dialect;
15use crate::filter::{FilterConfig, FilterError};
16use crate::names::SourceSubpath;
17
18/// Where an entry's package comes from: a git repository or a directory, never both.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum Source {
21    Git { url: String },
22    Path { path: PathBuf },
23}
24
25/// One dependency entry. It serializes in the spelling of the file (`url` or `path`, `version`,
26/// `subpath`, `dialect`, `plugin`, the filter keys), so a consumer's `mars.toml` writes it back as
27/// it was authored. `version` is a git source's constraint; a path source has none and ignores it.
28#[derive(Debug, Clone, PartialEq)]
29pub struct Entry {
30    pub source: Source,
31    pub version: Option<String>,
32    pub subpath: Option<SourceSubpath>,
33    /// Inbound lift dialect for the package.
34    pub dialect: Option<Dialect>,
35    /// The plugin to install from the marketplace at this source.
36    pub plugin: Option<String>,
37    pub filter: FilterConfig,
38    /// Keys Mars does not read here, kept so the file round-trips and a caller can warn.
39    pub unknown: BTreeMap<String, toml::Value>,
40}
41
42/// The authored shape of an entry, before the rules that need its name. A consumer's `mars.toml`
43/// holds entries in this shape, so a file with a bad entry still loads and `mars remove` can repair
44/// it; [`Entry::read`] applies the rules where an entry is used.
45#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
46pub struct RawEntry {
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub url: Option<String>,
49    #[serde(default, skip_serializing_if = "Option::is_none", with = "path_serde")]
50    pub path: Option<PathBuf>,
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub subpath: Option<SourceSubpath>,
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub version: Option<String>,
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub dialect: Option<Dialect>,
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub plugin: Option<String>,
59    #[serde(flatten)]
60    pub filter: FilterConfig,
61    #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")]
62    pub unknown: BTreeMap<String, toml::Value>,
63}
64
65/// A path is written with `/` on every host.
66mod path_serde {
67    use std::path::PathBuf;
68
69    use serde::{Deserialize, Deserializer, Serializer};
70
71    pub fn serialize<S: Serializer>(
72        path: &Option<PathBuf>,
73        serializer: S,
74    ) -> Result<S::Ok, S::Error> {
75        match path {
76            Some(path) => serializer.serialize_some(&path.to_string_lossy().replace('\\', "/")),
77            None => serializer.serialize_none(),
78        }
79    }
80
81    pub fn deserialize<'de, D: Deserializer<'de>>(
82        deserializer: D,
83    ) -> Result<Option<PathBuf>, D::Error> {
84        Ok(Option::<String>::deserialize(deserializer)?.map(PathBuf::from))
85    }
86}
87
88/// An entry the schema refuses, by the rule it breaks. Each message names the entry.
89#[derive(Debug, thiserror::Error, PartialEq, Eq)]
90pub enum EntryError {
91    #[error("source `{name}` has both `url` and `path` — pick one")]
92    BothSources { name: String },
93    #[error("source `{name}` has neither `url` nor `path` — one is required")]
94    NoSource { name: String },
95    #[error(transparent)]
96    PluginSelector(#[from] PluginSelectorError),
97    /// A filter that contradicts itself, refused under [`Strictness::Consumer`].
98    #[error(transparent)]
99    Filter(#[from] FilterError),
100    #[error(
101        "dependency name `{name}` is reserved: names starting `{prefix}` are what Mars records the user level's and a host's content under in a project"
102    )]
103    Reserved { name: String, prefix: &'static str },
104}
105
106/// The prefix of the dependencies a project's sync brings in from the user level: `_user-<name>`.
107pub const USER_PREFIX: &str = "_user-";
108/// The prefix of a host's content in a project: `_provided-<host>`.
109pub const HOST_PREFIX: &str = "_provided-";
110/// The prefixes no manifest may name a dependency with: Mars gives them only to the content it
111/// brings into a project from another layer, so a package naming one would pass as that layer.
112pub const RESERVED_PREFIXES: [&str; 2] = [USER_PREFIX, HOST_PREFIX];
113
114impl EntryError {
115    /// The diagnostic code the manifest reading reports it under.
116    pub fn code(&self) -> &'static str {
117        match self {
118            Self::BothSources { .. } | Self::NoSource { .. } => "dependency.source",
119            Self::PluginSelector(_) => "dependency.plugin-selector",
120            Self::Filter(_) => "dependency.filter-conflict",
121            Self::Reserved { .. } => "dependency.reserved-name",
122        }
123    }
124}
125
126/// Who an entry is read for, which decides what a rule does when it breaks.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum Strictness {
129    /// The project's own `mars.toml`, or an entry about to be written to it: every rule refuses.
130    Consumer,
131    /// A dependency's manifest, read as written: its dependents' syncs must not break on it, so a
132    /// conflicting filter warns (and `FilterConfig::to_mode` picks the mode it always has) and a
133    /// `plugin` entry's `dialect` is dropped with a warning.
134    Package,
135}
136
137/// A rule a [`Strictness::Package`] entry broke and was kept anyway.
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct EntryWarning {
140    pub code: &'static str,
141    pub message: String,
142}
143
144impl Entry {
145    /// A git entry with no selector, version or filter.
146    pub fn git(url: impl Into<String>) -> Self {
147        Self::from_source(Source::Git { url: url.into() })
148    }
149
150    /// A path entry with no selector or filter.
151    pub fn at_path(path: impl Into<PathBuf>) -> Self {
152        Self::from_source(Source::Path { path: path.into() })
153    }
154
155    /// An entry for `source` with no selector, version or filter.
156    pub fn from_source(source: Source) -> Self {
157        Self {
158            source,
159            version: None,
160            subpath: None,
161            dialect: None,
162            plugin: None,
163            filter: FilterConfig::default(),
164            unknown: BTreeMap::new(),
165        }
166    }
167
168    /// The git URL, for a git entry.
169    pub fn url(&self) -> Option<&str> {
170        match &self.source {
171            Source::Git { url } => Some(url),
172            Source::Path { .. } => None,
173        }
174    }
175
176    /// The directory, for a path entry.
177    pub fn path(&self) -> Option<&std::path::Path> {
178        match &self.source {
179            Source::Path { path } => Some(path),
180            Source::Git { .. } => None,
181        }
182    }
183
184    /// Read an authored entry under every rule: exactly one of `url` and `path`, a bare
185    /// `host/path` URL spelled with `https://` (see [`crate::git_url::with_default_scheme`]), a
186    /// `plugin` selector that does not contradict `subpath` or `dialect`, a consistent filter
187    /// ([`FilterConfig::validate`]), and a name with no reserved prefix ([`RESERVED_PREFIXES`]).
188    /// `strictness` decides whether a broken filter or a `plugin` with `dialect` refuses or warns;
189    /// the rest refuse for every reader.
190    pub fn read(
191        name: &str,
192        mut raw: RawEntry,
193        strictness: Strictness,
194    ) -> Result<(Self, Vec<EntryWarning>), EntryError> {
195        if let Some(prefix) = RESERVED_PREFIXES
196            .into_iter()
197            .find(|prefix| name.starts_with(prefix))
198        {
199            return Err(EntryError::Reserved {
200                name: name.into(),
201                prefix,
202            });
203        }
204        let mut warnings = Vec::new();
205        if strictness == Strictness::Package && raw.plugin.is_some() && raw.dialect.take().is_some()
206        {
207            warnings.push(EntryWarning {
208                code: "dependency.dialect-ignored",
209                message: format!(
210                    "source `{name}` has both `plugin` and `dialect`; the dialect is ignored"
211                ),
212            });
213        }
214        let source = match (raw.url, raw.path) {
215            (Some(url), None) => Source::Git {
216                url: crate::git_url::with_default_scheme(&url),
217            },
218            (None, Some(path)) => Source::Path { path },
219            (Some(_), Some(_)) => return Err(EntryError::BothSources { name: name.into() }),
220            (None, None) => return Err(EntryError::NoSource { name: name.into() }),
221        };
222        validate_plugin_selector(
223            name,
224            raw.plugin.as_deref(),
225            raw.subpath.as_ref(),
226            raw.dialect,
227        )?;
228        match (raw.filter.validate(name), strictness) {
229            (Err(conflict), Strictness::Consumer) => return Err(conflict.into()),
230            (Err(conflict), Strictness::Package) => warnings.push(EntryWarning {
231                code: "dependency.filter-conflict",
232                message: conflict.to_string(),
233            }),
234            (Ok(()), _) => {}
235        }
236        let entry = Self {
237            source,
238            version: raw.version,
239            subpath: raw.subpath,
240            dialect: raw.dialect,
241            plugin: raw.plugin,
242            filter: raw.filter,
243            unknown: raw.unknown,
244        };
245        Ok((entry, warnings))
246    }
247}
248
249impl From<&Entry> for RawEntry {
250    fn from(entry: &Entry) -> Self {
251        let (url, path) = match &entry.source {
252            Source::Git { url } => (Some(url.clone()), None),
253            Source::Path { path } => (None, Some(path.clone())),
254        };
255        Self {
256            url,
257            path,
258            subpath: entry.subpath.clone(),
259            version: entry.version.clone(),
260            dialect: entry.dialect,
261            plugin: entry.plugin.clone(),
262            filter: entry.filter.clone(),
263            unknown: entry.unknown.clone(),
264        }
265    }
266}
267
268impl From<Entry> for RawEntry {
269    fn from(entry: Entry) -> Self {
270        Self::from(&entry)
271    }
272}
273
274impl Serialize for Entry {
275    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
276        RawEntry::from(self).serialize(serializer)
277    }
278}
279
280/// A package manifest's two dependency tables, entries by name in declaration order.
281#[derive(Debug, Clone, Default, PartialEq, Serialize)]
282pub struct Dependencies {
283    #[serde(skip_serializing_if = "IndexMap::is_empty")]
284    pub dependencies: IndexMap<String, Entry>,
285    #[serde(
286        rename = "local-dependencies",
287        skip_serializing_if = "IndexMap::is_empty"
288    )]
289    pub local_dependencies: IndexMap<String, Entry>,
290}
291
292impl Dependencies {
293    /// Read both tables of a parsed `mars.toml`, entries in declaration order. An entry that
294    /// breaks a rule is left out and reported at `[<table>.<name>]`. A refusal in `[dependencies]`
295    /// is an error, because a dependent installs from it; `[local-dependencies]` is never
296    /// installed from by a dependent, so its refusals are warnings. A filter conflict, and a
297    /// `plugin` entry's `dialect` (ignored there), are warnings on an entry that is kept. A table
298    /// that is not a table leaves both out with one error.
299    pub fn read(
300        document: &toml_edit::DocumentMut,
301        diagnostics: &mut Vec<SchemaDiagnostic>,
302    ) -> Self {
303        let tables = ["dependencies", "local-dependencies"].map(|key| match document.get(key) {
304            None => Ok(None),
305            Some(item) => item.as_table_like().map(Some).ok_or(key),
306        });
307        let [Ok(dependencies), Ok(local_dependencies)] = tables else {
308            let bad = tables.iter().find_map(|table| table.as_ref().err());
309            diagnostics.push(SchemaDiagnostic::new(
310                "dependency.invalid",
311                Severity::Error,
312                Vec::new(),
313                format!(
314                    "`dependencies` and `local-dependencies` must be tables: `{}` is not",
315                    bad.copied().unwrap_or_default()
316                ),
317            ));
318            return Self::default();
319        };
320        Self {
321            dependencies: read_table("dependencies", dependencies, Severity::Error, diagnostics),
322            local_dependencies: read_table(
323                "local-dependencies",
324                local_dependencies,
325                Severity::Warning,
326                diagnostics,
327            ),
328        }
329    }
330}
331
332/// Read one table's entries. A refused entry is left out and reported at `refusal` severity.
333fn read_table(
334    table: &str,
335    items: Option<&dyn toml_edit::TableLike>,
336    refusal: Severity,
337    diagnostics: &mut Vec<SchemaDiagnostic>,
338) -> IndexMap<String, Entry> {
339    let mut entries = IndexMap::new();
340    for (name, item) in items.into_iter().flat_map(|items| items.iter()) {
341        let path = child_path(table, name);
342        // Entries reach JavaScript as plain objects: a name or value JSON can't hold exactly is
343        // left out here, as in every other table `read` returns.
344        if let Err(message) = crate::ordered::reject_unholdable_key(name) {
345            diagnostics.push(SchemaDiagnostic::new(
346                "toml.non-json-value",
347                refusal,
348                path,
349                message,
350            ));
351            continue;
352        }
353        let key_path = format!("{table}.{name}");
354        let raw = match item.clone().into_value() {
355            Ok(value) => RawEntry::deserialize(
356                serde::de::IntoDeserializer::<toml_edit::de::Error>::into_deserializer(value),
357            )
358            .map_err(|error| format!("{key_path}: {}", error.to_string().trim_end())),
359            Err(_) => Err(format!("{key_path}: must be a table")),
360        };
361        let raw = match raw {
362            Ok(raw) => raw,
363            Err(message) => {
364                diagnostics.push(SchemaDiagnostic::new(
365                    "dependency.invalid",
366                    refusal,
367                    path,
368                    message,
369                ));
370                continue;
371            }
372        };
373        match Entry::read(name, raw, Strictness::Package) {
374            Ok((mut entry, warnings)) => {
375                // Unknown keys are only reported and handed to JavaScript, never written back,
376                // so each value is kept as JSON holds it: a datetime becomes its text.
377                let written = item.as_table_like();
378                let unknown = std::mem::take(&mut entry.unknown);
379                for (key, value) in unknown {
380                    let holdable = crate::ordered::reject_unholdable_key(&key).and_then(|()| {
381                        match written.and_then(|table| table.get(&key)) {
382                            Some(item) => crate::manifest::item_json(item).and_then(|json| {
383                                toml::Value::try_from(&json).map_err(|error| error.to_string())
384                            }),
385                            None => Ok(value),
386                        }
387                    });
388                    match holdable {
389                        Ok(value) => {
390                            entry.unknown.insert(key, value);
391                        }
392                        Err(message) => {
393                            let mut at = path.clone();
394                            at.push(crate::diagnostic::PathSegment::Key(key));
395                            diagnostics.push(SchemaDiagnostic::new(
396                                "toml.non-json-value",
397                                Severity::Warning,
398                                at,
399                                message,
400                            ));
401                        }
402                    }
403                }
404                diagnostics.extend(warnings.into_iter().map(|warning| {
405                    SchemaDiagnostic::new(
406                        warning.code,
407                        Severity::Warning,
408                        path.clone(),
409                        warning.message,
410                    )
411                }));
412                entries.insert(name.to_owned(), entry);
413            }
414            Err(error) => diagnostics.push(SchemaDiagnostic::new(
415                error.code(),
416                refusal,
417                path,
418                error.to_string(),
419            )),
420        }
421    }
422    entries
423}
424
425/// A dependency entry that selects a marketplace plugin with a key that contradicts it.
426#[derive(Debug, thiserror::Error, PartialEq, Eq)]
427pub enum PluginSelectorError {
428    #[error("source `{name}` has `plugin = \"{plugin}\"`; a plugin name is {rule}")]
429    BadName {
430        name: String,
431        plugin: String,
432        rule: &'static str,
433    },
434    #[error(
435        "source `{name}` has both `plugin` and `subpath` — a marketplace is read at the root of its source, and the marketplace entry says where the plugin is"
436    )]
437    WithSubpath { name: String },
438    #[error(
439        "source `{name}` has both `plugin` and `dialect` — a marketplace plugin is read as a Claude plugin"
440    )]
441    WithDialect { name: String },
442}
443
444/// `plugin` picks one plugin of the marketplace at the source's root, read as a Claude
445/// marketplace; a `subpath` or `dialect` would name a different root or reading.
446pub fn validate_plugin_selector(
447    name: &str,
448    plugin: Option<&str>,
449    subpath: Option<&SourceSubpath>,
450    dialect: Option<Dialect>,
451) -> Result<(), PluginSelectorError> {
452    let Some(plugin) = plugin else {
453        return Ok(());
454    };
455    let name = name.to_string();
456    if !crate::claude::manifest::is_plugin_name(plugin) {
457        return Err(PluginSelectorError::BadName {
458            name,
459            plugin: plugin.to_string(),
460            rule: crate::claude::manifest::PLUGIN_NAME_RULE,
461        });
462    }
463    if subpath.is_some() {
464        return Err(PluginSelectorError::WithSubpath { name });
465    }
466    if dialect.is_some() {
467        return Err(PluginSelectorError::WithDialect { name });
468    }
469    Ok(())
470}