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