crosup_core/
config.rs

1use anyhow::Error;
2use owo_colors::OwoColorize;
3use std::path::Path;
4
5use crosup_types::{
6    configuration::Configuration, inventory::Inventory, CROSFILE_HCL, CROSFILE_TOML, INVENTORY_HCL,
7    INVENTORY_TOML,
8};
9
10pub fn verify_if_config_file_is_present() -> Result<(Configuration, String, String, bool), Error> {
11    if !Path::new(CROSFILE_HCL).exists() && !Path::new(CROSFILE_TOML).exists() {
12        let config = Configuration::default();
13        return Ok((
14            config.clone(),
15            CROSFILE_HCL.into(),
16            hcl::to_string(&config)?,
17            false,
18        ));
19    }
20
21    let current_dir = std::env::current_dir()?;
22
23    if Path::new(CROSFILE_HCL).exists() {
24        let config = std::fs::read_to_string(current_dir.join(CROSFILE_HCL))?;
25        let content = config.clone();
26        let config = hcl::from_str(&config)?;
27        return Ok((config, CROSFILE_HCL.into(), content, true));
28    }
29
30    let config = std::fs::read_to_string(current_dir.join(CROSFILE_TOML))?;
31    let content = config.clone();
32    let config = toml::from_str(&config)?;
33    return Ok((config, CROSFILE_TOML.into(), content, true));
34}
35
36pub fn verify_if_inventory_config_file_is_present() -> Result<Inventory, Error> {
37    if !Path::new(INVENTORY_HCL).exists() && !Path::new(INVENTORY_TOML).exists() {
38        return Err(anyhow::anyhow!(format!(
39            "Inventory file not found, please create one using {}",
40            "crosup init --inventory".bright_green()
41        )));
42    }
43
44    let current_dir = std::env::current_dir()?;
45
46    if Path::new(INVENTORY_HCL).exists() {
47        let config = std::fs::read_to_string(current_dir.join(INVENTORY_HCL))?;
48        let config = hcl::from_str(&config)?;
49        return Ok(config);
50    }
51
52    let config = std::fs::read_to_string(current_dir.join(INVENTORY_TOML))?;
53    let config = toml::from_str(&config)?;
54    return Ok(config);
55}