plm_rs/
config.rs

1use anyhow::anyhow;
2use serde::{Deserialize, Serialize};
3use std::path::{Path, PathBuf};
4#[derive(Debug, Serialize, Deserialize)]
5pub enum AttritionType {
6    Each,
7    Percentage,
8}
9
10#[derive(Debug, Serialize, Deserialize)]
11pub struct AttritionEntry {
12    pub value: u32,
13    pub attype: AttritionType,
14}
15
16#[derive(Debug, Serialize, Deserialize)]
17pub struct AttritionConfig {
18    pub entries: Vec<AttritionEntry>,
19}
20
21/// Config that can be installed locally
22#[derive(Debug, Serialize, Deserialize)]
23pub struct Config {
24    /// Name of database within config folder
25    pub database_name: String,
26
27    /// Library name
28    pub library_name: String,
29
30    /// Attrition config
31    pub attrition_config: AttritionConfig,
32
33    /// Ignore parts that contain one of these
34    pub part_number_ignore_list: Vec<String>,
35}
36
37/// Set config
38pub fn save_config(config: &Config, config_path: &Path) -> anyhow::Result<()> {
39    // With init data create config.toml
40    let config_string = toml::to_string(config).unwrap();
41
42    // Save config toml
43    std::fs::write(config_path, config_string)?;
44
45    Ok(())
46}
47
48/// Fetch the configuration from the provided folder path
49pub fn load_config(config_path: &Path) -> anyhow::Result<Config> {
50    // Read file to end
51    let config = std::fs::read_to_string(&config_path)?;
52
53    // Deserialize
54    Ok(toml::from_str(&config)?)
55}
56
57/// Calculate config path depending on input
58pub fn get_config_path(config_path: &Option<String>) -> anyhow::Result<PathBuf> {
59    match config_path {
60        Some(c) => Ok(PathBuf::from(c)),
61        None => {
62            // Get config path
63            let mut path = get_default_config_path()?;
64
65            // Create the config path
66            std::fs::create_dir_all(&path)?;
67
68            // Add file to path
69            path.push("config.toml");
70
71            // Return this guy
72            Ok(path)
73        }
74    }
75}
76
77/// Get default config path. ($HOME/.eagle-plm)
78pub fn get_default_config_path() -> anyhow::Result<PathBuf> {
79    // Get the config file from standard location
80    let mut config_path = match home::home_dir() {
81        Some(path) => path,
82        None => {
83            return Err(anyhow!("Impossible to get your home dir!"));
84        }
85    };
86
87    // Append config path to home directory
88    config_path.push(".eagle-plm");
89
90    // Return it
91    Ok(config_path)
92}