clayers-repo 0.2.1

Content-addressed Merkle DAG repository for XML documents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Porcelain API for repository operations.
//!
//! `Repo<S>` composes `ObjectStore + RefStore` to provide git-like
//! operations on XML Merkle DAGs.

use clayers_xml::ContentHash;
use chrono::Utc;

use crate::diff::{self, TreeDiff};
use crate::error::{Error, Result};
use crate::graph;
use crate::hash;
use crate::import;
use crate::export;
use crate::conflict::{self, ConflictInfo};
use crate::merge::{self, MergeOutcome, MergePolicy};
use crate::object::{Author, CommitObject, Object, TagObject, TreeEntry, TreeObject};
use crate::query::{self, QueryStore, QueryMode, QueryResult, NamespaceMap, RefQueryResult};
use crate::refs;
use crate::store::{ObjectStore, RefStore};

/// A repository with pluggable storage.
pub struct Repo<S: ObjectStore + RefStore + QueryStore> {
    store: S,
}

impl<S: ObjectStore + RefStore + QueryStore> Repo<S> {
    /// Create a new repository with the given store.
    #[must_use]
    pub fn init(store: S) -> Self {
        Self { store }
    }

    // --- Import/Export ---

    /// Import an XML string, decompose into the content-addressed store,
    /// and return the document hash.
    ///
    /// # Errors
    ///
    /// Returns an error if the XML is malformed or storage fails.
    pub async fn import_xml(&self, xml: &str) -> Result<ContentHash> {
        import::import_xml(&self.store, xml).await
    }

    /// Export a document from the store as a canonical XML string.
    ///
    /// # Errors
    ///
    /// Returns an error if the document is not found or reconstruction fails.
    pub async fn export_xml(&self, hash: ContentHash) -> Result<String> {
        export::export_xml(&self.store, hash).await
    }

    // --- Trees ---

    /// Build a tree object from file path -> document hash mappings.
    ///
    /// # Errors
    ///
    /// Returns an error if storage fails.
    pub async fn build_tree(
        &self,
        entries: Vec<(String, ContentHash)>,
    ) -> Result<ContentHash> {
        let tree_entries: Vec<TreeEntry> = entries
            .into_iter()
            .map(|(path, document)| TreeEntry { path, document })
            .collect();
        let tree = TreeObject::new(tree_entries);
        let xml = tree.to_xml();
        let tree_hash = hash::hash_exclusive(&xml)?;

        let mut tx = self.store.transaction().await?;
        tx.put(tree_hash, Object::Tree(tree)).await?;
        tx.commit().await?;

        Ok(tree_hash)
    }

    // --- Commits ---

    /// Create a commit on a branch.
    ///
    /// # Errors
    ///
    /// Returns an error if the tree is not found or storage fails.
    pub async fn commit(
        &self,
        branch: &str,
        tree: ContentHash,
        author: &Author,
        message: &str,
    ) -> Result<ContentHash> {
        // Get current branch tip as parent.
        let parents = match refs::get_branch(&self.store, branch).await? {
            Some(tip) => vec![tip],
            None => Vec::new(),
        };

        let commit = CommitObject {
            tree,
            parents,
            author: author.clone(),
            timestamp: Utc::now(),
            message: message.to_string(),
        };

        let xml = commit.to_xml();
        let commit_hash = hash::hash_exclusive(&xml)?;

        let mut tx = self.store.transaction().await?;
        tx.put(commit_hash, Object::Commit(commit)).await?;
        tx.commit().await?;

        // Update branch ref.
        self.store
            .set_ref(&refs::branch_ref(branch), commit_hash)
            .await?;

        // Update HEAD.
        refs::set_head(&self.store, commit_hash).await?;

        Ok(commit_hash)
    }

    // --- Branches ---

    /// Create a new branch pointing to a commit.
    ///
    /// # Errors
    ///
    /// Returns an error if the ref cannot be created.
    pub async fn create_branch(&self, name: &str, target: ContentHash) -> Result<()> {
        self.store
            .set_ref(&refs::branch_ref(name), target)
            .await
    }

    /// Delete a branch.
    ///
    /// # Errors
    ///
    /// Returns an error if the ref cannot be deleted.
    pub async fn delete_branch(&self, name: &str) -> Result<()> {
        self.store.delete_ref(&refs::branch_ref(name)).await
    }

    /// List all branches with their target commit hashes.
    ///
    /// # Errors
    ///
    /// Returns an error if refs cannot be listed.
    pub async fn list_branches(&self) -> Result<Vec<(String, ContentHash)>> {
        refs::list_branches(&self.store).await
    }

    // --- Tags ---

