1use std::path::{Path, PathBuf};
33
34use anyhow::{Context, Result};
35use serde::{Deserialize, Serialize};
36
37pub const CURRENT_CREDENTIAL_VERSION: u32 = 2;
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
46#[serde(default)]
47pub struct Config {
48 pub bucket: String,
50
51 pub local: LocalConfig,
53
54 #[serde(default)]
57 pub indexd: Option<IndexdConfig>,
58
59 pub serve: ServeConfig,
61
62 pub chunking: ChunkingConfig,
64
65 #[serde(default)]
73 pub credential_store_version: Option<u32>,
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
78#[serde(default)]
79pub struct LocalConfig {
80 pub data_dir: PathBuf,
82}
83
84#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct IndexdConfig {
87 pub url: String,
89 pub bucket: String,
91}
92
93#[derive(Debug, Clone, Serialize, Deserialize)]
95#[serde(default)]
96pub struct ServeConfig {
97 pub bind: String,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
103#[serde(default)]
104pub struct ChunkingConfig {
105 pub window_secs: u64,
107}
108
109impl Default for Config {
110 fn default() -> Self {
111 Self {
112 bucket: "obsidianlog".to_string(),
113 local: LocalConfig {
114 data_dir: PathBuf::from("./obsidianlog-data"),
115 },
116 indexd: None,
118 serve: ServeConfig {
119 bind: "127.0.0.1:7080".to_string(),
120 },
121 chunking: ChunkingConfig { window_secs: 3600 },
122 credential_store_version: Some(CURRENT_CREDENTIAL_VERSION),
125 }
126 }
127}
128
129impl Default for LocalConfig {
130 fn default() -> Self {
131 Config::default().local
132 }
133}
134
135impl Default for ServeConfig {
136 fn default() -> Self {
137 Config::default().serve
138 }
139}
140
141impl Default for ChunkingConfig {
142 fn default() -> Self {
143 Config::default().chunking
144 }
145}
146
147fn resolve_default_path(xdg_config_home: Option<&str>, home: Option<&str>) -> Result<PathBuf> {
152 if let Some(xdg) = xdg_config_home.filter(|s| !s.is_empty()) {
153 return Ok(PathBuf::from(xdg).join("obsidianlog").join("config.toml"));
154 }
155 let home = home.context(
156 "could not determine the config directory: neither XDG_CONFIG_HOME nor HOME is set \
157 (pass --config explicitly)",
158 )?;
159 Ok(PathBuf::from(home)
160 .join(".config")
161 .join("obsidianlog")
162 .join("config.toml"))
163}
164
165fn parse(text: &str, path: &Path) -> Result<Config> {
170 toml::from_str(text).with_context(|| format!("parsing config file at {}", path.display()))
171}
172
173pub enum ConfigLoadOutcome {
176 Missing,
178 Current(Config),
180 Legacy(Config),
185}
186
187impl Config {
188 pub fn default_path() -> Result<PathBuf> {
191 resolve_default_path(
192 std::env::var("XDG_CONFIG_HOME").ok().as_deref(),
193 std::env::var("HOME").ok().as_deref(),
194 )
195 }
196
197 pub fn load(path: Option<&Path>) -> Result<Self> {
211 match path {
212 Some(path) => {
213 let text = std::fs::read_to_string(path)
214 .with_context(|| format!("reading config file at {}", path.display()))?;
215 let config = parse(&text, path)?;
216 config.require_supported_credential_store()?;
217 Ok(config)
218 }
219 None => {
220 let default_path = Self::default_path()?;
221 match std::fs::read_to_string(&default_path) {
222 Ok(text) => {
223 let config = parse(&text, &default_path)?;
224 config.require_supported_credential_store()?;
225 Ok(config)
226 }
227 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
228 Err(e) => Err(e).with_context(|| {
229 format!("reading config file at {}", default_path.display())
230 }),
231 }
232 }
233 }
234 }
235
236 pub fn load_for_init(path: Option<&Path>) -> Result<ConfigLoadOutcome> {
246 let resolved = match path {
247 Some(p) => p.to_path_buf(),
248 None => Self::default_path()?,
249 };
250 match std::fs::read_to_string(&resolved) {
251 Ok(text) => {
252 let config = parse(&text, &resolved)?;
253 match config.credential_store_version {
254 Some(v) if v == CURRENT_CREDENTIAL_VERSION => {
255 Ok(ConfigLoadOutcome::Current(config))
256 }
257 Some(v) if v > CURRENT_CREDENTIAL_VERSION => {
258 Err(unsupported_future_version_error(v))
259 }
260 _ => Ok(ConfigLoadOutcome::Legacy(config)),
261 }
262 }
263 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(ConfigLoadOutcome::Missing),
264 Err(e) => {
265 Err(e).with_context(|| format!("reading config file at {}", resolved.display()))
266 }
267 }
268 }
269
270 pub fn save(&self, path: Option<&Path>) -> Result<()> {
272 let path = match path {
273 Some(path) => path.to_path_buf(),
274 None => Self::default_path()?,
275 };
276 if let Some(parent) = path.parent() {
277 std::fs::create_dir_all(parent)
278 .with_context(|| format!("creating config directory {}", parent.display()))?;
279 }
280 let text = toml::to_string_pretty(self).context("serializing config")?;
281 std::fs::write(&path, text)
282 .with_context(|| format!("writing config file at {}", path.display()))?;
283 Ok(())
284 }
285
286 fn require_supported_credential_store(&self) -> Result<()> {
290 match self.credential_store_version {
291 Some(v) if v == CURRENT_CREDENTIAL_VERSION => Ok(()),
292 Some(v) if v > CURRENT_CREDENTIAL_VERSION => Err(unsupported_future_version_error(v)),
293 _ => anyhow::bail!(
294 "this config uses the pre-0.2 credential storage layout (one encryption key \
295 and one Sia app key stored as two separate OS keychain items). obsidianlog \
296 0.2 stores them as a single bundled item instead, and there is no automatic \
297 migration. To keep reading archives created under the old layout, use \
298 obsidianlog v0.1.1. To start fresh under the new layout — this rotates the \
299 encryption key, and previously archived data will no longer be decryptable — \
300 run `obsidianlog init --force`."
301 ),
302 }
303 }
304}
305
306fn unsupported_future_version_error(found: u32) -> anyhow::Error {
307 anyhow::anyhow!(
308 "this config was written by a newer version of obsidianlog (credential storage \
309 format {found}, this build only understands up to {CURRENT_CREDENTIAL_VERSION}) — \
310 upgrade obsidianlog to use it"
311 )
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317
318 #[test]
319 fn default_path_prefers_xdg_config_home() {
320 let path = resolve_default_path(Some("/xdg"), Some("/home/user")).unwrap();
321 assert_eq!(path, PathBuf::from("/xdg/obsidianlog/config.toml"));
322 }
323
324 #[test]
325 fn default_path_falls_back_to_home_when_xdg_unset() {
326 let path = resolve_default_path(None, Some("/home/user")).unwrap();
327 assert_eq!(
328 path,
329 PathBuf::from("/home/user/.config/obsidianlog/config.toml")
330 );
331 }
332
333 #[test]
334 fn default_path_falls_back_to_home_when_xdg_empty() {
335 let path = resolve_default_path(Some(""), Some("/home/user")).unwrap();
336 assert_eq!(
337 path,
338 PathBuf::from("/home/user/.config/obsidianlog/config.toml")
339 );
340 }
341
342 #[test]
343 fn default_path_errors_when_neither_is_set() {
344 assert!(resolve_default_path(None, None).is_err());
345 }
346
347 #[test]
348 fn load_with_explicit_path_parses_the_file() {
349 let dir = tempfile::tempdir().unwrap();
350 let path = dir.path().join("config.toml");
351 std::fs::write(
352 &path,
353 r#"
354 bucket = "custom-bucket"
355 credential_store_version = 2
356
357 [local]
358 data_dir = "/data"
359
360 [serve]
361 bind = "0.0.0.0:9000"
362
363 [chunking]
364 window_secs = 60
365 "#,
366 )
367 .unwrap();
368
369 let config = Config::load(Some(&path)).unwrap();
370 assert_eq!(config.bucket, "custom-bucket");
371 assert_eq!(config.local.data_dir, PathBuf::from("/data"));
372 assert_eq!(config.serve.bind, "0.0.0.0:9000");
373 assert_eq!(config.chunking.window_secs, 60);
374 assert!(config.indexd.is_none());
375 }
376
377 #[test]
378 fn load_with_missing_explicit_path_errors() {
379 let dir = tempfile::tempdir().unwrap();
380 let missing = dir.path().join("does-not-exist.toml");
381 assert!(Config::load(Some(&missing)).is_err());
382 }
383
384 #[test]
385 fn load_with_partial_file_fills_in_defaults() {
386 let dir = tempfile::tempdir().unwrap();
387 let path = dir.path().join("config.toml");
388 std::fs::write(
389 &path,
390 "bucket = \"only-the-bucket\"\ncredential_store_version = 2\n",
391 )
392 .unwrap();
393
394 let config = Config::load(Some(&path)).unwrap();
395 assert_eq!(config.bucket, "only-the-bucket");
396 assert_eq!(config.serve.bind, Config::default().serve.bind);
397 assert_eq!(
398 config.chunking.window_secs,
399 Config::default().chunking.window_secs
400 );
401 }
402
403 #[test]
404 fn save_then_load_round_trips() {
405 let dir = tempfile::tempdir().unwrap();
406 let path = dir.path().join("nested").join("config.toml");
407 let config = Config {
408 bucket: "roundtrip".to_string(),
409 ..Config::default()
410 };
411
412 config.save(Some(&path)).unwrap();
413 let loaded = Config::load(Some(&path)).unwrap();
414 assert_eq!(loaded.bucket, "roundtrip");
415 }
416
417 #[test]
418 fn save_then_load_round_trips_an_indexd_config() {
419 let dir = tempfile::tempdir().unwrap();
420 let path = dir.path().join("config.toml");
421 let config = Config {
422 indexd: Some(IndexdConfig {
423 url: "https://indexd.example.com".to_string(),
424 bucket: "sia-bucket".to_string(),
425 }),
426 ..Config::default()
427 };
428
429 config.save(Some(&path)).unwrap();
430 let loaded = Config::load(Some(&path)).unwrap();
431 let indexd = loaded.indexd.expect("indexd section must round-trip");
432 assert_eq!(indexd.url, "https://indexd.example.com");
433 assert_eq!(indexd.bucket, "sia-bucket");
434 }
435
436 #[test]
437 fn save_writes_the_current_credential_version() {
438 let dir = tempfile::tempdir().unwrap();
439 let path = dir.path().join("config.toml");
440 Config::default().save(Some(&path)).unwrap();
441
442 let text = std::fs::read_to_string(&path).unwrap();
443 assert!(text.contains("credential_store_version = 2"));
444 }
445
446 #[test]
447 fn load_rejects_a_legacy_config_missing_the_version_field() {
448 let dir = tempfile::tempdir().unwrap();
449 let path = dir.path().join("config.toml");
450 std::fs::write(&path, "bucket = \"legacy\"\n").unwrap();
451
452 let err = Config::load(Some(&path)).unwrap_err();
453 let message = err.to_string();
454 assert!(message.contains("pre-0.2"), "{message}");
455 assert!(message.contains("v0.1.1"), "{message}");
456 assert!(message.contains("--force"), "{message}");
457 }
458
459 #[test]
460 fn load_rejects_an_unrecognized_future_version() {
461 let dir = tempfile::tempdir().unwrap();
462 let path = dir.path().join("config.toml");
463 std::fs::write(
464 &path,
465 "bucket = \"future\"\ncredential_store_version = 99\n",
466 )
467 .unwrap();
468
469 let err = Config::load(Some(&path)).unwrap_err();
470 let message = err.to_string();
471 assert!(message.contains("newer version"), "{message}");
472 }
473
474 #[test]
475 fn load_accepts_the_current_version() {
476 let dir = tempfile::tempdir().unwrap();
477 let path = dir.path().join("config.toml");
478 std::fs::write(&path, "bucket = \"ok\"\ncredential_store_version = 2\n").unwrap();
479
480 assert!(Config::load(Some(&path)).is_ok());
481 }
482
483 #[test]
484 fn load_for_init_reports_missing_when_no_file_exists() {
485 let dir = tempfile::tempdir().unwrap();
486 let path = dir.path().join("does-not-exist.toml");
487
488 assert!(matches!(
489 Config::load_for_init(Some(&path)).unwrap(),
490 ConfigLoadOutcome::Missing
491 ));
492 }
493
494 #[test]
495 fn load_for_init_reports_current_for_a_current_format_config() {
496 let dir = tempfile::tempdir().unwrap();
497 let path = dir.path().join("config.toml");
498 std::fs::write(&path, "bucket = \"ok\"\ncredential_store_version = 2\n").unwrap();
499
500 assert!(matches!(
501 Config::load_for_init(Some(&path)).unwrap(),
502 ConfigLoadOutcome::Current(_)
503 ));
504 }
505
506 #[test]
507 fn load_for_init_reports_legacy_for_a_config_missing_the_version_field() {
508 let dir = tempfile::tempdir().unwrap();
509 let path = dir.path().join("config.toml");
510 std::fs::write(&path, "bucket = \"legacy\"\n").unwrap();
511
512 match Config::load_for_init(Some(&path)).unwrap() {
513 ConfigLoadOutcome::Legacy(config) => assert_eq!(config.bucket, "legacy"),
514 _ => panic!("expected Legacy"),
515 }
516 }
517
518 #[test]
519 fn load_for_init_still_rejects_an_unrecognized_future_version() {
520 let dir = tempfile::tempdir().unwrap();
521 let path = dir.path().join("config.toml");
522 std::fs::write(
523 &path,
524 "bucket = \"future\"\ncredential_store_version = 99\n",
525 )
526 .unwrap();
527
528 assert!(Config::load_for_init(Some(&path)).is_err());
529 }
530}