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::tool_rule_map::ToolRuleMap;
7
8/// The first Mars release that reads schema 1. An older one reads a `schema = 1` package as
9/// pre-v1, so a schema v1 package's `requires-mars` may not admit one.
10pub const SCHEMA_1_MARS_FLOOR: &str = "0.20.0";
11
12/// Parse a `requires-mars` or `requires-meridian` requirement. A bare version means `>=` it
13/// (`0.19.0` is `>=0.19.0`), as `mars.toml` documents both fields.
14pub fn parse_requirement(raw: &str) -> Result<VersionReq, semver::Error> {
15    let raw = raw.trim();
16    let parts: Vec<&str> = raw.split('.').collect();
17    let normalized = if (1..=3).contains(&parts.len())
18        && parts
19            .iter()
20            .all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()))
21    {
22        let mut parts = parts;
23        while parts.len() < 3 {
24            parts.push("0");
25        }
26        format!(">={}", parts.join("."))
27    } else {
28        raw.to_string()
29    };
30    VersionReq::parse(&normalized)
31}
32
33/// Whether `requirement` demands at least `floor`, so a Mars older than one floor cannot read
34/// the package. A range with no lower bound (`<0.25`) does not; an unparseable one cannot say.
35pub fn requirement_has_floor(requirement: Option<&str>, floor: &Version) -> bool {
36    let Some(raw) = requirement else {
37        return false;
38    };
39    let Ok(requirement) = parse_requirement(raw) else {
40        return false;
41    };
42    requirement
43        .comparators
44        .iter()
45        .any(|comparator| comparator_floor(comparator).is_some_and(|minimum| minimum >= *floor))
46}
47
48fn comparator_floor(comparator: &semver::Comparator) -> Option<Version> {
49    use semver::Op;
50
51    // Partial strict bounds advance to the next specified component: `>0.18`
52    // means `>=0.19.0`, unlike the fully specified `>0.18.0`.
53    let (major, minor, patch) = match comparator.op {
54        Op::Greater if comparator.minor.is_none() => (comparator.major.checked_add(1)?, 0, 0),
55        Op::Greater if comparator.patch.is_none() => {
56            (comparator.major, comparator.minor?.checked_add(1)?, 0)
57        }
58        Op::Exact | Op::Greater | Op::GreaterEq | Op::Tilde | Op::Caret | Op::Wildcard => (
59            comparator.major,
60            comparator.minor.unwrap_or(0),
61            comparator.patch.unwrap_or(0),
62        ),
63        _ => return None,
64    };
65    let mut version = Version::new(major, minor, patch);
66    version.pre = comparator.pre.clone();
67    Some(version)
68}
69
70/// The advice `mars check` prints for a schema v1 package's `requires-mars`, which `mars migrate`
71/// prints with it when it leaves an authored requirement alone.
72pub fn schema_1_requires_mars_warning(requirement: Option<&str>) -> Option<String> {
73    requires_mars_floor_warning(
74        requirement,
75        SCHEMA_1_MARS_FLOOR,
76        "older Mars versions read a `schema = 1` package as pre-v1; a floor keeps them on the last release they can read",
77    )
78}
79
80/// The advice for a requirement that is missing or admits a Mars older than `floor`. `None` when
81/// it does not, or when it is not a requirement this Mars can read: a broken requirement is its
82/// own error.
83pub fn requires_mars_floor_warning(
84    requirement: Option<&str>,
85    floor: &str,
86    reason: &str,
87) -> Option<String> {
88    if let Some(raw) = requirement {
89        parse_requirement(raw).ok()?;
90    }
91    let floor = Version::parse(floor).expect("a Mars floor is valid semver");
92    (!requirement_has_floor(requirement, &floor)).then(|| {
93        format!("[package] `requires-mars` should be `\">={floor}\"` or a higher floor; {reason}")
94    })
95}
96
97/// Package metadata carried by `mars.toml`.
98#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
99pub struct PackageMetadata {
100    pub name: String,
101    #[serde(default)]
102    pub version: String,
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub description: Option<String>,
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub authors: Option<toml::Value>,
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub homepage: Option<toml::Value>,
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub license: Option<toml::Value>,
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub schema: Option<u64>,
113    #[serde(
114        default,
115        rename = "uses-providers",
116        skip_serializing_if = "Vec::is_empty"
117    )]
118    pub uses_providers: Vec<String>,
119    #[serde(
120        default,
121        rename = "requires-mars",
122        skip_serializing_if = "Option::is_none"
123    )]
124    pub requires_mars: Option<String>,
125    #[serde(
126        default,
127        rename = "requires-meridian",
128        skip_serializing_if = "Option::is_none"
129    )]
130    pub requires_meridian: Option<String>,
131    /// Rules that act as if each entry were written in the `tools:` map of every agent this
132    /// package ships; a key the profile already has keeps the profile's action.
133    #[serde(default, skip_serializing_if = "ToolRuleMap::is_empty")]
134    pub tools: ToolRuleMap,
135}
136
137/// The schema dispatch result for a package root's optional `mars.toml`.
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub enum ManifestClassification {
140    Schema1,
141    SchemaNewer {
142        schema: u64,
143    },
144    MarsLegacy,
145    /// A `mars.toml` with no `[package]`: a consumer project's configuration, which makes the
146    /// directory a project and not a package.
147    ConsumerConfig,
148    Invalid {
149        message: String,
150    },
151    NoManifest,
152}
153
154/// Classify manifest bytes before any package content is lifted or discovered.
155pub fn classify_manifest(bytes: Option<&[u8]>) -> ManifestClassification {
156    let Some(bytes) = bytes else {
157        return ManifestClassification::NoManifest;
158    };
159    let text = match std::str::from_utf8(bytes) {
160        Ok(text) => text,
161        Err(error) => {
162            return ManifestClassification::Invalid {
163                message: format!("mars.toml is not UTF-8: {error}"),
164            };
165        }
166    };
167    let manifest: toml::Value = match toml::from_str(text) {
168        Ok(manifest) => manifest,
169        Err(error) => {
170            return ManifestClassification::Invalid {
171                message: format!("failed to parse mars.toml: {error}"),
172            };
173        }
174    };
175    let Some(package) = manifest.get("package") else {
176        return ManifestClassification::ConsumerConfig;
177    };
178    let Some(package) = package.as_table() else {
179        return ManifestClassification::Invalid {
180            message: "mars.toml at a package root must contain [package]".to_string(),
181        };
182    };
183    let Some(schema) = package.get("schema") else {
184        return ManifestClassification::MarsLegacy;
185    };
186    let Some(schema) = schema
187        .as_integer()
188        .and_then(|value| u64::try_from(value).ok())
189    else {
190        return ManifestClassification::Invalid {
191            message: "[package] schema must be a positive integer".to_string(),
192        };
193    };
194    match schema {
195        0 => ManifestClassification::Invalid {
196            message: "[package] schema must be a positive integer".to_string(),
197        },
198        1 => ManifestClassification::Schema1,
199        schema => ManifestClassification::SchemaNewer { schema },
200    }
201}