1use std::path::{Path, PathBuf};
2
3#[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 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 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
74pub(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); #[cfg(unix)]
85 std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
86 builder.create(dir)
87}