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 = 6;
41
42const OLDEST_READABLE_SCHEMA: u64 = 1;
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "lowercase")]
49pub enum Workflow {
50 Worktree,
53 Branches,
56}
57
58impl Workflow {
59 #[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 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
84const fn workflow_branches() -> Workflow {
86 Workflow::Branches
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(rename_all = "lowercase")]
96pub enum Style {
97 Trunk,
100 Lines,
103}
104
105impl Style {
106 #[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 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#[derive(Debug, Serialize, Deserialize)]
133pub struct Manifest {
134 pub schema_version: u64,
136 pub rk_version: String,
138 pub payload_sha256: Digest,
141 pub origin: String,
143 pub tech: String,
145 pub forge: String,
147 pub landed_at: String,
149 pub parameters: Parameters,
152 pub files: Vec<FileRecord>,
154 pub pins: BTreeMap<String, String>,
157}
158
159#[derive(Debug, Serialize, Deserialize)]
161pub struct Parameters {
162 pub repo: String,
165 #[serde(default = "workflow_branches")]
171 pub workflow: Workflow,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub style: Option<Style>,
179 #[serde(default)]
186 pub nix: bool,
187 #[serde(default = "trunk_master")]
191 pub trunk: String,
192 #[serde(default = "line_prefix_release")]
196 pub line_prefix: String,
197 #[serde(default, deserialize_with = "read_contact")]
202 pub security_contact: String,
203 #[serde(default = "response_best_effort", deserialize_with = "read_response")]
207 pub security_response: String,
208}
209
210fn trunk_master() -> String {
212 crate::config::TRUNK_DEFAULT.to_owned()
213}
214
215fn line_prefix_release() -> String {
217 crate::config::LINE_PREFIX_DEFAULT.to_owned()
218}
219
220fn response_best_effort() -> String {
222 crate::config::RESPONSE_DEFAULT.to_owned()
223}
224
225fn read_contact<'de, D: serde::Deserializer<'de>>(reader: D) -> Result<String, D::Error> {
231 canonical(reader, "security_contact", crate::config::canonical_contact)
232}
233
234fn 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
243fn 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#[derive(Debug, Serialize, Deserialize)]
263pub struct FileRecord {
264 pub destination: String,
266 pub kind: Kind,
268 pub sha256: Digest,
271 #[serde(skip_serializing_if = "Option::is_none")]
280 pub baseline_sha256: Option<Digest>,
281}
282
283impl Manifest {
284 #[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
293pub 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 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
344pub 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#[must_use]
358pub fn now() -> String {
359 humantime::format_rfc3339_seconds(std::time::SystemTime::now()).to_string()
360}
361
362#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
364#[serde(rename_all = "kebab-case")]
365pub enum Alignment {
366 Aligned,
368 BinaryNewer,
370 TargetNewer,
373}
374
375impl Alignment {
376 #[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#[must_use]
389pub fn alignment(recorded: &str, binary: &str) -> Alignment {
390 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 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#[must_use]
426pub fn version_is_newer(candidate: &str, pinned: &str) -> bool {
427 alignment(pinned, candidate) == Alignment::BinaryNewer
428}
429
430fn 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
460fn 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 #[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 #[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 #[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 ("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 #[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 #[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}