pub mod defaults;
pub mod settings;
use self::{
defaults::DEFAULT_CONFIG,
settings::{Config, Flags, LayoutItem},
};
use dirs::config_dir;
use json5;
use std::io::Write;
use std::path::PathBuf;
use std::{
collections::HashMap,
fs::{self, File},
};
fn load_config() -> Config {
let path = config_file("config.jsonc");
let data = fs::read_to_string(path).expect("Failed to read config.jsonc");
load_config_from_str(&data)
}
fn load_config_from_str(data: &str) -> Config {
json5::from_str(data).expect("Invalid JSONC in config.jsonc")
}
pub fn load_config_at(path: Option<&str>) -> Result<Config, String> {
match path {
Some(custom_path) => {
let data = fs::read_to_string(custom_path)
.map_err(|err| format!("Failed to read config at {}: {}", custom_path, err))?;
Ok(load_config_from_str(&data))
}
None => Ok(load_config()),
}
}
pub fn default_config() -> Config {
load_config_from_str(DEFAULT_CONFIG)
}
pub fn default_layout() -> Vec<LayoutItem> {
default_config().layout
}
pub fn load_print_layout() -> Vec<LayoutItem> {
let layout = load_config().layout;
if layout.is_empty() {
default_layout()
} else {
layout
}
}
pub fn load_flags() -> Flags {
load_config().flags
}
pub fn generate_config_files() -> HashMap<String, bool> {
let mut results = HashMap::new();
let result = save_to_config_file("config.jsonc", DEFAULT_CONFIG).is_ok();
results.insert("config.jsonc".to_string(), result);
results
}
fn save_to_config_file(file_name: &str, content: &str) -> std::io::Result<()> {
let path = config_file(file_name);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let mut file = File::create(&path)?;
file.write_all(content.as_bytes())?;
Ok(())
}
pub fn delete_config_files() -> HashMap<String, bool> {
let mut results = HashMap::new();
let file = "config.jsonc";
let result = delete_config_file(file).is_ok();
results.insert(file.to_string(), result);
results
}
fn delete_config_file(file_name: &str) -> std::io::Result<()> {
let path = config_file(file_name);
if path.exists() {
std::fs::remove_file(path)?;
}
Ok(())
}
fn config_file(name: &str) -> PathBuf {
config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("leenfetch")
.join(name)
}
pub fn ensure_config_files_exist() -> HashMap<String, bool> {
let mut results = HashMap::new();
let filename = "config.jsonc";
let created = ensure_config_file_exists(filename, DEFAULT_CONFIG).unwrap_or(false);
results.insert(filename.to_string(), created);
results
}
fn ensure_config_file_exists(file_name: &str, default_content: &str) -> std::io::Result<bool> {
let path = config_file(file_name);
if path.exists() {
return Ok(false); }
save_to_config_file(file_name, default_content)?;
Ok(true) }