hyprforge_paths/user_dirs.rs
1//! The XDG user directories — Documents, Downloads, Pictures, Music,
2//! Videos, Desktop — read from `~/.config/user-dirs.dirs` rather than
3//! hardcoded, so a sidebar built on a machine set up in another language
4//! shows that language's own folder names instead of a translated set of
5//! English guesses sitting next to directories that don't exist.
6//!
7//! `xdg-user-dirs-update` writes lines like:
8//! ```text
9//! XDG_DOCUMENTS_DIR="$HOME/Dokumente"
10//! ```
11//! — one `KEY="value"` pair per line, `$HOME` a literal prefix to be
12//! substituted, `#`-comments and blank lines allowed anywhere. This
13//! parses exactly that shape and nothing more: no shell expansion beyond
14//! the one `$HOME` substitution the format actually uses, because a
15//! general shell parser is a dependency this crate does not need for a
16//! file with eight fixed keys.
17//!
18//! Here rather than in `hyprforge-files-core`, where it started, because
19//! the photo viewer's sidebar needs Pictures and Downloads too, and the
20//! alternatives were a dependency on the whole file browser or a second
21//! parser. `hyprforge-files-core` re-exports it as `xdg_user_dirs`.
22
23use std::path::{Path, PathBuf};
24
25/// The subset of XDG user directories a sidebar cares about. `None` for
26/// a directory the file doesn't mention — a partially customised file is
27/// common (someone deletes the `XDG_TEMPLATES_DIR` line and nothing
28/// else), and a missing key is not this module's business to guess at;
29/// a sidebar built from it simply won't offer a shortcut for it.
30#[derive(Debug, Clone, Default, PartialEq, Eq)]
31pub struct UserDirs {
32 pub desktop: Option<PathBuf>,
33 pub download: Option<PathBuf>,
34 pub documents: Option<PathBuf>,
35 pub music: Option<PathBuf>,
36 pub pictures: Option<PathBuf>,
37 pub videos: Option<PathBuf>,
38}
39
40/// Reads and parses `user-dirs.dirs` from the config directory, or falls
41/// back to the conventional English names under `home` if the file
42/// isn't there.
43///
44/// The fallback is deliberately only for a **missing** file, not a file
45/// that exists and fails to parse in some unexpected way — a
46/// syntactically odd but present file still goes through [`parse`],
47/// which is forgiving line-by-line (an unrecognised line is skipped, not
48/// a hard failure) rather than needing its own could-not-read/could-not-parse
49/// split the way `Prefs` does. There is no realistic way for this format
50/// to be "present but unparseable" as a whole, unlike a TOML file: every
51/// line either matches the one shape this parser looks for, or it
52/// doesn't and is ignored. Performs blocking file I/O — call this off
53/// the UI thread.
54pub fn load(config_dir: &Path, home: &Path) -> UserDirs {
55 let path = config_dir.join("user-dirs.dirs");
56 match std::fs::read_to_string(&path) {
57 Ok(text) => parse(&text, home),
58 Err(_) => fallback(home),
59 }
60}
61
62/// The conventional English names, used only when there is no
63/// `user-dirs.dirs` to read at all (see [`load`]). A sidebar
64/// still checks each of these against the real filesystem before
65/// offering it, so a guess that doesn't exist on this machine is dropped
66/// rather than shown as a dead shortcut.
67pub fn fallback(home: &Path) -> UserDirs {
68 UserDirs {
69 desktop: Some(home.join("Desktop")),
70 download: Some(home.join("Downloads")),
71 documents: Some(home.join("Documents")),
72 music: Some(home.join("Music")),
73 pictures: Some(home.join("Pictures")),
74 videos: Some(home.join("Videos")),
75 }
76}
77
78/// Parses the contents of a `user-dirs.dirs` file. `home` is substituted
79/// for a leading `$HOME` in each value, matching how `xdg-user-dirs`
80/// itself writes the file.
81pub fn parse(contents: &str, home: &Path) -> UserDirs {
82 let mut dirs = UserDirs::default();
83 for line in contents.lines() {
84 let line = line.trim();
85 if line.is_empty() || line.starts_with('#') {
86 continue;
87 }
88 let Some((key, value)) = line.split_once('=') else {
89 continue;
90 };
91 let key = key.trim();
92 let Some(value) = unquote(value.trim()) else {
93 continue;
94 };
95 let path = resolve(&value, home);
96 match key {
97 "XDG_DESKTOP_DIR" => dirs.desktop = Some(path),
98 "XDG_DOWNLOAD_DIR" => dirs.download = Some(path),
99 "XDG_DOCUMENTS_DIR" => dirs.documents = Some(path),
100 "XDG_MUSIC_DIR" => dirs.music = Some(path),
101 "XDG_PICTURES_DIR" => dirs.pictures = Some(path),
102 "XDG_VIDEOS_DIR" => dirs.videos = Some(path),
103 // XDG_PUBLICSHARE_DIR and XDG_TEMPLATES_DIR exist in the
104 // real format too, but nothing in this browser's sidebar
105 // brief asks for either — see the module doc's own scoping.
106 _ => {}
107 }
108 }
109 dirs
110}
111
112/// Strips one layer of double quotes, the only quoting `user-dirs.dirs`
113/// actually uses. A value with no closing quote is malformed and
114/// skipped rather than guessed at.
115fn unquote(value: &str) -> Option<String> {
116 let value = value.strip_prefix('"')?;
117 let value = value.strip_suffix('"')?;
118 Some(value.to_string())
119}
120
121/// Replaces a leading `$HOME` with the real home directory; anything
122/// else is treated as already-absolute (or, rarely, relative — left as
123/// written, since the spec doesn't otherwise define what a bare relative
124/// path here would mean).
125fn resolve(value: &str, home: &Path) -> PathBuf {
126 match value.strip_prefix("$HOME") {
127 Some(rest) => {
128 let rest = rest.trim_start_matches('/');
129 if rest.is_empty() {
130 home.to_path_buf()
131 } else {
132 home.join(rest)
133 }
134 }
135 None => PathBuf::from(value),
136 }
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142
143 #[test]
144 fn a_typical_file_resolves_home_relative_paths() {
145 let contents = r#"
146 # This file is written by xdg-user-dirs-update
147 XDG_DESKTOP_DIR="$HOME/Desktop"
148 XDG_DOCUMENTS_DIR="$HOME/Dokumente"
149 XDG_DOWNLOAD_DIR="$HOME/Downloads"
150 "#;
151 let home = Path::new("/home/alex");
152 let dirs = parse(contents, home);
153 assert_eq!(dirs.desktop, Some(PathBuf::from("/home/alex/Desktop")));
154 assert_eq!(dirs.documents, Some(PathBuf::from("/home/alex/Dokumente")));
155 assert_eq!(dirs.download, Some(PathBuf::from("/home/alex/Downloads")));
156 }
157
158 #[test]
159 fn a_key_the_file_never_mentions_stays_none_rather_than_guessed() {
160 let contents = r#"XDG_DOCUMENTS_DIR="$HOME/Documents""#;
161 let dirs = parse(contents, Path::new("/home/alex"));
162 assert_eq!(dirs.documents, Some(PathBuf::from("/home/alex/Documents")));
163 assert_eq!(dirs.music, None, "a directory the file doesn't mention is not a guess");
164 }
165
166 #[test]
167 fn an_unrecognised_line_is_skipped_not_fatal() {
168 let contents = "this is not a valid line at all\nXDG_MUSIC_DIR=\"$HOME/Music\"";
169 let dirs = parse(contents, Path::new("/home/alex"));
170 assert_eq!(dirs.music, Some(PathBuf::from("/home/alex/Music")));
171 }
172
173 #[test]
174 fn a_missing_file_falls_back_to_english_names_under_home() {
175 let dir = tempfile::tempdir().unwrap();
176 let home = Path::new("/home/alex");
177 let dirs = load(dir.path(), home);
178 assert_eq!(dirs, fallback(home));
179 assert_eq!(dirs.documents, Some(PathBuf::from("/home/alex/Documents")));
180 }
181
182 #[test]
183 fn a_present_file_is_used_instead_of_the_fallback() {
184 let dir = tempfile::tempdir().unwrap();
185 std::fs::write(
186 dir.path().join("user-dirs.dirs"),
187 r#"XDG_DOCUMENTS_DIR="$HOME/OnlyThis""#,
188 )
189 .unwrap();
190 let home = Path::new("/home/alex");
191 let dirs = load(dir.path(), home);
192 assert_eq!(dirs.documents, Some(PathBuf::from("/home/alex/OnlyThis")));
193 assert_eq!(dirs.download, None, "present file wins outright, no fallback merge");
194 }
195}