Skip to main content

surjection_core/
paths.rs

1//! `SURJECTION_HOME` resolution, data layout and sync-root detection (SPEC 4.5).
2
3use std::borrow::Cow;
4use std::ffi::{OsStr, OsString};
5use std::path::{Component, Path, PathBuf, Prefix};
6
7use crate::brand;
8use crate::env::{Env, KnownFolder, Os};
9use crate::error::{CoreError, ErrorCode};
10use crate::fs::Fs;
11
12/// The machine-local state directory inside `SURJECTION_HOME`.
13pub const STATE_DIR: &str = "state";
14
15/// Where the resolved `SURJECTION_HOME` came from, highest precedence first.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum HomeSource {
18    /// The `--home` command-line flag.
19    Flag,
20    /// The `SURJECTION_HOME` environment variable.
21    EnvVar,
22    /// The per-OS default.
23    Default,
24}
25
26impl HomeSource {
27    pub const fn as_str(self) -> &'static str {
28        match self {
29            HomeSource::Flag => "flag",
30            HomeSource::EnvVar => "env",
31            HomeSource::Default => "default",
32        }
33    }
34}
35
36/// File-sync tool owning a folder. Live git repos and lock files must not
37/// live inside one.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum SyncRootKind {
40    Resilio,
41    Syncthing,
42    OneDrive,
43    Dropbox,
44    GoogleDrive,
45}
46
47impl SyncRootKind {
48    pub const fn as_str(self) -> &'static str {
49        match self {
50            SyncRootKind::Resilio => "resilio",
51            SyncRootKind::Syncthing => "syncthing",
52            SyncRootKind::OneDrive => "onedrive",
53            SyncRootKind::Dropbox => "dropbox",
54            SyncRootKind::GoogleDrive => "google_drive",
55        }
56    }
57}
58
59/// A sync folder containing a path. Reported by `surject doctor` as
60/// `sync_root_detected`.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct SyncRoot {
63    pub kind: SyncRootKind,
64    /// Top folder managed by the sync tool.
65    pub root: PathBuf,
66}
67
68/// The resolved data directory.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct SurjectionHome {
71    /// Absolute and lexically normalized.
72    pub path: PathBuf,
73    pub source: HomeSource,
74    /// Set when `path` lies inside a file-sync folder.
75    pub sync_root: Option<SyncRoot>,
76}
77
78impl SurjectionHome {
79    /// Versioned desired state (git repo).
80    pub fn store_dir(&self) -> PathBuf {
81        self.path.join("store")
82    }
83
84    /// Machine-local, unversioned state.
85    pub fn state_dir(&self) -> PathBuf {
86        self.path.join(STATE_DIR)
87    }
88
89    /// Pre-write copies of client files and trash; never pushed.
90    pub fn backups_dir(&self) -> PathBuf {
91        self.path.join("backups")
92    }
93
94    /// Re-creatable caches.
95    pub fn cache_dir(&self) -> PathBuf {
96        self.path.join("cache")
97    }
98
99    /// Migration inputs.
100    pub fn imports_dir(&self) -> PathBuf {
101        self.path.join("imports")
102    }
103
104    pub fn logs_dir(&self) -> PathBuf {
105        self.path.join("logs")
106    }
107}
108
109/// Resolves `SURJECTION_HOME`: `flag` (the CLI `--home`), else the
110/// `SURJECTION_HOME` variable, else the former `LOADOUT_HOME` variable,
111/// else the per-OS default. Overrides must be absolute. The result is
112/// checked for an enclosing sync folder.
113pub fn surjection_home(
114    env: &Env,
115    fs: &dyn Fs,
116    flag: Option<&Path>,
117) -> Result<SurjectionHome, CoreError> {
118    let (path, source, name) = match (flag, home_var(env)) {
119        (Some(flag), _) => (flag.to_path_buf(), HomeSource::Flag, brand::HOME_ENV_VAR),
120        (None, Some((name, var))) => (PathBuf::from(var), HomeSource::EnvVar, name),
121        (None, None) => (
122            default_or_legacy(env, fs),
123            HomeSource::Default,
124            brand::HOME_ENV_VAR,
125        ),
126    };
127    if !path.is_absolute() {
128        return Err(CoreError::new(
129            ErrorCode::InvalidPath,
130            format!("{name} must be an absolute path"),
131        )
132        .with_path(path));
133    }
134    let path = normalize(&path);
135    let sync_root = detect_sync_root(env, fs, &path);
136    Ok(SurjectionHome {
137        path,
138        source,
139        sync_root,
140    })
141}
142
143/// The data folder variable in effect and its value: `SURJECTION_HOME`, or
144/// `LOADOUT_HOME` (Loadout 1.0.x) when the former is unset.
145pub fn home_var(env: &Env) -> Option<(&'static str, &std::ffi::OsStr)> {
146    env.var(brand::HOME_ENV_VAR)
147        .map(|value| (brand::HOME_ENV_VAR, value))
148        .or_else(|| {
149            env.var(brand::legacy::HOME_ENV_VAR)
150                .map(|value| (brand::legacy::HOME_ENV_VAR, value))
151        })
152}
153
154/// The per-OS default data directory of Loadout 1.0.x (what
155/// `surject migrate loadout` moves).
156pub fn legacy_default_home(env: &Env) -> PathBuf {
157    let current = default_surjection_home(env);
158    let name = match env.os() {
159        Os::Windows => brand::legacy::DATA_DIR_WINDOWS,
160        Os::Linux => brand::legacy::DATA_DIR_LINUX,
161        Os::MacOs => brand::legacy::DATA_DIR_MACOS,
162    };
163    current.with_file_name(name)
164}
165
166/// The per-OS default data directory. Never reads `HOME` on Windows: the
167/// profile comes from [`Env::home`] and the base from `FOLDERID_LocalAppData`.
168pub fn default_surjection_home(env: &Env) -> PathBuf {
169    match env.os() {
170        Os::Windows => env
171            .known_folder(KnownFolder::LocalAppData)
172            .map(Path::to_path_buf)
173            .unwrap_or_else(|| env.home().join("AppData").join("Local"))
174            .join(brand::DATA_DIR_WINDOWS),
175        Os::Linux => env
176            .var("XDG_DATA_HOME")
177            .map(PathBuf::from)
178            // The XDG spec says relative values are invalid and ignored.
179            .filter(|path| path.is_absolute())
180            .unwrap_or_else(|| env.home().join(".local").join("share"))
181            .join(brand::DATA_DIR_LINUX),
182        Os::MacOs => env
183            .home()
184            .join("Library")
185            .join("Application Support")
186            .join(brand::DATA_DIR_MACOS),
187    }
188}
189
190/// Finds a file-sync folder containing `path`.
191///
192/// Walks the ancestors of `path` (stopping at [`Fs::root`]) for a Resilio
193/// `.sync` folder holding `ID` or `IgnoreList`, or a Syncthing `.stfolder`.
194/// Then compares against provider roots: OneDrive (`OneDrive`,
195/// `OneDriveConsumer`, `OneDriveCommercial` variables), Dropbox
196/// (`info.json`), Google Drive (`~/My Drive`, `~/Google Drive`, a
197/// `<drive>:\My Drive` stream mount) and macOS `~/Library/CloudStorage`.
198pub fn detect_sync_root(env: &Env, fs: &dyn Fs, path: &Path) -> Option<SyncRoot> {
199    let path = normalize(path);
200    marker_root(env.os(), fs, &path).or_else(|| provider_root(env, fs, &path))
201}
202
203fn marker_root(os: Os, fs: &dyn Fs, path: &Path) -> Option<SyncRoot> {
204    let ceiling = fs.root().map(normalize);
205    for dir in path.ancestors() {
206        if ceiling
207            .as_deref()
208            .is_some_and(|ceiling| !is_within(os, dir, ceiling))
209        {
210            break;
211        }
212        let resilio = dir.join(".sync");
213        if fs.is_dir(&resilio)
214            && (fs.exists(&resilio.join("ID")) || fs.exists(&resilio.join("IgnoreList")))
215        {
216            return Some(sync_root(SyncRootKind::Resilio, dir));
217        }
218        if fs.exists(&dir.join(".stfolder")) {
219            return Some(sync_root(SyncRootKind::Syncthing, dir));
220        }
221    }
222    None
223}
224
225fn provider_root(env: &Env, fs: &dyn Fs, path: &Path) -> Option<SyncRoot> {
226    let os = env.os();
227    let home = env.home();
228
229    let onedrive = ["OneDrive", "OneDriveConsumer", "OneDriveCommercial"]
230        .into_iter()
231        .filter_map(|name| env.var(name))
232        .map(|root| (SyncRootKind::OneDrive, PathBuf::from(root)));
233    let dropbox = dropbox_info_files(env)
234        .into_iter()
235        .filter(|info| fs.exists(info))
236        .filter_map(|info| fs.read_to_string(&info).ok())
237        .flat_map(|text| dropbox_roots(&text))
238        .map(|root| (SyncRootKind::Dropbox, root));
239    let google = ["My Drive", "Google Drive"]
240        .into_iter()
241        .map(|name| (SyncRootKind::GoogleDrive, home.join(name)));
242
243    onedrive
244        .chain(dropbox)
245        .chain(google)
246        .filter(|(_, root)| root.is_absolute())
247        .map(|(kind, root)| sync_root(kind, &root))
248        .find(|candidate| is_within(os, path, &candidate.root))
249        .or_else(|| cloud_storage_root(env, path))
250        .or_else(|| google_drive_mount(path))
251}
252
253fn dropbox_info_files(env: &Env) -> Vec<PathBuf> {
254    match env.os() {
255        Os::Windows => [KnownFolder::LocalAppData, KnownFolder::RoamingAppData]
256            .into_iter()
257            .filter_map(|folder| env.known_folder(folder))
258            .map(|base| base.join("Dropbox").join("info.json"))
259            .collect(),
260        Os::Linux | Os::MacOs => vec![env.home().join(".dropbox").join("info.json")],
261    }
262}
263
264/// Account roots from Dropbox's `info.json` (`{"personal": {"path": ...}, ...}`).
265fn dropbox_roots(text: &str) -> Vec<PathBuf> {
266    let Ok(serde_json::Value::Object(accounts)) = serde_json::from_str(text) else {
267        return Vec::new();
268    };
269    accounts
270        .values()
271        .filter_map(|account| account.get("path")?.as_str())
272        .map(PathBuf::from)
273        .collect()
274}
275
276/// macOS File Provider roots: `~/Library/CloudStorage/<Provider>-<account>`.
277fn cloud_storage_root(env: &Env, path: &Path) -> Option<SyncRoot> {
278    if env.os() != Os::MacOs {
279        return None;
280    }
281    let base = normalize(&env.home().join("Library").join("CloudStorage"));
282    let rest = path.strip_prefix(&base).ok()?;
283    let Some(Component::Normal(entry)) = rest.components().next() else {
284        return None;
285    };
286    let name = entry.to_string_lossy();
287    let kind = [
288        ("OneDrive", SyncRootKind::OneDrive),
289        ("Dropbox", SyncRootKind::Dropbox),
290        ("GoogleDrive", SyncRootKind::GoogleDrive),
291    ]
292    .into_iter()
293    .find_map(|(prefix, kind)| name.starts_with(prefix).then_some(kind))?;
294    Some(sync_root(kind, &base.join(entry)))
295}
296
297/// Google Drive for desktop in streaming mode mounts `<drive>:\My Drive`.
298fn google_drive_mount(path: &Path) -> Option<SyncRoot> {
299    path.ancestors()
300        .find(|dir| {
301            dir.file_name() == Some(OsStr::new("My Drive"))
302                && dir.parent().is_some_and(|parent| parent.parent().is_none())
303        })
304        .map(|dir| sync_root(SyncRootKind::GoogleDrive, dir))
305}
306
307fn sync_root(kind: SyncRootKind, root: &Path) -> SyncRoot {
308    SyncRoot {
309        kind,
310        root: normalize(root),
311    }
312}
313
314/// Lexically normalizes a path: drops `.` and resolves `..` against earlier
315/// components without touching the file system. `..` above a root is dropped.
316pub fn normalize(path: &Path) -> PathBuf {
317    let mut out = PathBuf::new();
318    for component in path.components() {
319        match component {
320            Component::CurDir => {}
321            Component::ParentDir => match out.components().next_back() {
322                Some(Component::Normal(_)) => {
323                    out.pop();
324                }
325                Some(Component::RootDir) => {}
326                _ => out.push(".."),
327            },
328            other => out.push(other.as_os_str()),
329        }
330    }
331    out
332}
333
334/// The `\\?\` (extended-length) form of an absolute Windows path, which
335/// file system calls accept past `MAX_PATH` (SPEC 16.1): `C:\x` is
336/// `\\?\C:\x`, `\\server\share\x` is `\\?\UNC\server\share\x`. The path is
337/// normalized first, since the OS takes a `\\?\` path literally (no `/`,
338/// `.` or `..` handling). Any other path, and every path off Windows, is
339/// returned as it is.
340pub fn extended(path: &Path) -> Cow<'_, Path> {
341    if !path.is_absolute() {
342        return Cow::Borrowed(path);
343    }
344    let normal = normalize(path);
345    let mut components = normal.components();
346    let Some(Component::Prefix(prefix)) = components.next() else {
347        return Cow::Borrowed(path);
348    };
349    let mut out = match prefix.kind() {
350        Prefix::Disk(letter) => OsString::from(format!(r"\\?\{}:", char::from(letter))),
351        Prefix::UNC(server, share) => {
352            let mut out = OsString::from(r"\\?\UNC\");
353            out.push(server);
354            out.push(r"\");
355            out.push(share);
356            out
357        }
358        _ => return Cow::Borrowed(path),
359    };
360    let mut named = false;
361    for component in components {
362        if let Component::Normal(name) = component {
363            out.push(r"\");
364            out.push(name);
365            named = true;
366        }
367    }
368    if !named {
369        out.push(r"\");
370    }
371    Cow::Owned(PathBuf::from(out))
372}
373
374/// `path` without a `\\?\` prefix ([`extended`] undone): `\\?\C:\x` is
375/// `C:\x`, `\\?\UNC\server\share\x` is `\\server\share\x`. Any other path,
376/// and every path off Windows, is returned as it is.
377pub fn plain(path: &Path) -> Cow<'_, Path> {
378    let mut components = path.components();
379    let Some(Component::Prefix(prefix)) = components.next() else {
380        return Cow::Borrowed(path);
381    };
382    let head = match prefix.kind() {
383        Prefix::VerbatimDisk(letter) => OsString::from(format!("{}:", char::from(letter))),
384        Prefix::VerbatimUNC(server, share) => {
385            let mut head = OsString::from(r"\\");
386            head.push(server);
387            head.push(r"\");
388            head.push(share);
389            head
390        }
391        _ => return Cow::Borrowed(path),
392    };
393    let mut out = PathBuf::from(head);
394    out.extend(components);
395    Cow::Owned(out)
396}
397
398/// Whether `path` equals `base` or lies below it, comparing components
399/// case-insensitively on Windows and treating `\\?\C:` like `C:`.
400fn is_within(os: Os, path: &Path, base: &Path) -> bool {
401    let mut path = path.components();
402    base.components().all(|expected| {
403        path.next()
404            .is_some_and(|actual| same_component(os, actual, expected))
405    })
406}
407
408fn same_component(os: Os, a: Component<'_>, b: Component<'_>) -> bool {
409    match os {
410        Os::Windows => component_key(a).to_lowercase() == component_key(b).to_lowercase(),
411        Os::Linux | Os::MacOs => a == b,
412    }
413}
414
415fn component_key(component: Component<'_>) -> Cow<'_, str> {
416    if let Component::Prefix(prefix) = component {
417        match prefix.kind() {
418            Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => {
419                return Cow::Owned(format!("{}:", char::from(letter)));
420            }
421            Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => {
422                return Cow::Owned(format!(
423                    r"\\{}\{}",
424                    server.to_string_lossy(),
425                    share.to_string_lossy()
426                ));
427            }
428            Prefix::Verbatim(_) | Prefix::DeviceNS(_) => {}
429        }
430    }
431    component.as_os_str().to_string_lossy()
432}
433
434/// The per-OS default data directory, or Loadout 1.0.x's default one while
435/// only that exists (before `surject migrate loadout` moved it, or when the
436/// move could not run yet), so nothing starts over in an empty folder.
437fn default_or_legacy(env: &Env, fs: &dyn Fs) -> PathBuf {
438    let current = default_surjection_home(env);
439    if fs.exists(&current) {
440        return current;
441    }
442    let legacy = legacy_default_home(env);
443    if fs.is_dir(&legacy) { legacy } else { current }
444}