| 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 | use option_ext::OptionExt; |
| 10 | |
| 11 | /// Returns all XDG user directories obtained from $(XDG_CONFIG_HOME)/user-dirs.dirs. |
| 12 | pub fn all(home_dir_path: &Path, user_dir_file_path: &Path) -> HashMap<String, PathBuf> { |
| 13 | let bytes: Vec = read_all(user_dir_file_path).unwrap_or(default:Vec::new()); |
| 14 | parse_user_dirs(home_dir_path, user_dir:None, &bytes) |
| 15 | } |
| 16 | |
| 17 | /// Returns a single XDG user directory obtained from $(XDG_CONFIG_HOME)/user-dirs.dirs. |
| 18 | pub fn single(home_dir_path: &Path, user_dir_file_path: &Path, user_dir_name: &str) -> HashMap<String, PathBuf> { |
| 19 | let bytes: Vec = read_all(user_dir_file_path).unwrap_or(default:Vec::new()); |
| 20 | parse_user_dirs(home_dir_path, user_dir:Some(user_dir_name), &bytes) |
| 21 | } |
| 22 | |
| 23 | fn parse_user_dirs(home_dir: &Path, user_dir: Option<&str>, bytes: &[u8]) -> HashMap<String, PathBuf> { |
| 24 | let mut user_dirs = HashMap::new(); |
| 25 | |
| 26 | for line in bytes.split(|b| *b == b' \n' ) { |
| 27 | let mut single_dir_found = false; |
| 28 | let (key, value) = match split_once(line, b'=' ) { |
| 29 | Some(kv) => kv, |
| 30 | None => continue, |
| 31 | }; |
| 32 | |
| 33 | let key = trim_blank(key); |
| 34 | let key = if key.starts_with(b"XDG_" ) && key.ends_with(b"_DIR" ) { |
| 35 | match str::from_utf8(&key[4..key.len()-4]) { |
| 36 | Ok(key) => |
| 37 | if user_dir.contains(&key) { |
| 38 | single_dir_found = true; |
| 39 | key |
| 40 | } else if user_dir.is_none() { |
| 41 | key |
| 42 | } else { |
| 43 | continue |
| 44 | }, |
| 45 | Err(_) => continue, |
| 46 | } |
| 47 | } else { |
| 48 | continue |
| 49 | }; |
| 50 | |
| 51 | // xdg-user-dirs-update uses double quotes and we don't support anything else. |
| 52 | let value = trim_blank(value); |
| 53 | let mut value = if value.starts_with(b" \"" ) && value.ends_with(b" \"" ) { |
| 54 | &value[1..value.len()-1] |
| 55 | } else { |
| 56 | continue |
| 57 | }; |
| 58 | |
| 59 | // Path should be either relative to the home directory or absolute. |
| 60 | let is_relative = if value == b"$HOME/" { |
| 61 | // "Note: To disable a directory, point it to the homedir." |
| 62 | // Source: https://www.freedesktop.org/wiki/Software/xdg-user-dirs/ |
| 63 | // Additionally directory is reassigned to homedir when removed. |
| 64 | continue |
| 65 | } else if value.starts_with(b"$HOME/" ) { |
| 66 | value = &value[b"$HOME/" .len()..]; |
| 67 | true |
| 68 | } else if value.starts_with(b"/" ) { |
| 69 | false |
| 70 | } else { |
| 71 | continue |
| 72 | }; |
| 73 | |
| 74 | let value = OsString::from_vec(shell_unescape(value)); |
| 75 | |
| 76 | let path = if is_relative { |
| 77 | let mut path = PathBuf::from(&home_dir); |
| 78 | path.push(value); |
| 79 | path |
| 80 | } else { |
| 81 | PathBuf::from(value) |
| 82 | }; |
| 83 | |
| 84 | user_dirs.insert(key.to_owned(), path); |
| 85 | if single_dir_found { |
| 86 | break; |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | user_dirs |
| 91 | } |
| 92 | |
| 93 | /// Reads the entire contents of a file into a byte vector. |
| 94 | fn read_all(path: &Path) -> io::Result<Vec<u8>> { |
| 95 | let mut file: File = fs::File::open(path)?; |
| 96 | let mut bytes: Vec = Vec::with_capacity(1024); |
| 97 | file.read_to_end(&mut bytes)?; |
| 98 | Ok(bytes) |
| 99 | } |
| 100 | |
| 101 | /// Returns bytes before and after first occurrence of separator. |
| 102 | fn split_once(bytes: &[u8], separator: u8) -> Option<(&[u8], &[u8])> { |
| 103 | bytes.iter().position(|b: &u8| *b == separator).map(|i: usize| { |
| 104 | (&bytes[..i], &bytes[i+1..]) |
| 105 | }) |
| 106 | } |
| 107 | |
| 108 | /// Returns a slice with leading and trailing <blank> characters removed. |
| 109 | fn trim_blank(bytes: &[u8]) -> &[u8] { |
| 110 | // Trim leading <blank> characters. |
| 111 | let i: usize = bytes.iter().cloned().take_while(|b: &u8| *b == b' ' || *b == b' \t' ).count(); |
| 112 | let bytes: &[u8] = &bytes[i..]; |
| 113 | |
| 114 | // Trim trailing <blank> characters. |
| 115 | let i: usize = bytes.iter().cloned().rev().take_while(|b: &u8| *b == b' ' || *b == b' \t' ).count(); |
| 116 | &bytes[..bytes.len()-i] |
| 117 | } |
| 118 | |
| 119 | /// Unescape bytes escaped with POSIX shell double-quotes rules (as used by xdg-user-dirs-update). |
| 120 | fn shell_unescape(escaped: &[u8]) -> Vec<u8> { |
| 121 | // We assume that byte string was created by xdg-user-dirs-update which |
| 122 | // escapes all characters that might potentially have special meaning, |
| 123 | // so there is no need to check if backslash is actually followed by |
| 124 | // $ ` " \ or a <newline>. |
| 125 | |
| 126 | let mut unescaped: Vec<u8> = Vec::with_capacity(escaped.len()); |
| 127 | let mut i: impl Iterator = escaped.iter().cloned(); |
| 128 | |
| 129 | while let Some(b: u8) = i.next() { |
| 130 | if b == b' \\' { |
| 131 | if let Some(b: u8) = i.next() { |
| 132 | unescaped.push(b); |
| 133 | } |
| 134 | } else { |
| 135 | unescaped.push(b); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | unescaped |
| 140 | } |
| 141 | |
| 142 | #[cfg (test)] |
| 143 | mod tests { |
| 144 | use std::collections::HashMap; |
| 145 | use std::path::{Path, PathBuf}; |
| 146 | |
| 147 | use super::{parse_user_dirs, shell_unescape, split_once, trim_blank}; |
| 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 | |