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