use std::fs;
use std::path::PathBuf;
use std::sync::Arc;
use crate::config::{ConfigFile, ConfigScope, ConfigSet};
use crate::error::Result;
use crate::repo::Repository;
#[derive(Debug, Copy, Clone)]
pub struct Config<'repo> {
repo: &'repo Repository,
}
impl<'repo> Config<'repo> {
#[inline]
#[must_use]
pub fn new(repo: &'repo Repository) -> Self {
Self { repo }
}
#[inline]
#[must_use]
pub fn repository(&self) -> &'repo Repository {
self.repo
}
#[inline]
pub fn snapshot(&self) -> Result<Arc<ConfigSet>> {
self.repo.ensure_config_arc()
}
pub fn get(&self, key: &str) -> Result<Option<String>> {
Ok(self.snapshot()?.get(key)?)
}
pub fn get_all(&self, key: &str) -> Result<Vec<String>> {
Ok(self.snapshot()?.get_all(key)?)
}
pub fn get_bool(&self, key: &str) -> Result<Option<bool>> {
Ok(self.snapshot()?.get_bool(key)?)
}
pub fn get_i64(&self, key: &str) -> Result<Option<i64>> {
Ok(self.snapshot()?.get_i64(key)?)
}
pub fn get_path(&self, key: &str) -> Result<Option<PathBuf>> {
Ok(self.snapshot()?.get_path(self.repo.environment(), key)?)
}
pub fn get_color(&self, key: &str) -> Result<Option<String>> {
Ok(self.snapshot()?.get_color(key)?)
}
pub fn entries_with_prefix(&self, prefix: &str) -> Result<Vec<crate::config::ConfigEntry>> {
self.snapshot()?.entries_with_prefix(prefix)
}
#[deprecated(note = "use ConfigEditor and explicit reload where needed")]
#[inline]
pub fn set_local(&self, key: &str, value: &str) -> Result<()> {
let path = crate::repo::local_config_write_path(self.repo.git_dir());
let content = fs::read_to_string(&path).unwrap_or_default();
let mut file = ConfigFile::parse(&path, &content, ConfigScope::Local)?;
file.set(key, value)?;
file.write()?;
self.repo.reload_config()
}
#[deprecated(note = "use ConfigEditor and explicit reload where needed")]
pub fn unset_local(&self, key: &str) -> Result<()> {
let path = crate::repo::local_config_write_path(self.repo.git_dir());
let content = fs::read_to_string(&path).unwrap_or_default();
let mut file = ConfigFile::parse(&path, &content, ConfigScope::Local)?;
file.unset(key)?;
file.write()?;
self.repo.reload_config()
}
#[deprecated(note = "use ConfigEditor and explicit reload where needed")]
pub fn remove_local_section(&self, section: &str) -> Result<()> {
let path = crate::repo::local_config_write_path(self.repo.git_dir());
let content = fs::read_to_string(&path).unwrap_or_default();
let mut file = ConfigFile::parse(&path, &content, ConfigScope::Local)?;
file.remove_section(section)?;
file.write()?;
self.repo.reload_config()
}
}