From 2db770038805ea00ef85d6c659e84b7b11d7ddc0 Mon Sep 17 00:00:00 2001 From: Tassilo Horn Date: Thu, 24 Jun 2021 22:00:07 +0200 Subject: [PATCH] Loading and saving the config --- src/config.rs | 86 +++++++++++++++++++++++++++++++++++++++++++++++++-- src/lib.rs | 1 + 2 files changed, 84 insertions(+), 3 deletions(-) diff --git a/src/config.rs b/src/config.rs index 25e55ee..49b3543 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,17 +1,97 @@ -#[derive(Serialize, Deserialize)] +use directories::ProjectDirs; +use serde::{Deserialize, Serialize}; +use std::fs::DirBuilder; +use std::fs::OpenOptions; +use std::io::{Read, Write}; +use std::path::Path; + +#[derive(Debug, Serialize, Deserialize)] pub struct Config { launcher: Option, format: Option, } -#[derive(Serialize, Deserialize)] +impl Default for Config { + fn default() -> Self { + Config { + launcher: Some(Launcher { + executable: Some("wofi".to_string()), + args: Some(vec![ + "--show=dmenu".to_string(), + "--allow-markup".to_string(), + "--allow-images".to_string(), + "--insensitive".to_string(), + "--cache-file=/dev/null".to_string(), + "--parse-search".to_string(), + "--prompt={prompt}".to_string(), + ]), + }), + format: Some(Format { + window_format: Some( + "\"{title}\"\t{app_name} on workspace {workspace_name}\t({id})" + .to_string(), + ), + workspace_format: Some("Workspace {name}\t({id})".to_string()), + }), + } + } +} + +#[derive(Debug, Serialize, Deserialize)] pub struct Launcher { executable: Option, args: Option>, } -#[derive(Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize)] pub struct Format { window_format: Option, workspace_format: Option, } + +fn get_config_file_path() -> Box { + let proj_dirs = ProjectDirs::from("", "", "swayr").expect(""); + let config_dir = proj_dirs.config_dir(); + if !config_dir.exists() { + DirBuilder::new() + .recursive(true) + .create(config_dir) + .unwrap(); + } + config_dir.join("config.toml").into_boxed_path() +} + +pub fn save_config(cfg: Config) { + let path = get_config_file_path(); + let content = + toml::to_string_pretty(&cfg).expect("Cannot serialize config."); + let mut file = OpenOptions::new() + .read(false) + .write(true) + .create(true) + .open(path) + .unwrap(); + file.write_all(content.as_str().as_bytes()).unwrap(); +} + +pub fn load_config() -> Config { + let path = get_config_file_path(); + if !path.exists() { + save_config(Config::default()); + } + let mut file = OpenOptions::new() + .read(true) + .write(false) + .create(false) + .open(path) + .unwrap(); + let mut buf: String = String::new(); + file.read_to_string(&mut buf).unwrap(); + toml::from_str(&buf).expect("Invalid config.") +} + +#[test] +fn test_load_config() { + let cfg = load_config(); + println!("{:?}", cfg); +} diff --git a/src/lib.rs b/src/lib.rs index b5b9670..73ee0af 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ pub mod client; pub mod cmds; pub mod con; +pub mod config; pub mod demon; pub mod ipc; pub mod util;