Radish alpha
h
rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5
Radicle Heartwood Protocol & Stack
Radicle
Git
radicle: Change `TryFrom` for `radicle::profile::Home` to `Home::load`
Merged did:key:z6MkkfM3...sVz5 opened 5 months ago

Instead of creating missing directories in the TryFrom<PathBuf> for Home, this commit will return Errors when there are issues with the folder structure.

radicle: Add a load method to radicle::profile::Home

Home::new always creates the missing subdirectories, in some cases where we only want a valid Home we need to fail and know that there isn’t a valid radicle::profile::Home at a specific path.

1 file changed +50 -9 ff85c74e 9dbbb01d
modified crates/radicle/src/profile.rs
@@ -536,14 +536,6 @@ pub struct Home {
    path: PathBuf,
}

-
impl TryFrom<PathBuf> for Home {
-
    type Error = io::Error;
-

-
    fn try_from(home: PathBuf) -> Result<Self, Self::Error> {
-
        Self::new(home)
-
    }
-
}
-

impl Home {
    /// Creates the Radicle Home directories.
    ///
@@ -565,7 +557,7 @@ impl Home {
            path: dunce::canonicalize(path)?,
        };

-
        for dir in &[home.storage(), home.keys(), home.node(), home.cobs()] {
+
        for dir in &home.subdirectories() {
            if !dir.exists() {
                fs::create_dir_all(dir)?;
            }
@@ -574,6 +566,55 @@ impl Home {
        Ok(home)
    }

+
    /// Load existing Radicle Home directories.
+
    ///
+
    /// The `home` path is the expected base directory for all necessary
+
    /// subdirectories.
+
    ///
+
    /// # Errors
+
    ///
+
    /// If `home` or any of the subdirectories are missing an [`io::Error`] is
+
    /// returned.
+
    pub fn load<P>(home: P) -> Result<Self, io::Error>
+
    where
+
        P: AsRef<Path>,
+
    {
+
        let path = home.as_ref();
+
        if !path.exists() {
+
            return Err(io::Error::new(
+
                io::ErrorKind::NotFound,
+
                format!("Radicle home directory does not exist: {}", path.display()),
+
            ));
+
        }
+
        let home = Self {
+
            path: dunce::canonicalize(path)?,
+
        };
+

+
        let missing = home
+
            .subdirectories()
+
            .into_iter()
+
            .filter(|dir| !dir.exists())
+
            .collect::<Vec<_>>();
+

+
        if !missing.is_empty() {
+
            let missing = missing
+
                .into_iter()
+
                .map(|dir| dir.display().to_string())
+
                .collect::<Vec<_>>()
+
                .join(",");
+
            return Err(io::Error::new(
+
                io::ErrorKind::NotFound,
+
                format!("Required Radicle directories are missing: [{}]", missing),
+
            ));
+
        }
+

+
        Ok(home)
+
    }
+

+
    fn subdirectories(&self) -> [PathBuf; 4] {
+
        [self.storage(), self.keys(), self.node(), self.cobs()]
+
    }
+

    pub fn path(&self) -> &Path {
        self.path.as_path()
    }