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`.
7#[derive(Clone)]
8pub struct Paths {
9    base: PathBuf,
10    config_base: PathBuf,
11}
12
13impl Default for Paths {
14    fn default() -> Self {
15        Self::new()
16    }
17}
18
19impl Paths {
20    pub fn new() -> Self {
21        if let Some(home) = std::env::var_os("PAPER_HOME") {
22            let base = PathBuf::from(home);
23            return Self {
24                base: base.clone(),
25                config_base: base,
26            };
27        }
28
29        let base = dirs::cache_dir()
30            .unwrap_or_else(|| PathBuf::from("."))
31            .join("paper");
32        let config_base = dirs::config_dir()
33            .unwrap_or_else(|| PathBuf::from("."))
34            .join("paper");
35        Self { base, config_base }
36    }
37
38    /// Paths rooted at an explicit directory. Useful for tests.
39    pub fn with_base(base: impl AsRef<Path>) -> Self {
40        let base = base.as_ref().to_path_buf();
41        Self {
42            config_base: base.clone(),
43            base,
44        }
45    }
46
47    pub fn base_dir(&self) -> PathBuf {
48        self.base.clone()
49    }
50
51    pub fn model_cache_dir(&self) -> PathBuf {
52        self.base.join("models")
53    }
54
55    pub fn db_path(&self) -> PathBuf {
56        self.base.join("chunks.db")
57    }
58
59    pub fn config_path(&self) -> PathBuf {
60        self.config_base.join("config.toml")
61    }
62
63    /// Create the directories Paper writes into. Safe to call repeatedly.
64    pub fn ensure_dirs(&self) -> std::io::Result<()> {
65        create_private_dir(&self.base)?;
66        std::fs::create_dir_all(self.model_cache_dir())?;
67        if let Some(parent) = self.config_path().parent() {
68            create_private_dir(parent)?;
69        }
70        Ok(())
71    }
72}
73
74/// Create `dir` and any missing parents. On Unix a newly created `dir` is
75/// 0700: it holds the index (a plaintext copy of every indexed document) or
76/// the config (which can hold an API key). Parents get the default mode and
77/// existing directories are left untouched.
78pub(crate) fn create_private_dir(dir: &Path) -> std::io::Result<()> {
79    if let Some(parent) = dir.parent() {
80        std::fs::create_dir_all(parent)?;
81    }
82    let mut builder = std::fs::DirBuilder::new();
83    builder.recursive(true); // an existing directory is not an error
84    #[cfg(unix)]
85    std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
86    builder.create(dir)
87}