1use semver::{Version, VersionReq};
4use serde::{Deserialize, Serialize};
5
6use crate::keys::Floor;
7use crate::tool_rule_map::ToolRuleMap;
8
9pub 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
30pub 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
57pub 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
66pub 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 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
103pub 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
129pub 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#[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 #[serde(default, skip_serializing_if = "ToolRuleMap::is_empty")]
193 pub tools: ToolRuleMap,
194}
195
196#[derive(Debug, Clone, PartialEq, Eq)]
198pub enum ManifestClassification {
199 Schema1,
200 SchemaNewer {
201 schema: u64,
202 },
203 NoSchema,
205 ConsumerConfig,
208 Invalid {
209 message: String,
210 },
211 NoManifest,
212}
213
214pub 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}