Skip to main content

mars_schema/
package.rs

1//! Versioned package metadata and manifest classification.
2
3use semver::{Version, VersionReq};
4use serde::{Deserialize, Serialize};
5
6use crate::keys::Floor;
7use crate::tool_rule_map::ToolRuleMap;
8
9/// Parse a `requires-mars` or `requires-meridian` requirement. A bare version means `>=` it
10/// (`0.19.0` is `>=0.19.0`), as `mars.toml` documents both fields.
11pub fn parse_requirement(raw: &str) -> Result<VersionReq, semver::Error> {
12    let raw = raw.trim();
13    let parts: Vec<&str> = raw.split('.').collect();
14    let normalized = if (1..=3).contains(&parts.len())
15        && parts
16            .iter()
17            .all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()))
18    {
19        let mut parts = parts;
20        while parts.len() < 3 {
21            parts.push("0");
22        }
23        format!(">={}", parts.join("."))
24    } else {
25        raw.to_string()
26    };
27    VersionReq::parse(&normalized)
28}
29
30/// Each of `requires-mars` and `requires-meridian` that is set and is not a version requirement:
31/// the key and why.
32pub fn requirement_errors(package: &PackageMetadata) -> Vec<(&'static str, String)> {
33    [
34        ("requires-mars", "mars", package.requires_mars.as_deref()),
35        (
36            "requires-meridian",
37            "meridian",
38            package.requires_meridian.as_deref(),
39        ),
40    ]
41    .into_iter()
42    .filter_map(|(key, engine, raw)| {
43        let raw = raw?;
44        let error = parse_requirement(raw).err()?;
45        Some((
46            key,
47            format!(
48                "invalid {engine} version requirement `{}` in package `{}`: {error}",
49                raw.trim(),
50                package.name
51            ),
52        ))
53    })
54    .collect()
55}
56
57/// Whether `running` meets `requirement`. A prerelease or build of a Mars meets what its release
58/// does: `0.31.0-rc.1` runs a project that asks for `0.31.0`.
59pub fn requirement_matches(requirement: &VersionReq, running: &Version) -> bool {
60    let mut stable = running.clone();
61    stable.pre = semver::Prerelease::EMPTY;
62    stable.build = semver::BuildMetadata::EMPTY;
63    requirement.matches(&stable)
64}
65
66/// Whether `requirement` demands at least `floor`, so a Mars older than one floor cannot read
67/// the package. A range with no lower bound (`<0.25`) does not; an unparseable one cannot say.
68pub fn requirement_has_floor(requirement: Option<&str>, floor: &Version) -> bool {
69    let Some(raw) = requirement else {
70        return false;
71    };
72    let Ok(requirement) = parse_requirement(raw) else {
73        return false;
74    };
75    requirement
76        .comparators
77        .iter()
78        .any(|comparator| comparator_floor(comparator).is_some_and(|minimum| minimum >= *floor))
79}
80
81fn comparator_floor(comparator: &semver::Comparator) -> Option<Version> {
82    use semver::Op;
83
84    // Partial strict bounds advance to the next specified component: `>0.18`
85    // means `>=0.19.0`, unlike the fully specified `>0.18.0`.
86    let (major, minor, patch) = match comparator.op {
87        Op::Greater if comparator.minor.is_none() => (comparator.major.checked_add(1)?, 0, 0),
88        Op::Greater if comparator.patch.is_none() => {
89            (comparator.major, comparator.minor?.checked_add(1)?, 0)
90        }
91        Op::Exact | Op::Greater | Op::GreaterEq | Op::Tilde | Op::Caret | Op::Wildcard => (
92            comparator.major,
93            comparator.minor.unwrap_or(0),
94            comparator.patch.unwrap_or(0),
95        ),
96        _ => return None,
97    };
98    let mut version = Version::new(major, minor, patch);
99    version.pre = comparator.pre.clone();
100    Some(version)
101}
102
103/// `requirement` with its lower bound raised to `floor` and every other bound kept
104/// (`>=0.20.0, <1.0.0` becomes `>=0.30.0, <1.0.0`), or `None` when the lower bound is not a
105/// plain `>=` comparator or a bare version that can be replaced without guessing (`^0.20`, `~0.20`).
106pub fn raised_requirement(requirement: &str, floor: &Floor) -> Option<String> {
107    let new = floor.requirement();
108    let parts: Vec<&str> = requirement.split(',').map(str::trim).collect();
109    let bare = |part: &str| {
110        parts.len() == 1 && parse_requirement(part).is_ok() && {
111            part.chars().all(|c| c.is_ascii_digit() || c == '.')
112        }
113    };
114    let lower = parts
115        .iter()
116        .position(|part| part.starts_with(">=") || bare(part))?;
117    let mut raised = parts.clone();
118    if parts
119        .iter()
120        .enumerate()
121        .any(|(at, part)| at != lower && (part.starts_with(">=") || part.starts_with('>')))
122    {
123        return None;
124    }
125    raised[lower] = &new;
126    Some(raised.join(", "))
127}
128
129/// The error for a `requires-mars` that does not state `floor`, naming the key that sets it and
130/// the line to write. `None` when it does, or when it is not a requirement this Mars can read: a
131/// broken requirement is its own error.
132pub fn requires_mars_shortfall(requirement: Option<&str>, floor: &Floor) -> Option<String> {
133    if let Some(raw) = requirement {
134        parse_requirement(raw).ok()?;
135    }
136    if requirement_has_floor(requirement, &floor.since.version()) {
137        return None;
138    }
139    let written = requirement
140        .and_then(|raw| raised_requirement(raw, floor))
141        .unwrap_or_else(|| floor.requirement());
142    let line = format!("requires-mars = \"{written}\"");
143    let stated = match requirement {
144        Some(raw) => format!(
145            "`requires-mars = \"{raw}\"` admits a Mars before {}",
146            floor.since
147        ),
148        None => "`requires-mars` is not set".to_string(),
149    };
150    Some(format!(
151        "[package] {stated}, but {} needs Mars {}: write `{line}`",
152        floor.at, floor.since
153    ))
154}
155
156/// Package metadata carried by `mars.toml`.
157#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
158pub struct PackageMetadata {
159    pub name: String,
160    #[serde(default)]
161    pub version: String,
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub description: Option<String>,
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub authors: Option<toml::Value>,
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub homepage: Option<toml::Value>,
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub license: Option<toml::Value>,
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub schema: Option<u64>,
172    #[serde(
173        default,
174        rename = "uses-providers",
175        skip_serializing_if = "Vec::is_empty"
176    )]
177    pub uses_providers: Vec<String>,
178    #[serde(
179        default,
180        rename = "requires-mars",
181        skip_serializing_if = "Option::is_none"
182    )]
183    pub requires_mars: Option<String>,
184    #[serde(
185        default,
186        rename = "requires-meridian",
187        skip_serializing_if = "Option::is_none"
188    )]
189    pub requires_meridian: Option<String>,
190    /// Rules that act as if each entry were written in the `tools:` map of every agent this
191    /// package ships; a key the profile already has keeps the profile's action.
192    #[serde(default, skip_serializing_if = "ToolRuleMap::is_empty")]
193    pub tools: ToolRuleMap,
194}
195
196/// The schema dispatch result for a package root's optional `mars.toml`.
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub enum ManifestClassification {
199    Schema1,
200    SchemaNewer {
201        schema: u64,
202    },
203    /// A `[package]` with no `schema`: a package written before schema 1.
204    NoSchema,
205    /// A `mars.toml` with no `[package]`: a consumer project's configuration, which makes the
206    /// directory a project and not a package.
207    ConsumerConfig,
208    Invalid {
209        message: String,
210    },
211    NoManifest,
212}
213
214/// Classify manifest bytes before any package content is lifted or discovered.
215pub fn classify_manifest(bytes: Option<&[u8]>) -> ManifestClassification {
216    let Some(bytes) = bytes else {
217        return ManifestClassification::NoManifest;
218    };
219    let text = match std::str::from_utf8(bytes) {
220        Ok(text) => text,
221        Err(error) => {
222            return ManifestClassification::Invalid {
223                message: format!("mars.toml is not UTF-8: {error}"),
224            };
225        }
226    };
227    let manifest: toml::Value = match toml::from_str(text) {
228        Ok(manifest) => manifest,
229        Err(error) => {
230            return ManifestClassification::Invalid {
231                message: format!("failed to parse mars.toml: {error}"),
232            };
233        }
234    };
235    let Some(package) = manifest.get("package") else {
236        return ManifestClassification::ConsumerConfig;
237    };
238    let Some(package) = package.as_table() else {
239        return ManifestClassification::Invalid {
240            message: "mars.toml at a package root must contain [package]".to_string(),
241        };
242    };
243    let Some(schema) = package.get("schema") else {
244        return ManifestClassification::NoSchema;
245    };
246    let Some(schema) = schema
247        .as_integer()
248        .and_then(|value| u64::try_from(value).ok())
249    else {
250        return ManifestClassification::Invalid {
251            message: "[package] schema must be a positive integer".to_string(),
252        };
253    };
254    match schema {
255        0 => ManifestClassification::Invalid {
256            message: "[package] schema must be a positive integer".to_string(),
257        },
258        1 => ManifestClassification::Schema1,
259        schema => ManifestClassification::SchemaNewer { schema },
260    }
261}