1use std::collections::HashMap;
2use std::ffi::OsString;
3use std::fs;
4use std::io::{self, Read};
5use std::os::unix::ffi::OsStringExt;
6use std::path::{Path, PathBuf};
7use std::str;
8
9/// Returns all XDG user directories obtained from $(XDG_CONFIG_HOME)/user-dirs.dirs.
10pub fn all(home_dir_path: &Path, user_dir_file_path: &Path) -> HashMap<String, PathBuf> {
11 let bytes: Vec = read_all(user_dir_file_path).unwrap_or(default:Vec::new());
12 parse_user_dirs(home_dir_path, user_dir:None, &bytes)
13}
14
15/// Returns a single XDG user directory obtained from $(XDG_CONFIG_HOME)/user-dirs.dirs.
16pub fn single(home_dir_path: &Path, user_dir_file_path: &Path, user_dir_name: &str) -> HashMap<String, PathBuf> {
17 let bytes: Vec = read_all(user_dir_file_path).unwrap_or(default:Vec::new());
18 parse_user_dirs(home_dir_path, user_dir:Some(user_dir_name), &bytes)
19}
20
21fn parse_user_dirs(home_dir: &Path, user_dir: Option<&str>, bytes: &[u8]) -> HashMap<String, PathBuf> {
22 let mut user_dirs = HashMap::new();
23
24 for line in bytes.split(|b| *b == b'\n') {
25 let mut single_dir_found = false;
26 let (key, value) = match split_once(line, b'=') {
27 Some(kv) => kv,
28 None => continue,
29 };
30
31 let key = trim_blank(key);
32 let key = if key.starts_with(b"XDG_") && key.ends_with(b"_DIR") {
33 match str::from_utf8(&key[4..key.len()-4]) {
34 Ok(key) =>
35 if user_dir.is_some() && option_contains(user_dir, key) {
36 single_dir_found = true;
37 key
38 } else if user_dir.is_none() {
39 key
40 } else {
41 continue
42 },
43 Err(_) => continue,
44 }
45 } else {
46 continue
47 };
48
49 // xdg-user-dirs-update uses double quotes and we don't support anything else.
50 let value = trim_blank(value);
51 let mut value = if value.starts_with(b"\"") && value.ends_with(b"\"") {
52 &value[1..value.len()-1]
53 } else {
54 continue
55 };
56
57 // Path should be either relative to the home directory or absolute.
58 let is_relative = if value == b"$HOME/" {
59 // "Note: To disable a directory, point it to the homedir."
60 // Source: https://www.freedesktop.org/wiki/Software/xdg-user-dirs/
61 // Additionally directory is reassigned to homedir when removed.
62 continue
63 } else if value.starts_with(b"$HOME/") {
64 value = &value[b"$HOME/".len()..];
65 true
66 } else if value.starts_with(b"/") {
67 false
68 } else {
69 continue
70 };
71
72 let value = OsString::from_vec(shell_unescape(value));
73
74 let path = if is_relative {
75 let mut path = PathBuf::from(&home_dir);
76 path.push(value);
77 path
78 } else {
79 PathBuf::from(value)
80 };
81
82 user_dirs.insert(key.to_owned(), path);
83 if single_dir_found {
84 break;
85 }
86 }
87
88 user_dirs
89}
90
91/// Reads the entire contents of a file into a byte vector.
92fn read_all(path: &Path) -> io::Result<Vec<u8>> {
93 let mut file: File = fs::File::open(path)?;
94 let mut bytes: Vec = Vec::with_capacity(1024);
95 file.read_to_end(&mut bytes)?;
96 Ok(bytes)
97}
98
99/// Returns bytes before and after first occurrence of separator.
100fn split_once(bytes: &[u8], separator: u8) -> Option<(&[u8], &[u8])> {
101 bytes.iter().position(|b: &u8| *b == separator).map(|i: usize| {
102 (&bytes[..i], &bytes[i+1..])
103 })
104}
105
106/// Returns a slice with leading and trailing <blank> characters removed.
107fn trim_blank(bytes: &[u8]) -> &[u8] {
108 // Trim leading <blank> characters.
109 let i: usize = bytes.iter().cloned().take_while(|b: &u8| *b == b' ' || *b == b'\t').count();
110 let bytes: &[u8] = &bytes[i..];
111
112 // Trim trailing <blank> characters.
113 let i: usize = bytes.iter().cloned().rev().take_while(|b: &u8| *b == b' ' || *b == b'\t').count();
114 &bytes[..bytes.len()-i]
115}
116
117/// Unescape bytes escaped with POSIX shell double-quotes rules (as used by xdg-user-dirs-update).
118fn shell_unescape(escaped: &[u8]) -> Vec<u8> {
119 // We assume that byte string was created by xdg-user-dirs-update which
120 // escapes all characters that might potentially have special meaning,
121 // so there is no need to check if backslash is actually followed by
122 // $ ` " \ or a <newline>.
123
124 let mut unescaped: Vec<u8> = Vec::with_capacity(escaped.len());
125 let mut i: impl Iterator = escaped.iter().cloned();
126
127 while let Some(b: u8) = i.next() {
128 if b == b'\\' {
129 if let Some(b: u8) = i.next() {
130 unescaped.push(b);
131 }
132 } else {
133 unescaped.push(b);
134 }
135 }
136
137 unescaped
138}
139
140fn option_contains<T : PartialEq>(option: Option<T>, value: T) -> bool {
141 match option {
142 Some(val: T) => val == value,
143 None => false
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use std::collections::HashMap;
150 use std::path::{Path, PathBuf};
151 use super::{trim_blank, shell_unescape, split_once, parse_user_dirs};
152
153 #[test]
154 fn test_trim_blank() {
155 assert_eq!(b"x", trim_blank(b"x"));
156 assert_eq!(b"", trim_blank(b" \t "));
157 assert_eq!(b"hello there", trim_blank(b" \t hello there \t "));
158 assert_eq!(b"\r\n", trim_blank(b"\r\n"));
159 }
160
161 #[test]
162 fn test_split_once() {
163 assert_eq!(None, split_once(b"a b c", b'='));
164 assert_eq!(Some((b"before".as_ref(), b"after".as_ref())), split_once(b"before=after", b'='));
165 }
166
167 #[test]
168 fn test_shell_unescape() {
169 assert_eq!(b"abc", shell_unescape(b"abc").as_slice());
170 assert_eq!(b"x\\y$z`", shell_unescape(b"x\\\\y\\$z\\`").as_slice());
171 }
172
173 #[test]
174 fn test_parse_empty() {
175 assert_eq!(HashMap::new(), parse_user_dirs(Path::new("/root/"), None, b""));
176 assert_eq!(HashMap::new(), parse_user_dirs(Path::new("/root/"), Some("MUSIC"), b""));
177 }
178
179 #[test]
180 fn test_absolute_path_is_accepted() {
181 let mut dirs = HashMap::new();
182 dirs.insert("MUSIC".to_owned(), PathBuf::from("/media/music"));
183 let bytes = br#"XDG_MUSIC_DIR="/media/music""#;
184 assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), None, bytes));
185 assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), Some("MUSIC"), bytes));
186 }
187
188 #[test]
189 fn test_relative_path_is_rejected() {
190 let dirs = HashMap::new();
191 let bytes = br#"XDG_MUSIC_DIR="music""#;
192 assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), None, bytes));
193 assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), Some("MUSIC"), bytes));
194 }
195
196 #[test]
197 fn test_relative_to_home() {
198 let mut dirs = HashMap::new();
199 dirs.insert("MUSIC".to_owned(), PathBuf::from("/home/john/Music"));
200 let bytes = br#"XDG_MUSIC_DIR="$HOME/Music""#;
201 assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), None, bytes));
202 assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), Some("MUSIC"), bytes));
203 }
204
205 #[test]
206 fn test_disabled_directory() {
207 let dirs = HashMap::new();
208 let bytes = br#"XDG_MUSIC_DIR="$HOME/""#;
209 assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), None, bytes));
210 assert_eq!(dirs, parse_user_dirs(Path::new("/home/john"), Some("MUSIC"), bytes));
211 }
212
213 #[test]
214 fn test_parse_user_dirs() {
215 let mut dirs: HashMap<String, PathBuf> = HashMap::new();
216 dirs.insert("DESKTOP".to_string(), PathBuf::from("/home/bob/Desktop"));
217 dirs.insert("DOWNLOAD".to_string(), PathBuf::from("/home/bob/Downloads"));
218 dirs.insert("PICTURES".to_string(), PathBuf::from("/home/eve/pics"));
219
220 let bytes = br#"
221# This file is written by xdg-user-dirs-update
222# If you want to change or add directories, just edit the line you're
223# interested in. All local changes will be retained on the next run.
224# Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
225# homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an
226# absolute path. No other format is supported.
227XDG_DESKTOP_DIR="$HOME/Desktop"
228XDG_DOWNLOAD_DIR="$HOME/Downloads"
229XDG_TEMPLATES_DIR=""
230XDG_PUBLICSHARE_DIR="$HOME"
231XDG_DOCUMENTS_DIR="$HOME/"
232XDG_PICTURES_DIR="/home/eve/pics"
233XDG_VIDEOS_DIR="$HOxyzME/Videos"
234"#;
235
236 assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), None, bytes));
237
238 let mut dirs: HashMap<String, PathBuf> = HashMap::new();
239 dirs.insert("DESKTOP".to_string(), PathBuf::from("/home/bob/Desktop"));
240 assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), Some("DESKTOP"), bytes));
241
242 let mut dirs: HashMap<String, PathBuf> = HashMap::new();
243 dirs.insert("PICTURES".to_string(), PathBuf::from("/home/eve/pics"));
244 assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), Some("PICTURES"), bytes));
245
246 let dirs: HashMap<String, PathBuf> = HashMap::new();
247 assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), Some("TEMPLATES"), bytes));
248 assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), Some("PUBLICSHARE"), bytes));
249 assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), Some("DOCUMENTS"), bytes));
250 assert_eq!(dirs, parse_user_dirs(Path::new("/home/bob"), Some("VIDEOS"), bytes));
251 }
252}
253