Skip to main content

packdiff_dto/
lib.rs

1//! # packdiff-dto — the data model
2//!
3//! This crate is the single source of truth for every piece of data packdiff
4//! handles. It is **pure logic**: no filesystem, no subprocess, no clock, no
5//! randomness — those all live in the callers (`packdiff-cli` natively,
6//! `packdiff-wasm` in the browser). That is what lets the *same* compiled
7//! semantics run on both sides of the tool.
8//!
9//! Two document families:
10//!
11//! - [`diff::DiffDocument`] — the **immutable build artifact**: everything the
12//!   CLI extracted from git (refs, commits, per-file hunks and lines). It is
13//!   produced once per render and embedded/consumed read-only.
14//! - [`review::ReviewDocument`] — the **mutable review state**: the comments a
15//!   human leaves on the page. It lives in the browser's localStorage, and
16//!   every mutation (upsert, delete, merge/import) goes through this crate via
17//!   WASM — the page's JavaScript never edits the document itself.
18//!
19//! Schema rules:
20//!
21//! - JSON field names are `snake_case`; union variants are `CamelCase` and
22//!   encode as single-key objects — `{ "VariantName": { ...payload } }` — with
23//!   no discriminator field.
24//! - Every struct strict-rejects unknown fields (`deny_unknown_fields`): a
25//!   typo or a drifted producer is a hard, loud error, never a silently
26//!   ignored key.
27//! - Both documents carry `schema_version` ([`SCHEMA_VERSION`]). This is the
28//!   one deliberate opt-in to long-term compatibility (review documents live
29//!   in users' localStorage): parsers reject documents from a *newer* schema
30//!   than they understand and accept older ones (there is only v1 today, so
31//!   "accept" means "equal").
32//! - Determinism: same inputs → byte-identical outputs. Ordering is always
33//!   explicit ([`review::ReviewDocument::sort`]), timestamps and ids are
34//!   caller-supplied, and exports are stable.
35
36pub mod diff;
37pub mod export;
38pub mod markdown;
39pub mod review;
40pub mod snapshot;
41
42/// Version stamped into (and required of) every document this crate touches.
43pub const SCHEMA_VERSION: u32 = 1;
44
45/// Tool identifier stamped into documents.
46pub const TOOL: &str = "packdiff";
47
48/// A named ref pinned to the commit it resolved to at build time.
49#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
50#[serde(deny_unknown_fields)]
51pub struct RefInfo {
52  /// What the user asked for: branch, tag, or SHA — kept verbatim so pages
53  /// and exports show the name the reviewer thinks in.
54  pub name: String,
55  /// The full commit SHA the name resolved to; pins the document to an exact
56  /// state even if the ref later moves.
57  pub sha: String,
58}
59
60/// Errors surfaced by any model operation. Typed so callers branch on
61/// variants; the WASM ABI ships them as `{ "Error": { "message": ... } }`.
62#[derive(Debug, PartialEq, Eq, thiserror::Error)]
63pub enum ModelError {
64  /// Input was not valid JSON for the expected shape.
65  #[error("invalid JSON: {0}")]
66  Json(String),
67  /// Document is from a newer schema than this build understands.
68  #[error("unsupported schema_version {found} (this build supports up to {supported})")]
69  UnsupportedSchema {
70    /// The `schema_version` the document claims.
71    found: u32,
72    /// The newest `schema_version` this build can read.
73    supported: u32,
74  },
75  /// A comment failed validation.
76  #[error("invalid comment: {0}")]
77  InvalidComment(String),
78  /// A commit-range request did not match the snapshot store (bad boundary
79  /// indices, or a boundary referencing a blob the store does not carry).
80  #[error("invalid snapshot range: {0}")]
81  InvalidRange(String),
82}
83
84/// The localStorage key a review document is filed under.
85///
86/// The key pins the exact endpoint SHAs on purpose: line numbers are only
87/// meaningful against the diff they were written on. Regenerating the same
88/// diff finds the same comments; new commits get a fresh store (carry
89/// comments over with export → import, where [`review::ReviewDocument::merge`]
90/// applies).
91pub fn storage_key(repo: &str, base_sha: &str, head_sha: &str) -> String {
92  fn short(sha: &str) -> &str {
93    &sha[..sha.len().min(12)]
94  }
95  format!("packdiff:v{}:{}:{}..{}", SCHEMA_VERSION, repo, short(base_sha), short(head_sha))
96}
97
98#[cfg(test)]
99mod tests {
100  use super::*;
101
102  #[test]
103  fn storage_key_pins_repo_and_short_shas() {
104    let key =
105      storage_key("myrepo", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
106    assert_eq!(key, "packdiff:v1:myrepo:aaaaaaaaaaaa..bbbbbbbbbbbb");
107  }
108
109  #[test]
110  fn storage_key_tolerates_short_shas() {
111    assert_eq!(storage_key("r", "abc", "def"), "packdiff:v1:r:abc..def");
112  }
113}