Skip to main content

deedar/
url.rs

1use std::path::{Path, PathBuf};
2
3use deed::{Error, Result};
4
5use crate::fs::FsStore;
6
7/// `DEEDAR_URL` contract: `file:///abs/path` is the store.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct StoreUrl {
10    dir: PathBuf,
11}
12
13impl StoreUrl {
14    pub fn parse(raw: &str) -> Result<Self> {
15        let raw = raw.trim();
16        let path = if let Some(rest) = raw.strip_prefix("file://") {
17            PathBuf::from(rest)
18        } else if raw.starts_with('/') {
19            PathBuf::from(raw)
20        } else {
21            return Err(Error::InvalidUrl(raw.into()));
22        };
23        if !path.is_absolute() {
24            return Err(Error::InvalidUrl(raw.into()));
25        }
26        Ok(Self { dir: path })
27    }
28
29    pub fn dir(&self) -> &Path {
30        &self.dir
31    }
32
33    pub fn as_url(&self) -> String {
34        format!("file://{}", self.dir.display())
35    }
36}
37
38/// Where a seat keeps its store when nobody says otherwise.
39///
40/// `$XDG_DATA_HOME/deedar/store`, or `$HOME/.local/share/deedar/store`.
41/// An empty or relative value is ignored for either variable: it would
42/// follow the working directory, and two runs would not share one store.
43/// The command line and the MCP server both ask here, so they open one store.
44#[must_use]
45pub fn default_store() -> Option<PathBuf> {
46    seat_store(std::env::var_os("XDG_DATA_HOME"), std::env::var_os("HOME"))
47}
48
49/// `$XDG_DATA_HOME` when it is absolute, otherwise an absolute `$HOME`.
50fn seat_store(
51    xdg: Option<std::ffi::OsString>,
52    home: Option<std::ffi::OsString>,
53) -> Option<PathBuf> {
54    let base = absolute(xdg).or_else(|| absolute(home).map(|home| home.join(".local/share")))?;
55    Some(base.join("deedar").join("store"))
56}
57
58/// An empty or relative directory is not a data directory.
59fn absolute(raw: Option<std::ffi::OsString>) -> Option<PathBuf> {
60    raw.map(PathBuf::from).filter(|path| path.is_absolute())
61}
62
63pub fn open(raw: &str) -> Result<FsStore> {
64    let url = StoreUrl::parse(raw)?;
65    FsStore::open(url.dir())
66}
67
68#[cfg(test)]
69mod tests {
70    use std::ffi::OsString;
71    use std::path::PathBuf;
72
73    use super::seat_store;
74
75    fn path(raw: &str) -> OsString {
76        OsString::from(raw)
77    }
78
79    #[test]
80    fn home_is_the_fallback_when_xdg_data_home_is_unset_or_not_absolute() {
81        let want = PathBuf::from("/seat/.local/share/deedar/store");
82        assert_eq!(seat_store(None, Some(path("/seat"))), Some(want.clone()));
83        assert_eq!(
84            seat_store(Some(path("")), Some(path("/seat"))),
85            Some(want.clone())
86        );
87        assert_eq!(
88            seat_store(Some(path("relative")), Some(path("/seat"))),
89            Some(want)
90        );
91    }
92
93    #[test]
94    fn an_empty_or_relative_home_is_ignored() {
95        assert_eq!(seat_store(None, Some(path(""))), None);
96        assert_eq!(seat_store(None, Some(path("relative"))), None);
97        assert_eq!(seat_store(Some(path("")), Some(path(""))), None);
98        assert_eq!(
99            seat_store(Some(path("relative")), Some(path("relative"))),
100            None
101        );
102        assert_eq!(
103            seat_store(Some(path("/xdg")), Some(path("relative"))),
104            Some(PathBuf::from("/xdg/deedar/store"))
105        );
106    }
107}