    /// Create an annotated tag.
    ///
    /// # Errors
    ///
    /// Returns an error if the tag cannot be created.
    pub async fn create_tag(
        &self,
        name: &str,
        target: ContentHash,
        tagger: &Author,
        message: &str,
    ) -> Result<()> {
        let tag = TagObject {
            target,
            name: name.to_string(),
            tagger: tagger.clone(),
            timestamp: Utc::now(),
            message: message.to_string(),
        };

        let xml = tag.to_xml();
        let tag_hash = hash::hash_exclusive(&xml)?;

        let mut tx = self.store.transaction().await?;
        tx.put(tag_hash, Object::Tag(tag)).await?;
        tx.commit().await?;

        self.store
            .set_ref(&refs::tag_ref(name), tag_hash)
            .await
    }

    /// List all tags with their target hashes.
    ///
    /// # Errors
    ///
    /// Returns an error if refs cannot be listed.
    pub async fn list_tags(&self) -> Result<Vec<(String, ContentHash)>> {
        refs::list_tags(&self.store).await
    }

    // --- History ---

    /// Walk commit history from a starting commit.
    ///
    /// # Errors
    ///
    /// Returns an error if commit objects cannot be loaded.
    pub async fn log(
        &self,
        from: ContentHash,
        limit: Option<usize>,
    ) -> Result<Vec<(ContentHash, CommitObject)>> {
        graph::walk_history(&self.store, from, limit).await
    }

    // --- Diff ---

    /// Compute a structural diff between two content-addressed trees.
    ///
    /// # Errors
    ///
    /// Returns an error if objects cannot be loaded.
    pub async fn diff(&self, a: ContentHash, b: ContentHash) -> Result<TreeDiff> {
        diff::diff(&self.store, a, b).await
    }

    // --- File-level diff ---

    /// Compare two tree objects and return file-level changes.
    ///
    /// # Errors
    ///
    /// Returns an error if tree objects cannot be loaded.
    pub async fn diff_trees(
        &self,
        tree_hash_a: ContentHash,
        tree_hash_b: ContentHash,
    ) -> Result<Vec<diff::FileChange>> {
        let obj_a = self
            .store
            .get(&tree_hash_a)
            .await?
            .ok_or(crate::error::Error::NotFound(tree_hash_a))?;
        let obj_b = self
            .store
            .get(&tree_hash_b)
            .await?
            .ok_or(crate::error::Error::NotFound(tree_hash_b))?;

        let Object::Tree(ta) = obj_a else {
            return Err(crate::error::Error::InvalidObject(
                "expected Tree object".into(),
            ));
        };
        let Object::Tree(tb) = obj_b else {
            return Err(crate::error::Error::InvalidObject(
                "expected Tree object".into(),
            ));
        };

        Ok(diff::diff_trees(&ta, &tb))
    }

    /// Export two documents and diff them as XML strings.
    ///
    /// # Errors
    ///
    /// Returns an error if documents cannot be exported or diff fails.
    pub async fn diff_file(
        &self,
        doc_a: ContentHash,
        doc_b: ContentHash,
    ) -> Result<clayers_xml::XmlDiff> {
        let xml_a = self.export_xml(doc_a).await?;
        let xml_b = self.export_xml(doc_b).await?;
        clayers_xml::diff_xml(&xml_a, &xml_b).map_err(|e| {
            crate::error::Error::InvalidObject(format!("XML diff failed: {e}"))
        })
    }

    // --- Conflict detection ---

    /// Check whether a document contains unresolved conflicts.
    ///
    /// # Errors
    ///
    /// Returns an error if objects cannot be loaded.
    pub async fn has_conflicts(&self, document: ContentHash) -> Result<bool> {
        conflict::has_conflicts(&self.store, document).await
    }

    /// List all unresolved conflicts in a document.
    ///
    /// # Errors
    ///
    /// Returns an error if objects cannot be loaded.
    pub async fn list_conflicts(&self, document: ContentHash) -> Result<Vec<ConflictInfo>> {
        conflict::list_conflicts(&self.store, document).await
    }

    // --- Merge ---

