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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! This library is a storage agnostic abstraction over [OCFL repositories](https://ocfl.io/).
//! Currently, the only concrete implementation, [FsOcflRepo](rocfl::FsOcflRepo) works against
//! local filesystems.

use core::fmt;
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap};
use std::convert::TryFrom;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::path::Path;
use std::rc::Rc;
use std::str::FromStr;

use anyhow::{anyhow, Error, Result};
use chrono::{DateTime, Local};
use grep::regex::RegexMatcher;
use lazy_static::lazy_static;
use regex::Regex;
use serde::Deserialize;
use serde::export::Formatter;
use thiserror::Error;

pub use self::fs::FsOcflStore;

mod fs;

const OBJECT_MARKER: &str = "0=ocfl_object_1.0";
const ROOT_INVENTORY_FILE: &str = "inventory.json";
const MUTABLE_HEAD_INVENTORY_FILE: &str = "extensions/0004-mutable-head/head/inventory.json";

lazy_static! {
    static ref VERSION_REGEX: Regex = Regex::new(r#"^v\d+$"#).unwrap();
    static ref OBJECT_ID_MATCHER: RegexMatcher = RegexMatcher::new(r#""id"\s*:\s*"([^"]+)""#).unwrap();
}

/// Interface for interacting with an OCFL repository
pub struct OcflRepo {
    store: Box<dyn OcflStore>
}

impl OcflRepo {
    /// Creates a new `OcflRepo` instance backed by the local filesystem. `storage_root` is the
    /// location of the OCFL repository to open.
    pub fn new_fs_repo<P: AsRef<Path>>(storage_root: P) -> Result<Self> {
        Ok(Self {
            store: Box::new(FsOcflStore::new(storage_root)?)
        })
    }

    /// Returns an iterator that iterate through all of the objects in an OCFL repository.
    /// Objects are lazy-loaded. An optional glob pattern may be provided to filter the objects
    /// that are returned.
    ///
    /// The iterator return an error if it encounters a problem accessing an object. This does
    /// terminate the iterator; there are still more objects until it returns `None`.
    pub fn list_objects(&self, filter_glob: Option<&str>) -> Result<Box<dyn Iterator<Item=Result<ObjectVersionDetails>>>> {
        let inv_iter = self.store.iter_inventories(filter_glob)?;

        Ok(Box::new(InventoryAdapterIter::new(inv_iter, |inventory| {
            ObjectVersionDetails::from_inventory(inventory, None)
        })))
    }

    /// Returns a view of a version of an object. If a [VersionNum](rocfl::VersionNum) is not specified,
    /// then the head version of the object is returned.
    ///
    /// If the object or version of the object cannot be found, then a [NotFound](rocfl::RocflError::NotFound)
    /// error is returned.
    pub fn get_object(&self, object_id: &str, version_num: Option<&VersionNum>) -> Result<ObjectVersion> {
        let inventory = self.store.get_inventory(object_id)?;
        Ok(ObjectVersion::from_inventory(inventory, version_num)?)
    }

    /// Returns high-level details about an object version. This method is similar to
    /// [get_object](rocfl::OcflRepo::get_object) except that it does less processing and does not
    /// include the version's state.
    ///
    /// If the object or version of the object cannot be found, then a [NotFound](rocfl::RocflError::NotFound)
    /// error is returned.
    pub fn get_object_details(&self, object_id: &str, version_num: Option<&VersionNum>) -> Result<ObjectVersionDetails> {
        let inventory = self.store.get_inventory(object_id)?;
        Ok(ObjectVersionDetails::from_inventory(inventory, version_num)?)
    }

    /// Returns a vector containing the version metadata for ever version of an object. The vector
    /// is sorted in ascending order.
    ///
    /// If the object cannot be found, then a [NotFound](rocfl::RocflError::NotFound) error is returned.
    pub fn list_object_versions(&self, object_id: &str) -> Result<Vec<VersionDetails>> {
        let inventory = self.store.get_inventory(object_id)?;
        let mut versions = Vec::with_capacity(inventory.versions.len());

        for (id, version) in inventory.versions {
            versions.push(VersionDetails::from_version(id, version))
        }

        Ok(versions)
    }

    /// Returns a vector contain the version metadata for every version of an object that
    /// affected the specified file. The vector is sorted in ascending order.
    ///
    /// If the object or path cannot be found, then a [NotFound](rocfl::RocflError::NotFound) error is returned.
    pub fn list_file_versions(&self, object_id: &str, path: &str) -> Result<Vec<VersionDetails>> {
        let inventory = self.store.get_inventory(object_id)?;

        let mut versions = Vec::new();

        let path = path.to_string();
        let mut current_digest: Option<String> = None;

        for (id, version) in inventory.versions {
            match version.lookup_digest(&path) {
                Some(digest) => {
                    if current_digest.is_none() || current_digest.as_ref().unwrap().ne(digest) {
                        current_digest = Some(digest.clone());
                        versions.push(VersionDetails::from_version(id, version));
                    }
                },
                None => {
                    if current_digest.is_some() {
                        current_digest = None;
                        versions.push(VersionDetails::from_version(id, version));
                    }
                }
            }
        }

        Ok(versions)
    }

    /// Returns the diff of two object versions. If only one version is specified, then the diff
    /// is between the specified version and the version before it.
    ///
    /// If the object cannot be found, then a [NotFound](rocfl::RocflError::NotFound) error is returned.
    pub fn diff(&self, object_id: &str, left_version: &VersionNum, right_version: Option<&VersionNum>) -> Result<Vec<Diff>> {
        if right_version.is_some() && left_version.eq(right_version.unwrap()) {
            return Ok(vec![])
        }

        let mut inventory = self.store.get_inventory(object_id)?;

        let left = inventory.remove_version(&left_version)?;

        let right = match right_version {
            Some(version) => Some(inventory.remove_version(version)?),
            None => {
                if left_version.number > 1 {
                    Some(inventory.remove_version(&left_version.previous().unwrap())?)
                } else {
                    None
                }
            }
        };

        let mut left_state = invert_path_map(left.state);

        let mut diffs = Vec::new();

        if right.is_none() {
            for (path, _digest) in left_state {
                diffs.push(Diff::added(path));
            }
        } else {
            let right_state = invert_path_map(right.unwrap().state);

            for (path, right_digest) in right_state {
                match left_state.remove(&path) {
                    None => diffs.push(Diff::added(path)),
                    Some(left_digest) => {
                        if right_digest.deref().ne(left_digest.deref()) {
                            diffs.push(Diff::modified(path))
                        }
                    }
                }
            }

            for (path, _digest) in left_state {
                diffs.push(Diff::deleted(path))
            }
        }

        Ok(diffs)
    }
}

/// Indicates the associated type can retrieve [Inventories](rocfl::Inventory). Implement this trait
/// to get a blanket implementation of [OcflRepo](rocfl::OcflRepo).
trait OcflStore {
    /// Returns the most recent inventory version for the specified object, or an a
    /// [NotFound](rocfl::RocflError::NotFound) if it does not exist.
    fn get_inventory(&self, object_id: &str) -> Result<Inventory>;

    /// Returns an iterator that iterates over every object in an OCFL repository, returning
    /// the most recent inventory of each. Optionally, a glob pattern may be provided that filters
    /// the objects that are returned by OCFL ID.
    fn iter_inventories(&self, filter_glob: Option<&str>) -> Result<Box<dyn Iterator<Item=Result<Inventory>>>>;
}

/// An iterator that adapts the out of `InventoryIter`.
struct InventoryAdapterIter<T> {
    iter: Box<dyn Iterator<Item=Result<Inventory>>>,
    adapter: Box<dyn Fn(Inventory) -> Result<T>>
}

impl<T> InventoryAdapterIter<T> {
    /// Creates a new `InventoryAdapterIter` that applies the `adapter` closure to the output
    /// of every `next()` call.
    fn new(iter: Box<dyn Iterator<Item=Result<Inventory>>>, adapter: impl Fn(Inventory) -> Result<T> + 'static) -> Self {
        Self {
            iter,
            adapter: Box::new(adapter)
        }
    }
}

impl<T> Iterator for InventoryAdapterIter<T> {
    type Item = Result<T>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.iter.next() {
            None => None,
            Some(Err(e)) => Some(Err(e)),
            Some(Ok(inventory)) => {
                Some(self.adapter.deref()(inventory))
            }
        }
    }
}

/// Represents an [OCFL object version](https://ocfl.io/1.0/spec/#version-directories).
#[derive(Deserialize, Debug)]
#[serde(try_from = "&str")]
pub struct VersionNum {
    pub number: u32,
    pub width: usize,
}

impl VersionNum {
    /// Returns the previous version, or an Error if the previous version is invalid (less than 1).
    pub fn previous(&self) -> Result<VersionNum> {
        if self.number - 1 < 1 {
            return Err(anyhow!("Versions cannot be less than 1"));
        }

        Ok(Self {
            number: self.number - 1,
            width: self.width,
        })
    }

    /// Returns the next version, or an Error if the next version is invalid. Version number only
    /// have limits if they are zero-padded.
    pub fn next(&self) -> Result<VersionNum> {
        let max = match self.width {
            0 => usize::MAX,
            _ => (10 * (self.width - 1)) - 1
        };

        if self.number + 1 > max as u32 {
            return Err(anyhow!("Version cannot be greater than {}", max));
        }

        Ok(Self {
            number: self.number + 1,
            width: self.width,
        })
    }
}

impl TryFrom<&str> for VersionNum {
    type Error = RocflError;

    /// Parses a string in the format of `v1` or `v0002` into a `VersionNum`. An error is return if
    /// the version string is invalid.
    fn try_from(version: &str) -> Result<Self, Self::Error> {
        if !VERSION_REGEX.is_match(version) {
            return Err(RocflError::IllegalArgument(format!("Invalid version {}", version)));
        }

        match version[1..].parse::<u32>() {
            Ok(num) => {
                if num < 1 {
                    return Err(RocflError::IllegalArgument(format!("Invalid version {}", version)));
                }

                let width = match version.starts_with("v0") {
                    true => version.len() - 1,
                    false => 0
                };

                Ok(Self {
                    number: num,
                    width,
                })
            },
            Err(_) => return Err(RocflError::IllegalArgument(format!("Invalid version {}", version)))
        }
    }
}

impl TryFrom<u32> for VersionNum {
    type Error = RocflError;

    /// Parses a positive integer into a `VersionNum`. An error is returned if it is invalid.
    fn try_from(version: u32) -> Result<Self, Self::Error> {
        if version < 1 {
            return Err(RocflError::IllegalArgument(format!("Invalid version number {}", version)));
        }

        Ok(Self {
            number: version,
            width: 0,
        })
    }
}

impl FromStr for VersionNum {
    type Err = Error;

    /// This function is used when parsing command line arguments. It attempts to interpret a string
    /// as a version if it is formatted like any of these examples: `v3`, `v00009`, or `8`.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match VersionNum::try_from(s) {
            Ok(v) => Ok(v),
            Err(_) => Ok(VersionNum::try_from(u32::from_str(s)?)?),
        }
    }
}

