use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
pub const CURRENT_CREDENTIAL_VERSION: u32 = 2;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
pub bucket: String,
pub local: LocalConfig,
#[serde(default)]
pub indexd: Option<IndexdConfig>,
pub serve: ServeConfig,
pub chunking: ChunkingConfig,
#[serde(default)]
pub credential_store_version: Option<u32>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LocalConfig {
pub data_dir: PathBuf,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexdConfig {
pub url: String,
pub bucket: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ServeConfig {
pub bind: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ChunkingConfig {
pub window_secs: u64,
}
impl Default for Config {
fn default() -> Self {
Self {
bucket: "obsidianlog".to_string(),
local: LocalConfig {
data_dir: PathBuf::from("./obsidianlog-data"),
},
indexd: None,
serve: ServeConfig {
bind: "127.0.0.1:7080".to_string(),
},
chunking: ChunkingConfig { window_secs: 3600 },
credential_store_version: Some(CURRENT_CREDENTIAL_VERSION),
}
}
}
impl Default for LocalConfig {
fn default() -> Self {
Config::default().local
}
}
impl Default for ServeConfig {
fn default() -> Self {
Config::default().serve
}
}
impl Default for ChunkingConfig {
fn default() -> Self {
Config::default().chunking
}
}
fn resolve_default_path(
xdg_config_home: Option<&str>,
home: Option<&str>,
userprofile: Option<&str>,
) -> Result<PathBuf> {
if let Some(xdg) = xdg_config_home.filter(|s| !s.is_empty()) {
return Ok(PathBuf::from(xdg).join("obsidianlog").join("config.toml"));
}
let home = home
.filter(|s| !s.is_empty())
.or_else(|| userprofile.filter(|s| !s.is_empty()))
.context(
"could not determine the config directory: none of XDG_CONFIG_HOME, HOME, or \
USERPROFILE is set (pass --config explicitly)",
)?;
Ok(PathBuf::from(home)
.join(".config")
.join("obsidianlog")
.join("config.toml"))
}
fn parse(text: &str, path: &Path) -> Result<Config> {
toml::from_str(text).with_context(|| format!("parsing config file at {}", path.display()))
}
pub enum ConfigLoadOutcome {
Missing,
Current(Config),
Legacy(Config),
}
impl Config {
pub fn default_path() -> Result<PathBuf> {
resolve_default_path(
std::env::var("XDG_CONFIG_HOME").ok().as_deref(),
std::env::var("HOME").ok().as_deref(),
std::env::var("USERPROFILE").ok().as_deref(),
)
}
pub fn load(path: Option<&Path>) -> Result<Self> {
match path {
Some(path) => {
let text = std::fs::read_to_string(path)
.with_context(|| format!("reading config file at {}", path.display()))?;
let config = parse(&text, path)?;
config.require_supported_credential_store()?;
Ok(config)
}
None => {
let default_path = Self::default_path()?;
match std::fs::read_to_string(&default_path) {
Ok(text) => {
let config = parse(&text, &default_path)?;
config.require_supported_credential_store()?;
Ok(config)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
Err(e) => Err(e).with_context(|| {
format!("reading config file at {}", default_path.display())
}),
}
}
}
}
pub fn load_for_init(path: Option<&Path>) -> Result<ConfigLoadOutcome> {
let resolved = match path {
Some(p) => p.to_path_buf(),
None => Self::default_path()?,
};
match std::fs::read_to_string(&resolved) {
Ok(text) => {
let config = parse(&text, &resolved)?;
match config.credential_store_version {
Some(v) if v == CURRENT_CREDENTIAL_VERSION => {
Ok(ConfigLoadOutcome::Current(config))
}
Some(v) if v > CURRENT_CREDENTIAL_VERSION => {
Err(unsupported_future_version_error(v))
}
_ => Ok(ConfigLoadOutcome::Legacy(config)),
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(ConfigLoadOutcome::Missing),
Err(e) => {
Err(e).with_context(|| format!("reading config file at {}", resolved.display()))
}
}
}
pub fn save(&self, path: Option<&Path>) -> Result<()> {
let path = match path {
Some(path) => path.to_path_buf(),
None => Self::default_path()?,
};
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("creating config directory {}", parent.display()))?;
}
let text = toml::to_string_pretty(self).context("serializing config")?;
std::fs::write(&path, text)
.with_context(|| format!("writing config file at {}", path.display()))?;
Ok(())
}
fn require_supported_credential_store(&self) -> Result<()> {
match self.credential_store_version {
Some(v) if v == CURRENT_CREDENTIAL_VERSION => Ok(()),
Some(v) if v > CURRENT_CREDENTIAL_VERSION => Err(unsupported_future_version_error(v)),
_ => anyhow::bail!(
"this config uses the pre-0.2 credential storage layout (one encryption key \
and one Sia app key stored as two separate OS keychain items). obsidianlog \
0.2 stores them as a single bundled item instead, and there is no automatic \
migration. To keep reading archives created under the old layout, use \
obsidianlog v0.1.1. To start fresh under the new layout — this rotates the \
encryption key, and previously archived data will no longer be decryptable — \
run `obsidianlog init --force`."
),
}
}
}
fn unsupported_future_version_error(found: u32) -> anyhow::Error {
anyhow::anyhow!(
"this config was written by a newer version of obsidianlog (credential storage \
format {found}, this build only understands up to {CURRENT_CREDENTIAL_VERSION}) — \
upgrade obsidianlog to use it"
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_path_prefers_xdg_config_home() {
let path = resolve_default_path(Some("/xdg"), Some("/home/user"), None).unwrap();
assert_eq!(path, PathBuf::from("/xdg/obsidianlog/config.toml"));
}
#[test]
fn default_path_falls_back_to_home_when_xdg_unset() {
let path = resolve_default_path(None, Some("/home/user"), None).unwrap();
assert_eq!(
path,
PathBuf::from("/home/user/.config/obsidianlog/config.toml")
);
}
#[test]
fn default_path_falls_back_to_home_when_xdg_empty() {
let path = resolve_default_path(Some(""), Some("/home/user"), None).unwrap();
assert_eq!(
path,
PathBuf::from("/home/user/.config/obsidianlog/config.toml")
);
}
#[test]
fn default_path_falls_back_to_userprofile_when_home_unset() {
let path = resolve_default_path(None, None, Some(r"C:\Users\user")).unwrap();
assert_eq!(
path,
PathBuf::from(r"C:\Users\user").join(".config/obsidianlog/config.toml")
);
}
#[test]
fn default_path_prefers_home_over_userprofile_when_both_set() {
let path = resolve_default_path(None, Some("/home/user"), Some(r"C:\Users\user")).unwrap();
assert_eq!(
path,
PathBuf::from("/home/user/.config/obsidianlog/config.toml")
);
}
#[test]
fn default_path_errors_when_none_are_set() {
assert!(resolve_default_path(None, None, None).is_err());
}
#[test]
fn load_with_explicit_path_parses_the_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(
&path,
r#"
bucket = "custom-bucket"
credential_store_version = 2
[local]
data_dir = "/data"
[serve]
bind = "0.0.0.0:9000"
[chunking]
window_secs = 60
"#,
)
.unwrap();
let config = Config::load(Some(&path)).unwrap();
assert_eq!(config.bucket, "custom-bucket");
assert_eq!(config.local.data_dir, PathBuf::from("/data"));
assert_eq!(config.serve.bind, "0.0.0.0:9000");
assert_eq!(config.chunking.window_secs, 60);
assert!(config.indexd.is_none());
}
#[test]
fn load_with_missing_explicit_path_errors() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("does-not-exist.toml");
assert!(Config::load(Some(&missing)).is_err());
}
#[test]
fn load_with_partial_file_fills_in_defaults() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(
&path,
"bucket = \"only-the-bucket\"\ncredential_store_version = 2\n",
)
.unwrap();
let config = Config::load(Some(&path)).unwrap();
assert_eq!(config.bucket, "only-the-bucket");
assert_eq!(config.serve.bind, Config::default().serve.bind);
assert_eq!(
config.chunking.window_secs,
Config::default().chunking.window_secs
);
}
#[test]
fn save_then_load_round_trips() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nested").join("config.toml");
let config = Config {
bucket: "roundtrip".to_string(),
..Config::default()
};
config.save(Some(&path)).unwrap();
let loaded = Config::load(Some(&path)).unwrap();
assert_eq!(loaded.bucket, "roundtrip");
}
#[test]
fn save_then_load_round_trips_an_indexd_config() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
let config = Config {
indexd: Some(IndexdConfig {
url: "https://indexd.example.com".to_string(),
bucket: "sia-bucket".to_string(),
}),
..Config::default()
};
config.save(Some(&path)).unwrap();
let loaded = Config::load(Some(&path)).unwrap();
let indexd = loaded.indexd.expect("indexd section must round-trip");
assert_eq!(indexd.url, "https://indexd.example.com");
assert_eq!(indexd.bucket, "sia-bucket");
}
#[test]
fn save_writes_the_current_credential_version() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
Config::default().save(Some(&path)).unwrap();
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("credential_store_version = 2"));
}
#[test]
fn load_rejects_a_legacy_config_missing_the_version_field() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "bucket = \"legacy\"\n").unwrap();
let err = Config::load(Some(&path)).unwrap_err();
let message = err.to_string();
assert!(message.contains("pre-0.2"), "{message}");
assert!(message.contains("v0.1.1"), "{message}");
assert!(message.contains("--force"), "{message}");
}
#[test]
fn load_rejects_an_unrecognized_future_version() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(
&path,
"bucket = \"future\"\ncredential_store_version = 99\n",
)
.unwrap();
let err = Config::load(Some(&path)).unwrap_err();
let message = err.to_string();
assert!(message.contains("newer version"), "{message}");
}
#[test]
fn load_accepts_the_current_version() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "bucket = \"ok\"\ncredential_store_version = 2\n").unwrap();
assert!(Config::load(Some(&path)).is_ok());
}
#[test]
fn load_for_init_reports_missing_when_no_file_exists() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("does-not-exist.toml");
assert!(matches!(
Config::load_for_init(Some(&path)).unwrap(),
ConfigLoadOutcome::Missing
));
}
#[test]
fn load_for_init_reports_current_for_a_current_format_config() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "bucket = \"ok\"\ncredential_store_version = 2\n").unwrap();
assert!(matches!(
Config::load_for_init(Some(&path)).unwrap(),
ConfigLoadOutcome::Current(_)
));
}
#[test]
fn load_for_init_reports_legacy_for_a_config_missing_the_version_field() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "bucket = \"legacy\"\n").unwrap();
match Config::load_for_init(Some(&path)).unwrap() {
ConfigLoadOutcome::Legacy(config) => assert_eq!(config.bucket, "legacy"),
_ => panic!("expected Legacy"),
}
}
#[test]
fn load_for_init_still_rejects_an_unrecognized_future_version() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(
&path,
"bucket = \"future\"\ncredential_store_version = 99\n",
)
.unwrap();
assert!(Config::load_for_init(Some(&path)).is_err());
}
}