    /// Three-way merge of a target branch into the current branch.
    ///
    /// Finds the common ancestor, performs file-level and element-level
    /// three-way merge using the given policy, and creates a merge commit
    /// with two parents.
    ///
    /// # Errors
    ///
    /// Returns an error if branches cannot be resolved, objects cannot be
    /// loaded, or storage fails.
    pub async fn merge(
        &self,
        current_branch: &str,
        target_branch: &str,
        author: &Author,
        message: &str,
        policy: &MergePolicy,
    ) -> Result<MergeOutcome> {
        // Resolve branch tips.
        let ours_commit = refs::get_branch(&self.store, current_branch)
            .await?
            .ok_or(Error::Ref(format!(
                "branch '{current_branch}' has no commits"
            )))?;
        let theirs_commit = refs::get_branch(&self.store, target_branch)
            .await?
            .ok_or(Error::Ref(format!("branch '{target_branch}' not found")))?;

        if ours_commit == theirs_commit {
            return Ok(MergeOutcome::UpToDate);
        }

        // Find lowest common ancestor.
        let ancestor =
            graph::common_ancestor(&self.store, ours_commit, theirs_commit).await?;
        let Some(ancestor_commit) = ancestor else {
            return Ok(MergeOutcome::NoCommonAncestor);
        };

        // Fast-forward: HEAD is behind target.
        if ancestor_commit == ours_commit {
            self.store
                .set_ref(&refs::branch_ref(current_branch), theirs_commit)
                .await?;
            refs::set_head(&self.store, theirs_commit).await?;
            return Ok(MergeOutcome::FastForward {
                commit: theirs_commit,
            });
        }

        // Already up to date: target is behind HEAD.
        if ancestor_commit == theirs_commit {
            return Ok(MergeOutcome::UpToDate);
        }

        // Load trees.
        let ours_tree = self.load_tree_from_commit(ours_commit).await?;
        let theirs_tree = self.load_tree_from_commit(theirs_commit).await?;
        let ancestor_tree = self.load_tree_from_commit(ancestor_commit).await?;

        // Three-way file-level merge.
        let ours_ref = refs::branch_ref(current_branch);
        let theirs_ref = refs::branch_ref(target_branch);
        let result = merge::merge_trees(
            &self.store,
            &ancestor_tree,
            &ours_tree,
            &theirs_tree,
            policy,
            &ours_ref,
            &theirs_ref,
            ours_commit,
            theirs_commit,
            ancestor_commit,
        )
        .await?;

        // Create merge commit (two parents).
        let commit = CommitObject {
            tree: result.tree,
            parents: vec![ours_commit, theirs_commit],
            author: author.clone(),
            timestamp: Utc::now(),
            message: message.to_string(),
        };
        let commit_xml = commit.to_xml();
        let commit_hash = hash::hash_exclusive(&commit_xml)?;

        let mut tx = self.store.transaction().await?;
        tx.put(commit_hash, Object::Commit(commit)).await?;
        tx.commit().await?;

        // Update branch and HEAD.
        self.store
            .set_ref(&refs::branch_ref(current_branch), commit_hash)
            .await?;
        refs::set_head(&self.store, commit_hash).await?;

        Ok(MergeOutcome::Merged {
            commit: commit_hash,
            result,
        })
    }

    /// Load a tree from a commit hash.
    async fn load_tree_from_commit(
        &self,
        commit_hash: ContentHash,
    ) -> Result<TreeObject> {
        let obj = self
            .store
            .get(&commit_hash)
            .await?
            .ok_or(Error::NotFound(commit_hash))?;
        let Object::Commit(commit) = obj else {
            return Err(Error::InvalidObject("expected Commit".into()));
        };
        let tree_obj = self
            .store
            .get(&commit.tree)
            .await?
            .ok_or(Error::NotFound(commit.tree))?;
        let Object::Tree(tree) = tree_obj else {
            return Err(Error::InvalidObject("expected Tree".into()));
        };
        Ok(tree)
    }

    // --- Query ---

    /// Query a document or revision with an `XPath` expression.
    ///
    /// # Errors
    ///
    /// Returns an error if the revspec cannot be resolved or the query fails.
    pub async fn query(
        &self,
        revspec: &str,
        xpath: &str,
        mode: QueryMode,
        namespaces: &NamespaceMap,
    ) -> Result<QueryResult> {
        query::query(&self.store, &self.store, &self.store, revspec, xpath, mode, namespaces).await
    }

    /// Query each document in the tree, returning per-document results.
    ///
    /// When `files` is non-empty, only matching documents are queried.
    ///
    /// # Errors
    ///
    /// Returns an error if resolution or query fails.
    pub async fn query_by_document(
        &self,
        revspec: &str,
        xpath: &str,
        mode: QueryMode,
        namespaces: &NamespaceMap,
        files: &[String],
    ) -> Result<Vec<query::DocumentQueryResult>> {
        query::query_by_document(
            &self.store, &self.store, &self.store, revspec, xpath, mode, namespaces, files,
        )
        .await
    }

