1use 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
23pub const MANIFEST_PATH: &str = ".release-kit/manifest.json";
25
26pub const SCHEMA_VERSION: u64 = 5;
38
39const OLDEST_READABLE_SCHEMA: u64 = 1;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "lowercase")]
46pub enum Workflow {
47 Worktree,
50 Branches,
53}
54
55impl Workflow {
56 #[must_use]
58 pub const fn as_str(self) -> &'static str {
59 match self {
60 Self::Worktree => "worktree",
61 Self::Branches => "branches",
62 }
63 }
64
65 pub fn parse(raw: &str) -> Result<Self, RkError> {
71 match raw {
72 "worktree" => Ok(Self::Worktree),
73 "branches" => Ok(Self::Branches),
74 other => Err(RkError::Usage(format!(
75 "unknown workflow '{other}'; the modes are: worktree, branches"
76 ))),
77 }
78 }
79}
80
81const fn workflow_branches() -> Workflow {
83 Workflow::Branches
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
92#[serde(rename_all = "lowercase")]
93pub enum Style {
94 Trunk,
97 Lines,
100}
101
102impl Style {
103 #[must_use]
105 pub const fn as_str(self) -> &'static str {
106 match self {
107 Self::Trunk => "trunk",
108 Self::Lines => "lines",
109 }
110 }
111
112 pub fn parse(raw: &str) -> Result<Self, RkError> {
118 match raw {
119 "trunk" => Ok(Self::Trunk),
120 "lines" => Ok(Self::Lines),
121 other => Err(RkError::Usage(format!(
122 "unknown style '{other}'; the styles are: trunk, lines"
123 ))),
124 }
125 }
126}
127
128#[derive(Debug, Serialize, Deserialize)]
130pub struct Manifest {
131 pub schema_version: u64,
133 pub rk_version: String,
135 pub payload_sha256: Digest,
138 pub origin: String,
140 pub tech: String,
142 pub forge: String,
144 pub landed_at: String,
146 pub parameters: Parameters,
149 pub files: Vec<FileRecord>,
151 pub pins: BTreeMap<String, String>,
154}
155
156#[derive(Debug, Serialize, Deserialize)]
158pub struct Parameters {
159 pub repo: String,
162 #[serde(default = "workflow_branches")]
168 pub workflow: Workflow,
169 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub style: Option<Style>,
176 #[serde(default)]
183 pub nix: bool,
184}
185
186#[derive(Debug, Serialize, Deserialize)]
188pub struct FileRecord {
189 pub destination: String,
191 pub kind: Kind,
193 pub sha256: Digest,
196 #[serde(skip_serializing_if = "Option::is_none")]
205 pub baseline_sha256: Option<Digest>,
206}
207
208impl Manifest {
209 #[must_use]
211 pub fn file(&self, destination: &str) -> Option<&FileRecord> {
212 self.files
213 .iter()
214 .find(|file| file.destination == destination)
215 }
216}
217
218pub fn load(target: &Utf8Path) -> Result<Option<Manifest>, RkError> {
227 let path = target.join(MANIFEST_PATH);
228 let bytes = match std::fs::read(&path) {
229 Ok(bytes) => bytes,
230 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
231 Err(e) => {
232 return Err(RkError::refusal(
233 Diagnostic::new(Reason::Io, format!("cannot read {path}: {e}"))
234 .expected("a readable landing record")
235 .target_state("unchanged"),
236 ));
237 }
238 };
239 let value: serde_json::Value = serde_json::from_slice(&bytes)
240 .map_err(|e| anyhow::anyhow!("{path} is not a landing record: {e}"))?;
241 let schema = value
247 .get("schema_version")
248 .and_then(serde_json::Value::as_u64);
249 if !schema.is_some_and(|version| (OLDEST_READABLE_SCHEMA..=SCHEMA_VERSION).contains(&version)) {
250 let found = schema.map_or_else(|| "none".to_owned(), |version| version.to_string());
251 return Err(RkError::refusal(
252 Diagnostic::new(
253 Reason::UnsupportedSchema,
254 format!(
255 "{path} declares schema_version {found}, and this binary knows only {OLDEST_READABLE_SCHEMA} through {SCHEMA_VERSION}"
256 ),
257 )
258 .expected("a record this binary can read")
259 .action("run the rk release that wrote this record, or a newer one")
260 .target_state("unchanged"),
261 ));
262 }
263 let declared = schema.unwrap_or(SCHEMA_VERSION);
264 let manifest: Manifest = serde_json::from_value(value)
265 .map_err(|e| anyhow::anyhow!("{path} does not parse at schema_version {declared}: {e}"))?;
266 Ok(Some(manifest))
267}
268
269pub fn write(target: &Utf8Path, manifest: &Manifest) -> Result<(), RkError> {
275 let text = serde_json::to_string_pretty(manifest).map_err(anyhow::Error::from)?;
276 let path = target.join(MANIFEST_PATH);
277 atomic::write(path.as_std_path(), format!("{text}\n").as_bytes())?;
278 Ok(())
279}
280
281#[must_use]
283pub fn now() -> String {
284 humantime::format_rfc3339_seconds(std::time::SystemTime::now()).to_string()
285}
286
287#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
289#[serde(rename_all = "kebab-case")]
290pub enum Alignment {
291 Aligned,
293 BinaryNewer,
295 TargetNewer,
298}
299
300impl Alignment {
301 #[must_use]
303 pub const fn as_str(self) -> &'static str {
304 match self {
305 Self::Aligned => "aligned",
306 Self::BinaryNewer => "binary-newer",
307 Self::TargetNewer => "target-newer",
308 }
309 }
310}
311
312#[must_use]
314pub fn alignment(recorded: &str, binary: &str) -> Alignment {
315 let recorded = recorded
317 .split_once('+')
318 .map_or(recorded, |(version, _)| version);
319 let binary = binary
320 .split_once('+')
321 .map_or(binary, |(version, _)| version);
322 let recorded_core = numeric_core(recorded);
323 let binary_core = numeric_core(binary);
324 match binary_core.cmp(&recorded_core) {
325 std::cmp::Ordering::Greater => Alignment::BinaryNewer,
326 std::cmp::Ordering::Less => Alignment::TargetNewer,
327 std::cmp::Ordering::Equal => {
328 let recorded_pre = recorded.split_once('-').map(|(_, pre)| pre);
333 let binary_pre = binary.split_once('-').map(|(_, pre)| pre);
334 match (recorded_pre, binary_pre) {
335 (Some(_), None) => Alignment::BinaryNewer,
336 (None, Some(_)) => Alignment::TargetNewer,
337 (None, None) => Alignment::Aligned,
338 (Some(r), Some(b)) => match prerelease_cmp(b, r) {
339 std::cmp::Ordering::Greater => Alignment::BinaryNewer,
340 std::cmp::Ordering::Less => Alignment::TargetNewer,
341 std::cmp::Ordering::Equal => Alignment::Aligned,
342 },
343 }
344 }
345 }
346}
347
348#[must_use]
351pub fn version_is_newer(candidate: &str, pinned: &str) -> bool {
352 alignment(pinned, candidate) == Alignment::BinaryNewer
353}
354
355fn prerelease_cmp(a: &str, b: &str) -> std::cmp::Ordering {
362 let numeric = |identifier: &str| identifier.bytes().all(|byte| byte.is_ascii_digit());
363 let mut left = a.split('.');
364 let mut right = b.split('.');
365 loop {
366 match (left.next(), right.next()) {
367 (None, None) => return std::cmp::Ordering::Equal,
368 (None, Some(_)) => return std::cmp::Ordering::Less,
369 (Some(_), None) => return std::cmp::Ordering::Greater,
370 (Some(x), Some(y)) => {
371 let ordering = match (numeric(x), numeric(y)) {
372 (true, true) => x.len().cmp(&y.len()).then_with(|| x.cmp(y)),
373 (true, false) => std::cmp::Ordering::Less,
374 (false, true) => std::cmp::Ordering::Greater,
375 (false, false) => x.cmp(y),
376 };
377 if ordering != std::cmp::Ordering::Equal {
378 return ordering;
379 }
380 }
381 }
382 }
383}
384
385fn numeric_core(version: &str) -> Vec<u64> {
387 let core = version.split_once('-').map_or(version, |(core, _)| core);
388 core.split('.')
389 .map(|part| part.parse::<u64>().unwrap_or(0))
390 .collect()
391}
392
393#[cfg(test)]
394mod tests {
395 #![allow(clippy::expect_used)]
396
397 use super::{Alignment, FileRecord, Manifest, Parameters, Style, Workflow, alignment};
398 use crate::digest::Digest;
399 use crate::landing::Kind;
400
401 #[test]
405 fn the_manifest_schema_snapshot_holds() {
406 let manifest = Manifest {
407 schema_version: 5,
408 rk_version: "0.1.0".into(),
409 payload_sha256: Digest::of(b""),
410 origin: "init".into(),
411 tech: "rust".into(),
412 forge: "github".into(),
413 landed_at: "2026-08-29T00:00:00Z".into(),
414 parameters: Parameters {
415 repo: "acme/widget".into(),
416 workflow: Workflow::Worktree,
417 style: Some(Style::Trunk),
418 nix: true,
419 },
420 files: vec![
421 FileRecord {
422 destination: "release-plz.toml".into(),
423 kind: Kind::Seeded,
424 sha256: Digest::of(b""),
425 baseline_sha256: Some(Digest::of(b"")),
426 },
427 FileRecord {
428 destination: "VERSION".into(),
429 kind: Kind::State,
430 sha256: Digest::of(b""),
431 baseline_sha256: None,
432 },
433 ],
434 pins: std::iter::once(("release-plz".to_owned(), "0.3.160".to_owned())).collect(),
435 };
436 let empty = Digest::of(b"").to_string();
437 assert_eq!(
438 serde_json::to_string(&manifest).expect("a manifest serializes"),
439 format!(
440 r#"{{"schema_version":5,"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}},"files":[{{"destination":"release-plz.toml","kind":"seeded","sha256":"{empty}","baseline_sha256":"{empty}"}},{{"destination":"VERSION","kind":"state","sha256":"{empty}"}}],"pins":{{"release-plz":"0.3.160"}}}}"#
441 ),
442 "a state file must omit baseline_sha256 rather than serializing null"
443 );
444 }
445
446 #[test]
451 fn a_schema_1_record_reads_as_branches_and_a_newer_schema_refuses() {
452 let dir = tempfile::tempdir().expect("a scratch target exists");
453 let target = camino::Utf8Path::from_path(dir.path()).expect("utf-8 path");
454 std::fs::create_dir_all(target.join(".release-kit")).expect("the record dir writes");
455 let record = |schema: u64| {
456 format!(
457 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":{{}}}}"#
458 )
459 };
460 std::fs::write(target.join(super::MANIFEST_PATH), record(1)).expect("the record writes");
461 let manifest = super::load(target)
462 .expect("a schema-1 record loads")
463 .expect("the record exists");
464 assert_eq!(manifest.parameters.workflow, Workflow::Branches);
465 assert_eq!(
466 manifest.parameters.style, None,
467 "a pre-style record carries no style; the upgrade demands one"
468 );
469 assert!(
470 !manifest.parameters.nix,
471 "a pre-nix record reads as opt-out, so an upgrade adds nothing unrequested"
472 );
473
474 std::fs::write(target.join(super::MANIFEST_PATH), record(6)).expect("the record writes");
475 let refused = super::load(target).expect_err("a schema-6 record refuses");
476 let message = refused.to_string();
477 assert!(message.contains('6'), "{message}");
478 }
479
480 #[test]
481 fn alignment_orders_versions_numerically() {
482 assert_eq!(alignment("0.1.0", "0.1.0"), Alignment::Aligned);
483 assert_eq!(alignment("0.1.0", "0.2.0"), Alignment::BinaryNewer);
484 assert_eq!(alignment("0.10.0", "0.9.9"), Alignment::TargetNewer);
485 assert_eq!(alignment("0.1.0-rc.1", "0.1.0"), Alignment::BinaryNewer);
486 assert_eq!(alignment("0.1.0", "0.1.0-rc.1"), Alignment::TargetNewer);
487 }
488
489 #[test]
494 fn alignment_orders_numeric_prerelease_identifiers_numerically() {
495 assert_eq!(
496 alignment("0.1.0-rc.10", "0.1.0-rc.2"),
497 Alignment::TargetNewer
498 );
499 assert_eq!(
500 alignment("0.1.0-rc.2", "0.1.0-rc.10"),
501 Alignment::BinaryNewer
502 );
503 assert_eq!(alignment("0.1.0-rc.1", "0.1.0-rc.1"), Alignment::Aligned);
504 assert_eq!(
505 alignment("0.1.0-alpha", "0.1.0-alpha.1"),
506 Alignment::BinaryNewer
507 );
508 assert_eq!(alignment("0.1.0-1", "0.1.0-alpha"), Alignment::BinaryNewer);
509 assert_eq!(
510 alignment("1.0.0-100000000000000000000", "1.0.0-99999999999999999999"),
511 Alignment::TargetNewer,
512 "identifiers past the u64 range still compare numerically"
513 );
514 assert_eq!(
515 alignment("1.0.0-99999999999999999999", "1.0.0-100000000000000000000"),
516 Alignment::BinaryNewer
517 );
518 }
519
520 #[test]
523 fn alignment_ignores_build_metadata() {
524 assert_eq!(alignment("1.2.10+build", "1.2.9"), Alignment::TargetNewer);
525 assert_eq!(alignment("1.2.9", "1.2.10+build"), Alignment::BinaryNewer);
526 assert_eq!(alignment("1.0.0+alpha", "1.0.0+beta"), Alignment::Aligned);
527 assert_eq!(
528 alignment("1.2.10-rc.1+build", "1.2.10-rc.1"),
529 Alignment::Aligned
530 );
531 assert_eq!(
532 alignment("1.2.10-rc.1+build", "1.2.10"),
533 Alignment::BinaryNewer
534 );
535 }
536}