impl Clone for VersionNum {
    fn clone(&self) -> Self {
        Self {
            number: self.number,
            width: self.width,
        }
    }
}

impl fmt::Display for VersionNum {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "v{:0width$}", self.number, width = self.width)
    }
}

impl PartialEq for VersionNum {
    fn eq(&self, other: &Self) -> bool {
        self.number == other.number
    }
}

impl Eq for VersionNum {}

impl Hash for VersionNum {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.number.hash(state)
    }
}

impl PartialOrd for VersionNum {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for VersionNum {
    fn cmp(&self, other: &Self) -> Ordering {
        self.number.cmp(&other.number)
    }
}

/// Represents a version of an OCFL object.
#[derive(Debug)]
pub struct ObjectVersion {
    /// The object's ID
    pub id: String,
    /// The path from the storage root to the object root
    pub object_root: String,
    /// The algorithm used to calculate digests (sha512 or sha256)
    pub digest_algorithm: String,
    /// Metadata about the version
    pub version_details: VersionDetails,
    /// A map of files (logical paths) in the version to details about the files.
    pub state: HashMap<String, FileDetails>,
}

/// Details about a file in an OCFL object.
#[derive(Debug)]
pub struct FileDetails {
    /// The file's digest
    pub digest: Rc<String>,
    /// The digest algorithm
    pub digest_algorithm: Rc<String>,
    /// The path to the file relative the object root
    pub content_path: String,
    /// The path to the file relative the storage root
    pub storage_path: String,
    /// The version metadata for when the file was last updated
    pub last_update: Rc<VersionDetails>,
}

/// Metadata about a version.
#[derive(Debug)]
pub struct VersionDetails {
    /// The version number of the version
    pub version_num: VersionNum,
    /// When the version was created
    pub created: DateTime<Local>,
    /// The name of the person who created the version
    pub user_name: Option<String>,
    /// The address of the person who created the version
    pub user_address: Option<String>,
    /// A description of the version
    pub message: Option<String>,
}

/// Similar to [ObjectVersion](rocfl::ObjectVersion), except it does not contain the state map.
#[derive(Debug)]
pub struct ObjectVersionDetails {
    /// The object's ID
    pub id: String,
    /// The path from the storage root to the object root
    pub object_root: String,
    /// The algorithm used to calculate digests (sha512 or sha256)
    pub digest_algorithm: String,
    /// Metadata about the version
    pub version_details: VersionDetails,
}

impl ObjectVersion {
    /// Creates an `ObjectVersion` by consuming the supplied `Inventory`.
    fn from_inventory(mut inventory: Inventory, version_num: Option<&VersionNum>) -> Result<Self> {
        let version_num = match version_num {
            Some(version) => version.clone(),
            None => inventory.head.clone(),
        };

        let version = inventory.get_version(&version_num)?;
        let version_details = VersionDetails::new(&version_num, version);

        let state = ObjectVersion::construct_state(&version_num, &mut inventory)?;

        Ok(Self {
            id: inventory.id,
            object_root: inventory.object_root,
            digest_algorithm: inventory.digest_algorithm,
            version_details,
            state
        })
    }

