use std::ffi::OsString;
use std::path::PathBuf;
mod app;
mod caps;
pub mod desktop_service;
mod location;
pub mod login;
pub mod session;
pub use app::{AppPaths, DEFAULT_PROFILE, default_profile, set_default_profile};
pub use caps::{Availability, Feature, Unsupported, availability, available};
pub use location::{InvalidVPath, Location, VPath, VirtualRoot};
pub const WORKSPACE_MOUNT: &str = "/var/workspace";
pub const TRUSTED_IDENTITIES: &str = "/run/tilo/identity-projection/trusted-identities.json";
#[must_use]
pub fn runtime_publishers() -> PathBuf {
const FILE: &str = "runtime-bundle-trusted-publishers.txt";
#[cfg(target_os = "macos")]
if let Some(contents) = std::env::current_exe()
.and_then(std::fs::canonicalize)
.ok()
.and_then(|exe| Some(exe.parent()?.parent()?.to_path_buf()))
.filter(|contents| contents.join("Info.plist").is_file())
{
return contents.join("Resources").join(FILE);
}
PathBuf::from("/etc/tilo").join(FILE)
}
pub const WORKSPACE_TREES_DIR: &str = ".workspaces";
#[must_use]
pub fn workspace_tree(files: &std::path::Path, id: &str) -> Option<PathBuf> {
is_workspace_tree_id(id).then(|| files.join(WORKSPACE_TREES_DIR).join(id))
}
#[must_use]
pub fn is_workspace_tree_id(id: &str) -> bool {
(1..=128).contains(&id.len())
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
#[must_use]
pub fn workspace_root() -> Option<PathBuf> {
let location = AppPaths::for_app("workspace").workspace_root().ok()?;
location
.native_path()
.ok()
.map(std::path::Path::to_path_buf)
}
#[must_use]
pub fn language_packs_dir() -> Option<PathBuf> {
xdg::data_home().map(|data| data.join("tilo").join("language-packs"))
}
#[must_use]
pub fn language_of(tag: &str) -> String {
tag.trim()
.split(['-', '_', '.', '@'])
.next()
.unwrap_or_default()
.to_ascii_lowercase()
}
#[must_use]
pub fn locale_tag(locale: &str) -> String {
locale
.split(':')
.next()
.unwrap_or_default()
.split(['.', '@'])
.next()
.unwrap_or_default()
.trim()
.replace('_', "-")
}
#[must_use]
pub fn names_language(tag: &str) -> bool {
!matches!(language_of(tag).as_str(), "" | "c" | "posix")
}
#[must_use]
pub fn matching<'a>(
locale: &str,
mut candidates: impl Iterator<Item = &'a str> + Clone,
) -> Option<usize> {
if !names_language(locale) {
return None;
}
let tag = locale_tag(locale);
let language = language_of(locale);
let mut exact = candidates.clone();
exact
.position(|candidate| locale_tag(candidate).eq_ignore_ascii_case(&tag))
.or_else(|| candidates.position(|candidate| language_of(candidate) == language))
}
#[must_use]
pub fn home() -> Option<PathBuf> {
#[cfg(windows)]
{
platform::home()
}
#[cfg(not(windows))]
{
home_from(&|name| var(name), std::env::home_dir)
}
}
#[cfg(not(windows))]
fn home_from(
var: &dyn Fn(&str) -> Option<OsString>,
account_home: impl FnOnce() -> Option<PathBuf>,
) -> Option<PathBuf> {
#[cfg(unix)]
match var("HOME") {
Some(home) if home.is_empty() => None,
Some(home) => Some(PathBuf::from(home)),
None => account_home().filter(|home| !home.as_os_str().is_empty()),
}
#[cfg(not(unix))]
{
let _ = var;
account_home().filter(|home| !home.as_os_str().is_empty())
}
}
#[must_use]
pub fn env_dir(name: &str) -> Option<PathBuf> {
absolute(var(name))
}
thread_local! {
static PROFILE_ROOT: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
}
#[must_use = "the scope ends when the guard is dropped"]
pub struct ProfileScope {
earlier: Option<PathBuf>,
}
impl Drop for ProfileScope {
fn drop(&mut self) {
PROFILE_ROOT.with(|root| *root.borrow_mut() = self.earlier.take());
}
}
pub fn scope_profile(root: impl Into<PathBuf>) -> ProfileScope {
let earlier = PROFILE_ROOT.with(|scoped| scoped.borrow_mut().replace(root.into()));
ProfileScope { earlier }
}
pub fn unscoped<R>(work: impl FnOnce() -> R) -> R {
let _scope = ProfileScope {
earlier: PROFILE_ROOT.with(|root| root.borrow_mut().take()),
};
work()
}
#[must_use]
pub fn scoped_profile() -> Option<PathBuf> {
PROFILE_ROOT.with(|root| root.borrow().clone())
}
#[must_use]
pub fn var(name: &str) -> Option<OsString> {
let Some(root) = scoped_profile() else {
return std::env::var_os(name);
};
let below = match name {
"HOME" => "",
"XDG_DATA_HOME" => ".local/share",
"XDG_CONFIG_HOME" => ".config",
"XDG_STATE_HOME" => ".local/state",
"XDG_CACHE_HOME" => ".cache",
"XDG_RUNTIME_DIR" => "run",
"TMPDIR" => "tmp",
name if name.starts_with("TILO_WORKSPACE") => return None,
name if name.starts_with("XDG_") && name.ends_with("_DIR") => return None,
_ => return std::env::var_os(name),
};
Some(root.join(below).into_os_string())
}
fn absolute(value: Option<OsString>) -> Option<PathBuf> {
value.map(PathBuf::from).filter(|path| path.is_absolute())
}
pub mod xdg {
use std::ffi::{OsStr, OsString};
use std::path::PathBuf;
use super::{absolute, home};
#[must_use]
pub fn data_home() -> Option<PathBuf> {
Base::Data.resolve(&env, home)
}
#[must_use]
pub fn config_home() -> Option<PathBuf> {
Base::Config.resolve(&env, home)
}
#[must_use]
pub fn state_home() -> Option<PathBuf> {
Base::State.resolve(&env, home)
}
#[must_use]
pub fn cache_home() -> Option<PathBuf> {
Base::Cache.resolve(&env, home)
}
#[must_use]
pub fn runtime_dir() -> Option<PathBuf> {
Base::Runtime.resolve(&env, home)
}
#[cfg(any(unix, windows))]
#[must_use]
pub fn runtime_dir_or_default() -> PathBuf {
runtime_dir().unwrap_or_else(|| {
#[cfg(any(target_os = "macos", windows))]
{
std::env::temp_dir()
}
#[cfg(all(unix, not(target_os = "macos")))]
{
PathBuf::from(format!("/run/user/{}", rustix::process::geteuid().as_raw()))
}
})
}
#[cfg(any(unix, windows))]
#[must_use]
pub fn services_dir() -> PathBuf {
runtime_dir_or_default().join("tilo/services")
}
#[cfg(any(unix, windows))]
#[must_use]
pub fn service_socket(name: &str) -> PathBuf {
services_dir().join(format!("{name}.sock"))
}
#[must_use]
pub fn data_dirs() -> Vec<PathBuf> {
search_path(
env("XDG_DATA_DIRS").as_deref(),
&["/usr/local/share", "/usr/share"],
)
}
#[must_use]
pub fn config_dirs() -> Vec<PathBuf> {
search_path(env("XDG_CONFIG_DIRS").as_deref(), &["/etc/xdg"])
}
fn env(name: &str) -> Option<OsString> {
super::var(name)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Base {
Data,
Config,
State,
Cache,
Runtime,
}
impl Base {
#[must_use]
pub const fn env_var(self) -> &'static str {
match self {
Self::Data => "XDG_DATA_HOME",
Self::Config => "XDG_CONFIG_HOME",
Self::State => "XDG_STATE_HOME",
Self::Cache => "XDG_CACHE_HOME",
Self::Runtime => "XDG_RUNTIME_DIR",
}
}
const fn home_default(self) -> Option<&'static str> {
match self {
Self::Data => Some(".local/share"),
Self::Config => Some(".config"),
Self::State => Some(".local/state"),
Self::Cache => Some(".cache"),
Self::Runtime => None,
}
}
#[must_use]
pub fn resolve_from(self, value: Option<&OsStr>, home: Option<&OsStr>) -> Option<PathBuf> {
self.resolve(&|_| value.map(OsStr::to_os_string), || {
home.filter(|home| !home.is_empty()).map(PathBuf::from)
})
}
pub(crate) fn resolve(
self,
var: &dyn Fn(&str) -> Option<OsString>,
home: impl FnOnce() -> Option<PathBuf>,
) -> Option<PathBuf> {
absolute(var(self.env_var())).or_else(|| {
let default = self.home_default()?;
Some(home()?.join(default))
})
}
}
pub(crate) fn search_path(value: Option<&OsStr>, default: &[&str]) -> Vec<PathBuf> {
let listed: Vec<PathBuf> = value
.map(|value| {
std::env::split_paths(value)
.filter(|path| path.is_absolute())
.collect()
})
.unwrap_or_default();
if listed.is_empty() {
default.iter().map(PathBuf::from).collect()
} else {
listed
}
}
}
#[must_use]
pub fn data_dir() -> Option<PathBuf> {
platform::data()
}
#[must_use]
pub fn data_local_dir() -> Option<PathBuf> {
platform::data_local()
}
#[must_use]
pub fn config_dir() -> Option<PathBuf> {
platform::config()
}
#[must_use]
pub fn state_dir() -> Option<PathBuf> {
platform::state()
}
#[must_use]
pub fn profile_root() -> Option<PathBuf> {
Some(xdg::config_home()?.join("tilo"))
}
#[must_use]
pub fn cache_dir() -> Option<PathBuf> {
platform::cache()
}
#[must_use]
pub fn runtime_dir() -> Option<PathBuf> {
platform::runtime()
}
#[must_use]
pub fn temp_dir() -> Option<PathBuf> {
(available(Feature::NativePaths)).then(std::env::temp_dir)
}
#[must_use]
pub fn memory_temp_dir() -> Option<PathBuf> {
if !cfg!(target_os = "linux") {
return None;
}
Some(PathBuf::from("/dev/shm")).filter(|directory| directory.is_dir())
}
#[must_use]
pub fn system_font_dirs() -> Vec<PathBuf> {
platform::font_dirs()
}
#[cfg(all(unix, not(target_os = "macos")))]
mod platform {
use std::path::PathBuf;
use super::{UserDir, home, xdg};
pub fn data() -> Option<PathBuf> {
xdg::data_home()
}
pub fn data_local() -> Option<PathBuf> {
xdg::data_home()
}
pub fn config() -> Option<PathBuf> {
xdg::config_home()
}
pub fn state() -> Option<PathBuf> {
xdg::state_home()
}
pub fn cache() -> Option<PathBuf> {
xdg::cache_home()
}
pub fn runtime() -> Option<PathBuf> {
xdg::runtime_dir()
}
pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
dir.resolve_for_home(&home()?)
}
pub fn font_dirs() -> Vec<PathBuf> {
[
"/usr/share/fonts",
"/usr/local/share/fonts",
"/usr/share/X11/fonts/Type1",
"/usr/share/X11/fonts/TTF",
]
.into_iter()
.map(PathBuf::from)
.collect()
}
}
#[cfg(target_os = "macos")]
mod platform {
use std::path::PathBuf;
use super::xdg::Base;
use super::{UserDir, home, macos};
fn base(base: Base) -> Option<PathBuf> {
macos::base(base, &|name| crate::var(name), home)
}
pub fn data() -> Option<PathBuf> {
base(Base::Data)
}
pub fn data_local() -> Option<PathBuf> {
data()
}
pub fn config() -> Option<PathBuf> {
base(Base::Config)
}
pub fn state() -> Option<PathBuf> {
base(Base::State)
}
pub fn cache() -> Option<PathBuf> {
base(Base::Cache)
}
pub fn runtime() -> Option<PathBuf> {
base(Base::Runtime)
}
pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
Some(macos::user_dir(dir, &home()?))
}
pub fn font_dirs() -> Vec<PathBuf> {
let mut dirs = vec![
PathBuf::from("/System/Library/Fonts"),
PathBuf::from("/Library/Fonts"),
];
dirs.extend(home().map(|home| home.join("Library/Fonts")));
dirs
}
}
#[cfg(any(target_os = "macos", all(test, unix)))]
mod macos {
use std::ffi::OsString;
use std::path::PathBuf;
use super::absolute;
use super::xdg::Base;
pub(crate) fn base(
base: Base,
var: &dyn Fn(&str) -> Option<OsString>,
home: impl FnOnce() -> Option<PathBuf>,
) -> Option<PathBuf> {
match base {
Base::Data | Base::Config | Base::State => {
Some(home()?.join("Library/Application Support"))
}
Base::Cache => Some(home()?.join("Library/Caches")),
Base::Runtime => absolute(var("TMPDIR")),
}
}
#[cfg(target_os = "macos")]
pub(crate) fn user_dir(dir: super::UserDir, home: &std::path::Path) -> PathBuf {
home.join(match dir {
super::UserDir::Videos => "Movies",
other => other.conventional_name(),
})
}
}
#[cfg(windows)]
mod platform {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::path::PathBuf;
use windows_sys::Win32::System::Com::CoTaskMemFree;
use windows_sys::Win32::UI::Shell::{
FOLDERID_Desktop, FOLDERID_Documents, FOLDERID_Downloads, FOLDERID_LocalAppData,
FOLDERID_Music, FOLDERID_Pictures, FOLDERID_Profile, FOLDERID_Public,
FOLDERID_RoamingAppData, FOLDERID_Templates, FOLDERID_Videos, SHGetKnownFolderPath,
};
use windows_sys::core::{GUID, PWSTR};
use super::UserDir;
fn known_folder(id: &GUID) -> Option<PathBuf> {
let mut raw: PWSTR = std::ptr::null_mut();
let status = unsafe { SHGetKnownFolderPath(id, 0, std::ptr::null_mut(), &raw mut raw) };
let path = (status == 0 && !raw.is_null()).then(|| {
let mut len = 0_usize;
while unsafe { *raw.add(len) } != 0 {
len = len.saturating_add(1);
}
let wide = unsafe { std::slice::from_raw_parts(raw, len) };
PathBuf::from(OsString::from_wide(wide))
});
unsafe { CoTaskMemFree(raw.cast()) };
path.filter(|path| !path.as_os_str().is_empty())
}
pub fn home() -> Option<PathBuf> {
known_folder(&FOLDERID_Profile)
}
pub fn data() -> Option<PathBuf> {
known_folder(&FOLDERID_RoamingAppData)
}
pub fn data_local() -> Option<PathBuf> {
known_folder(&FOLDERID_LocalAppData)
}
pub fn config() -> Option<PathBuf> {
data()
}
pub fn state() -> Option<PathBuf> {
data_local()
}
pub fn cache() -> Option<PathBuf> {
data_local()
}
pub fn runtime() -> Option<PathBuf> {
None
}
pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
known_folder(match dir {
UserDir::Desktop => &FOLDERID_Desktop,
UserDir::Documents => &FOLDERID_Documents,
UserDir::Download => &FOLDERID_Downloads,
UserDir::Music => &FOLDERID_Music,
UserDir::Pictures => &FOLDERID_Pictures,
UserDir::Videos => &FOLDERID_Videos,
UserDir::Templates => &FOLDERID_Templates,
UserDir::PublicShare => &FOLDERID_Public,
})
}
pub fn font_dirs() -> Vec<PathBuf> {
super::env_dir("WINDIR")
.map(|windows| windows.join("Fonts"))
.into_iter()
.collect()
}
}
#[cfg(not(any(unix, windows)))]
mod platform {
use std::path::PathBuf;
use super::{UserDir, env_dir, home};
pub fn data() -> Option<PathBuf> {
env_dir("APPDATA")
}
pub fn data_local() -> Option<PathBuf> {
env_dir("LOCALAPPDATA")
}
pub fn config() -> Option<PathBuf> {
data()
}
pub fn state() -> Option<PathBuf> {
None
}
pub fn cache() -> Option<PathBuf> {
env_dir("LOCALAPPDATA")
}
pub fn runtime() -> Option<PathBuf> {
None
}
pub fn user_dir(dir: UserDir) -> Option<PathBuf> {
Some(home()?.join(dir.conventional_name()))
}
pub fn font_dirs() -> Vec<PathBuf> {
Vec::new()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum UserDir {
Desktop,
Documents,
Download,
Music,
Pictures,
Videos,
Templates,
PublicShare,
}
impl UserDir {
#[must_use]
pub const fn env_var(self) -> &'static str {
match self {
Self::Desktop => "XDG_DESKTOP_DIR",
Self::Documents => "XDG_DOCUMENTS_DIR",
Self::Download => "XDG_DOWNLOAD_DIR",
Self::Music => "XDG_MUSIC_DIR",
Self::Pictures => "XDG_PICTURES_DIR",
Self::Videos => "XDG_VIDEOS_DIR",
Self::Templates => "XDG_TEMPLATES_DIR",
Self::PublicShare => "XDG_PUBLICSHARE_DIR",
}
}
#[must_use]
pub const fn conventional_name(self) -> &'static str {
match self {
Self::Desktop => "Desktop",
Self::Documents => "Documents",
Self::Download => "Downloads",
Self::Music => "Music",
Self::Pictures => "Pictures",
#[cfg(target_os = "macos")]
Self::Videos => "Movies",
#[cfg(not(target_os = "macos"))]
Self::Videos => "Videos",
Self::Templates => "Templates",
Self::PublicShare => "Public",
}
}
#[must_use]
pub fn resolve(self) -> Option<PathBuf> {
platform::user_dir(self)
}
#[must_use]
pub fn from_environment(self) -> Option<PathBuf> {
absolute(var(self.env_var()))
}
#[must_use]
pub fn resolve_for_home(self, home: &std::path::Path) -> Option<PathBuf> {
let config_home = xdg::Base::Config
.resolve_from(var("XDG_CONFIG_HOME").as_deref(), Some(home.as_os_str()))?;
let file = std::fs::read(config_home.join("user-dirs.dirs")).ok();
self.resolve_from(var(self.env_var()).as_deref(), file.as_deref(), home)
}
#[must_use]
pub fn resolve_from(
self,
value: Option<&std::ffi::OsStr>,
user_dirs: Option<&[u8]>,
home: &std::path::Path,
) -> Option<PathBuf> {
absolute(value.map(std::ffi::OsStr::to_os_string))
.or_else(|| user_dirs_entry(user_dirs?, self.env_var(), home))
}
}
fn user_dirs_entry(contents: &[u8], key: &str, home: &std::path::Path) -> Option<PathBuf> {
let mut found = None;
for line in contents.split(|&byte| byte == b'\n') {
let Some(separator) = line.iter().position(|&byte| byte == b'=') else {
continue;
};
let (name, value) = line.split_at(separator);
if trim_blank(name) != key.as_bytes() {
continue;
}
let value = trim_blank(value.get(1..).unwrap_or_default());
let Some(value) = value
.strip_prefix(b"\"")
.and_then(|value| value.strip_suffix(b"\""))
else {
continue;
};
found = if value == b"$HOME/" || value == b"$HOME" {
None
} else if let Some(relative) = value.strip_prefix(b"$HOME/") {
Some(home.join(path_from_bytes(shell_unescape(relative))))
} else if value.starts_with(b"/") {
Some(path_from_bytes(shell_unescape(value)))
} else {
continue;
};
}
found
}
fn trim_blank(bytes: &[u8]) -> &[u8] {
let blank = |byte: &u8| *byte == b' ' || *byte == b'\t' || *byte == b'\r';
let start = bytes
.iter()
.position(|byte| !blank(byte))
.unwrap_or(bytes.len());
let end = bytes
.iter()
.rposition(|byte| !blank(byte))
.map_or(start, |last| last.saturating_add(1));
bytes.get(start..end).unwrap_or_default()
}
fn shell_unescape(escaped: &[u8]) -> Vec<u8> {
let mut unescaped = Vec::with_capacity(escaped.len());
let mut bytes = escaped.iter().copied().peekable();
while let Some(byte) = bytes.next() {
if byte == b'\\'
&& let Some(&next) = bytes.peek()
&& matches!(next, b'$' | b'`' | b'"' | b'\\' | b'\n')
{
unescaped.push(next);
bytes.next();
} else {
unescaped.push(byte);
}
}
unescaped
}
#[cfg(unix)]
fn path_from_bytes(bytes: Vec<u8>) -> PathBuf {
use std::os::unix::ffi::OsStringExt;
PathBuf::from(OsString::from_vec(bytes))
}
#[cfg(not(unix))]
fn path_from_bytes(bytes: Vec<u8>) -> PathBuf {
match String::from_utf8(bytes) {
Ok(text) => PathBuf::from(text),
Err(error) => PathBuf::from(String::from_utf8_lossy(error.as_bytes()).into_owned()),
}
}
#[must_use]
pub fn desktop_dir() -> Option<PathBuf> {
UserDir::Desktop.resolve()
}
#[must_use]
pub fn document_dir() -> Option<PathBuf> {
UserDir::Documents.resolve()
}
#[must_use]
pub fn download_dir() -> Option<PathBuf> {
UserDir::Download.resolve()
}
#[must_use]
pub fn audio_dir() -> Option<PathBuf> {
UserDir::Music.resolve()
}
#[must_use]
pub fn picture_dir() -> Option<PathBuf> {
UserDir::Pictures.resolve()
}
#[must_use]
pub fn video_dir() -> Option<PathBuf> {
UserDir::Videos.resolve()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AppDirs<'a> {
name: &'a str,
}
impl<'a> AppDirs<'a> {
#[must_use]
pub const fn new(name: &'a str) -> Self {
Self { name }
}
#[must_use]
pub fn data(&self) -> Option<PathBuf> {
Some(data_dir()?.join(self.name))
}
#[must_use]
pub fn config(&self) -> Option<PathBuf> {
Some(config_dir()?.join(self.name))
}
#[must_use]
pub fn state(&self) -> Option<PathBuf> {
Some(state_dir()?.join(self.name))
}
#[must_use]
pub fn cache(&self) -> Option<PathBuf> {
Some(cache_dir()?.join(self.name))
}
#[must_use]
pub fn runtime(&self) -> Option<PathBuf> {
Some(runtime_dir()?.join(self.name))
}
}
#[cfg(test)]
mod tests {
use super::xdg::Base;
#[cfg(unix)]
use super::xdg::search_path;
use super::*;
#[cfg(unix)]
use std::ffi::OsStr;
fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
move |name| {
pairs
.iter()
.find(|(key, _)| *key == name)
.map(|(_, value)| OsString::from(value))
}
}
#[cfg(unix)]
fn home_is(path: &str) -> impl FnOnce() -> Option<PathBuf> + '_ {
move || Some(PathBuf::from(path))
}
#[test]
fn a_locale_names_one_language_however_it_is_spelled() {
for (locale, language, tag, named) in [
("de", "de", "de", true),
("de-DE", "de", "de-DE", true),
("de_DE", "de", "de-DE", true),
("de_DE.UTF-8", "de", "de-DE", true),
("de_DE.UTF-8@euro", "de", "de-DE", true),
("de.UTF-8", "de", "de", true),
(" de-DE ", "de", "de-DE", true),
("DE-de", "de", "DE-de", true),
("de_AT:en_US", "de", "de-AT", true),
("en-US", "en", "en-US", true),
("es-419", "es", "es-419", true),
("zh-Hant-TW", "zh", "zh-Hant-TW", true),
("C", "c", "C", false),
("C.UTF-8", "c", "C", false),
("POSIX", "posix", "POSIX", false),
("", "", "", false),
] {
assert_eq!(language_of(locale), language, "{locale:?}");
assert_eq!(locale_tag(locale), tag, "{locale:?}");
assert_eq!(names_language(locale), named, "{locale:?}");
}
}
#[test]
fn a_reader_is_served_by_its_own_tag_or_another_region_of_its_language() {
for (locale, candidates, want) in [
("de-DE", &["en-US", "de-DE"][..], Some(1)),
("de_DE.UTF-8", &["en-US", "de-DE"], Some(1)),
("de-AT", &["en-US", "de-DE"], Some(1)),
("de", &["de-DE", "de"], Some(1)),
("en-US", &["de-DE", "en-US"], Some(1)),
("fr-FR", &["de-DE", "en-US"], None),
("fr-FR", &[], None),
("C", &["de-DE"], None),
("", &["de-DE"], None),
] {
assert_eq!(
matching(locale, candidates.iter().copied()),
want,
"{locale:?}"
);
}
}
#[cfg(unix)]
#[test]
#[allow(
clippy::too_many_lines,
reason = "each phase keeps one former test's body verbatim"
)]
fn base_directories_follow_absolute_variables_or_home_defaults() {
{
let vars = [
("XDG_DATA_HOME", "/data"),
("XDG_CONFIG_HOME", "/config"),
("XDG_STATE_HOME", "/state"),
("XDG_CACHE_HOME", "/cache"),
("XDG_RUNTIME_DIR", "/run/user/1000"),
];
let var = env(&vars);
for (base, expected) in [
(Base::Data, "/data"),
(Base::Config, "/config"),
(Base::State, "/state"),
(Base::Cache, "/cache"),
(Base::Runtime, "/run/user/1000"),
] {
assert_eq!(
base.resolve(&var, home_is("/home/u")),
Some(PathBuf::from(expected))
);
}
}
{
let var = env(&[]);
for (base, expected) in [
(Base::Data, Some("/home/u/.local/share")),
(Base::Config, Some("/home/u/.config")),
(Base::State, Some("/home/u/.local/state")),
(Base::Cache, Some("/home/u/.cache")),
(Base::Runtime, None),
] {
assert_eq!(
base.resolve(&var, home_is("/home/u")),
expected.map(PathBuf::from),
"{base:?}"
);
}
}
{
for value in ["relative/data", "", "./data", "~/data"] {
let vars = [("XDG_DATA_HOME", value), ("XDG_RUNTIME_DIR", value)];
let var = env(&vars);
assert_eq!(
Base::Data.resolve(&var, home_is("/home/u")),
Some(PathBuf::from("/home/u/.local/share")),
"{value:?}"
);
assert_eq!(
Base::Runtime.resolve(&var, home_is("/home/u")),
None,
"{value:?}"
);
}
}
{
let home = Some(OsStr::new("/home/u"));
assert_eq!(
Base::State.resolve_from(Some(OsStr::new("/state")), home),
Some(PathBuf::from("/state"))
);
for invalid in [None, Some(OsStr::new("")), Some(OsStr::new("rel"))] {
assert_eq!(
Base::State.resolve_from(invalid, home),
Some(PathBuf::from("/home/u/.local/state"))
);
}
assert_eq!(Base::State.resolve_from(None, Some(OsStr::new(""))), None);
assert_eq!(Base::Runtime.resolve_from(None, home), None);
assert_eq!(Base::Config.env_var(), "XDG_CONFIG_HOME");
}
{
let account = || Some(PathBuf::from("/var/home/account"));
assert_eq!(
home_from(&env(&[("HOME", "/home/u")]), account),
Some(PathBuf::from("/home/u"))
);
assert_eq!(home_from(&env(&[("HOME", "")]), account), None);
assert_eq!(
home_from(&env(&[]), account),
Some(PathBuf::from("/var/home/account"))
);
assert_eq!(home_from(&env(&[]), || Some(PathBuf::new())), None);
}
{
let defaults = ["/usr/local/share", "/usr/share"];
let expected_defaults: Vec<PathBuf> = defaults.iter().map(PathBuf::from).collect();
assert_eq!(search_path(None, &defaults), expected_defaults);
assert_eq!(
search_path(Some(OsStr::new("")), &defaults),
expected_defaults
);
assert_eq!(
search_path(Some(OsStr::new("relative:also/relative")), &defaults),
expected_defaults
);
assert_eq!(
search_path(
Some(OsStr::new("/opt/share::relative:/usr/share")),
&defaults
),
vec![PathBuf::from("/opt/share"), PathBuf::from("/usr/share")]
);
}
}
#[test]
fn app_and_user_dir_names_follow_the_spec_without_a_home() {
{
assert_eq!(Base::Config.resolve(&env(&[]), || None), None);
#[cfg(unix)]
assert_eq!(
Base::Config.resolve(&env(&[("XDG_CONFIG_HOME", "/cfg")]), || None),
Some(PathBuf::from("/cfg"))
);
}
{
assert_eq!(UserDir::Download.env_var(), "XDG_DOWNLOAD_DIR");
assert_eq!(UserDir::PublicShare.env_var(), "XDG_PUBLICSHARE_DIR");
assert_eq!(UserDir::Download.conventional_name(), "Downloads");
}
{
let app = AppDirs::new("tilo-example");
for (joined, base) in [
(app.data(), data_dir()),
(app.config(), config_dir()),
(app.state(), state_dir()),
(app.cache(), cache_dir()),
(app.runtime(), runtime_dir()),
] {
assert_eq!(joined, base.map(|base| base.join("tilo-example")));
}
}
}
#[cfg(unix)]
const USER_DIRS: &[u8] = b"# This file is written by xdg-user-dirs-update\n\
XDG_DESKTOP_DIR=\"$HOME/Schreibtisch\"\n\
XDG_DOWNLOAD_DIR=\"$HOME/Downloads\"\n\
XDG_DOCUMENTS_DIR = \"$HOME/Dokumente\" \n\
XDG_MUSIC_DIR=\"/srv/music\"\n\
XDG_PICTURES_DIR=\"$HOME/\"\n\
XDG_VIDEOS_DIR=$HOME/Videos\n\
XDG_TEMPLATES_DIR=\"relative/templates\"\n\
XDG_PUBLICSHARE_DIR=\"$HOME/My \\\"Public\\\" \\$hare\"\n";
#[cfg(unix)]
#[test]
fn user_dirs_files_resolve_below_home_and_yield_to_variables() {
{
let home = std::path::Path::new("/home/u");
let resolve = |dir: UserDir| dir.resolve_from(None, Some(USER_DIRS), home);
assert_eq!(
resolve(UserDir::Desktop),
Some(PathBuf::from("/home/u/Schreibtisch"))
);
assert_eq!(
resolve(UserDir::Download),
Some(PathBuf::from("/home/u/Downloads"))
);
assert_eq!(
resolve(UserDir::Documents),
Some(PathBuf::from("/home/u/Dokumente")),
"blanks around the key and value are not part of either"
);
assert_eq!(resolve(UserDir::Music), Some(PathBuf::from("/srv/music")));
assert_eq!(
resolve(UserDir::PublicShare),
Some(PathBuf::from("/home/u/My \"Public\" $hare")),
"double-quote escapes are undone"
);
}
{
let home = std::path::Path::new("/home/u");
for dir in [UserDir::Pictures, UserDir::Videos, UserDir::Templates] {
assert_eq!(
dir.resolve_from(None, Some(USER_DIRS), home),
None,
"{dir:?}"
);
}
assert_eq!(UserDir::Desktop.resolve_from(None, None, home), None);
assert_eq!(UserDir::Desktop.resolve_from(None, Some(b""), home), None);
}
{
let home = std::path::Path::new("/home/u");
assert_eq!(
UserDir::Download.resolve_from(Some(OsStr::new("/data/dl")), Some(USER_DIRS), home),
Some(PathBuf::from("/data/dl"))
);
for ignored in ["", "relative/dl"] {
assert_eq!(
UserDir::Download.resolve_from(
Some(OsStr::new(ignored)),
Some(USER_DIRS),
home
),
Some(PathBuf::from("/home/u/Downloads")),
"{ignored:?}"
);
}
}
}
#[cfg(unix)]
#[test]
fn the_last_matching_line_wins() {
let home = std::path::Path::new("/home/u");
let file = b"XDG_DESKTOP_DIR=\"$HOME/One\"\nXDG_DESKTOP_DIR=\"$HOME/Two\"\n";
assert_eq!(
UserDir::Desktop.resolve_from(None, Some(file), home),
Some(PathBuf::from("/home/u/Two"))
);
}
#[cfg(unix)]
#[test]
fn macos_keeps_data_config_and_state_in_application_support() {
let tmpdir = [("TMPDIR", "/var/folders/ab/xyz/T/")];
let var = env(&tmpdir);
for (base, expected) in [
(Base::Data, "/Users/u/Library/Application Support"),
(Base::Config, "/Users/u/Library/Application Support"),
(Base::State, "/Users/u/Library/Application Support"),
(Base::Cache, "/Users/u/Library/Caches"),
(Base::Runtime, "/var/folders/ab/xyz/T/"),
] {
assert_eq!(
macos::base(base, &var, home_is("/Users/u")),
Some(PathBuf::from(expected)),
"{base:?}"
);
}
}
#[cfg(unix)]
#[test]
fn macos_runtime_needs_an_absolute_tmpdir_and_ignores_xdg() {
for value in ["", "tmp", "./T"] {
let vars = [("TMPDIR", value), ("XDG_RUNTIME_DIR", "/run/user/501")];
assert_eq!(
macos::base(Base::Runtime, &env(&vars), home_is("/Users/u")),
None,
"{value:?}"
);
}
assert_eq!(
macos::base(Base::Data, &env(&[("XDG_DATA_HOME", "/data")]), || None),
None,
"without a home only the runtime directory can resolve"
);
}
#[test]
fn a_workspace_tree_is_one_component_under_the_files_root() {
let files = std::path::Path::new("/var/workspace");
let id = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
assert_eq!(
workspace_tree(files, id),
Some(files.join(".workspaces").join(id))
);
for bad in [
"",
".",
"..",
"a/b",
"../x",
"a.b",
"a\0b",
&"x".repeat(129),
] {
assert_eq!(workspace_tree(files, bad), None, "{bad:?}");
}
}
}