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