    fn construct_state(target: &VersionNum, inventory: &mut Inventory) -> Result<HashMap<String, FileDetails>> {
        let mut state = HashMap::new();

        let digest_algorithm = Rc::new(inventory.digest_algorithm.clone());
        let mut current_version_num = (*target).clone();
        let mut current_version = inventory.remove_version(target)?;
        let mut target_path_map = invert_path_map(current_version.state);
        current_version.state = HashMap::new();

        while !target_path_map.is_empty() {
            let mut not_found = HashMap::new();
            let version_details = Rc::new(VersionDetails::from_version(current_version_num, current_version));

            // No versions left to compare to; any remaining files were last updated here
            if version_details.version_num.number == 1 {
                for (target_path, target_digest) in target_path_map.into_iter() {
                    let content_path = inventory.lookup_content_path(&target_digest)?.to_string();
                    state.insert(target_path, FileDetails::new(content_path,
                                                               target_digest,
                                                               Rc::clone(&digest_algorithm),
                                                               &inventory.object_root,
                                                               Rc::clone(&version_details)));
                }

                break;
            }

            let previous_version_num = version_details.version_num.previous()?;
            let mut previous_version = inventory.remove_version(&previous_version_num)?;
            let mut previous_path_map = invert_path_map(previous_version.state);
            previous_version.state = HashMap::new();

            for (target_path, target_digest) in target_path_map.into_iter() {
                let entry = previous_path_map.remove_entry(&target_path);

                if entry.is_none() || entry.unwrap().1 != target_digest {
                    let content_path = inventory.lookup_content_path(&target_digest)?.to_string();
                    state.insert(target_path, FileDetails::new(content_path,
                                                               target_digest,
                                                               Rc::clone(&digest_algorithm),
                                                               &inventory.object_root,
                                                               Rc::clone(&version_details)));
                } else {
                    not_found.insert(target_path, target_digest);
                }
            }

            current_version_num = previous_version_num;
            current_version = previous_version;

            target_path_map = not_found;
        }

        Ok(state)
    }
}

impl FileDetails {
    fn new(content_path: String, digest: Rc<String>, digest_algorithm: Rc<String>,
           object_root: &str, version_details: Rc<VersionDetails>) -> Self {
        Self {
            storage_path: format!("{}/{}", object_root, content_path),
            content_path,
            digest,
            digest_algorithm,
            last_update: version_details,
        }
    }
}

impl VersionDetails {
    /// Creates `VersionDetails` by cloning the input.
    fn new(version_num: &VersionNum, version: &Version) -> Self {
        let (user, address) = match &version.user {
            Some(user) => (user.name.clone(), user.address.clone()),
            None => (None, None)
        };

        Self {
            version_num: version_num.clone(),
            created: version.created.clone(),
            user_name: user,
            user_address: address,
            message: version.message.clone()
        }
    }

