hawk_cli/models/
workspace.rs

1use colored::*;
2use serde::Deserialize;
3use serde::Serialize;
4use std::fmt;
5use std::fs;
6
7use crate::log;
8use crate::models::environment_files::PackageJson;
9
10pub type Result<T> = std::result::Result<T, WorkspaceError>;
11
12#[derive(Debug)]
13pub enum WorkspaceError {
14    InvalidName(String),
15    InvalidPath(String),
16}
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct Workspace {
20    pub name: String,
21    pub path: String,
22    pub package_json: Option<String>,
23}
24
25impl fmt::Display for WorkspaceError {
26    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
27        match self {
28            WorkspaceError::InvalidPath(path) => {
29                write!(f, "Workspace path ({}) does not exist", path)
30            }
31            WorkspaceError::InvalidName(name) => {
32                write!(f, "Workspace name ({}) cannot contain spaces", name)
33            }
34        }
35    }
36}
37
38impl Workspace {
39    pub fn validate_name(&self) -> Result<()> {
40        if self.name.contains(' ') {
41            return Err(WorkspaceError::InvalidName(self.name.clone()));
42        }
43
44        Ok(())
45    }
46
47    pub fn validate_path(&self) -> Result<()> {
48        if !std::path::Path::new(&self.path).exists() {
49            return Err(WorkspaceError::InvalidPath(self.path.clone()));
50        }
51
52        Ok(())
53    }
54
55    pub fn load_name_if_possible(&mut self) -> serde_json::Result<()> {
56        if let Some(path) = &self.package_json {
57            let mut p: String = path.into();
58
59            if std::path::Path::new(path).is_dir() {
60                p = format!("{}/package.json", path);
61            }
62
63            if !std::path::Path::new(&p).exists() {
64                log::warn(&format!(
65                    "Could not load package.json name for workspace: {}. Cannot find file.",
66                    self.name.underline()
67                ));
68                return Ok(());
69            }
70
71            let f = fs::File::open(p).expect("Unable to open package.json");
72            let pkg: PackageJson = serde_json::from_reader(f)?;
73
74            self.name = pkg.name;
75        }
76
77        Ok(())
78    }
79}