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
//! Provides utilities for developing Crates for the Crab-Shell.
//! 
//! The most useful one is the Environment struct,  
//! 
//! 
//! 
//!
//! 

use once_cell::sync::Lazy;

/// Struct that contains all Crab-Shell variables.
#[allow(dead_code)]
#[derive(serde_derive::Deserialize, serde_derive::Serialize, Debug, Clone)]
pub struct Environment {
    /// Same as `std::env::current_dir`, used to modify the current directory of the shell from a Crate
    pub current_dir: String,

    /// Extra directories the shell will look for Crates
    pub crate_dirs: Vec<String>,

    /// Vector of all the global variables of the shell. 
    /// 
    /// It is saved between executions.
    pub global_vars: Vec<toml::Value>,

    /// Return value the shell will use when using a Crate as an argument for another Crate.
    /// 
    /// It is sent to the other Crate as an arg, so it's the developer's job to parse it correctly.
    /// # Example: 
    /// 
    /// Shell input: `cd(location(cd))`
    /// ```
    /// // Returns the path of a Crate
    /// fn location() {
    ///     let env = crab_env::load();
    ///     
    /// 
    /// }
    /// 
    /// 
    ///
    /// 
    /// ```
    /// 
    pub return_val: String,
}

#[allow(dead_code)]
impl Environment {
    // Creates a new Environment with empty values.
    pub fn default() -> Self {
        Self { current_dir: String::new(), crate_dirs: Vec::new(), global_vars: Vec::new(), return_val: String::new() }
    }

    /// Loads the current Environment from CONFIG_PATH/env.toml and returns it.
    pub fn load() -> Environment {
        toml::from_str(
            &std::fs::read_to_string(ENV_PATH.as_path())
            .unwrap_or(String::new()))
            .unwrap_or(Environment::default())
    }

    /// Loads the current Environment from CONFIG_PATH/env.toml into the provided env, overwriting it.
    pub fn load_into(&mut self) {
        let temp = Environment::load();
        self.current_dir = temp.current_dir;
        self.global_vars = temp.global_vars;
        self.return_val = temp.return_val;
    }

    /// Saves Environment into CONFIG_PATH/env.toml
    pub fn save(&self) {
        std::fs::write(ENV_PATH.as_path(), toml::to_string(self).unwrap_or(ENV_DEFAULT.into())).unwrap();
    }

    /// Assigns `value` to [return_val](`struct.Environment.return_val`) and [saves](`save`) it to 
    pub fn return_and_save(&mut self, value: &str) {
        self.return_val = value.into();
        Environment::save(self);
    }
}

/// Loads the current Environment from CONFIG_PATH/env.toml and returns it.
pub fn load() -> Environment {
    Environment::load()
}

/// Loads the current Environment from `CONFIG_PATH/env.toml` into the provided env, overwriting it.
pub fn load_into(env: &mut Environment) {
    Environment::load_into(env)
}

/// Saves Environment into `CONFIG_PATH/env.toml`
/// 
/// Panics if `CONFIG_PATH/env.toml` cannot be accessed.
pub fn save(env: &Environment) {
    Environment::save(env)
}

/// Returns Crab-Shell's main directories paths (CONFIG and DATA).
pub static PATHS: Lazy<directories::ProjectDirs> =
    Lazy::new(|| match directories::ProjectDirs::from("com", "", "crab") {
        None => {
            println!("Unable to write to home directory, maybe you don't have permissions?");
            std::process::exit(1);
        }
        Some(v) => {
            if !v.config_dir().join("env.toml").exists() {
                std::fs::write(
                    v.config_dir().join("crates/env.toml"),
                    ENV_DEFAULT,
                )
                .unwrap();
            }
            v
        }
    });

pub const CONFIG_PATH: Lazy<&'static std::path::Path> = Lazy::new(|| PATHS.config_dir());

pub const ENV_DEFAULT: &'static str = include_str!("env.toml");
pub static ENV_PATH: Lazy<std::path::PathBuf> = Lazy::new(|| PATHS.config_dir().join("env.toml"));

pub static CRATES_PATH: Lazy<std::path::PathBuf> = Lazy::new(|| PATHS.config_dir().join("crates"));

/// List of Crates currently installed.
pub static CRATES: Lazy<std::collections::HashSet<String>> = Lazy::new(|| {
    let mut crates = std::collections::HashSet::new();
    let dirs = match CRATES_PATH.read_dir() {
        Ok(p) => p,
        Err(e) => {
            std::fs::create_dir_all(CRATES_PATH.as_path()).expect(&e.to_string());
            std::process::exit(1);
        }
    };

    for file in dirs {
        if file.is_err() {
            break;
        }
        if file.as_ref().unwrap().file_type().unwrap().is_dir() {
            crates.insert(file.unwrap().file_name().to_string_lossy().into());
        }
    }

    for dir in load().crate_dirs {
        for file in std::fs::read_dir(dir).unwrap() {
            if file.is_err() {
                break;
            }
            let file = file.unwrap();
            if file.file_type().unwrap().is_dir() {
                crates.insert(file.file_name().to_string_lossy().into());
            }
        }
    }

    crates
});