use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};
use sapphire_bridge_api::settings::{Scope, SettingDef};
use crate::Result;
pub trait SettingsOwner: Send + Sync {
fn defs(&self) -> Vec<SettingDef>;
fn file(&self, scope: Scope) -> Result<PathBuf>;
fn secret_file(&self, key: &str) -> Result<PathBuf>;
fn validate(&self, staged: &Staged) -> std::result::Result<(), Vec<FieldError>>;
fn scope_note(&self, _scope: Scope) -> Option<String> {
None
}
}
#[derive(Clone, Debug, Default)]
pub struct Staged {
pub files: BTreeMap<PathBuf, String>,
}
impl Staged {
pub fn text(&self, path: &Path) -> Option<&str> {
self.files.get(path).map(String::as_str)
}
pub fn read(&self, path: &Path) -> Result<Option<String>> {
if let Some(text) = self.text(path) {
return Ok(Some(text.to_string()));
}
match std::fs::read_to_string(path) {
Ok(text) => Ok(Some(text)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FieldError {
pub key: Option<String>,
pub file: Option<PathBuf>,
pub message: String,
}
impl fmt::Display for FieldError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (&self.key, &self.file) {
(Some(key), _) => write!(f, "{key}: {}", self.message),
(None, Some(file)) => write!(f, "{}: {}", file.display(), self.message),
(None, None) => f.write_str(&self.message),
}
}
}
#[cfg(test)]
pub(crate) mod test_support {
use super::*;
use crate::{Apply, Kind, Process, Scope, SettingDef};
pub struct TestOwner {
pub dir: tempfile::TempDir,
pub defs: Vec<SettingDef>,
}
impl TestOwner {
pub fn new(defs: Vec<SettingDef>) -> Self {
Self {
dir: tempfile::tempdir().unwrap(),
defs,
}
}
pub fn write(&self, name: &str, text: &str) {
std::fs::write(self.dir.path().join(name), text).unwrap();
}
}
impl SettingsOwner for TestOwner {
fn defs(&self) -> Vec<SettingDef> {
self.defs.clone()
}
fn file(&self, scope: Scope) -> crate::Result<PathBuf> {
match scope {
Scope::Device => Ok(self.dir.path().join("dev.toml")),
Scope::Workgroup => Ok(self.dir.path().join("wg.toml")),
Scope::Workspace => Err(crate::Error::Io(std::io::Error::other("no workspace"))),
}
}
fn secret_file(&self, key: &str) -> crate::Result<PathBuf> {
Ok(self.dir.path().join(format!("secret-{key}")))
}
fn validate(&self, _: &Staged) -> std::result::Result<(), Vec<FieldError>> {
Ok(())
}
fn scope_note(&self, scope: Scope) -> Option<String> {
(scope == Scope::Workgroup).then(|| "wg note".to_string())
}
}
pub fn def(key: &str, kind: Kind) -> SettingDef {
SettingDef {
key: key.into(),
kind,
scopes: vec![Scope::Workgroup],
overridable: false,
apply: Apply::Live,
default: None,
section: "test".into(),
doc: "test".into(),
process: Process::Bridge,
}
}
}