quick_links_rofi/
config.rs1use std::{
2 fs::{create_dir_all, File},
3 io::{Read, Write},
4};
5
6use serde_derive::{Deserialize, Serialize};
7
8#[derive(Debug, Deserialize, Serialize)]
9pub struct Config {
10 pub input_file: String,
11 pub theme: String,
12 pub separator: char,
13 pub browser_command_name: String,
14 pub workspace_switcher: Option<WorkspaceSwitcher>,
15}
16
17#[derive(Debug, Deserialize, Serialize)]
18pub struct WorkspaceSwitcher {
19 pub custom: Option<String>,
20 pub i3: Option<I3Switcher>,
21}
22
23impl From<I3Switcher> for WorkspaceSwitcher {
24 fn from(value: I3Switcher) -> Self {
25 WorkspaceSwitcher {
26 custom: None,
27 i3: Some(value),
28 }
29 }
30}
31
32impl From<String> for WorkspaceSwitcher {
33 fn from(value: String) -> Self {
34 WorkspaceSwitcher {
35 custom: Some(value),
36 i3: None,
37 }
38 }
39}
40
41#[derive(Debug, Deserialize, Serialize)]
42pub struct I3Switcher {
43 pub workspace_number: u8,
44}
45
46impl Default for I3Switcher {
47 fn default() -> Self {
48 I3Switcher {
49 workspace_number: 1,
50 }
51 }
52}
53
54impl I3Switcher {
55 pub fn new(number: u8) -> Self {
56 Self {
57 workspace_number: number,
58 }
59 }
60}
61
62impl Default for Config {
63 fn default() -> Self {
64 Self {
65 input_file: format!("{}/links.txt", config_folder_path()),
66 theme: format!("{}/theme.rasi", config_folder_path()),
67 separator: ',',
68 browser_command_name: String::from("firefox"),
69 workspace_switcher: Some(I3Switcher::default().into()),
70 }
71 }
72}
73
74fn save_yml_config(config: &Config, path: &str) -> anyhow::Result<()> {
75 let yaml_string = serde_yaml::to_string(&config)?;
76
77 let mut file = File::create(path)?;
78 file.write_all(yaml_string.as_bytes())?;
79
80 Ok(())
81}
82
83fn save_default_config(config_path: &str) -> anyhow::Result<Config> {
84 let config = Config::default();
85 save_yml_config(&config, config_path)?;
86 Ok(config)
87}
88
89pub fn get_configuration() -> anyhow::Result<Config> {
90 let config_path = format!("{}/config.yml", config_folder_path());
91
92 create_dir_all(config_folder_path())?;
93
94 if let Ok(mut file) = File::open(config_path.clone()) {
95 let mut string_value = String::new();
96 file.read_to_string(&mut string_value)?;
97 if string_value.is_empty() {
98 save_default_config(config_path.as_str())
99 } else {
100 Ok(serde_yaml::from_str(&string_value)?)
101 }
102 } else {
103 save_default_config(config_path.as_str())
104 }
105}
106
107fn config_folder_path() -> String {
108 format!(
109 "{}/.config/quick-links",
110 home::home_dir().unwrap().to_str().unwrap()
111 )
112}