autosurgeon 0.12.0

A library for working with data in automerge 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
//! # AutoSurgeon
//!
//! `autosurgeon` is a library for interaction with [`automerge`] documents in Rust with an API
//! inspired by `serde`. The core of the library are two traits: [`Reconcile`], which describes how
//! to take a rust value and update an automerge document to match the value; and [`Hydrate`],
//! which describes how to create a rust value given an automerge document.
//!
//! Whilst you can implement [`Reconcile`] and [`Hydrate`] manually, `autosurgeon` provides derive
//! macros to do this work mechanically.
//!
//! Additionally `autosurgeon` provides the [`Counter`] and [`Text`] data types which implement
//! [`Reconcile`] and [`Hydrate`] for counters and text respectively.
//!
//! Currently this library does not handle incremental updates, that means that every time you
//! receive concurrent changes from other documents you will need to re-`hydrate` your data
//! structures from your document. This will be addressed in future versions.
//!
//! ## Feature Flags
//!
//! * `uuid` - Includes implementations of `Reconcile` and `Hydrate` for the [`Uuid`](https://docs.rs/uuid/latest/uuid/) crate which will
//!   reconcile to a [`automerge::ScalarValue::Bytes`]
//!
//! ## Example
//!
//! Imagine we are writing a program to interact with a document containing some contact details.
//! We start by writing some data types to represent the contact and deriving the [`Reconcile`] and
//! [`Hydrate`] traits.
//!
//! ```rust
//! # use autosurgeon::{Reconcile, Hydrate};
//! #[derive(Debug, Clone, Reconcile, Hydrate, PartialEq)]
//! struct Contact {
//!     name: String,
//!     address: Address,
//! }
//! #[derive(Debug, Clone, Reconcile, Hydrate, PartialEq)]
//! struct Address {
//!    line_one: String,
//!    line_two: Option<String>,
//!    city: String,
//!    postcode: String,
//! }
//! ```
//!
//! First we create a contact and put it into a document
//!
//! ```rust
//! # use autosurgeon::{Reconcile, Hydrate, reconcile};
//! # #[derive(Debug, Clone, Reconcile, Hydrate, PartialEq)]
//! # struct Contact {
//! #     name: String,
//! #     address: Address,
//! # }
//!
//! # #[derive(Debug, Clone, Reconcile, Hydrate, PartialEq)]
//! # struct Address {
//! #    line_one: String,
//! #    line_two: Option<String>,
//! #    city: String,
//! # }
//! let contact = Contact {
//!      name: "Sherlock Holmes".to_string(),
//!      address: Address{
//!          line_one: "221B Baker St".to_string(),
//!          line_two: None,
//!          city: "London".to_string(),
//!      },
//! };
//!
//! let mut doc = automerge::AutoCommit::new();
//! reconcile(&mut doc, &contact).unwrap();
//! ```
//!
//! Now we can reconstruct the contact from the document
//!
//! ```rust
//! # use autosurgeon::{Reconcile, Hydrate, reconcile, hydrate};
//! # #[derive(Debug, Clone, Reconcile, Hydrate, PartialEq)]
//! # struct Contact {
//! #     name: String,
//! #     address: Address,
//! # }
//!
//! # #[derive(Debug, Clone, Reconcile, Hydrate, PartialEq)]
//! # struct Address {
//! #    line_one: String,
//! #    line_two: Option<String>,
//! #    city: String,
//! # }
//! #
//! # let mut contact = Contact {
//! #      name: "Sherlock Holmes".to_string(),
//! #      address: Address{
//! #          line_one: "221B Baker St".to_string(),
//! #          line_two: None,
//! #          city: "London".to_string(),
//! #      },
//! # };
//! #
//! # let mut doc = automerge::AutoCommit::new();
//! # reconcile(&mut doc, &contact).unwrap();
//! let contact2: Contact = hydrate(&doc).unwrap();
//! assert_eq!(contact, contact2);
//! ```
//!
//! `reconcile` is smart though, it doesn't just update everything in the document, it figures out
//! what's changed, which means merging modified documents works as you would imagine. Let's fork
//! our document and make concurrent changes to it, then merge it and see how it looks.
//!
//! ```rust
//! # use autosurgeon::{Reconcile, Hydrate, reconcile, hydrate};
//! # #[derive(Debug, Clone, Reconcile, Hydrate, PartialEq)]
//! # struct Contact {
//! #     name: String,
//! #     address: Address,
//! # }
//! # #[derive(Debug, Clone, Reconcile, Hydrate, PartialEq)]
//! # struct Address {
//! #    line_one: String,
//! #    line_two: Option<String>,
//! #    city: String,
//! # }
//! #
//! # let mut contact = Contact {
//! #      name: "Sherlock Holmes".to_string(),
//! #      address: Address{
//! #          line_one: "221B Baker St".to_string(),
//! #          line_two: None,
//! #          city: "London".to_string(),
//! #      },
//! # };
//! #
//! # let mut doc = automerge::AutoCommit::new();
//! # reconcile(&mut doc, &contact).unwrap();
//! // Fork and make changes
//! let mut doc2 = doc.fork().with_actor(automerge::ActorId::random());
//! let mut contact2: Contact = hydrate(&doc2).unwrap();
//! contact2.name = "Dangermouse".to_string();
//! reconcile(&mut doc2, &contact2).unwrap();
//!
//! // Concurrently on doc1
//! contact.address.line_one = "221C Baker St".to_string();
//! reconcile(&mut doc, &contact).unwrap();
//!
//! // Now merge the documents
//! doc.merge(&mut doc2).unwrap();
//!
//! let merged: Contact = hydrate(&doc).unwrap();
//! assert_eq!(merged, Contact {
//!     name: "Dangermouse".to_string(), // This was updated in the first doc
//!     address: Address {
//!           line_one: "221C Baker St".to_string(), // This was concurrently updated in doc2
//!           line_two: None,
//!           city: "London".to_string(),
//!     }
//! })
//! ```
//!
//! ## Derive Macro
//!
//! ### Automerge Representation
//!
//! The derive macros map rust structs to the automerge structures in a similar manner to `serde`
//!
//! ```rust,no_run
//! struct W {
//!     a: i32,
//!     b: i32,
//! }
//! let w = W { a: 0, b: 0 }; // Represented as `{"a":0,"b":0}`
//!
//! struct X(i32, i32);
//! let x = X(0, 0); // Represented as `[0,0]`
//!
//! struct Y(i32);
//! let y = Y(0); // Represented as just the inner value `0`
//!
//! enum E {
//!     W { a: i32, b: i32 },
//!     X(i32, i32),
//!     Y(i32),
//!     Z,
//! }
//! let w = E::W { a: 0, b: 0 }; // Represented as `{"W":{"a":0,"b":0}}`
//! let x = E::X(0, 0);          // Represented as `{"X":[0,0]}`
//! let y = E::Y(0);             // Represented as `{"Y":0}`
//! let z = E::Z;                // Represented as `"Z"`
//! ```
//!
//! ### The `key` attribute
//!
//! `autosurgeon` will generally do its best to generate smart diffs. But sometimes you know
//! additional information about your data which can make merges smarter. Consider the following
//! scenario where we create a product catalog and then make concurrent changes to it.
//!
//! ```rust
//! # use automerge_test::{assert_doc, map, list};
//! # use autosurgeon::{reconcile, Reconcile, Hydrate};
//! #[derive(Reconcile, Hydrate, Clone, Debug, Eq, PartialEq)]
//! struct Product {
//!     id: u64,
//!     name: String,
//! }
//!
//! #[derive(Reconcile, Hydrate, Clone, Debug, Eq, PartialEq)]
//! struct Catalog {
//!     products: Vec<Product>,
//! }
//!
//! let mut catalog = Catalog {
//!     products: vec![
//!         Product {
//!             id: 1,
//!             name: "Lawnmower".to_string(),
//!         },
//!         Product {
//!             id: 2,
//!             name: "Strimmer".to_string(),
//!         }
//!     ]
//! };
//!
//! // Put the catalog into the document
//! let mut doc = automerge::AutoCommit::new();
//! reconcile(&mut doc, &catalog).unwrap();
//!
//! // Fork the document and insert a new product at the start of the catalog
//! let mut doc2 = doc.fork().with_actor(automerge::ActorId::random());
//! let mut catalog2 = catalog.clone();
//! catalog2.products.insert(0, Product {
//!     id: 3,
//!     name: "Leafblower".to_string(),
//! });
//! reconcile(&mut doc2, &catalog2).unwrap();
//!
//! // Concurrenctly remove a product from the catalog in the original doc
//! catalog.products.remove(0);
//! reconcile(&mut doc, &catalog).unwrap();
//!
//! // Merge the two changes
//! doc.merge(&mut doc2).unwrap();
//! assert_doc!(
//!     doc.document(),
//!     map! {
//!         "products" => { list! {
//!             // This first item is conflicted, we expected it to be the leafblower
//!             { map! {
//!                 "id" => { 2_u64, 3_u64 }, // Conflict on the ID
//!                 "name" => { "Strimmer", "Leafblower" }, // Conflict on the name
//!             }},
//!             { map! {
//!                 "id" => { 2_u64 },
//!                 "name" => { "Strimmer" },
//!             }}
//!         }}
//!     }
//! );
//! ```
//!
//! This is surprising, we have a bunch of merge conflicts on the fields of the first product in
//! the list (as signified by the multiple values in the `{..}` on the inner values of the `map!`)
//! and the second product in the list is also a strimmer. This is because `autosurgeon` has no way
//! of knowing the difference between "I inserted an item at the front of the products list" and "I
//! updated the first item in the products list".
//!
//! But we have an `id` field on the product, we can make autosurgeon aware of this.
//!
//! ```rust
//! # use automerge_test::{assert_doc, map, list};
//! # use autosurgeon::{reconcile, Reconcile, Hydrate};
//! #[derive(Reconcile, Hydrate, Clone, Debug, Eq, PartialEq)]
//! struct Product {
//!     #[key] // This is the important bit
//!     id: u64,
//!     name: String,
//! }
//! ```
//!
//! And with this our concurrent changes look like the following:
//!
//! ```rust
//! # use automerge_test::{assert_doc, map, list};
//! # use autosurgeon::{reconcile, Reconcile, Hydrate};
//! # #[derive(Reconcile, Hydrate, Clone, Debug, Eq, PartialEq)]
//! # struct Product {
//! #     #[key]
//! #     id: u64,
//! #     name: String,
//! # }
//! # #[derive(Reconcile, Hydrate, Clone, Debug, Eq, PartialEq)]
//! # struct Catalog {
//! #     products: Vec<Product>,
//! # }
//! # let mut catalog = Catalog {
//! #     products: vec![
//! #         Product {
//! #             id: 1,
//! #             name: "Lawnmower".to_string(),
//! #         },
//! #         Product {
//! #             id: 2,
//! #             name: "Strimmer".to_string(),
//! #         }
//! #     ]
//! # };
//! # let mut doc = automerge::AutoCommit::new();
//! # reconcile(&mut doc, &catalog).unwrap();
//! # let mut doc2 = doc.fork().with_actor(automerge::ActorId::random());
//! # let mut catalog2 = catalog.clone();
//! # catalog2.products.insert(0, Product {
//! #     id: 3,
//! #     name: "Leafblower".to_string(),
//! # });
//! # reconcile(&mut doc2, &catalog2).unwrap();
//! # catalog.products.remove(0);
//! # reconcile(&mut doc, &catalog).unwrap();
//! doc.merge(&mut doc2).unwrap();
//! assert_doc!(
//!     doc.document(),
//!     map! {
//!         "products" => { list! {
//!             { map! {
//!                 "id" => { 3_u64 },
//!                 "name" => { "Leafblower" },
//!             }},
//!             { map! {
//!                 "id" => { 2_u64 },
//!                 "name" => { "Strimmer" },
//!             }}
//!         }}
//!     }
//! );
//! ```
//!
//! ### Providing Implementations for foreign types
//!
//! Deriving `Hydrate` and `Reconcile` is fine for your own types, but sometimes you are using a
//! type which you did not write. For these situations there are a few attributes you can use.
//!
//! #### `reconcile=`
//!
//! The value of this attribute must be the name of a function with the same signature as
//! [`Reconcile::reconcile`]
//!
//! ```rust
//! # use autosurgeon::{Reconcile, Reconciler};
//! #[derive(Reconcile)]
//! struct File {
//!     #[autosurgeon(reconcile="reconcile_path")]
//!     path: std::path::PathBuf,
//! }
//!
//! fn reconcile_path<R: Reconciler>(
//!         path: &std::path::PathBuf, mut reconciler: R
//! ) -> Result<(), R::Error> {
//!     reconciler.str(path.display().to_string())
//! }
//! ```
//!
//! #### `hydrate=`
//!
//! The value of this attribute must be the name of a function with the same signature as
//! [`Hydrate::hydrate`]
//!
//! ```rust
//! # use autosurgeon::{Hydrate, ReadDoc, Prop, HydrateError};
//! #[derive(Hydrate)]
//! struct File {
//!     #[autosurgeon(hydrate="hydrate_path")]
//!     path: std::path::PathBuf,
//! }
//!
//! fn hydrate_path<'a, D: ReadDoc>(
//!     doc: &D,
//!     obj: &automerge::ObjId,
//!     prop: Prop<'a>,
//! ) -> Result<std::path::PathBuf, HydrateError> {
//!      let inner = String::hydrate(doc, obj, prop)?;
//!      inner.parse().map_err(|e| HydrateError::unexpected(
//!          "a valid path", format!("a path which failed to parse due to {}", e)
//!      ))
//! }
//! ```
//!
//! #### `with=`
//!
//! The value of this attribute must be the name of a module wich has both a `reconcile` function
//! and a `hydrate` function, with the same signatures as [`Reconcile::reconcile`] and
//! [`Hydrate::hydrate`] respectively.
//!
//! ```rust
//! # use autosurgeon::{Reconcile, Hydrate, ReadDoc, Prop, HydrateError};
//! #[derive(Hydrate)]
//! struct File {
//!     #[autosurgeon(with="autosurgeon_path")]
//!     path: std::path::PathBuf,
//! }
//!
//! mod autosurgeon_path {
//!     use autosurgeon::{Reconcile, Reconciler, Hydrate, ReadDoc, Prop, HydrateError};
//!     pub(super) fn hydrate<'a, D: ReadDoc>(
//!         doc: &D,
//!         obj: &automerge::ObjId,
//!         prop: Prop<'a>,
//!     ) -> Result<std::path::PathBuf, HydrateError> {
//!          let inner = String::hydrate(doc, obj, prop)?;
//!          inner.parse().map_err(|e| HydrateError::unexpected(
//!              "a valid path", format!("a path which failed to parse due to {}", e)
//!          ))
//!     }
//!
//!     pub(super) fn reconcile<R: Reconciler>(
//!             path: &std::path::PathBuf, mut reconciler: R
//!     ) -> Result<(), R::Error> {
//!         reconciler.str(path.display().to_string())
//!     }
//! }
//! ```
//!
//! #### Providing default values with `missing=`
//!
//! Occasionally you may want to provide a default value for a field which
//! wasn't found in the document. This can be done using the `missing` attribute.
//! The value of the `missing` attribute should be the name of a function which
//! returns a value of the annotated field.
//!
//! ```rust
//! # use autosurgeon::{Reconcile, Hydrate, ReadDoc, Prop, HydrateError, hydrate};
//! # use automerge::transaction::Transactable;
//! #[derive(Hydrate)]
//! struct Contact {
//!     name: String,
//!     #[autosurgeon(missing="Visibility::default")]
//!     visibility: Visibility
//! }
//!
//! #[derive(Hydrate, Default, Debug, PartialEq)]
//! enum Visibility {
//!     #[default]
//!     Public,
//!     Private,
//! }
//!
//! let mut doc = automerge::AutoCommit::new();
//! doc.put(&automerge::ROOT, "name", "Sherlock Holmes".to_string());
//! let contact: Contact = hydrate(&doc).unwrap();
//! assert_eq!(contact.visibility, Visibility::Public);
//!
//! ```
//!
//! ### Renaming fields and variants with `rename=`
//!
//! By default, struct fields and enum variants are serialized using their Rust identifier names.
//! The `rename` attribute allows you to specify a custom name for the serialized form. This is
//! useful when:
//!
//! - You need to use names that aren't valid Rust identifiers (e.g., names with hyphens)
//! - You want to maintain compatibility with existing data that uses different naming conventions
//! - You're interoperating with other systems that expect specific field names
//!
//! #### Renaming struct fields
//!
//! ```rust
//! # use autosurgeon::{Reconcile, Hydrate, reconcile, hydrate};
//! #[derive(Reconcile, Hydrate, Debug, PartialEq)]
//! struct Config {
//!     #[autosurgeon(rename = "api-key")]
//!     api_key: String,
//!
//!     #[autosurgeon(rename = "max-retries")]
//!     max_retries: u64,
//! }
//!
//! let config = Config {
//!     api_key: "secret".to_string(),
//!     max_retries: 3,
//! };
//!
//! let mut doc = automerge::AutoCommit::new();
//! reconcile(&mut doc, &config).unwrap();
//!
//! // The document now contains keys "api-key" and "max-retries"
//! // instead of "api_key" and "max_retries"
//!
//! let hydrated: Config = hydrate(&doc).unwrap();
//! assert_eq!(config, hydrated);
//! ```
//!
//! #### Renaming enum variants
//!
//! The `rename` attribute can also be applied to enum variants:
//!
//! ```rust
//! # use autosurgeon::{Reconcile, Hydrate, reconcile, hydrate};
//! # use autosurgeon::reconcile::reconcile_prop;
//! #[derive(Reconcile, Hydrate, Debug, PartialEq)]
//! enum Status {
//!     #[autosurgeon(rename = "in-progress")]
//!     InProgress,
//!
//!     #[autosurgeon(rename = "done")]
//!     Completed,
//!
//!     Active,  // Not renamed, uses "Active"
//! }
//!
//! let mut doc = automerge::AutoCommit::new();
//! reconcile_prop(&mut doc, automerge::ROOT, "status", Status::InProgress).unwrap();
//!
//! // The document contains "in-progress" as the status value
//!
//! let status: Status = autosurgeon::hydrate_prop(&doc, automerge::ROOT, "status").unwrap();
//! assert_eq!(status, Status::InProgress);
//! ```
//!
//! #### Combining field and variant renames
//!
//! You can combine field renames within enum variants:
//!
//! ```rust
//! # use autosurgeon::{Reconcile, Hydrate, reconcile, hydrate};
//! #[derive(Reconcile, Hydrate, Debug, PartialEq)]
//! enum Event {
//!     #[autosurgeon(rename = "user-login")]
//!     UserLogin {
//!         #[autosurgeon(rename = "user-id")]
//!         user_id: String,
//!         timestamp: u64,
//!     },
//! }
//!
//! let event = Event::UserLogin {
//!     user_id: "user123".to_string(),
//!     timestamp: 1234567890,
//! };
//!
//! let mut doc = automerge::AutoCommit::new();
//! reconcile(&mut doc, &event).unwrap();
//!
//! // The document contains {"user-login": {"user-id": "user123", "timestamp": 1234567890}}
//!
//! let hydrated: Event = hydrate(&doc).unwrap();
//! assert_eq!(event, hydrated);
//! ```

#[doc = include_str!("../../README.md")]
#[cfg(doctest)]
pub struct ReadmeDoctests;

mod counter;
pub use counter::Counter;
pub mod bytes;
mod doc;
pub use doc::{Doc, ReadDoc};
pub mod hydrate;
#[doc(inline)]
pub use hydrate::{hydrate, hydrate_path, hydrate_prop, Hydrate, HydrateError, MaybeMissing};
pub mod reconcile;
#[doc(inline)]
pub use reconcile::{
    hydrate_key, reconcile, reconcile_insert, reconcile_prop, Reconcile, ReconcileError, Reconciler,
};
mod text;
pub use text::Text;
pub mod map_with_parseable_keys;

mod prop;
pub use prop::Prop;

pub use autosurgeon_derive::{Hydrate, Reconcile};

#[cfg(feature = "uuid")]
mod uuid;