Skip to main content

release_kit/landing/
manifest.rs

1//! The landing record: `.release-kit/manifest.json`.
2//!
3//! The record is a manifest, not a stamp: `rk status` and `rk upgrade`
4//! make decisions from it, so it earns a parser that can fail and a
5//! stated schema version — an unknown shape refuses naming the record,
6//! never a best-effort read. It is written last, after every file has
7//! landed, through the temp-plus-rename writer, and it is committed:
8//! every reader it exists for sees only committed files, and it carries
9//! digests of committed files, nothing secret and nothing
10//! machine-specific.
11
12use std::collections::BTreeMap;
13
14use camino::Utf8Path;
15use serde::{Deserialize, Serialize};
16
17use crate::atomic;
18use crate::diagnostic::{Diagnostic, Reason};
19use crate::digest::Digest;
20use crate::error::RkError;
21use crate::landing::Kind;
22
23/// Where the record lives, relative to the target root.
24pub const MANIFEST_PATH: &str = ".release-kit/manifest.json";
25
26/// The schema this binary writes.
27///
28/// It also reads schema 1 — the pre-mode record, whose absent `workflow`
29/// parameter reads as `branches` — schema 2 — the pre-style record,
30/// whose absent `style` parameter reads as none and holds an upgrade
31/// until `--style` names one — and schema 3 — the pre-nix record, whose
32/// absent `nix` parameter reads as opt-out, so an existing target's
33/// upgrade never sprouts files nobody requested — and schema 4 — the
34/// scope-vocabulary record, whose `scopes` parameter this binary renders
35/// nowhere, so a read drops it and the next rewrite lands without it —
36/// and schema 5 — the pre-policy record, whose absent security parameters
37/// read as the empty contact and the best-effort stance, which is exactly
38/// what such a landing wrote into `SECURITY.md`, so its bytes reproduce —
39/// and refuses anything else by name.
40pub const SCHEMA_VERSION: u64 = 6;
41
42/// The oldest schema this binary still reads.
43const OLDEST_READABLE_SCHEMA: u64 = 1;
44
45/// The working-copy mode a landing records: a project decision, rendered
46/// into the landed blocks and changed only through the landing verbs.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "lowercase")]
49pub enum Workflow {
50    /// Every code-changing branch lives in a linked worktree and the main
51    /// checkout commits nothing.
52    Worktree,
53    /// Branches are worked in the main checkout; worktrees stay available
54    /// beside them and nothing refuses either form.
55    Branches,
56}
57
58impl Workflow {
59    /// The flag, wire, and report form.
60    #[must_use]
61    pub const fn as_str(self) -> &'static str {
62        match self {
63            Self::Worktree => "worktree",
64            Self::Branches => "branches",
65        }
66    }
67
68    /// Parse a `--workflow` flag value.
69    ///
70    /// # Errors
71    ///
72    /// Returns [`RkError::Usage`] naming the two values.
73    pub fn parse(raw: &str) -> Result<Self, RkError> {
74        match raw {
75            "worktree" => Ok(Self::Worktree),
76            "branches" => Ok(Self::Branches),
77            other => Err(RkError::Usage(format!(
78                "unknown workflow '{other}'; the modes are: worktree, branches"
79            ))),
80        }
81    }
82}
83
84/// The serde default for a record from before the parameter existed.
85const fn workflow_branches() -> Workflow {
86    Workflow::Branches
87}
88
89/// The release style a landing records.
90///
91/// Whether the bot's release request stands armed to merge itself: a
92/// project decision, rendered into the landed release workflow and
93/// changed only through the landing verbs.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(rename_all = "lowercase")]
96pub enum Style {
97    /// The trunk style: the release request carries auto-merge from
98    /// creation, so a green trunk ships itself.
99    Trunk,
100    /// The lines style: every request waits for a human's merge, because
101    /// a line's candidate is validated by hand.
102    Lines,
103}
104
105impl Style {
106    /// The flag, wire, and report form.
107    #[must_use]
108    pub const fn as_str(self) -> &'static str {
109        match self {
110            Self::Trunk => "trunk",
111            Self::Lines => "lines",
112        }
113    }
114
115    /// Parse a `--style` flag value.
116    ///
117    /// # Errors
118    ///
119    /// Returns [`RkError::Usage`] naming the two values.
120    pub fn parse(raw: &str) -> Result<Self, RkError> {
121        match raw {
122            "trunk" => Ok(Self::Trunk),
123            "lines" => Ok(Self::Lines),
124            other => Err(RkError::Usage(format!(
125                "unknown style '{other}'; the styles are: trunk, lines"
126            ))),
127        }
128    }
129}
130
131/// The record a landing writes and every target-side verb reads.
132#[derive(Debug, Serialize, Deserialize)]
133pub struct Manifest {
134    /// An integer this binary either knows or refuses on.
135    pub schema_version: u64,
136    /// The binary that produced the landing.
137    pub rk_version: String,
138    /// The aggregate payload digest from `rk payload`: which payload
139    /// actually landed, where the version alone is ambiguous.
140    pub payload_sha256: Digest,
141    /// `init` or `adopt` — how the record came to exist.
142    pub origin: String,
143    /// The technology that selected the payload.
144    pub tech: String,
145    /// The forge that selected the payload.
146    pub forge: String,
147    /// When the first landing happened; an upgrade preserves it.
148    pub landed_at: String,
149    /// Every value substituted into a `rendered` file, so a re-render is
150    /// reproducible without asking again.
151    pub parameters: Parameters,
152    /// Every landed destination with its kind and digests.
153    pub files: Vec<FileRecord>,
154    /// The registry pins the landed technology uses, copied at landing
155    /// time; `rk status` compares them offline.
156    pub pins: BTreeMap<String, String>,
157}
158
159/// The landing parameters, recorded whole.
160#[derive(Debug, Serialize, Deserialize)]
161pub struct Parameters {
162    /// The project path on the forge, recorded whole because a GitLab
163    /// project may nest below its group.
164    pub repo: String,
165    /// The working-copy mode the project chose: every code-changing branch
166    /// in a linked worktree (`worktree`), or branches worked in the main
167    /// checkout with worktrees optional beside them (`branches`). A record
168    /// predating the field reads as `branches`, so an upgrade never imposes
169    /// a guard the project did not choose.
170    #[serde(default = "workflow_branches")]
171    pub workflow: Workflow,
172    /// The release style the project chose: the bot's request armed to
173    /// merge itself (`trunk`), or every merge a human's (`lines`). A
174    /// record predating the field carries none, and an upgrade refuses
175    /// until `--style` names one: neither value is a compatibility-safe
176    /// reading of a target nobody asked.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub style: Option<Style>,
179    /// Whether the landing carries the Nix capability: the seeded package
180    /// expression, the flake pair where the target had none, and the
181    /// workflow that proves the build. A record predating the field reads
182    /// as opt-out, so an upgrade adds nothing unrequested; the projection
183    /// stays reproducible from the record because this field is part of
184    /// it.
185    #[serde(default)]
186    pub nix: bool,
187    /// The one permanent branch, rendered into every landed artifact that
188    /// names it. A record predating the field reads as `master`, which is
189    /// what such a landing wrote, so the projection stays reproducible.
190    #[serde(default = "trunk_master")]
191    pub trunk: String,
192    /// The release-line branch prefix, rendered into the release triggers
193    /// and branch guards. A record predating the field reads as
194    /// `release/`, which is what such a landing wrote.
195    #[serde(default = "line_prefix_release")]
196    pub line_prefix: String,
197    /// The contact the landed policy names where the forge's own channel
198    /// is unavailable, empty for the forge's authored wording. A record
199    /// predating the field reads as empty, which is what such a landing
200    /// wrote.
201    #[serde(default, deserialize_with = "read_contact")]
202    pub security_contact: String,
203    /// The acknowledgment window the landed policy promises. A record
204    /// predating the field reads as `best-effort`, which is what such a
205    /// landing wrote.
206    #[serde(default = "response_best_effort", deserialize_with = "read_response")]
207    pub security_response: String,
208}
209
210/// The trunk a record predating the field carries.
211fn trunk_master() -> String {
212    crate::config::TRUNK_DEFAULT.to_owned()
213}
214
215/// The prefix a record predating the field carries.
216fn line_prefix_release() -> String {
217    crate::config::LINE_PREFIX_DEFAULT.to_owned()
218}
219
220/// The stance a record predating the field carries.
221fn response_best_effort() -> String {
222    crate::config::RESPONSE_DEFAULT.to_owned()
223}
224
225/// A recorded contact, refused where the configuration reader would refuse
226/// it or where it is not already canonical.
227///
228/// The record is the one input a re-render reads, so a hand-edited record
229/// must not reach bytes the configured path could never have produced.
230fn read_contact<'de, D: serde::Deserializer<'de>>(reader: D) -> Result<String, D::Error> {
231    canonical(reader, "security_contact", crate::config::canonical_contact)
232}
233
234/// A recorded response stance, held to the same grammar as the key.
235fn read_response<'de, D: serde::Deserializer<'de>>(reader: D) -> Result<String, D::Error> {
236    canonical(
237        reader,
238        "security_response",
239        crate::config::canonical_response,
240    )
241}
242
243/// One recorded string held to its canonical form.
244fn canonical<'de, D: serde::Deserializer<'de>>(
245    reader: D,
246    field: &str,
247    judge: impl Fn(&str) -> Result<String, String>,
248) -> Result<String, D::Error> {
249    let raw = String::deserialize(reader)?;
250    let canonical = judge(&raw)
251        .map_err(|reason| serde::de::Error::custom(format!("parameters.{field}: {reason}")))?;
252    if canonical == raw {
253        Ok(canonical)
254    } else {
255        Err(serde::de::Error::custom(format!(
256            "parameters.{field} is not canonical: the record carries {raw:?} where a landing writes {canonical:?}"
257        )))
258    }
259}
260
261/// One landed destination.
262#[derive(Debug, Serialize, Deserialize)]
263pub struct FileRecord {
264    /// The destination, relative to the target root.
265    pub destination: String,
266    /// The declared ownership kind.
267    pub kind: Kind,
268    /// The digest of what was written — after substitution for a
269    /// `rendered` file, of the marked block for `AGENTS.md`.
270    pub sha256: Digest,
271    /// The digest of the bytes this file's comparisons start from — what
272    /// makes the three-way comparison at upgrade possible. For a
273    /// `rendered` file, the payload as it stood at landing, before
274    /// substitution; for a `seeded` file, the starting point the target
275    /// tunes away from — the seeding payload, or, where a later payload
276    /// reclassified the file from `rendered`, the rendered bytes
277    /// release-kit last wrote. Absent for `state` files, which are never
278    /// compared.
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub baseline_sha256: Option<Digest>,
281}
282
283impl Manifest {
284    /// The recorded entry for one destination, where the record names it.
285    #[must_use]
286    pub fn file(&self, destination: &str) -> Option<&FileRecord> {
287        self.files
288            .iter()
289            .find(|file| file.destination == destination)
290    }
291}
292
293/// Read the record at `target`, or `None` where no landing exists.
294///
295/// # Errors
296///
297/// The record's stated failure taxonomy: an unreadable record is a
298/// refusal naming it, a record at an unknown `schema_version` is a
299/// refusal naming the record, and one that does not parse at a known
300/// schema is a defect-class failure.
301pub fn load(target: &Utf8Path) -> Result<Option<Manifest>, RkError> {
302    let path = target.join(MANIFEST_PATH);
303    let bytes = match std::fs::read(&path) {
304        Ok(bytes) => bytes,
305        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
306        Err(e) => {
307            return Err(RkError::refusal(
308                Diagnostic::new(Reason::Io, format!("cannot read {path}: {e}"))
309                    .expected("a readable landing record")
310                    .target_state("unchanged"),
311            ));
312        }
313    };
314    let value: serde_json::Value = serde_json::from_slice(&bytes)
315        .map_err(|e| anyhow::anyhow!("{path} is not a landing record: {e}"))?;
316    // Schema 1 is the pre-mode record: it parses through the same
317    // `Parameters`, whose serde default reads the absent `workflow` as
318    // `branches`. Anything past this binary's schema refuses by name —
319    // the record decides whether a guard is landed, and an older binary
320    // must never silently ignore that.
321    let schema = value
322        .get("schema_version")
323        .and_then(serde_json::Value::as_u64);
324    if !schema.is_some_and(|version| (OLDEST_READABLE_SCHEMA..=SCHEMA_VERSION).contains(&version)) {
325        let found = schema.map_or_else(|| "none".to_owned(), |version| version.to_string());
326        return Err(RkError::refusal(
327            Diagnostic::new(
328                Reason::UnsupportedSchema,
329                format!(
330                    "{path} declares schema_version {found}, and this binary knows only {OLDEST_READABLE_SCHEMA} through {SCHEMA_VERSION}"
331                ),
332            )
333            .expected("a record this binary can read")
334            .action("run the rk release that wrote this record, or a newer one")
335            .target_state("unchanged"),
336        ));
337    }
338    let declared = schema.unwrap_or(SCHEMA_VERSION);
339    let manifest: Manifest = serde_json::from_value(value)
340        .map_err(|e| anyhow::anyhow!("{path} does not parse at schema_version {declared}: {e}"))?;
341    Ok(Some(manifest))
342}
343
344/// Write the record, last, through the temp-plus-rename writer.
345///
346/// # Errors
347///
348/// Any write failure; the destination then holds what it held.
349pub fn write(target: &Utf8Path, manifest: &Manifest) -> Result<(), RkError> {
350    let text = serde_json::to_string_pretty(manifest).map_err(anyhow::Error::from)?;
351    let path = target.join(MANIFEST_PATH);
352    atomic::write(path.as_std_path(), format!("{text}\n").as_bytes())?;
353    Ok(())
354}
355
356/// The current instant in the record's RFC 3339 form.
357#[must_use]
358pub fn now() -> String {
359    humantime::format_rfc3339_seconds(std::time::SystemTime::now()).to_string()
360}
361
362/// How a record's `rk_version` stands against this binary's.
363#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
364#[serde(rename_all = "kebab-case")]
365pub enum Alignment {
366    /// The landing came from this binary's version.
367    Aligned,
368    /// The binary is newer; `rk upgrade` takes the target forward.
369    BinaryNewer,
370    /// The landing came from a newer `rk` than this one, which an upgrade
371    /// refuses rather than downgrading.
372    TargetNewer,
373}
374
375impl Alignment {
376    /// The wire form, identical to the serde rendering.
377    #[must_use]
378    pub const fn as_str(self) -> &'static str {
379        match self {
380            Self::Aligned => "aligned",
381            Self::BinaryNewer => "binary-newer",
382            Self::TargetNewer => "target-newer",
383        }
384    }
385}
386
387/// Compare a record's version against this binary's.
388#[must_use]
389pub fn alignment(recorded: &str, binary: &str) -> Alignment {
390    // Build metadata after `+` carries no precedence.
391    let recorded = recorded
392        .split_once('+')
393        .map_or(recorded, |(version, _)| version);
394    let binary = binary
395        .split_once('+')
396        .map_or(binary, |(version, _)| version);
397    let recorded_core = numeric_core(recorded);
398    let binary_core = numeric_core(binary);
399    match binary_core.cmp(&recorded_core) {
400        std::cmp::Ordering::Greater => Alignment::BinaryNewer,
401        std::cmp::Ordering::Less => Alignment::TargetNewer,
402        std::cmp::Ordering::Equal => {
403            // Equal numeric cores: a pre-release is older than the plain
404            // release it precedes, and two pre-releases compare by semver
405            // precedence — dot-separated identifiers, numeric ones
406            // numerically and below alphanumeric ones.
407            let recorded_pre = recorded.split_once('-').map(|(_, pre)| pre);
408            let binary_pre = binary.split_once('-').map(|(_, pre)| pre);
409            match (recorded_pre, binary_pre) {
410                (Some(_), None) => Alignment::BinaryNewer,
411                (None, Some(_)) => Alignment::TargetNewer,
412                (None, None) => Alignment::Aligned,
413                (Some(r), Some(b)) => match prerelease_cmp(b, r) {
414                    std::cmp::Ordering::Greater => Alignment::BinaryNewer,
415                    std::cmp::Ordering::Less => Alignment::TargetNewer,
416                    std::cmp::Ordering::Equal => Alignment::Aligned,
417                },
418            }
419        }
420    }
421}
422
423/// Whether `candidate` is ahead of `pinned`, by the same ordering the
424/// alignment uses.
425#[must_use]
426pub fn version_is_newer(candidate: &str, pinned: &str) -> bool {
427    alignment(pinned, candidate) == Alignment::BinaryNewer
428}
429
430/// Semver pre-release precedence: identifier by identifier, numeric ones
431/// numerically and below any alphanumeric one, and — all preceding
432/// identifiers equal — the longer list wins. An all-digit identifier
433/// compares by digit count and then lexically, which is numeric order at
434/// any length — semver forbids leading zeroes — so no integer parse can
435/// overflow into a wrong answer.
436fn prerelease_cmp(a: &str, b: &str) -> std::cmp::Ordering {
437    let numeric = |identifier: &str| identifier.bytes().all(|byte| byte.is_ascii_digit());
438    let mut left = a.split('.');
439    let mut right = b.split('.');
440    loop {
441        match (left.next(), right.next()) {
442            (None, None) => return std::cmp::Ordering::Equal,
443            (None, Some(_)) => return std::cmp::Ordering::Less,
444            (Some(_), None) => return std::cmp::Ordering::Greater,
445            (Some(x), Some(y)) => {
446                let ordering = match (numeric(x), numeric(y)) {
447                    (true, true) => x.len().cmp(&y.len()).then_with(|| x.cmp(y)),
448                    (true, false) => std::cmp::Ordering::Less,
449                    (false, true) => std::cmp::Ordering::Greater,
450                    (false, false) => x.cmp(y),
451                };
452                if ordering != std::cmp::Ordering::Equal {
453                    return ordering;
454                }
455            }
456        }
457    }
458}
459
460/// The dotted numeric components before any pre-release suffix.
461fn numeric_core(version: &str) -> Vec<u64> {
462    let core = version.split_once('-').map_or(version, |(core, _)| core);
463    core.split('.')
464        .map(|part| part.parse::<u64>().unwrap_or(0))
465        .collect()
466}
467
468#[cfg(test)]
469mod tests {
470    use super::{Alignment, FileRecord, Manifest, Parameters, Style, Workflow, alignment};
471    use crate::digest::Digest;
472    use crate::landing::Kind;
473
474    /// The complete record shape at schema 6, held by snapshot: a field
475    /// rename or removal fails here and becomes a schema-version bump
476    /// instead of a silent break at every reader.
477    #[test]
478    fn the_manifest_schema_snapshot_holds() {
479        let manifest = Manifest {
480            schema_version: 6,
481            rk_version: "0.1.0".into(),
482            payload_sha256: Digest::of(b""),
483            origin: "init".into(),
484            tech: "rust".into(),
485            forge: "github".into(),
486            landed_at: "2026-08-29T00:00:00Z".into(),
487            parameters: Parameters {
488                repo: "acme/widget".into(),
489                workflow: Workflow::Worktree,
490                style: Some(Style::Trunk),
491                nix: true,
492                trunk: crate::config::TRUNK_DEFAULT.to_owned(),
493                line_prefix: crate::config::LINE_PREFIX_DEFAULT.to_owned(),
494                security_contact: String::new(),
495                security_response: crate::config::RESPONSE_DEFAULT.to_owned(),
496            },
497            files: vec![
498                FileRecord {
499                    destination: "release-plz.toml".into(),
500                    kind: Kind::Seeded,
501                    sha256: Digest::of(b""),
502                    baseline_sha256: Some(Digest::of(b"")),
503                },
504                FileRecord {
505                    destination: "VERSION".into(),
506                    kind: Kind::State,
507                    sha256: Digest::of(b""),
508                    baseline_sha256: None,
509                },
510            ],
511            pins: std::iter::once(("release-plz".to_owned(), "0.3.160".to_owned())).collect(),
512        };
513        let empty = Digest::of(b"").to_string();
514        assert_eq!(
515            serde_json::to_string(&manifest).expect("a manifest serializes"),
516            format!(
517                r#"{{"schema_version":6,"rk_version":"0.1.0","payload_sha256":"{empty}","origin":"init","tech":"rust","forge":"github","landed_at":"2026-08-29T00:00:00Z","parameters":{{"repo":"acme/widget","workflow":"worktree","style":"trunk","nix":true,"trunk":"master","line_prefix":"release/","security_contact":"","security_response":"best-effort"}},"files":[{{"destination":"release-plz.toml","kind":"seeded","sha256":"{empty}","baseline_sha256":"{empty}"}},{{"destination":"VERSION","kind":"state","sha256":"{empty}"}}],"pins":{{"release-plz":"0.3.160"}}}}"#
518            ),
519            "a state file must omit baseline_sha256 rather than serializing null"
520        );
521    }
522
523    /// A record written before the mode existed reads as `branches`, and
524    /// its scope vocabulary drops, because this binary renders none. A
525    /// record past this binary's schema refuses by name, because the field
526    /// it cannot see decides whether a guard is landed.
527    #[test]
528    fn a_schema_1_record_reads_as_branches_and_a_newer_schema_refuses() {
529        let dir = tempfile::tempdir().expect("a scratch target exists");
530        let target = camino::Utf8Path::from_path(dir.path()).expect("utf-8 path");
531        std::fs::create_dir_all(target.join(".release-kit")).expect("the record dir writes");
532        let record = |schema: u64| {
533            format!(
534                r#"{{"schema_version":{schema},"rk_version":"0.1.0","payload_sha256":"0000000000000000000000000000000000000000000000000000000000000000","origin":"init","tech":"rust","forge":"github","landed_at":"2026-08-29T00:00:00Z","parameters":{{"repo":"acme/widget","scopes":["api"]}},"files":[],"pins":{{}}}}"#
535            )
536        };
537        std::fs::write(target.join(super::MANIFEST_PATH), record(1)).expect("the record writes");
538        let manifest = super::load(target)
539            .expect("a schema-1 record loads")
540            .expect("the record exists");
541        assert_eq!(manifest.parameters.workflow, Workflow::Branches);
542        assert_eq!(
543            manifest.parameters.style, None,
544            "a pre-style record carries no style; the upgrade demands one"
545        );
546        assert!(
547            !manifest.parameters.nix,
548            "a pre-nix record reads as opt-out, so an upgrade adds nothing unrequested"
549        );
550        assert_eq!(
551            manifest.parameters.security_contact, "",
552            "a pre-policy record names no contact, which is what its policy landed"
553        );
554        assert_eq!(
555            manifest.parameters.security_response,
556            crate::config::RESPONSE_DEFAULT,
557            "a pre-policy record promises no window, which is what its policy landed"
558        );
559
560        std::fs::write(target.join(super::MANIFEST_PATH), record(7)).expect("the record writes");
561        let refused = super::load(target).expect_err("a schema-7 record refuses");
562        let message = refused.to_string();
563        assert!(message.contains('7'), "{message}");
564    }
565
566    /// The record is the one input a re-render reads, so a hand-edited
567    /// record must not reach bytes the configured path could never write:
568    /// a value the configuration reader refuses, and a value it would
569    /// canonicalize, both refuse at deserialization.
570    #[test]
571    fn a_record_carrying_an_uncanonical_security_parameter_refuses() {
572        let dir = tempfile::tempdir().expect("a scratch target exists");
573        let target = camino::Utf8Path::from_path(dir.path()).expect("utf-8 path");
574        std::fs::create_dir_all(target.join(".release-kit")).expect("the record dir writes");
575        for (field, value) in [
576            // A JSON escape, so the record parses and the value it decodes
577            // to is the line feed the policy could never carry.
578            ("security_contact", "team@acme.example\\nsecond line"),
579            ("security_contact", "  team@acme.example  "),
580            ("security_response", "90d"),
581            ("security_response", "0 days"),
582            ("security_response", "07 days"),
583            ("security_response", "1 days"),
584            ("security_response", ""),
585        ] {
586            let record = format!(
587                r#"{{"schema_version":6,"rk_version":"0.1.0","payload_sha256":"0000000000000000000000000000000000000000000000000000000000000000","origin":"init","tech":"rust","forge":"github","landed_at":"2026-08-29T00:00:00Z","parameters":{{"repo":"acme/widget","{field}":"{value}"}},"files":[],"pins":{{}}}}"#
588            );
589            std::fs::write(target.join(super::MANIFEST_PATH), record).expect("the record writes");
590            let refused = super::load(target).expect_err("an uncanonical record refuses");
591            assert!(refused.to_string().contains(field), "{field}: {refused}");
592        }
593    }
594
595    #[test]
596    fn alignment_orders_versions_numerically() {
597        assert_eq!(alignment("0.1.0", "0.1.0"), Alignment::Aligned);
598        assert_eq!(alignment("0.1.0", "0.2.0"), Alignment::BinaryNewer);
599        assert_eq!(alignment("0.10.0", "0.9.9"), Alignment::TargetNewer);
600        assert_eq!(alignment("0.1.0-rc.1", "0.1.0"), Alignment::BinaryNewer);
601        assert_eq!(alignment("0.1.0", "0.1.0-rc.1"), Alignment::TargetNewer);
602    }
603
604    /// Pre-release identifiers order by semver precedence, not by text:
605    /// `rc.10` is newer than `rc.2`, so a binary at `rc.2` must refuse a
606    /// landing from `rc.10` rather than downgrade it — at any identifier
607    /// length, so no integer width bounds the protection.
608    #[test]
609    fn alignment_orders_numeric_prerelease_identifiers_numerically() {
610        assert_eq!(
611            alignment("0.1.0-rc.10", "0.1.0-rc.2"),
612            Alignment::TargetNewer
613        );
614        assert_eq!(
615            alignment("0.1.0-rc.2", "0.1.0-rc.10"),
616            Alignment::BinaryNewer
617        );
618        assert_eq!(alignment("0.1.0-rc.1", "0.1.0-rc.1"), Alignment::Aligned);
619        assert_eq!(
620            alignment("0.1.0-alpha", "0.1.0-alpha.1"),
621            Alignment::BinaryNewer
622        );
623        assert_eq!(alignment("0.1.0-1", "0.1.0-alpha"), Alignment::BinaryNewer);
624        assert_eq!(
625            alignment("1.0.0-100000000000000000000", "1.0.0-99999999999999999999"),
626            Alignment::TargetNewer,
627            "identifiers past the u64 range still compare numerically"
628        );
629        assert_eq!(
630            alignment("1.0.0-99999999999999999999", "1.0.0-100000000000000000000"),
631            Alignment::BinaryNewer
632        );
633    }
634
635    /// Build metadata carries no precedence: it never corrupts a numeric
636    /// component and never separates two otherwise-equal versions.
637    #[test]
638    fn alignment_ignores_build_metadata() {
639        assert_eq!(alignment("1.2.10+build", "1.2.9"), Alignment::TargetNewer);
640        assert_eq!(alignment("1.2.9", "1.2.10+build"), Alignment::BinaryNewer);
641        assert_eq!(alignment("1.0.0+alpha", "1.0.0+beta"), Alignment::Aligned);
642        assert_eq!(
643            alignment("1.2.10-rc.1+build", "1.2.10-rc.1"),
644            Alignment::Aligned
645        );
646        assert_eq!(
647            alignment("1.2.10-rc.1+build", "1.2.10"),
648            Alignment::BinaryNewer
649        );
650    }
651}