    /// Query across all refs matching a prefix.
    ///
    /// # Errors
    ///
    /// Returns an error if refs cannot be listed or queries fail.
    pub async fn query_refs(
        &self,
        prefix: &str,
        xpath: &str,
        mode: QueryMode,
        namespaces: &NamespaceMap,
    ) -> Result<Vec<RefQueryResult>> {
        query::query_refs(&self.store, &self.store, &self.store, prefix, xpath, mode, namespaces).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::memory::MemoryStore;

    #[tokio::test]
    async fn init_import_commit_export_roundtrip() {
        let store = MemoryStore::new();
        let repo = Repo::init(store);

        let xml = "<root>hello</root>";
        let doc_hash = repo.import_xml(xml).await.unwrap();
        let tree_hash = repo
            .build_tree(vec![("doc.xml".into(), doc_hash)])
            .await
            .unwrap();

        let author = Author {
            name: "Alice".into(),
            email: "alice@example.com".into(),
        };
        let commit_hash = repo
            .commit("main", tree_hash, &author, "Initial commit")
            .await
            .unwrap();

        // Verify branch was created.
        let branches = repo.list_branches().await.unwrap();
        assert!(branches.iter().any(|(name, _)| name == "main"));

        // Verify commit is in history.
        let history = repo.log(commit_hash, None).await.unwrap();
        assert_eq!(history.len(), 1);
        assert_eq!(history[0].1.message, "Initial commit");
    }

    #[tokio::test]
    async fn build_tree_stores_object() {
        let store = MemoryStore::new();
        let repo = Repo::init(store);
        let doc_hash = repo.import_xml("<r>x</r>").await.unwrap();
        let tree_hash = repo
            .build_tree(vec![("a.xml".into(), doc_hash)])
            .await
            .unwrap();
        let exported = repo.export_xml(doc_hash).await.unwrap();
        assert!(exported.contains('x'));
        // Tree object should exist in store.
        assert!(tree_hash != doc_hash);
    }

    #[tokio::test]
    async fn build_tree_sorts() {
        let store = MemoryStore::new();
        let repo = Repo::init(store);
        let h1 = repo.import_xml("<a/>").await.unwrap();
        let h2 = repo.import_xml("<b/>").await.unwrap();
        // Input in reverse order, tree should sort.
        let t1 = repo.build_tree(vec![
            ("z.xml".into(), h1),
            ("a.xml".into(), h2),
        ]).await.unwrap();
        let t2 = repo.build_tree(vec![
            ("a.xml".into(), h2),
            ("z.xml".into(), h1),
        ]).await.unwrap();
        assert_eq!(t1, t2, "same entries in different order should produce same tree hash");
    }

    #[tokio::test]
    async fn multi_file_commit_roundtrip() {
        let store = MemoryStore::new();
        let repo = Repo::init(store);
        let h1 = repo.import_xml("<a>one</a>").await.unwrap();
        let h2 = repo.import_xml("<b>two</b>").await.unwrap();
        let h3 = repo.import_xml("<c>three</c>").await.unwrap();
        let tree_hash = repo.build_tree(vec![
            ("a.xml".into(), h1),
            ("b.xml".into(), h2),
            ("c.xml".into(), h3),
        ]).await.unwrap();
        let author = Author { name: "T".into(), email: "t@t".into() };
        let commit_hash = repo.commit("main", tree_hash, &author, "multi").await.unwrap();
        let history = repo.log(commit_hash, None).await.unwrap();
        assert_eq!(history.len(), 1);
        assert_eq!(history[0].1.message, "multi");
    }

    #[tokio::test]
    async fn create_and_delete_branch() {
        let store = MemoryStore::new();
        let repo = Repo::init(store);
        let h = ContentHash::from_canonical(b"target");

        repo.create_branch("feature", h).await.unwrap();
        let branches = repo.list_branches().await.unwrap();
        assert!(branches.iter().any(|(n, _)| n == "feature"));

        repo.delete_branch("feature").await.unwrap();
        let branches = repo.list_branches().await.unwrap();
        assert!(!branches.iter().any(|(n, _)| n == "feature"));
    }

    #[tokio::test]
    async fn create_and_list_tags() {
        let store = MemoryStore::new();
        let repo = Repo::init(store);
        let h = ContentHash::from_canonical(b"target");

        let tagger = Author {
            name: "Bob".into(),
            email: "bob@example.com".into(),
        };
        repo.create_tag("v1.0", h, &tagger, "Release v1.0")
            .await
            .unwrap();

        let tags = repo.list_tags().await.unwrap();
        assert!(tags.iter().any(|(n, _)| n == "v1.0"));
    }

    #[tokio::test]
    async fn diff_identical_documents() {
        let store = MemoryStore::new();
        let repo = Repo::init(store);
        let h = ContentHash::from_canonical(b"same");
        let d = repo.diff(h, h).await.unwrap();
        assert!(d.is_empty());
    }
}