    /// Creates `VersionDetails` by consuming the input.
    fn from_version(version_num: VersionNum, version: Version) -> Self {
        let (user, address) = match version.user {
            Some(user) => (user.name, user.address),
            None => (None, None)
        };

        Self {
            version_num,
            created: version.created,
            user_name: user,
            user_address: address,
            message: version.message,
        }
    }
}

/// Transforms an input map of digest to vector of paths to a map of paths to digests.
/// The original map is consumed.
fn invert_path_map(map: HashMap<String, Vec<String>>) -> HashMap<String, Rc<String>> {
    let mut inverted = HashMap::new();

    for (digest, paths) in map.into_iter() {
        let digest = Rc::new(digest);
        for path in paths.into_iter() {
            inverted.insert(path, Rc::clone(&digest));
        }
    }

    inverted
}

impl ObjectVersionDetails {
    /// Creates `ObjectVersionDetails` by consuming the `Inventory`.
    fn from_inventory(mut inventory: Inventory, version_num: Option<&VersionNum>) -> Result<Self> {
        let version_num = match version_num {
            Some(version) => version.clone(),
            None => inventory.head.clone(),
        };

        let version = inventory.remove_version(&version_num)?;
        let version_details = VersionDetails::from_version(version_num, version);

        Ok(Self {
            id: inventory.id,
            object_root: inventory.object_root,
            digest_algorithm: inventory.digest_algorithm,
            version_details,
        })
    }
}

/// Represents a change to a file
#[derive(Debug)]
pub struct Diff {
    /// The type of change
    pub diff_type: DiffType,
    /// The affected logical path
    pub path: String,
}

/// Represents a type of change
#[derive(Debug)]
pub enum DiffType {
    Added,
    Modified,
    Deleted,
}

impl Diff {
    fn added(path: String) -> Self {
        Self {
            diff_type: DiffType::Added,
            path
        }
    }
    fn modified(path: String) -> Self {
        Self {
            diff_type: DiffType::Modified,
            path
        }
    }
    fn deleted(path: String) -> Self {
        Self {
            diff_type: DiffType::Deleted,
            path
        }
    }
}

/// OCFL inventory serialization object
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Inventory {
    id: String,
    #[serde(rename = "type")]
    type_declaration: String,
    digest_algorithm: String,
    head: VersionNum,
    content_directory: Option<String>,
    manifest: HashMap<String, Vec<String>>,
    versions: BTreeMap<VersionNum, Version>,
    fixity: Option<HashMap<String, HashMap<String, Vec<String>>>>,

    // This field is not in the inventory json file and must be added after deserialization
    #[serde(skip)]
    object_root: String,
}

/// OCFL version serialization object
#[derive(Deserialize, Debug)]
struct Version {
    created: DateTime<Local>,
    state: HashMap<String, Vec<String>>,
    message: Option<String>,
    user: Option<User>
}

/// OCFL user serialization object
#[derive(Deserialize, Debug)]
struct User {
    name: Option<String>,
    address: Option<String>
}

impl Inventory {
    // TODO fill in more validations
    // TODO have a shallow and a deep validation
    /// Performs a spot check on the inventory to see if it appears valid. This is not an
    /// exhaustive check, and does not guarantee that the inventory is valid.
    pub fn validate(&self) -> Result<()> {
        if !self.versions.contains_key(&self.head) {
            return Err(RocflError::CorruptObject {
                object_id: self.id.clone(),
                message: format!("HEAD version {} was not found", self.head),
            }.into())
        }
        Ok(())
    }

