ecode_core/configs/
config.rs1use crate::configs::dirs_and_files;
2use serde::{Deserialize, Serialize};
3use std::{
4 fs::{self, File, OpenOptions},
5 io::prelude::*,
6 path::{Path, PathBuf},
7};
8
9#[derive(Serialize, Deserialize, Debug)]
10#[serde(rename_all = "camelCase")]
11pub struct Config {
12 pub profiles_folder: String,
13 pub create_new_profile_from: String,
14 pub vs_code_path: String,
15 #[serde(default = "bool::default")]
16 pub default_current_folder: bool,
17 #[serde(default = "bool::default")]
18 pub shared_profiles_configs: bool,
19}
20
21impl Config {
22 fn new() -> Self {
23 let bin_name = dirs_and_files::get_bin_or_cmd_name();
24 let bin_code_path = dirs_and_files::find_it(bin_name).unwrap_or_default();
25
26 let profiles_dir = dirs_and_files::create_or_get_ena_home_folder()
27 .unwrap()
28 .join("vs-code-profiles");
29
30 Self {
31 create_new_profile_from: "Default".into(),
32 profiles_folder: dirs_and_files::path_to_string(profiles_dir),
33 vs_code_path: dirs_and_files::path_to_string(bin_code_path),
34 default_current_folder: false,
35 shared_profiles_configs: false,
36 }
37 }
38
39 pub fn get_config_raw() -> Self {
40 let mut config = Self::new();
41
42 let config_file_path = get_ena_config_path();
43
44 if let Ok(config_string) = fs::read_to_string(config_file_path) {
45 let config_obj = serde_yaml::from_str::<Config>(&config_string[..]);
46
47 if let Ok(config_obj) = config_obj {
48 config = config_obj;
49 }
50 }
51
52 config
53 }
54
55 pub fn create_config() {
56 let config_file_path = get_ena_config_path();
57
58 match File::create(config_file_path) {
59 Ok(mut file) => {
60 let obj = Self::new();
61
62 if let Ok(yml) = serde_yaml::to_string(&obj) {
63 if let Err(why) = file.write_all(yml.as_bytes()) {
64 println!("Config couldn't be written, {:?}", why);
65 }
66 }
67 }
68 Err(why) => println!("Error creating config.yml, {:?}", why),
69 }
70 }
71
72 pub fn get_config(verbose: bool) -> Self {
73 if !Path::new(&get_ena_config_path()).exists() {
74 Self::create_config();
75 }
76 let config = Self::get_config_raw();
77 if verbose {
78 println!("{:?}", &config)
79 }
80 config
81 }
82
83 pub fn save_config(&self) {
84 let ena_config_path = get_ena_config_path();
85
86 let string = serde_yaml::to_string(self).unwrap();
87 let mut file = OpenOptions::new()
88 .read(false)
89 .write(true)
90 .append(false)
91 .create(true)
92 .open(ena_config_path)
93 .unwrap();
94
95 let string_encoded = string.as_bytes();
96 file.write_all(string_encoded).unwrap();
97 }
98}
99
100fn get_ena_config_path() -> PathBuf {
101 dirs_and_files::create_or_get_ena_home_folder()
102 .unwrap()
103 .join("config.yml")
104}