├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── lib.rs └── xdg_user_dirs.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse 12 | RUST_BACKTRACE: full 13 | 14 | jobs: 15 | build-and-test: 16 | runs-on: ${{ matrix.os }} 17 | 18 | strategy: 19 | matrix: 20 | os: [ubuntu-latest, windows-latest, macos-latest] 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Build 25 | run: cargo build --verbose 26 | - name: Test 27 | run: cargo test --verbose -- --nocapture 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | /target 3 | **/*.rs.bk 4 | .idea -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Unless you explicitly state otherwise, any contribution intentionally submitted 2 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 3 | dual licensed as above, without any additional terms or conditions. 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "dirs-sys" 3 | version = "0.5.0" 4 | authors = ["Simon Ochsenreither "] 5 | description = "System-level helper functions for the dirs and directories crates." 6 | readme = "README.md" 7 | license = "MIT OR Apache-2.0" 8 | repository = "https://github.com/dirs-dev/dirs-sys-rs" 9 | maintenance = { status = "as-is" } 10 | 11 | [dependencies] 12 | option-ext = "0.2.0" 13 | 14 | [target.'cfg(unix)'.dependencies] 15 | libc = "0.2" 16 | 17 | [target.'cfg(target_os = "redox")'.dependencies] 18 | redox_users = { version = "0.5", default-features = false } 19 | 20 | [target.'cfg(windows)'.dependencies] 21 | windows-sys = { version = ">= 0.59.0", features = [ 22 | "Win32_UI_Shell", 23 | "Win32_Foundation", 24 | "Win32_Globalization", 25 | "Win32_System_Com", 26 | ] } 27 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018-2019 dirs-rs contributors 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![crates.io](https://img.shields.io/crates/v/dirs-sys.svg?style=for-the-badge)](https://crates.io/crates/dirs-sys) 2 | [![API documentation](https://img.shields.io/docsrs/dirs-sys/latest?style=for-the-badge)](https://docs.rs/dirs-sys/) 3 | ![as-is](https://img.shields.io/badge/maintenance-as--is-yellow.svg?style=for-the-badge) 4 | 5 | # `dirs-sys` 6 | 7 | System-level helper functions for the [`dirs`](https://github.com/dirs-dev/dirs-rs) 8 | and [`directories`](https://github.com/dirs-dev/directories-rs) crates. 9 | 10 | _Do not use this library directly, use [`dirs`](https://github.com/dirs-dev/dirs-rs) 11 | or [`directories`](https://github.com/dirs-dev/directories-rs)._ 12 | 13 | ## Compatibility 14 | 15 | This crate only exists to facilitate code sharing between [`dirs`](https://github.com/dirs-dev/dirs-rs) 16 | and [`directories`](https://github.com/dirs-dev/directories-rs). 17 | 18 | There are no compatibility guarantees whatsoever. 19 | Functions may change or disappear without warning or any kind of deprecation period. 20 | 21 | ## Platforms 22 | 23 | This library is written in Rust, and supports Linux, Redox, macOS and Windows. 24 | Other platforms are also supported; they use the Linux conventions. 25 | 26 | ## Build 27 | 28 | It's possible to cross-compile this library if the necessary toolchains are installed with rustup. 29 | This is helpful to ensure a change has not broken compilation on a different platform. 30 | 31 | The following commands will build this library on Linux, macOS and Windows: 32 | 33 | ``` 34 | cargo build --target=x86_64-unknown-linux-gnu 35 | cargo build --target=x86_64-pc-windows-gnu 36 | cargo build --target=x86_64-apple-darwin 37 | cargo build --target=x86_64-unknown-redox 38 | ``` 39 | 40 | ## License 41 | 42 | Licensed under either of 43 | 44 | * Apache License, Version 2.0 45 | ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 46 | * MIT license 47 | ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 48 | 49 | at your option. 50 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate option_ext; 2 | 3 | use std::ffi::OsString; 4 | use std::path::PathBuf; 5 | 6 | // we don't need to explicitly handle empty strings in the code above, 7 | // because an empty string is not considered to be a absolute path here. 8 | pub fn is_absolute_path(path: OsString) -> Option { 9 | let path = PathBuf::from(path); 10 | if path.is_absolute() { 11 | Some(path) 12 | } else { 13 | None 14 | } 15 | } 16 | 17 | #[cfg(all(unix, not(target_os = "redox")))] 18 | extern crate libc; 19 | 20 | #[cfg(all(unix, not(target_os = "redox")))] 21 | mod target_unix_not_redox { 22 | 23 | use std::env; 24 | use std::ffi::{CStr, OsString}; 25 | use std::mem; 26 | use std::os::unix::ffi::OsStringExt; 27 | use std::path::PathBuf; 28 | use std::ptr; 29 | 30 | use super::libc; 31 | 32 | // https://github.com/rust-lang/rust/blob/2682b88c526d493edeb2d3f2df358f44db69b73f/library/std/src/sys/unix/os.rs#L595 33 | pub fn home_dir() -> Option { 34 | return env::var_os("HOME") 35 | .and_then(|h| if h.is_empty() { None } else { Some(h) }) 36 | .or_else(|| unsafe { fallback() }) 37 | .map(PathBuf::from); 38 | 39 | #[cfg(any(target_os = "android", target_os = "ios", target_os = "emscripten"))] 40 | unsafe fn fallback() -> Option { 41 | None 42 | } 43 | #[cfg(not(any(target_os = "android", target_os = "ios", target_os = "emscripten")))] 44 | unsafe fn fallback() -> Option { 45 | let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) { 46 | n if n < 0 => 512 as usize, 47 | n => n as usize, 48 | }; 49 | let mut buf = Vec::with_capacity(amt); 50 | let mut passwd: libc::passwd = mem::zeroed(); 51 | let mut result = ptr::null_mut(); 52 | match libc::getpwuid_r( 53 | libc::getuid(), 54 | &mut passwd, 55 | buf.as_mut_ptr(), 56 | buf.capacity(), 57 | &mut result, 58 | ) { 59 | 0 if !result.is_null() => { 60 | let ptr = passwd.pw_dir as *const _; 61 | let bytes = CStr::from_ptr(ptr).to_bytes(); 62 | if bytes.is_empty() { 63 | None 64 | } else { 65 | Some(OsStringExt::from_vec(bytes.to_vec())) 66 | } 67 | } 68 | _ => None, 69 | } 70 | } 71 | } 72 | 73 | } 74 | 75 | #[cfg(all(unix, not(target_os = "redox")))] 76 | pub use self::target_unix_not_redox::home_dir; 77 | 78 | #[cfg(target_os = "redox")] 79 | extern crate redox_users; 80 | 81 | #[cfg(target_os = "redox")] 82 | mod target_redox { 83 | 84 | use std::path::PathBuf; 85 | 86 | use super::redox_users::{All, AllUsers, Config}; 87 | 88 | pub fn home_dir() -> Option { 89 | let current_uid = redox_users::get_uid().ok()?; 90 | let users = AllUsers::basic(Config::default()).ok()?; 91 | let user = users.get_by_id(current_uid)?; 92 | 93 | Some(PathBuf::from(user.home.clone())) 94 | } 95 | 96 | } 97 | 98 | #[cfg(target_os = "redox")] 99 | pub use self::target_redox::home_dir; 100 | 101 | #[cfg(all(unix, not(any(target_os = "macos", target_os = "ios"))))] 102 | mod xdg_user_dirs; 103 | 104 | #[cfg(all(unix, not(any(target_os = "macos", target_os = "ios"))))] 105 | mod target_unix_not_mac { 106 | 107 | use std::collections::HashMap; 108 | use std::env; 109 | use std::path::{Path, PathBuf}; 110 | 111 | use super::{home_dir, is_absolute_path}; 112 | use super::xdg_user_dirs; 113 | 114 | fn user_dir_file(home_dir: &Path) -> PathBuf { 115 | env::var_os("XDG_CONFIG_HOME").and_then(is_absolute_path).unwrap_or_else(|| home_dir.join(".config")).join("user-dirs.dirs") 116 | } 117 | 118 | // this could be optimized further to not create a map and instead retrieve the requested path only 119 | pub fn user_dir(user_dir_name: &str) -> Option { 120 | if let Some(home_dir) = home_dir() { 121 | xdg_user_dirs::single(&home_dir, &user_dir_file(&home_dir), user_dir_name).remove(user_dir_name) 122 | } else { 123 | None 124 | } 125 | } 126 | 127 | pub fn user_dirs(home_dir_path: &Path) -> HashMap { 128 | xdg_user_dirs::all(home_dir_path, &user_dir_file(home_dir_path)) 129 | } 130 | 131 | } 132 | 133 | #[cfg(all(unix, not(any(target_os = "macos", target_os = "ios"))))] 134 | pub use self::target_unix_not_mac::{user_dir, user_dirs}; 135 | 136 | #[cfg(target_os = "windows")] 137 | extern crate windows_sys as windows; 138 | 139 | #[cfg(target_os = "windows")] 140 | mod target_windows { 141 | 142 | use std::ffi::c_void; 143 | use std::ffi::OsString; 144 | use std::os::windows::ffi::OsStringExt; 145 | use std::path::PathBuf; 146 | use std::slice; 147 | 148 | use super::windows::Win32::UI::Shell; 149 | 150 | pub fn known_folder(folder_id: windows::core::GUID) -> Option { 151 | unsafe { 152 | let mut path_ptr: windows::core::PWSTR = std::ptr::null_mut(); 153 | let result = Shell::SHGetKnownFolderPath( 154 | &folder_id, 155 | 0, 156 | std::ptr::null_mut(), 157 | &mut path_ptr 158 | ); 159 | if result == 0 { 160 | let len = windows::Win32::Globalization::lstrlenW(path_ptr) as usize; 161 | let path = slice::from_raw_parts(path_ptr, len); 162 | let ostr: OsString = OsStringExt::from_wide(path); 163 | windows::Win32::System::Com::CoTaskMemFree(path_ptr as *const c_void); 164 | Some(PathBuf::from(ostr)) 165 | } else { 166 | windows::Win32::System::Com::CoTaskMemFree(path_ptr as *const c_void); 167 | None 168 | } 169 | } 170 | } 171 | 172 | pub fn known_folder_profile() -> Option { 173 | known_folder(Shell::FOLDERID_Profile) 174 | } 175 | 176 | pub fn known_folder_roaming_app_data() -> Option { 177 | known_folder(Shell::FOLDERID_RoamingAppData) 178 | } 179 | 180 | pub fn known_folder_local_app_data() -> Option { 181 | known_folder(Shell::FOLDERID_LocalAppData) 182 | } 183 | 184 | pub fn known_folder_music() -> Option { 185 | known_folder(Shell::FOLDERID_Music) 186 | } 187 | 188 | pub fn known_folder_desktop() -> Option { 189 | known_folder(Shell::FOLDERID_Desktop) 190 | } 191 | 192 | pub fn known_folder_documents() -> Option { 193 | known_folder(Shell::FOLDERID_Documents) 194 | } 195 | 196 | pub fn known_folder_downloads() -> Option { 197 | known_folder(Shell::FOLDERID_Downloads) 198 | } 199 | 200 | pub fn known_folder_pictures() -> Option { 201 | known_folder(Shell::FOLDERID_Pictures) 202 | } 203 | 204 | pub fn known_folder_public() -> Option { 205 | known_folder(Shell::FOLDERID_Public) 206 | } 207 | pub fn known_folder_templates() -> Option { 208 | known_folder(Shell::FOLDERID_Templates) 209 | } 210 | pub fn known_folder_videos() -> Option { 211 | known_folder(Shell::FOLDERID_Videos) 212 | } 213 | 214 | } 215 | 216 | #[cfg(target_os = "windows")] 217 | pub use self::target_windows::{ 218 | known_folder, known_folder_profile, known_folder_roaming_app_data, known_folder_local_app_data, 219 | known_folder_music, known_folder_desktop, known_folder_documents, known_folder_downloads, 220 | known_folder_pictures, known_folder_public, known_folder_templates, known_folder_videos 221 | }; 222 | -------------------------------------------------------------------------------- /src/xdg_user_dirs.rs: -------------------------------------------------------------------------------- 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 { 13 | let bytes = read_all(user_dir_file_path).unwrap_or(Vec::new()); 14 | parse_user_dirs(home_dir_path, 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 { 19 | let bytes = read_all(user_dir_file_path).unwrap_or(Vec::new()); 20 | parse_user_dirs(home_dir_path, Some(user_dir_name), &bytes) 21 | } 22 | 23 | fn parse_user_dirs(home_dir: &Path, user_dir: Option<&str>, bytes: &[u8]) -> HashMap { 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> { 95 | let mut file = fs::File::open(path)?; 96 | let mut bytes = 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| *b == separator).map(|i| { 104 | (&bytes[..i], &bytes[i+1..]) 105 | }) 106 | } 107 | 108 | /// Returns a slice with leading and trailing characters removed. 109 | fn trim_blank(bytes: &[u8]) -> &[u8] { 110 | // Trim leading characters. 111 | let i = bytes.iter().cloned().take_while(|b| *b == b' ' || *b == b'\t').count(); 112 | let bytes = &bytes[i..]; 113 | 114 | // Trim trailing characters. 115 | let i = bytes.iter().cloned().rev().take_while(|b| *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 { 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 . 125 | 126 | let mut unescaped: Vec = Vec::with_capacity(escaped.len()); 127 | let mut i = escaped.iter().cloned(); 128 | 129 | while let Some(b) = i.next() { 130 | if b == b'\\' { 131 | if let Some(b) = 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 = 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 = 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 = 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 = 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 | --------------------------------------------------------------------------------