Skip to main content

paper/core/
paths.rs

1use std::path::{Path, PathBuf};
2
3/// Resolves every on-disk location Paper uses.
4///
5/// The base directory is taken from `PAPER_HOME` when set (used by tests and by
6/// users who want a portable install), otherwise `dirs::cache_dir()/paper`.
7pub struct Paths {
8    base: PathBuf,
9    config_base: PathBuf,
10}
11
12impl Default for Paths {
13    fn default() -> Self {
14        Self::new()
15    }
16}
17
18impl Paths {
19    pub fn new() -> Self {
20        if let Some(home) = std::env::var_os("PAPER_HOME") {
21            let base = PathBuf::from(home);
22            return Self {
23                base: base.clone(),
24                config_base: base,
25            };
26        }
27
28        let base = dirs::cache_dir()
29            .unwrap_or_else(|| PathBuf::from("."))
30            .join("paper");
31        let config_base = dirs::config_dir()
32            .unwrap_or_else(|| PathBuf::from("."))
33            .join("paper");
34        Self { base, config_base }
35    }
36
37    /// Paths rooted at an explicit directory. Useful for tests.
38    pub fn with_base(base: impl AsRef<Path>) -> Self {
39        let base = base.as_ref().to_path_buf();
40        Self {
41            config_base: base.clone(),
42            base,
43        }
44    }
45
46    pub fn base_dir(&self) -> PathBuf {
47        self.base.clone()
48    }
49
50    pub fn model_cache_dir(&self) -> PathBuf {
51        self.base.join("models")
52    }
53
54    pub fn db_path(&self) -> PathBuf {
55        self.base.join("chunks.db")
56    }
57
58    pub fn config_path(&self) -> PathBuf {
59        self.config_base.join("config.toml")
60    }
61
62    /// Create the directories Paper writes into. Safe to call repeatedly.
63    pub fn ensure_dirs(&self) -> std::io::Result<()> {
64        std::fs::create_dir_all(&self.base)?;
65        std::fs::create_dir_all(self.model_cache_dir())?;
66        if let Some(parent) = self.config_path().parent() {
67            std::fs::create_dir_all(parent)?;
68        }
69        Ok(())
70    }
71}