Skip to main content

tilo_paths/
lib.rs

1//! Where per-user data, configuration, state, cache and runtime files live.
2//!
3//! [`AppPaths::for_app`] gives an app its data, config, cache, state and runtime
4//! locations, the user's folders, the workspace and the font catalog, on every
5//! target; the functions here are the same base directories for code without an app.
6
7use std::ffi::OsString;
8use std::path::PathBuf;
9
10mod app;
11mod caps;
12pub mod desktop_service;
13mod location;
14pub mod login;
15pub mod session;
16
17pub use app::{AppPaths, DEFAULT_PROFILE, default_profile, set_default_profile};
18pub use caps::{Availability, Feature, Unsupported, availability, available};
19pub use location::{InvalidVPath, Location, VPath, VirtualRoot};
20
21/// Where a Tilo Linux session mounts the collaborative workspace, and the
22/// root every member's documents name workspace files under, whatever
23/// this device mounts. [`AppPaths::workspace_root`] says whether (and where)
24/// this process has one mounted.
25pub const WORKSPACE_MOUNT: &str = "/var/workspace";
26
27/// The file a Tilo Linux session writes the people and devices it certifies
28/// to: what an app showing who a file is shared with names them from.
29pub const TRUSTED_IDENTITIES: &str = "/run/tilo/identity-projection/trusted-identities.json";
30
31/// The runtime publishers this device accepts, one hex Ed25519 key per line, `#` comments: the
32/// list the system ships beside the code that reads it. A Linux image ships it in `/etc/tilo`; on
33/// a Mac it is in the resources of the Tilo.app whose executable is running, sealed by the app's
34/// signature as that executable is. An executable outside an app bundle reads the image's path,
35/// which a Mac does not have, so it trusts no runtime.
36#[must_use]
37pub fn runtime_publishers() -> PathBuf {
38    const FILE: &str = "runtime-bundle-trusted-publishers.txt";
39    #[cfg(target_os = "macos")]
40    if let Some(contents) = std::env::current_exe()
41        .and_then(std::fs::canonicalize)
42        .ok()
43        .and_then(|exe| Some(exe.parent()?.parent()?.to_path_buf()))
44        .filter(|contents| contents.join("Info.plist").is_file())
45    {
46        return contents.join("Resources").join(FILE);
47    }
48    PathBuf::from("/etc/tilo").join(FILE)
49}
50
51/// The directory, at the root of the device's files, that holds one tree per
52/// workspace: `<files>/.workspaces/<workspace id>`. The device's files are
53/// one namespace (`fs` serves one per device); a workspace's own files are
54/// the tree under its id, so its access checks (`FsPath` grants, which scope
55/// by path prefix) cover each tree as they cover any folder.
56pub const WORKSPACE_TREES_DIR: &str = ".workspaces";
57
58/// The tree of the workspace `id`'s own files under the device's files at
59/// `files`: [`WORKSPACE_TREES_DIR`]`/<id>`. `None` for an id that is not one
60/// path component of `[A-Za-z0-9_-]`, 1 to 128 bytes, so no id names a
61/// directory outside its own tree.
62#[must_use]
63pub fn workspace_tree(files: &std::path::Path, id: &str) -> Option<PathBuf> {
64    is_workspace_tree_id(id).then(|| files.join(WORKSPACE_TREES_DIR).join(id))
65}
66
67#[must_use]
68pub fn is_workspace_tree_id(id: &str) -> bool {
69    (1..=128).contains(&id.len())
70        && id
71            .bytes()
72            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
73}
74
75#[must_use]
76pub fn workspace_root() -> Option<PathBuf> {
77    let location = AppPaths::for_app("workspace").workspace_root().ok()?;
78    location
79        .native_path()
80        .ok()
81        .map(std::path::Path::to_path_buf)
82}
83
84#[must_use]
85pub fn language_packs_dir() -> Option<PathBuf> {
86    xdg::data_home().map(|data| data.join("tilo").join("language-packs"))
87}
88
89/// The language a locale names, as a language pack is named: its language
90/// subtag, lower case (`de` of `de`, `de-DE`, `de_DE.UTF-8@euro`). One pack
91/// holds a language's catalogues whatever region, encoding or modifier a
92/// locale adds, so a choice, the pack's directory and its package id meet at
93/// this one name. Empty when no language is named.
94///
95/// This is the one rule for "which language is this tag": every reader of a
96/// language tag — the packs, the toolkits, history, desktop entries — asks
97/// here, so a language picked anywhere matches everywhere.
98#[must_use]
99pub fn language_of(tag: &str) -> String {
100    tag.trim()
101        .split(['-', '_', '.', '@'])
102        .next()
103        .unwrap_or_default()
104        .to_ascii_lowercase()
105}
106
107/// The BCP 47 tag a locale names: the POSIX `de_DE.UTF-8@euro`, the
108/// `LANGUAGE` list `de_AT:en_US` and the BCP 47 `de-DE` all name `de-DE`.
109/// The encoding and the modifier name no language, a list's first entry is
110/// the language, and a tag spells the `_` a POSIX locale uses as `-`.
111#[must_use]
112pub fn locale_tag(locale: &str) -> String {
113    locale
114        .split(':')
115        .next()
116        .unwrap_or_default()
117        .split(['.', '@'])
118        .next()
119        .unwrap_or_default()
120        .trim()
121        .replace('_', "-")
122}
123
124/// Whether `tag` names a language: `C`, `POSIX`, `C.UTF-8` and an empty
125/// value name none, so their text is read untranslated.
126#[must_use]
127pub fn names_language(tag: &str) -> bool {
128    !matches!(language_of(tag).as_str(), "" | "c" | "posix")
129}
130
131/// The position in `candidates` (language tags, in the order the caller
132/// prefers them) of the one a reader of `locale` reads best: their own tag
133/// (`de-DE` for `de_DE.UTF-8`), else another region of their language
134/// (`de-DE` for `de-AT`). `None` when neither is there or `locale` names no
135/// language. This is the one rule for which tag a reader gets, so every
136/// catalogue, name and window picks the same one.
137#[must_use]
138pub fn matching<'a>(
139    locale: &str,
140    mut candidates: impl Iterator<Item = &'a str> + Clone,
141) -> Option<usize> {
142    if !names_language(locale) {
143        return None;
144    }
145    let tag = locale_tag(locale);
146    let language = language_of(locale);
147    let mut exact = candidates.clone();
148    exact
149        .position(|candidate| locale_tag(candidate).eq_ignore_ascii_case(&tag))
150        .or_else(|| candidates.position(|candidate| language_of(candidate) == language))
151}
152
153/// The user's home directory: `$HOME` when set and non-empty, the account
154/// database's entry when `$HOME` is unset (on Unix), and `None` for an empty
155/// `$HOME` — an empty value names no directory, and resolving relative to the
156/// working directory would scatter state wherever the process started. On
157/// Windows it is the profile known folder, never an environment variable.
158#[must_use]
159pub fn home() -> Option<PathBuf> {
160    #[cfg(windows)]
161    {
162        platform::home()
163    }
164    #[cfg(not(windows))]
165    {
166        home_from(&|name| var(name), std::env::home_dir)
167    }
168}
169
170#[cfg(not(windows))]
171fn home_from(
172    var: &dyn Fn(&str) -> Option<OsString>,
173    account_home: impl FnOnce() -> Option<PathBuf>,
174) -> Option<PathBuf> {
175    #[cfg(unix)]
176    match var("HOME") {
177        Some(home) if home.is_empty() => None,
178        Some(home) => Some(PathBuf::from(home)),
179        None => account_home().filter(|home| !home.as_os_str().is_empty()),
180    }
181    #[cfg(not(unix))]
182    {
183        let _ = var;
184        account_home().filter(|home| !home.as_os_str().is_empty())
185    }
186}
187
188/// `$name` as a directory, following the XDG rule for every base-directory
189/// variable: honoured only when set, non-empty and absolute.
190#[must_use]
191pub fn env_dir(name: &str) -> Option<PathBuf> {
192    absolute(var(name))
193}
194
195thread_local! {
196    static PROFILE_ROOT: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
197}
198
199/// Keeps a thread's per-user folders below one root until it is dropped:
200/// see [`scope_profile`].
201#[must_use = "the scope ends when the guard is dropped"]
202pub struct ProfileScope {
203    earlier: Option<PathBuf>,
204}
205
206impl Drop for ProfileScope {
207    fn drop(&mut self) {
208        PROFILE_ROOT.with(|root| *root.borrow_mut() = self.earlier.take());
209    }
210}
211
212/// From now until the guard drops, this thread's home is `root`: [`home`],
213/// the per-user base folders, [`env_dir`] of the XDG variables and
214/// [`AppPaths::for_app`] all resolve below it, whatever the process
215/// environment says, and no workspace is mounted. A host that runs a
216/// member (an agent) on its own thread gives it a profile apart from
217/// the host user's this way. Threads the scoped thread starts do not
218/// inherit it.
219pub fn scope_profile(root: impl Into<PathBuf>) -> ProfileScope {
220    let earlier = PROFILE_ROOT.with(|scoped| scoped.borrow_mut().replace(root.into()));
221    ProfileScope { earlier }
222}
223
224pub fn unscoped<R>(work: impl FnOnce() -> R) -> R {
225    let _scope = ProfileScope {
226        earlier: PROFILE_ROOT.with(|root| root.borrow_mut().take()),
227    };
228    work()
229}
230
231#[must_use]
232pub fn scoped_profile() -> Option<PathBuf> {
233    PROFILE_ROOT.with(|root| root.borrow().clone())
234}
235
236/// The environment variable `name`, as this process's profile scopes it: a location variable
237/// resolves below the profile root a test or a stack lent this process, and any other is read as
238/// the process has it.
239#[must_use]
240pub fn var(name: &str) -> Option<OsString> {
241    let Some(root) = scoped_profile() else {
242        return std::env::var_os(name);
243    };
244    let below = match name {
245        "HOME" => "",
246        "XDG_DATA_HOME" => ".local/share",
247        "XDG_CONFIG_HOME" => ".config",
248        "XDG_STATE_HOME" => ".local/state",
249        "XDG_CACHE_HOME" => ".cache",
250        "XDG_RUNTIME_DIR" => "run",
251        "TMPDIR" => "tmp",
252        name if name.starts_with("TILO_WORKSPACE") => return None,
253        name if name.starts_with("XDG_") && name.ends_with("_DIR") => return None,
254        _ => return std::env::var_os(name),
255    };
256    Some(root.join(below).into_os_string())
257}
258
259fn absolute(value: Option<OsString>) -> Option<PathBuf> {
260    // An empty path is not absolute, so this also rejects empty values.
261    value.map(PathBuf::from).filter(|path| path.is_absolute())
262}
263
264pub mod xdg {
265    use std::ffi::{OsStr, OsString};
266    use std::path::PathBuf;
267
268    use super::{absolute, home};
269
270    #[must_use]
271    pub fn data_home() -> Option<PathBuf> {
272        Base::Data.resolve(&env, home)
273    }
274
275    #[must_use]
276    pub fn config_home() -> Option<PathBuf> {
277        Base::Config.resolve(&env, home)
278    }
279
280    #[must_use]
281    pub fn state_home() -> Option<PathBuf> {
282        Base::State.resolve(&env, home)
283    }
284
285    #[must_use]
286    pub fn cache_home() -> Option<PathBuf> {
287        Base::Cache.resolve(&env, home)
288    }
289
290    /// `$XDG_RUNTIME_DIR`. The spec defines no fallback: a substitute would
291    /// lack its guarantees (owner-only, removed at logout), so `None` makes
292    /// callers decide what to do without one.
293    #[must_use]
294    pub fn runtime_dir() -> Option<PathBuf> {
295        Base::Runtime.resolve(&env, home)
296    }
297
298    /// [`runtime_dir`], else where the platform keeps it without the
299    /// variable: `/run/user/<euid>` as systemd-logind creates it, the per-user
300    /// `$TMPDIR` on macOS, the per-user `%TEMP%` on Windows. For callers that
301    /// must name a per-user socket or file even in a session started without
302    /// `$XDG_RUNTIME_DIR`.
303    #[cfg(any(unix, windows))]
304    #[must_use]
305    pub fn runtime_dir_or_default() -> PathBuf {
306        runtime_dir().unwrap_or_else(|| {
307            #[cfg(any(target_os = "macos", windows))]
308            {
309                std::env::temp_dir()
310            }
311            #[cfg(all(unix, not(target_os = "macos")))]
312            {
313                PathBuf::from(format!("/run/user/{}", rustix::process::geteuid().as_raw()))
314            }
315        })
316    }
317
318    /// Where this login's Tilo services bind their sockets: one directory in
319    /// the runtime directory, so a socket found here belongs to this user and
320    /// is gone when their login ends.
321    #[cfg(any(unix, windows))]
322    #[must_use]
323    pub fn services_dir() -> PathBuf {
324        runtime_dir_or_default().join("tilo/services")
325    }
326
327    #[cfg(any(unix, windows))]
328    #[must_use]
329    pub fn service_socket(name: &str) -> PathBuf {
330        services_dir().join(format!("{name}.sock"))
331    }
332
333    /// `$XDG_DATA_DIRS` in preference order, else `/usr/local/share` and
334    /// `/usr/share`. Relative and empty entries are ignored, as the spec
335    /// requires.
336    #[must_use]
337    pub fn data_dirs() -> Vec<PathBuf> {
338        search_path(
339            env("XDG_DATA_DIRS").as_deref(),
340            &["/usr/local/share", "/usr/share"],
341        )
342    }
343
344    /// `$XDG_CONFIG_DIRS` in preference order, else `/etc/xdg`. Relative and
345    /// empty entries are ignored, as the spec requires.
346    #[must_use]
347    pub fn config_dirs() -> Vec<PathBuf> {
348        search_path(env("XDG_CONFIG_DIRS").as_deref(), &["/etc/xdg"])
349    }
350
351    fn env(name: &str) -> Option<OsString> {
352        super::var(name)
353    }
354
355    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
356    pub enum Base {
357        Data,
358        Config,
359        State,
360        Cache,
361        Runtime,
362    }
363
364    impl Base {
365        #[must_use]
366        pub const fn env_var(self) -> &'static str {
367            match self {
368                Self::Data => "XDG_DATA_HOME",
369                Self::Config => "XDG_CONFIG_HOME",
370                Self::State => "XDG_STATE_HOME",
371                Self::Cache => "XDG_CACHE_HOME",
372                Self::Runtime => "XDG_RUNTIME_DIR",
373            }
374        }
375
376        const fn home_default(self) -> Option<&'static str> {
377            match self {
378                Self::Data => Some(".local/share"),
379                Self::Config => Some(".config"),
380                Self::State => Some(".local/state"),
381                Self::Cache => Some(".cache"),
382                Self::Runtime => None,
383            }
384        }
385
386        /// Resolve from explicit values of the variable and `$HOME` instead of
387        /// the process environment — for callers that take them as parameters
388        /// so tests need not mutate the environment. The variable counts only
389        /// when non-empty and absolute; an empty `home` counts as unset.
390        #[must_use]
391        pub fn resolve_from(self, value: Option<&OsStr>, home: Option<&OsStr>) -> Option<PathBuf> {
392            self.resolve(&|_| value.map(OsStr::to_os_string), || {
393                home.filter(|home| !home.is_empty()).map(PathBuf::from)
394            })
395        }
396
397        pub(crate) fn resolve(
398            self,
399            var: &dyn Fn(&str) -> Option<OsString>,
400            home: impl FnOnce() -> Option<PathBuf>,
401        ) -> Option<PathBuf> {
402            absolute(var(self.env_var())).or_else(|| {
403                let default = self.home_default()?;
404                Some(home()?.join(default))
405            })
406        }
407    }
408
409    pub(crate) fn search_path(value: Option<&OsStr>, default: &[&str]) -> Vec<PathBuf> {
410        let listed: Vec<PathBuf> = value
411            .map(|value| {
412                std::env::split_paths(value)
413                    .filter(|path| path.is_absolute())
414                    .collect()
415            })
416            .unwrap_or_default();
417        // An unset, empty or entirely invalid list means the defaults.
418        if listed.is_empty() {
419            default.iter().map(PathBuf::from).collect()
420        } else {
421            listed
422        }
423    }
424}
425
426/// The platform's per-user data directory: [`xdg::data_home`] on Linux and
427/// other Unix, `~/Library/Application Support` on macOS, `%APPDATA%` on
428/// Windows.
429#[must_use]
430pub fn data_dir() -> Option<PathBuf> {
431    platform::data()
432}
433
434/// The platform's per-user local (non-roaming) data directory:
435/// [`xdg::data_home`] on Linux and other Unix, `~/Library/Application Support`
436/// on macOS, `%LOCALAPPDATA%` on Windows.
437#[must_use]
438pub fn data_local_dir() -> Option<PathBuf> {
439    platform::data_local()
440}
441
442/// The platform's per-user configuration directory: [`xdg::config_home`] on
443/// Linux and other Unix, `~/Library/Application Support` on macOS,
444/// `%APPDATA%` on Windows.
445#[must_use]
446pub fn config_dir() -> Option<PathBuf> {
447    platform::config()
448}
449
450/// The platform's per-user state directory: [`xdg::state_home`] on Linux and
451/// other Unix, `~/Library/Application Support` on macOS (which keeps state
452/// beside data), `%LOCALAPPDATA%` on Windows: state belongs to this computer,
453/// and what roams with the account (`%APPDATA%`) would carry it to others.
454#[must_use]
455pub fn state_dir() -> Option<PathBuf> {
456    platform::state()
457}
458
459/// The per-user Tilo profile root: `$XDG_CONFIG_HOME/tilo`, else
460/// `$HOME/.config/tilo` on Linux and other Unix, the platform's configuration
461/// directory elsewhere.
462#[must_use]
463pub fn profile_root() -> Option<PathBuf> {
464    Some(xdg::config_home()?.join("tilo"))
465}
466
467/// The platform's per-user cache directory: [`xdg::cache_home`] on Linux and
468/// other Unix, `~/Library/Caches` on macOS, `%LOCALAPPDATA%` on Windows.
469#[must_use]
470pub fn cache_dir() -> Option<PathBuf> {
471    platform::cache()
472}
473
474/// The per-login runtime directory: [`xdg::runtime_dir`] on Linux and other
475/// Unix, the per-user `$TMPDIR` on macOS when it is absolute; Windows defines
476/// none.
477#[must_use]
478pub fn runtime_dir() -> Option<PathBuf> {
479    platform::runtime()
480}
481
482/// The system's shared temporary directory (`$TMPDIR` or `/tmp`,
483/// `%TEMP%`), and `None` where there is no native file system (the web),
484/// where `std::env::temp_dir` panics instead. For scratch files that must
485/// have a native path; an app's own scratch space is [`AppPaths::runtime`].
486#[must_use]
487pub fn temp_dir() -> Option<PathBuf> {
488    (available(Feature::NativePaths)).then(std::env::temp_dir)
489}
490
491/// A temporary directory kept in memory, where the platform has one
492/// (`/dev/shm` on Linux): for scratch data that is synced like a person's
493/// but deleted moments later (a test's profile), whose syncs then cost
494/// nothing instead of waiting on a shared disk. `None` elsewhere.
495#[must_use]
496pub fn memory_temp_dir() -> Option<PathBuf> {
497    if !cfg!(target_os = "linux") {
498        return None;
499    }
500    Some(PathBuf::from("/dev/shm")).filter(|directory| directory.is_dir())
501}
502
503/// Directories the system and the user install fonts into, most general
504/// first, whether or not they exist: the system font trees on Linux and
505/// other Unix (not the user's own), `/System/Library/Fonts`, `/Library/Fonts` and
506/// `~/Library/Fonts` on macOS, the Windows font folder, and none on the web.
507/// For code that reads font files itself (a document renderer's fallback
508/// fonts, a confined helper's read grant).
509#[must_use]
510pub fn system_font_dirs() -> Vec<PathBuf> {
511    platform::font_dirs()
512}
513
514#[cfg(all(unix, not(target_os = "macos")))]
515mod platform {
516    use std::path::PathBuf;
517
518    use super::{UserDir, home, xdg};
519
520    pub fn data() -> Option<PathBuf> {
521        xdg::data_home()
522    }
523    pub fn data_local() -> Option<PathBuf> {
524        xdg::data_home()
525    }
526    pub fn config() -> Option<PathBuf> {
527        xdg::config_home()
528    }
529    pub fn state() -> Option<PathBuf> {
530        xdg::state_home()
531    }
532    pub fn cache() -> Option<PathBuf> {
533        xdg::cache_home()
534    }
535    pub fn runtime() -> Option<PathBuf> {
536        xdg::runtime_dir()
537    }
538    pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
539        dir.resolve_for_home(&home()?)
540    }
541    pub fn font_dirs() -> Vec<PathBuf> {
542        [
543            "/usr/share/fonts",
544            "/usr/local/share/fonts",
545            "/usr/share/X11/fonts/Type1",
546            "/usr/share/X11/fonts/TTF",
547        ]
548        .into_iter()
549        .map(PathBuf::from)
550        .collect()
551    }
552}
553
554#[cfg(target_os = "macos")]
555mod platform {
556    use std::path::PathBuf;
557
558    use super::xdg::Base;
559    use super::{UserDir, home, macos};
560
561    fn base(base: Base) -> Option<PathBuf> {
562        macos::base(base, &|name| crate::var(name), home)
563    }
564
565    pub fn data() -> Option<PathBuf> {
566        base(Base::Data)
567    }
568    pub fn data_local() -> Option<PathBuf> {
569        data()
570    }
571    pub fn config() -> Option<PathBuf> {
572        base(Base::Config)
573    }
574    pub fn state() -> Option<PathBuf> {
575        base(Base::State)
576    }
577    pub fn cache() -> Option<PathBuf> {
578        base(Base::Cache)
579    }
580    pub fn runtime() -> Option<PathBuf> {
581        base(Base::Runtime)
582    }
583    pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
584        Some(macos::user_dir(dir, &home()?))
585    }
586    pub fn font_dirs() -> Vec<PathBuf> {
587        let mut dirs = vec![
588            PathBuf::from("/System/Library/Fonts"),
589            PathBuf::from("/Library/Fonts"),
590        ];
591        dirs.extend(home().map(|home| home.join("Library/Fonts")));
592        dirs
593    }
594}
595
596/// The macOS per-user locations as functions of the environment and home
597/// directory, so the Linux test run checks the base directories too.
598#[cfg(any(target_os = "macos", all(test, unix)))]
599mod macos {
600    use std::ffi::OsString;
601    use std::path::PathBuf;
602
603    use super::absolute;
604    use super::xdg::Base;
605
606    /// Data, configuration and state share `~/Library/Application Support`,
607    /// which is where macOS keeps an app's durable files; caches go to
608    /// `~/Library/Caches`. The runtime directory is `$TMPDIR`, the per-user,
609    /// owner-only directory launchd assigns below `/var/folders` and the
610    /// system cleans up. It counts only when absolute: the shared `/tmp`
611    /// lacks those guarantees, so there is no fallback.
612    pub(crate) fn base(
613        base: Base,
614        var: &dyn Fn(&str) -> Option<OsString>,
615        home: impl FnOnce() -> Option<PathBuf>,
616    ) -> Option<PathBuf> {
617        match base {
618            Base::Data | Base::Config | Base::State => {
619                Some(home()?.join("Library/Application Support"))
620            }
621            Base::Cache => Some(home()?.join("Library/Caches")),
622            Base::Runtime => absolute(var("TMPDIR")),
623        }
624    }
625
626    #[cfg(target_os = "macos")]
627    pub(crate) fn user_dir(dir: super::UserDir, home: &std::path::Path) -> PathBuf {
628        home.join(match dir {
629            super::UserDir::Videos => "Movies",
630            other => other.conventional_name(),
631        })
632    }
633}
634
635#[cfg(windows)]
636mod platform {
637    use std::ffi::OsString;
638    use std::os::windows::ffi::OsStringExt;
639    use std::path::PathBuf;
640
641    use windows_sys::Win32::System::Com::CoTaskMemFree;
642    use windows_sys::Win32::UI::Shell::{
643        FOLDERID_Desktop, FOLDERID_Documents, FOLDERID_Downloads, FOLDERID_LocalAppData,
644        FOLDERID_Music, FOLDERID_Pictures, FOLDERID_Profile, FOLDERID_Public,
645        FOLDERID_RoamingAppData, FOLDERID_Templates, FOLDERID_Videos, SHGetKnownFolderPath,
646    };
647    use windows_sys::core::{GUID, PWSTR};
648
649    use super::UserDir;
650
651    fn known_folder(id: &GUID) -> Option<PathBuf> {
652        let mut raw: PWSTR = std::ptr::null_mut();
653        // SAFETY: `id` is a valid GUID reference, a null token selects the
654        // current user, and `raw` is a valid out-pointer the call fills with
655        // a CoTaskMem-allocated, NUL-terminated wide string (or leaves null).
656        let status = unsafe { SHGetKnownFolderPath(id, 0, std::ptr::null_mut(), &raw mut raw) };
657        let path = (status == 0 && !raw.is_null()).then(|| {
658            let mut len = 0_usize;
659            // SAFETY: on success `raw` points to a NUL-terminated wide string;
660            // every offset read here is at or before its terminator.
661            while unsafe { *raw.add(len) } != 0 {
662                len = len.saturating_add(1);
663            }
664            // SAFETY: the `len` units before the terminator were just read.
665            let wide = unsafe { std::slice::from_raw_parts(raw, len) };
666            PathBuf::from(OsString::from_wide(wide))
667        });
668        // SAFETY: the buffer is owned by us after the call, whether or not it
669        // succeeded; freeing null is a no-op.
670        unsafe { CoTaskMemFree(raw.cast()) };
671        path.filter(|path| !path.as_os_str().is_empty())
672    }
673
674    pub fn home() -> Option<PathBuf> {
675        known_folder(&FOLDERID_Profile)
676    }
677    pub fn data() -> Option<PathBuf> {
678        known_folder(&FOLDERID_RoamingAppData)
679    }
680    pub fn data_local() -> Option<PathBuf> {
681        known_folder(&FOLDERID_LocalAppData)
682    }
683    pub fn config() -> Option<PathBuf> {
684        data()
685    }
686    pub fn state() -> Option<PathBuf> {
687        data_local()
688    }
689    pub fn cache() -> Option<PathBuf> {
690        data_local()
691    }
692    pub fn runtime() -> Option<PathBuf> {
693        None
694    }
695    pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
696        known_folder(match dir {
697            UserDir::Desktop => &FOLDERID_Desktop,
698            UserDir::Documents => &FOLDERID_Documents,
699            UserDir::Download => &FOLDERID_Downloads,
700            UserDir::Music => &FOLDERID_Music,
701            UserDir::Pictures => &FOLDERID_Pictures,
702            UserDir::Videos => &FOLDERID_Videos,
703            UserDir::Templates => &FOLDERID_Templates,
704            UserDir::PublicShare => &FOLDERID_Public,
705        })
706    }
707    pub fn font_dirs() -> Vec<PathBuf> {
708        super::env_dir("WINDIR")
709            .map(|windows| windows.join("Fonts"))
710            .into_iter()
711            .collect()
712    }
713}
714
715#[cfg(not(any(unix, windows)))]
716mod platform {
717    use std::path::PathBuf;
718
719    use super::{UserDir, env_dir, home};
720
721    pub fn data() -> Option<PathBuf> {
722        env_dir("APPDATA")
723    }
724    pub fn data_local() -> Option<PathBuf> {
725        env_dir("LOCALAPPDATA")
726    }
727    pub fn config() -> Option<PathBuf> {
728        data()
729    }
730    pub fn state() -> Option<PathBuf> {
731        None
732    }
733    pub fn cache() -> Option<PathBuf> {
734        env_dir("LOCALAPPDATA")
735    }
736    pub fn runtime() -> Option<PathBuf> {
737        None
738    }
739    pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
740        Some(home()?.join(dir.conventional_name()))
741    }
742    pub fn font_dirs() -> Vec<PathBuf> {
743        Vec::new()
744    }
745}
746
747/// One of the user's well-known content directories (Documents, Downloads, …).
748///
749/// On Linux and other Unix these follow `xdg-user-dirs`: `$XDG_<NAME>_DIR` when
750/// set, non-empty and absolute, else the entry in
751/// `$XDG_CONFIG_HOME/user-dirs.dirs`, which is where a localized desktop
752/// records `~/Dokumente` instead of `~/Documents`. An entry pointing at `$HOME`
753/// itself means the directory is disabled and resolves to `None`, as does a
754/// missing entry. macOS and Windows use their conventional folders below the
755/// home directory.
756#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
757pub enum UserDir {
758    Desktop,
759    Documents,
760    Download,
761    Music,
762    Pictures,
763    Videos,
764    Templates,
765    PublicShare,
766}
767
768impl UserDir {
769    #[must_use]
770    pub const fn env_var(self) -> &'static str {
771        match self {
772            Self::Desktop => "XDG_DESKTOP_DIR",
773            Self::Documents => "XDG_DOCUMENTS_DIR",
774            Self::Download => "XDG_DOWNLOAD_DIR",
775            Self::Music => "XDG_MUSIC_DIR",
776            Self::Pictures => "XDG_PICTURES_DIR",
777            Self::Videos => "XDG_VIDEOS_DIR",
778            Self::Templates => "XDG_TEMPLATES_DIR",
779            Self::PublicShare => "XDG_PUBLICSHARE_DIR",
780        }
781    }
782
783    /// The folder name the platform conventionally uses below the home
784    /// directory (English, not localized). macOS and Windows resolve to it;
785    /// on XDG platforms it is only a hint for callers that need a default.
786    #[must_use]
787    pub const fn conventional_name(self) -> &'static str {
788        match self {
789            Self::Desktop => "Desktop",
790            Self::Documents => "Documents",
791            Self::Download => "Downloads",
792            Self::Music => "Music",
793            Self::Pictures => "Pictures",
794            #[cfg(target_os = "macos")]
795            Self::Videos => "Movies",
796            #[cfg(not(target_os = "macos"))]
797            Self::Videos => "Videos",
798            Self::Templates => "Templates",
799            Self::PublicShare => "Public",
800        }
801    }
802
803    #[must_use]
804    pub fn resolve(self) -> Option<PathBuf> {
805        platform::user_dir(self)
806    }
807
808    /// The directory the environment alone names: `$XDG_<NAME>_DIR` when set,
809    /// non-empty and absolute. Reads no `user-dirs.dirs`, so a caller that
810    /// must not read files (an app's startup) can still honour the variable.
811    #[must_use]
812    pub fn from_environment(self) -> Option<PathBuf> {
813        absolute(var(self.env_var()))
814    }
815
816    #[must_use]
817    pub fn resolve_for_home(self, home: &std::path::Path) -> Option<PathBuf> {
818        let config_home = xdg::Base::Config
819            .resolve_from(var("XDG_CONFIG_HOME").as_deref(), Some(home.as_os_str()))?;
820        let file = std::fs::read(config_home.join("user-dirs.dirs")).ok();
821        self.resolve_from(var(self.env_var()).as_deref(), file.as_deref(), home)
822    }
823
824    /// Resolve from an explicit variable value and `user-dirs.dirs` contents
825    /// instead of the process environment and file system. The variable counts
826    /// only when non-empty and absolute.
827    #[must_use]
828    pub fn resolve_from(
829        self,
830        value: Option<&std::ffi::OsStr>,
831        user_dirs: Option<&[u8]>,
832        home: &std::path::Path,
833    ) -> Option<PathBuf> {
834        absolute(value.map(std::ffi::OsStr::to_os_string))
835            .or_else(|| user_dirs_entry(user_dirs?, self.env_var(), home))
836    }
837}
838
839/// The value of `key` in a `user-dirs.dirs` file.
840///
841/// The file is a shell fragment, but `xdg-user-dirs-update` writes only
842/// `KEY="$HOME/relative"` or `KEY="/absolute"`, so exactly those two forms are
843/// accepted; a value of `"$HOME/"` disables the directory. The last matching
844/// line wins, as it would when the file is sourced.
845fn user_dirs_entry(contents: &[u8], key: &str, home: &std::path::Path) -> Option<PathBuf> {
846    let mut found = None;
847    for line in contents.split(|&byte| byte == b'\n') {
848        let Some(separator) = line.iter().position(|&byte| byte == b'=') else {
849            continue;
850        };
851        let (name, value) = line.split_at(separator);
852        if trim_blank(name) != key.as_bytes() {
853            continue;
854        }
855        let value = trim_blank(value.get(1..).unwrap_or_default());
856        let Some(value) = value
857            .strip_prefix(b"\"")
858            .and_then(|value| value.strip_suffix(b"\""))
859        else {
860            continue;
861        };
862        found = if value == b"$HOME/" || value == b"$HOME" {
863            None
864        } else if let Some(relative) = value.strip_prefix(b"$HOME/") {
865            Some(home.join(path_from_bytes(shell_unescape(relative))))
866        } else if value.starts_with(b"/") {
867            Some(path_from_bytes(shell_unescape(value)))
868        } else {
869            continue;
870        };
871    }
872    found
873}
874
875fn trim_blank(bytes: &[u8]) -> &[u8] {
876    let blank = |byte: &u8| *byte == b' ' || *byte == b'\t' || *byte == b'\r';
877    let start = bytes
878        .iter()
879        .position(|byte| !blank(byte))
880        .unwrap_or(bytes.len());
881    let end = bytes
882        .iter()
883        .rposition(|byte| !blank(byte))
884        .map_or(start, |last| last.saturating_add(1));
885    bytes.get(start..end).unwrap_or_default()
886}
887
888/// Undo POSIX double-quote escaping: a backslash quotes only `$`, `` ` ``,
889/// `"`, `\` and a newline, and is kept literally before anything else.
890fn shell_unescape(escaped: &[u8]) -> Vec<u8> {
891    let mut unescaped = Vec::with_capacity(escaped.len());
892    let mut bytes = escaped.iter().copied().peekable();
893    while let Some(byte) = bytes.next() {
894        if byte == b'\\'
895            && let Some(&next) = bytes.peek()
896            && matches!(next, b'$' | b'`' | b'"' | b'\\' | b'\n')
897        {
898            unescaped.push(next);
899            bytes.next();
900        } else {
901            unescaped.push(byte);
902        }
903    }
904    unescaped
905}
906
907#[cfg(unix)]
908fn path_from_bytes(bytes: Vec<u8>) -> PathBuf {
909    use std::os::unix::ffi::OsStringExt;
910    PathBuf::from(OsString::from_vec(bytes))
911}
912
913#[cfg(not(unix))]
914fn path_from_bytes(bytes: Vec<u8>) -> PathBuf {
915    match String::from_utf8(bytes) {
916        Ok(text) => PathBuf::from(text),
917        Err(error) => PathBuf::from(String::from_utf8_lossy(error.as_bytes()).into_owned()),
918    }
919}
920
921#[must_use]
922pub fn desktop_dir() -> Option<PathBuf> {
923    UserDir::Desktop.resolve()
924}
925
926#[must_use]
927pub fn document_dir() -> Option<PathBuf> {
928    UserDir::Documents.resolve()
929}
930
931#[must_use]
932pub fn download_dir() -> Option<PathBuf> {
933    UserDir::Download.resolve()
934}
935
936#[must_use]
937pub fn audio_dir() -> Option<PathBuf> {
938    UserDir::Music.resolve()
939}
940
941#[must_use]
942pub fn picture_dir() -> Option<PathBuf> {
943    UserDir::Pictures.resolve()
944}
945
946#[must_use]
947pub fn video_dir() -> Option<PathBuf> {
948    UserDir::Videos.resolve()
949}
950
951/// One app's subdirectories of the per-user base directories, e.g.
952/// `AppDirs::new("tilo-chat").data()` is `~/.local/share/tilo-chat` on Linux.
953#[derive(Clone, Copy, Debug, PartialEq, Eq)]
954pub struct AppDirs<'a> {
955    name: &'a str,
956}
957
958impl<'a> AppDirs<'a> {
959    #[must_use]
960    pub const fn new(name: &'a str) -> Self {
961        Self { name }
962    }
963
964    #[must_use]
965    pub fn data(&self) -> Option<PathBuf> {
966        Some(data_dir()?.join(self.name))
967    }
968
969    #[must_use]
970    pub fn config(&self) -> Option<PathBuf> {
971        Some(config_dir()?.join(self.name))
972    }
973
974    #[must_use]
975    pub fn state(&self) -> Option<PathBuf> {
976        Some(state_dir()?.join(self.name))
977    }
978
979    #[must_use]
980    pub fn cache(&self) -> Option<PathBuf> {
981        Some(cache_dir()?.join(self.name))
982    }
983
984    #[must_use]
985    pub fn runtime(&self) -> Option<PathBuf> {
986        Some(runtime_dir()?.join(self.name))
987    }
988}
989
990#[cfg(test)]
991mod tests {
992    use super::xdg::Base;
993    #[cfg(unix)]
994    use super::xdg::search_path;
995    use super::*;
996    #[cfg(unix)]
997    use std::ffi::OsStr;
998
999    fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
1000        move |name| {
1001            pairs
1002                .iter()
1003                .find(|(key, _)| *key == name)
1004                .map(|(_, value)| OsString::from(value))
1005        }
1006    }
1007
1008    #[cfg(unix)]
1009    fn home_is(path: &str) -> impl FnOnce() -> Option<PathBuf> + '_ {
1010        move || Some(PathBuf::from(path))
1011    }
1012
1013    #[test]
1014    fn a_locale_names_one_language_however_it_is_spelled() {
1015        for (locale, language, tag, named) in [
1016            ("de", "de", "de", true),
1017            ("de-DE", "de", "de-DE", true),
1018            ("de_DE", "de", "de-DE", true),
1019            ("de_DE.UTF-8", "de", "de-DE", true),
1020            ("de_DE.UTF-8@euro", "de", "de-DE", true),
1021            ("de.UTF-8", "de", "de", true),
1022            (" de-DE ", "de", "de-DE", true),
1023            ("DE-de", "de", "DE-de", true),
1024            ("de_AT:en_US", "de", "de-AT", true),
1025            ("en-US", "en", "en-US", true),
1026            ("es-419", "es", "es-419", true),
1027            ("zh-Hant-TW", "zh", "zh-Hant-TW", true),
1028            ("C", "c", "C", false),
1029            ("C.UTF-8", "c", "C", false),
1030            ("POSIX", "posix", "POSIX", false),
1031            ("", "", "", false),
1032        ] {
1033            assert_eq!(language_of(locale), language, "{locale:?}");
1034            assert_eq!(locale_tag(locale), tag, "{locale:?}");
1035            assert_eq!(names_language(locale), named, "{locale:?}");
1036        }
1037    }
1038
1039    #[test]
1040    fn a_reader_is_served_by_its_own_tag_or_another_region_of_its_language() {
1041        for (locale, candidates, want) in [
1042            ("de-DE", &["en-US", "de-DE"][..], Some(1)),
1043            ("de_DE.UTF-8", &["en-US", "de-DE"], Some(1)),
1044            ("de-AT", &["en-US", "de-DE"], Some(1)),
1045            ("de", &["de-DE", "de"], Some(1)),
1046            ("en-US", &["de-DE", "en-US"], Some(1)),
1047            ("fr-FR", &["de-DE", "en-US"], None),
1048            ("fr-FR", &[], None),
1049            ("C", &["de-DE"], None),
1050            ("", &["de-DE"], None),
1051        ] {
1052            assert_eq!(
1053                matching(locale, candidates.iter().copied()),
1054                want,
1055                "{locale:?}"
1056            );
1057        }
1058    }
1059
1060    #[cfg(unix)]
1061    #[test]
1062    #[allow(
1063        clippy::too_many_lines,
1064        reason = "each phase keeps one former test's body verbatim"
1065    )]
1066    fn base_directories_follow_absolute_variables_or_home_defaults() {
1067        {
1068            let vars = [
1069                ("XDG_DATA_HOME", "/data"),
1070                ("XDG_CONFIG_HOME", "/config"),
1071                ("XDG_STATE_HOME", "/state"),
1072                ("XDG_CACHE_HOME", "/cache"),
1073                ("XDG_RUNTIME_DIR", "/run/user/1000"),
1074            ];
1075            let var = env(&vars);
1076            for (base, expected) in [
1077                (Base::Data, "/data"),
1078                (Base::Config, "/config"),
1079                (Base::State, "/state"),
1080                (Base::Cache, "/cache"),
1081                (Base::Runtime, "/run/user/1000"),
1082            ] {
1083                assert_eq!(
1084                    base.resolve(&var, home_is("/home/u")),
1085                    Some(PathBuf::from(expected))
1086                );
1087            }
1088        }
1089        {
1090            let var = env(&[]);
1091            for (base, expected) in [
1092                (Base::Data, Some("/home/u/.local/share")),
1093                (Base::Config, Some("/home/u/.config")),
1094                (Base::State, Some("/home/u/.local/state")),
1095                (Base::Cache, Some("/home/u/.cache")),
1096                (Base::Runtime, None),
1097            ] {
1098                assert_eq!(
1099                    base.resolve(&var, home_is("/home/u")),
1100                    expected.map(PathBuf::from),
1101                    "{base:?}"
1102                );
1103            }
1104        }
1105        {
1106            for value in ["relative/data", "", "./data", "~/data"] {
1107                let vars = [("XDG_DATA_HOME", value), ("XDG_RUNTIME_DIR", value)];
1108                let var = env(&vars);
1109                assert_eq!(
1110                    Base::Data.resolve(&var, home_is("/home/u")),
1111                    Some(PathBuf::from("/home/u/.local/share")),
1112                    "{value:?}"
1113                );
1114                assert_eq!(
1115                    Base::Runtime.resolve(&var, home_is("/home/u")),
1116                    None,
1117                    "{value:?}"
1118                );
1119            }
1120        }
1121        {
1122            let home = Some(OsStr::new("/home/u"));
1123            assert_eq!(
1124                Base::State.resolve_from(Some(OsStr::new("/state")), home),
1125                Some(PathBuf::from("/state"))
1126            );
1127            for invalid in [None, Some(OsStr::new("")), Some(OsStr::new("rel"))] {
1128                assert_eq!(
1129                    Base::State.resolve_from(invalid, home),
1130                    Some(PathBuf::from("/home/u/.local/state"))
1131                );
1132            }
1133            assert_eq!(Base::State.resolve_from(None, Some(OsStr::new(""))), None);
1134            assert_eq!(Base::Runtime.resolve_from(None, home), None);
1135            assert_eq!(Base::Config.env_var(), "XDG_CONFIG_HOME");
1136        }
1137        {
1138            let account = || Some(PathBuf::from("/var/home/account"));
1139            assert_eq!(
1140                home_from(&env(&[("HOME", "/home/u")]), account),
1141                Some(PathBuf::from("/home/u"))
1142            );
1143            assert_eq!(home_from(&env(&[("HOME", "")]), account), None);
1144            assert_eq!(
1145                home_from(&env(&[]), account),
1146                Some(PathBuf::from("/var/home/account"))
1147            );
1148            assert_eq!(home_from(&env(&[]), || Some(PathBuf::new())), None);
1149        }
1150        {
1151            let defaults = ["/usr/local/share", "/usr/share"];
1152            let expected_defaults: Vec<PathBuf> = defaults.iter().map(PathBuf::from).collect();
1153            assert_eq!(search_path(None, &defaults), expected_defaults);
1154            assert_eq!(
1155                search_path(Some(OsStr::new("")), &defaults),
1156                expected_defaults
1157            );
1158            assert_eq!(
1159                search_path(Some(OsStr::new("relative:also/relative")), &defaults),
1160                expected_defaults
1161            );
1162            assert_eq!(
1163                search_path(
1164                    Some(OsStr::new("/opt/share::relative:/usr/share")),
1165                    &defaults
1166                ),
1167                vec![PathBuf::from("/opt/share"), PathBuf::from("/usr/share")]
1168            );
1169        }
1170    }
1171
1172    #[test]
1173    fn app_and_user_dir_names_follow_the_spec_without_a_home() {
1174        {
1175            assert_eq!(Base::Config.resolve(&env(&[]), || None), None);
1176            #[cfg(unix)]
1177            assert_eq!(
1178                Base::Config.resolve(&env(&[("XDG_CONFIG_HOME", "/cfg")]), || None),
1179                Some(PathBuf::from("/cfg"))
1180            );
1181        }
1182        {
1183            assert_eq!(UserDir::Download.env_var(), "XDG_DOWNLOAD_DIR");
1184            assert_eq!(UserDir::PublicShare.env_var(), "XDG_PUBLICSHARE_DIR");
1185            assert_eq!(UserDir::Download.conventional_name(), "Downloads");
1186        }
1187        {
1188            let app = AppDirs::new("tilo-example");
1189            for (joined, base) in [
1190                (app.data(), data_dir()),
1191                (app.config(), config_dir()),
1192                (app.state(), state_dir()),
1193                (app.cache(), cache_dir()),
1194                (app.runtime(), runtime_dir()),
1195            ] {
1196                assert_eq!(joined, base.map(|base| base.join("tilo-example")));
1197            }
1198        }
1199    }
1200
1201    #[cfg(unix)]
1202    const USER_DIRS: &[u8] = b"# This file is written by xdg-user-dirs-update\n\
1203XDG_DESKTOP_DIR=\"$HOME/Schreibtisch\"\n\
1204XDG_DOWNLOAD_DIR=\"$HOME/Downloads\"\n\
1205  XDG_DOCUMENTS_DIR = \"$HOME/Dokumente\"  \n\
1206XDG_MUSIC_DIR=\"/srv/music\"\n\
1207XDG_PICTURES_DIR=\"$HOME/\"\n\
1208XDG_VIDEOS_DIR=$HOME/Videos\n\
1209XDG_TEMPLATES_DIR=\"relative/templates\"\n\
1210XDG_PUBLICSHARE_DIR=\"$HOME/My \\\"Public\\\" \\$hare\"\n";
1211
1212    #[cfg(unix)]
1213    #[test]
1214    fn user_dirs_files_resolve_below_home_and_yield_to_variables() {
1215        {
1216            let home = std::path::Path::new("/home/u");
1217            let resolve = |dir: UserDir| dir.resolve_from(None, Some(USER_DIRS), home);
1218            assert_eq!(
1219                resolve(UserDir::Desktop),
1220                Some(PathBuf::from("/home/u/Schreibtisch"))
1221            );
1222            assert_eq!(
1223                resolve(UserDir::Download),
1224                Some(PathBuf::from("/home/u/Downloads"))
1225            );
1226            assert_eq!(
1227                resolve(UserDir::Documents),
1228                Some(PathBuf::from("/home/u/Dokumente")),
1229                "blanks around the key and value are not part of either"
1230            );
1231            assert_eq!(resolve(UserDir::Music), Some(PathBuf::from("/srv/music")));
1232            assert_eq!(
1233                resolve(UserDir::PublicShare),
1234                Some(PathBuf::from("/home/u/My \"Public\" $hare")),
1235                "double-quote escapes are undone"
1236            );
1237        }
1238        {
1239            let home = std::path::Path::new("/home/u");
1240            for dir in [UserDir::Pictures, UserDir::Videos, UserDir::Templates] {
1241                assert_eq!(
1242                    dir.resolve_from(None, Some(USER_DIRS), home),
1243                    None,
1244                    "{dir:?}"
1245                );
1246            }
1247            assert_eq!(UserDir::Desktop.resolve_from(None, None, home), None);
1248            assert_eq!(UserDir::Desktop.resolve_from(None, Some(b""), home), None);
1249        }
1250        {
1251            let home = std::path::Path::new("/home/u");
1252            assert_eq!(
1253                UserDir::Download.resolve_from(Some(OsStr::new("/data/dl")), Some(USER_DIRS), home),
1254                Some(PathBuf::from("/data/dl"))
1255            );
1256            for ignored in ["", "relative/dl"] {
1257                assert_eq!(
1258                    UserDir::Download.resolve_from(
1259                        Some(OsStr::new(ignored)),
1260                        Some(USER_DIRS),
1261                        home
1262                    ),
1263                    Some(PathBuf::from("/home/u/Downloads")),
1264                    "{ignored:?}"
1265                );
1266            }
1267        }
1268    }
1269
1270    #[cfg(unix)]
1271    #[test]
1272    fn the_last_matching_line_wins() {
1273        let home = std::path::Path::new("/home/u");
1274        let file = b"XDG_DESKTOP_DIR=\"$HOME/One\"\nXDG_DESKTOP_DIR=\"$HOME/Two\"\n";
1275        assert_eq!(
1276            UserDir::Desktop.resolve_from(None, Some(file), home),
1277            Some(PathBuf::from("/home/u/Two"))
1278        );
1279    }
1280
1281    #[cfg(unix)]
1282    #[test]
1283    fn macos_keeps_data_config_and_state_in_application_support() {
1284        let tmpdir = [("TMPDIR", "/var/folders/ab/xyz/T/")];
1285        let var = env(&tmpdir);
1286        for (base, expected) in [
1287            (Base::Data, "/Users/u/Library/Application Support"),
1288            (Base::Config, "/Users/u/Library/Application Support"),
1289            (Base::State, "/Users/u/Library/Application Support"),
1290            (Base::Cache, "/Users/u/Library/Caches"),
1291            (Base::Runtime, "/var/folders/ab/xyz/T/"),
1292        ] {
1293            assert_eq!(
1294                macos::base(base, &var, home_is("/Users/u")),
1295                Some(PathBuf::from(expected)),
1296                "{base:?}"
1297            );
1298        }
1299    }
1300
1301    #[cfg(unix)]
1302    #[test]
1303    fn macos_runtime_needs_an_absolute_tmpdir_and_ignores_xdg() {
1304        for value in ["", "tmp", "./T"] {
1305            let vars = [("TMPDIR", value), ("XDG_RUNTIME_DIR", "/run/user/501")];
1306            assert_eq!(
1307                macos::base(Base::Runtime, &env(&vars), home_is("/Users/u")),
1308                None,
1309                "{value:?}"
1310            );
1311        }
1312        assert_eq!(
1313            macos::base(Base::Data, &env(&[("XDG_DATA_HOME", "/data")]), || None),
1314            None,
1315            "without a home only the runtime directory can resolve"
1316        );
1317    }
1318
1319    #[test]
1320    fn a_workspace_tree_is_one_component_under_the_files_root() {
1321        let files = std::path::Path::new("/var/workspace");
1322        let id = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
1323        assert_eq!(
1324            workspace_tree(files, id),
1325            Some(files.join(".workspaces").join(id))
1326        );
1327        for bad in [
1328            "",
1329            ".",
1330            "..",
1331            "a/b",
1332            "../x",
1333            "a.b",
1334            "a\0b",
1335            &"x".repeat(129),
1336        ] {
1337            assert_eq!(workspace_tree(files, bad), None, "{bad:?}");
1338        }
1339    }
1340}