    /// Returns a reference to the specified version or an error if it does not exist.
    fn get_version(&self, version_num: &VersionNum) -> Result<&Version> {
        match self.versions.get(version_num) {
            Some(v) => Ok(v),
            None => Err(not_found(&self.id, Some(version_num)).into())
        }
    }

    /// Removes and returns the specified version from the inventory, or an error if it does not exist.
    fn remove_version(&mut self, version_num: &VersionNum) -> Result<Version> {
        match self.versions.remove(version_num) {
            Some(v) => Ok(v),
            None => Err(not_found(&self.id, Some(version_num)).into())
        }
    }

    /// Returns the first content path associated with the specified digest, or an error if it does
    /// not exist.
    fn lookup_content_path(&self, digest: &str) -> Result<&str> {
        match self.manifest.get(digest) {
            Some(paths) => {
                match paths.first() {
                    Some(path) => Ok(path.as_str()),
                    None => Err(RocflError::CorruptObject {
                        object_id: self.id.clone(),
                        message: format!("Digest {} is not mapped to any content paths", digest)
                    }.into())
                }
            },
            None => Err(RocflError::CorruptObject {
                object_id: self.id.clone(),
                message: format!("Digest {} not found in manifest", digest)
            }.into())
        }
    }
}

impl Version {
    /// Returns a reference to the digest associated to a logical path, or None if the logical
    /// path does not exist in the version's state.
    fn lookup_digest(&self, logical_path: &String) -> Option<&String> {
        for (digest, paths) in &self.state {
            if paths.contains(logical_path) {
                return Some(digest);
            }
        }

        None
    }
}

/// Constructs a NonFound Error.
fn not_found(object_id: &str, version_num: Option<&VersionNum>) -> RocflError {
    match version_num {
        Some(version) => RocflError::NotFound(format!("Object {} version {}", object_id, version)),
        None => RocflError::NotFound(format!("Object {}", object_id))
    }
}

#[derive(Error, Debug)]
pub enum RocflError {
    #[error("Object {object_id} is corrupt: {message}")]
    CorruptObject {
        object_id: String,
        message: String,
    },
    #[error("Not found: {0}")]
    NotFound(String),
    #[error("Illegal argument: {0}")]
    IllegalArgument(String)
}