pakx_core/lockfile/write.rs
1//! Serialise a [`Lockfile`] to deterministic JSON.
2
3use super::schema::{LockEntry, Lockfile};
4
5/// Render a lockfile to JSON.
6///
7/// Determinism guarantees:
8/// - Top-level keys: `lockfileVersion`, `manifestHash`, `entries` (in that
9/// order, fixed by the `Lockfile` struct's field order).
10/// - `entries` map keys: alphabetical, courtesy of `BTreeMap`.
11/// - Each entry's `agents` and `dependencies` arrays: alphabetical.
12/// - Trailing newline (POSIX-friendly diffs).
13pub fn write_lockfile(lockfile: &Lockfile) -> String {
14 // Clone so we can sort the per-entry arrays without mutating the caller's
15 // value. Cost is fine for v0.1; lockfiles are small.
16 let mut sorted = lockfile.clone();
17 for entry in sorted.entries.values_mut() {
18 sort_entry_arrays(entry);
19 }
20
21 let mut out = serde_json::to_string_pretty(&sorted)
22 .expect("Lockfile with String keys serializes infallibly");
23 out.push('\n');
24 out
25}
26
27fn sort_entry_arrays(entry: &mut LockEntry) {
28 entry.agents.sort_unstable();
29 entry.dependencies.sort_unstable();
30}