directories-1.0.2/.appveyor.yml010066400017510001751000000022231335175400600147240ustar0000000000000000environment: global: CHANNEL: stable #APPVEYOR_CACHE_SKIP_RESTORE: true # Uncomment when caching causes problems matrix: # Stable channel - TARGET: i686-pc-windows-msvc CHANNEL: stable - TARGET: i686-pc-windows-gnu CHANNEL: stable - TARGET: x86_64-pc-windows-msvc CHANNEL: stable - TARGET: x86_64-pc-windows-gnu CHANNEL: stable # Beta channel - TARGET: x86_64-pc-windows-msvc CHANNEL: beta - TARGET: x86_64-pc-windows-gnu CHANNEL: beta # 1.13.0 - TARGET: x86_64-pc-windows-msvc CHANNEL: 1.13.0 - TARGET: x86_64-pc-windows-gnu CHANNEL: 1.13.0 install: - ps: >- $Env:PATH += ';C:\msys64\usr\bin' - curl -sSf -o rustup-init.exe https://win.rustup.rs/ - rustup-init.exe -y --default-host %TARGET% --default-toolchain %CHANNEL% - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - rustc -Vv - cargo -V test_script: - cargo build --verbose - set RUST_BACKTRACE=full - cargo test --verbose -- --nocapture cache: - C:\Users\appveyor\.cargo\registry - target notifications: - provider: Email on_build_success: false # Building is done in the test phase, so we disable Appveyor's build phase. build: false directories-1.0.2/.gitignore010066400017510001751000000000231335175400600142420ustar0000000000000000Cargo.lock target/ directories-1.0.2/.travis.yml010066400017510001751000000003411335175400600143660ustar0000000000000000os: - linux - osx sudo: false language: rust rust: - stable - beta - 1.13.0 install: - rustc -Vv - cargo -V script: - cargo build --verbose - RUST_BACKTRACE=full cargo test --verbose -- --nocapture cache: cargo: true directories-1.0.2/Cargo.toml.orig010066400017510001751000000017051335200312400151360ustar0000000000000000[package] name = "directories" version = "1.0.2" authors = ["Simon Ochsenreither "] description = "A tiny mid-level library that provides platform-specific standard locations of directories for config, cache and other data on Linux, Windows and macOS by leveraging the mechanisms defined by the XDG base/user directory specifications on Linux, the Known Folder API on Windows, and the Standard Directory guidelines on macOS." readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/soc/directories-rs" maintenance = { status = "actively-developed" } keywords = ["xdg", "basedir", "app_dirs", "path", "folder"] [target.'cfg(unix)'.dependencies] libc = "0.2" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["knownfolders", "objbase", "shlobj", "winbase", "winerror"] } [dev-dependencies] bencher = "0.1.5" [[bench]] name = "constructors" harness = false directories-1.0.2/Cargo.toml0000644000000026130000000000000114070ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "directories" version = "1.0.2" authors = ["Simon Ochsenreither "] description = "A tiny mid-level library that provides platform-specific standard locations of directories for config, cache and other data on Linux, Windows and macOS by leveraging the mechanisms defined by the XDG base/user directory specifications on Linux, the Known Folder API on Windows, and the Standard Directory guidelines on macOS." readme = "README.md" keywords = ["xdg", "basedir", "app_dirs", "path", "folder"] license = "MIT OR Apache-2.0" repository = "https://github.com/soc/directories-rs" [[bench]] name = "constructors" harness = false [dev-dependencies.bencher] version = "0.1.5" [target."cfg(unix)".dependencies.libc] version = "0.2" [target."cfg(windows)".dependencies.winapi] version = "0.3" features = ["knownfolders", "objbase", "shlobj", "winbase", "winerror"] directories-1.0.2/LICENSE-APACHE010066400017510001751000000227361335175400600142150ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. directories-1.0.2/LICENSE-MIT010066400017510001751000000020571335175400600137170ustar0000000000000000Copyright (c) 2018 directories-rs contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. directories-1.0.2/README.md010066400017510001751000000343071335200310700135330ustar0000000000000000[![crates.io](https://img.shields.io/crates/v/directories.svg)](https://crates.io/crates/directories) [![API documentation](https://docs.rs/directories/badge.svg)](https://docs.rs/directories/) ![actively developed](https://img.shields.io/badge/maintenance-actively--developed-brightgreen.svg) [![TravisCI status](https://img.shields.io/travis/soc/directories-rs/master.svg?label=Linux/macOS%20build)](https://travis-ci.org/soc/directories-rs) [![AppVeyor status](https://img.shields.io/appveyor/ci/soc/directories-rs/master.svg?label=Windows%20build)](https://ci.appveyor.com/project/soc/directories-rs/branch/master) ![License: MIT/Apache-2.0](https://img.shields.io/badge/license-MIT%2FApache--2.0-orange.svg) # `directories` ## Introduction - a tiny mid-level library with a minimal API - that provides the platform-specific, user-accessible locations - for retrieving and storing configuration, cache and other data - on Linux, Windows (≥ Vista), macOS and other platforms. The library provides the location of these directories by leveraging the mechanisms defined by - the [XDG base directory](https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html) and the [XDG user directory](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/) specifications on Linux - the [Known Folder](https://msdn.microsoft.com/en-us/library/windows/desktop/dd378457.aspx) API on Windows - the [Standard Directories](https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW6) guidelines on macOS ## Platforms This library is written in Rust, and supports Linux, macOS and Windows. Other platforms are also supported; they use the Linux conventions. _dirs_, the low-level sister library, is available at [dirs-rs](https://github.com/soc/dirs-rs). A version of this library running on the JVM is provided by [directories-jvm](https://github.com/soc/directories-jvm). ## Usage #### Dependency Add the library as a dependency to your project by inserting ```toml directories = "1.0" ``` into the `[dependencies]` section of your Cargo.toml file. #### Example Library run by user Alice: ```rust extern crate directories; use directories::{BaseDirs, UserDirs, ProjectDirs}; if let Some(proj_dirs) = ProjectDirs::from("com", "Foo Corp", "Bar App") { proj_dirs.config_dir(); // Lin: /home/alice/.config/barapp // Win: C:\Users\Alice\AppData\Roaming\Foo Corp\Bar App\config // Mac: /Users/Alice/Library/Preferences/com.Foo-Corp.Bar-App } if let Some(base_dirs) = BaseDirs::new() { base_dirs.executable_dir(); // Lin: Some(/home/alice/.local/bin) // Win: None // Mac: None } if let Some(user_dirs) = UserDirs::new() { user_dirs.audio_dir(); // Lin: /home/alice/Music // Win: C:\Users\Alice\Music // Mac: /Users/Alice/Music } ``` ## Design Goals - The _directories_ library is designed to provide an accurate snapshot of the system's state at the point of invocation of `BaseDirs::new`, `UserDirs::new` or `ProjectDirs::from`. Subsequent changes to the state of the system are not reflected in values created prior to such a change. - This library does not create directories or check for their existence. The library only provides information on what the path to a certain directory _should_ be. How this information is used is a decision that developers need to make based on the requirements of each individual application. - This library is intentionally focused on providing information on user-writable directories only. There is no discernible benefit in returning a path that points to a user-level, writable directory on one operating system, but a system-level, read-only directory on another, that would outweigh the confusion and unexpected failures such an approach would cause. - `executable_dir` is specified to provide the path to a user-writable directory for binaries.
As such a directory only commonly exists on Linux, it returns `None` on macOS and Windows. - `font_dir` is specified to provide the path to a user-writable directory for fonts.
As such a directory only exists on Linux and macOS, it returns `None` on Windows. - `runtime_dir` is specified to provide the path to a directory for non-essential runtime data. It is required that this directory is created when the user logs in, is only accessible by the user itself, is deleted when the user logs out, and supports all filesystem features of the operating system.
As such a directory only commonly exists on Linux, it returns `None` on macOS and Windows. ## Features ### `BaseDirs` The intended use case for `BaseDirs` is to query the paths of user-invisible standard directories that have been defined according to the conventions of the operating system the library is running on. If you want to compute the location of cache, config or data directories for your own application or project, use `ProjectDirs` instead. | Function name | Value on Linux | Value on Windows | Value on macOS | | ---------------- | ----------------------------------------------------------------------------------------------- | --------------------------- | ----------------------------------- | | `home_dir` | `$HOME` | `{FOLDERID_Profile}` | `$HOME` | | `cache_dir` | `$XDG_CACHE_HOME` or `$HOME`/.cache | `{FOLDERID_LocalAppData}` | `$HOME`/Library/Caches | | `config_dir` | `$XDG_CONFIG_HOME` or `$HOME`/.config | `{FOLDERID_RoamingAppData}` | `$HOME`/Library/Preferences | | `data_dir` | `$XDG_DATA_HOME` or `$HOME`/.local/share | `{FOLDERID_RoamingAppData}` | `$HOME`/Library/Application Support | | `data_local_dir` | `$XDG_DATA_HOME` or `$HOME`/.local/share | `{FOLDERID_LocalAppData}` | `$HOME`/Library/Application Support | | `executable_dir` | `Some($XDG_BIN_HOME`/../bin`)` or `Some($XDG_DATA_HOME`/../bin`)` or `Some($HOME`/.local/bin`)` | `None` | `None` | | `runtime_dir` | `Some($XDG_RUNTIME_DIR)` or `None` | `None` | `None` | ### `UserDirs` The intended use case for `UserDirs` is to query the paths of user-facing standard directories that have been defined according to the conventions of the operating system the library is running on. | Function name | Value on Linux | Value on Windows | Value on macOS | | ---------------- | ---------------------------------------------------------------------- | -------------------------------- | ------------------------------ | | `home_dir` | `$HOME` | `{FOLDERID_Profile}` | `$HOME` | | `audio_dir` | `Some(XDG_MUSIC_DIR)` or `None` | `Some({FOLDERID_Music})` | `Some($HOME`/Music/`)` | | `desktop_dir` | `Some(XDG_DESKTOP_DIR)` or `None` | `Some({FOLDERID_Desktop})` | `Some($HOME`/Desktop/`)` | | `document_dir` | `Some(XDG_DOCUMENTS_DIR)` or `None` | `Some({FOLDERID_Documents})` | `Some($HOME`/Documents/`)` | | `download_dir` | `Some(XDG_DOWNLOAD_DIR)` or `None` | `Some({FOLDERID_Downloads})` | `Some($HOME`/Downloads/`)` | | `font_dir` | `Some($XDG_DATA_HOME`/fonts/`)` or `Some($HOME`/.local/share/fonts/`)` | `None` | `Some($HOME`/Library/Fonts/`)` | | `picture_dir` | `Some(XDG_PICTURES_DIR)` or `None` | `Some({FOLDERID_Pictures})` | `Some($HOME`/Pictures/`)` | | `public_dir` | `Some(XDG_PUBLICSHARE_DIR)` or `None` | `Some({FOLDERID_Public})` | `Some($HOME`/Public/`)` | | `template_dir` | `Some(XDG_TEMPLATES_DIR)` or `None` | `Some({FOLDERID_Templates})` | `None` | | `video_dir` | `Some(XDG_VIDEOS_DIR)` or `None` | `Some({FOLDERID_Videos})` | `Some($HOME`/Movies/`)` | ### `ProjectDirs` The intended use case for `ProjectDirs` is to compute the location of cache, config or data directories for your own application or project, which are derived from the standard directories. | Function name | Value on Linux | Value on Windows | Value on macOS | | ---------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------- | ---------------------------------------------------- | | `cache_dir` | `$XDG_CACHE_HOME`/`` or `$HOME`/.cache/`` | `{FOLDERID_LocalAppData}`/``/cache | `$HOME`/Library/Caches/`` | | `config_dir` | `$XDG_CONFIG_HOME`/`` or `$HOME`/.config/`` | `{FOLDERID_RoamingAppData}`/``/config | `$HOME`/Library/Preferences/`` | | `data_dir` | `$XDG_DATA_HOME`/`` or `$HOME`/.local/share/`` | `{FOLDERID_RoamingAppData}`/``/data | `$HOME`/Library/Application Support/`` | | `data_local_dir` | `$XDG_DATA_HOME`/`` or `$HOME`/.local/share/`` | `{FOLDERID_LocalAppData}`/``/data | `$HOME`/Library/Application Support/`` | | `runtime_dir` | `Some($XDG_RUNTIME_DIR`/`_project_path_)` | `None` | `None` | The specific value of `` is computed by the ProjectDirs::from(qualifier: &str, organization: &str, application: &str) function and varies across operating systems. As an example, calling ProjectDirs::from("org" /*qualifier*/, "Baz Corp" /*organization*/, "Foo Bar-App" /*application*/) results in the following values: | Value on Linux | Value on Windows | Value on macOS | | -------------- | ------------------------ | ---------------------------- | | `"foobar-app"` | `"Baz Corp/Foo Bar-App"` | `"org.Baz-Corp.Foo-Bar-App"` | The `ProjectDirs::from_path` function allows the creation of `ProjectDirs` structs directly from a `PathBuf` value. This argument is used verbatim and is not adapted to operating system standards. The use of `ProjectDirs::from_path` is strongly discouraged, as its results will not follow operating system standards on at least two of three platforms. ## Comparison There are other crates in the Rust ecosystem that try similar or related things. Here is an overview of them, combined with ratings on properties that guided the design of this crate. Please take this table with a grain of salt: a different crate might very well be more suitable for your specific use case. (Of course _my_ crate achieves _my_ design goals better than other crates, which might have had different design goals.) | Library | Status | Lin | Mac | Win |Base|User|Proj|Conv| | --------------------------------------------------------- | -------------- |:---:|:---:|:---:|:--:|:--:|:--:|:--:| | [app_dirs](https://crates.io/crates/app_dirs) | Unmaintained | ✔ | ✔ | ✔ | 🞈 | ✖ | ✔ | ✖ | | [app_dirs2](https://crates.io/crates/app_dirs2) | Maintained | ✔ | ✔ | ✔ | 🞈 | ✖ | ✔ | ✖ | | [dirs](https://crates.io/crates/dirs) | Developed | ✔ | ✔ | ✔ | ✔ | ✔ | ✖ | ✔ | | **directories** | **Developed** | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | [s_app_dir](https://crates.io/crates/s_app_dir) | Unmaintained? | ✔ | ✖ | 🞈 | ✖ | ✖ | 🞈 | ✖ | | [standard_paths](https://crates.io/crates/standard_paths) | Maintained | ✔ | ✖ | ✔ | ✔ | ✔ | ✔ | ✖ | | [xdg](https://crates.io/crates/xdg) | Maintained | ✔ | ✖ | ✖ | ✔ | ✖ | ✔ | 🞈 | | [xdg-basedir](https://crates.io/crates/xdg-basedir) | Unmaintained? | ✔ | ✖ | ✖ | ✔ | ✖ | ✖ | 🞈 | | [xdg-rs](https://crates.io/crates/xdg-rs) | Obsolete | ✔ | ✖ | ✖ | ✔ | ✖ | ✖ | 🞈 | - Lin: Linux support - Mac: macOS support - Win: Windows support - Base: Supports [generic base directories](#basedirs) - User: Supports [user directories](#userdirs) - Proj: Supports [project-specific base directories](#projectdirs) - Conv: Follows naming conventions of the operating system ti runs on ## Versioning After 1.0, the version number of this library consists of a whole number, which is incremented with each release. (Think semantic versioning without _minor_ and _patch_ versions.) ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. directories-1.0.2/benches/constructors.rs010066400017510001751000000014601335175400600170050ustar0000000000000000#[macro_use] extern crate bencher; extern crate directories; use bencher::Bencher; use bencher::black_box; use directories::BaseDirs; use directories::ProjectDirs; use directories::UserDirs; fn base_dirs(b: &mut Bencher) { b.iter(|| { let _ = black_box(BaseDirs::new()); }); } fn user_dirs(b: &mut Bencher) { b.iter(|| { let _ = black_box(UserDirs::new()); }); } fn project_dirs_from_path(b: &mut Bencher) { b.iter(|| { let _ = black_box(ProjectDirs::from_path(Default::default())); }); } fn project_dirs(b: &mut Bencher) { b.iter(|| { let _ = black_box(ProjectDirs::from("org", "foo", "Bar App")); }); } benchmark_group!(constructors, base_dirs, user_dirs, project_dirs_from_path, project_dirs, ); benchmark_main!(constructors); directories-1.0.2/src/lib.rs010066400017510001751000000567321335175773400142120ustar0000000000000000//! The _directories_ crate is //! //! - a tiny library with a minimal API (3 structs, 4 factory functions, getters) //! - that provides the platform-specific, user-accessible locations //! - for finding and storing configuration, cache and other data //! - on Linux, Windows (≥ Vista) and macOS. //! //! The library provides the location of these directories by leveraging the mechanisms defined by //! //! - the [XDG base directory](https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html) and the [XDG user directory](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/) specifications on Linux, //! - the [Known Folder](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776911(v=vs.85).aspx) system on Windows, and //! - the [Standard Directories](https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW6) on macOS. //! #![deny(missing_docs)] use std::path::Path; use std::path::PathBuf; #[cfg(target_os = "windows")] mod win; #[cfg(target_os = "macos")] mod mac; #[cfg(not(any(target_os = "windows", target_os = "macos")))] mod lin; #[cfg(unix)] mod unix; #[cfg(target_os = "windows")] use win as sys; #[cfg(target_os = "macos")] use mac as sys; #[cfg(not(any(target_os = "windows", target_os = "macos")))] use lin as sys; /// `BaseDirs` provides paths of user-invisible standard directories, following the conventions of the operating system the library is running on. /// /// To compute the location of cache, config or data directories for individual projects or applications, use `ProjectDirs` instead. /// /// # Examples /// /// All examples on this page are computed with a user named _Alice_. /// /// ``` /// use directories::BaseDirs; /// if let Some(base_dirs) = BaseDirs::new() { /// base_dirs.config_dir(); /// // Linux: /home/alice/.config /// // Windows: C:\Users\Alice\AppData\Roaming /// // macOS: /Users/Alice/Library/Preferences /// } /// ``` #[derive(Debug, Clone)] pub struct BaseDirs { // home directory home_dir: PathBuf, // base directories cache_dir: PathBuf, config_dir: PathBuf, data_dir: PathBuf, data_local_dir: PathBuf, executable_dir: Option, runtime_dir: Option, } /// `UserDirs` provides paths of user-facing standard directories, following the conventions of the operating system the library is running on. /// /// # Examples /// /// All examples on this page are computed with a user named _Alice_. /// /// ``` /// use directories::UserDirs; /// if let Some(user_dirs) = UserDirs::new() { /// user_dirs.audio_dir(); /// // Linux: /home/alice/Music /// // Windows: /Users/Alice/Music /// // macOS: C:\Users\Alice\Music /// } /// ``` #[derive(Debug, Clone)] pub struct UserDirs { // home directory home_dir: PathBuf, // user directories audio_dir: Option, desktop_dir: Option, document_dir: Option, download_dir: Option, font_dir: Option, picture_dir: Option, public_dir: Option, template_dir: Option, // trash_dir: PathBuf, video_dir: Option } /// `ProjectDirs` computes the location of cache, config or data directories for a specific application, /// which are derived from the standard directories and the name of the project/organization. /// /// # Examples /// /// All examples on this page are computed with a user named _Alice_, /// and a `ProjectDirs` struct created with `ProjectDirs::from("com", "Foo Corp", "Bar App")`. /// /// ``` /// use directories::ProjectDirs; /// if let Some(proj_dirs) = ProjectDirs::from("com", "Foo Corp", "Bar App") { /// proj_dirs.config_dir(); /// // Linux: /home/alice/.config/barapp /// // Windows: C:\Users\Alice\AppData\Roaming\Foo Corp\Bar App /// // macOS: /Users/Alice/Library/Preferences/com.Foo-Corp.Bar-App /// } /// ``` #[derive(Debug, Clone)] pub struct ProjectDirs { project_path: PathBuf, // base directories cache_dir: PathBuf, config_dir: PathBuf, data_dir: PathBuf, data_local_dir: PathBuf, runtime_dir: Option } impl BaseDirs { /// Creates a `BaseDirs` struct which holds the paths to user-invisible directories for cache, config, etc. data on the system. /// /// The returned value depends on the operating system and is either /// - `Some`, containing a snapshot of the state of the system's paths at the time `new()` was invoked, or /// - `None`, if no valid home directory path could be retrieved from the operating system. /// /// To determine whether a system provides a valid `$HOME` path, the following rules are applied: /// /// ### Linux and macOS: /// /// - Use `$HOME` if it is set and not empty. /// - If `$HOME` is not set or empty, then the function `getpwuid_r` is used to determine /// the home directory of the current user. /// - If `getpwuid_r` lacks an entry for the current user id or the home directory field is empty, /// then the function returns `None`. /// /// ### Windows: /// /// - Retrieve the user profile folder using `SHGetKnownFolderPath`. /// - If this fails, then the function returns `None`. /// /// _Note:_ This logic differs from [`std::env::home_dir`], /// which works incorrectly on Linux, macOS and Windows. /// /// [`std::env::home_dir`]: https://doc.rust-lang.org/std/env/fn.home_dir.html pub fn new() -> Option { sys::base_dirs() } /// Returns the path to the user's home directory. /// /// |Platform | Value | Example | /// | ------- | -------------------- | -------------- | /// | Linux | `$HOME` | /home/alice | /// | macOS | `$HOME` | /Users/Alice | /// | Windows | `{FOLDERID_Profile}` | C:\Users\Alice | pub fn home_dir(&self) -> &Path { self.home_dir.as_path() } /// Returns the path to the user's cache directory. /// /// |Platform | Value | Example | /// | ------- | ----------------------------------- | ---------------------------- | /// | Linux | `$XDG_CACHE_HOME` or `$HOME`/.cache | /home/alice/.cache | /// | macOS | `$HOME`/Library/Caches | /Users/Alice/Library/Caches | /// | Windows | `{FOLDERID_LocalAppData}` | C:\Users\Alice\AppData\Local | pub fn cache_dir(&self) -> &Path { self.cache_dir.as_path() } /// Returns the path to the user's config directory. /// /// |Platform | Value | Example | /// | ------- | ------------------------------------- | -------------------------------- | /// | Linux | `$XDG_CONFIG_HOME` or `$HOME`/.config | /home/alice/.config | /// | macOS | `$HOME`/Library/Preferences | /Users/Alice/Library/Preferences | /// | Windows | `{FOLDERID_RoamingAppData}` | C:\Users\Alice\AppData\Roaming | pub fn config_dir(&self) -> &Path { self.config_dir.as_path() } /// Returns the path to the user's data directory. /// /// |Platform | Value | Example | /// | ------- | ---------------------------------------- | ---------------------------------------- | /// | Linux | `$XDG_DATA_HOME` or `$HOME`/.local/share | /home/alice/.local/share | /// | macOS | `$HOME`/Library/Application Support | /Users/Alice/Library/Application Support | /// | Windows | `{FOLDERID_RoamingAppData}` | C:\Users\Alice\AppData\Roaming | pub fn data_dir(&self) -> &Path { self.data_dir.as_path() } /// Returns the path to the user's local data directory. /// /// |Platform | Value | Example | /// | ------- | ---------------------------------------- | ---------------------------------------- | /// | Linux | `$XDG_DATA_HOME` or `$HOME`/.local/share | /home/alice/.local/share | /// | macOS | `$HOME`/Library/Application Support | /Users/Alice/Library/Application Support | /// | Windows | `{FOLDERID_LocalAppData}` | C:\Users\Alice\AppData\Local | pub fn data_local_dir(&self) -> &Path { self.data_local_dir.as_path() } /// Returns the path to the user's executable directory. /// /// |Platform | Value | Example | /// | ------- | ---------------------------------------------------------------- | ---------------------- | /// | Linux | `$XDG_BIN_HOME` or `$XDG_DATA_HOME`/../bin or `$HOME`/.local/bin | /home/alice/.local/bin | /// | macOS | – | – | /// | Windows | – | – | pub fn executable_dir(&self) -> Option<&Path> { self.executable_dir.as_ref().map(|p| p.as_path()) } /// Returns the path to the user's runtime directory. /// /// |Platform | Value | Example | /// | ------- | ------------------ | --------------- | /// | Linux | `$XDG_RUNTIME_DIR` | /run/user/1001/ | /// | macOS | – | – | /// | Windows | – | – | pub fn runtime_dir(&self) -> Option<&Path> { self.runtime_dir.as_ref().map(|p| p.as_path()) } } impl UserDirs { /// Creates a `UserDirs` struct which holds the paths to user-facing directories for audio, font, video, etc. data on the system. /// /// The returned value depends on the operating system and is either /// - `Some`, containing a snapshot of the state of the system's paths at the time `new()` was invoked, or /// - `None`, if no valid home directory path could be retrieved from the operating system. /// /// To determine whether a system provides a valid `$HOME` path, please refer to [`BaseDirs::new`] pub fn new() -> Option { sys::user_dirs() } /// Returns the path to the user's home directory. /// /// |Platform | Value | Example | /// | ------- | -------------------- | -------------- | /// | Linux | `$HOME` | /home/alice | /// | macOS | `$HOME` | /Users/Alice | /// | Windows | `{FOLDERID_Profile}` | C:\Users\Alice | pub fn home_dir(&self) -> &Path { self.home_dir.as_path() } /// Returns the path to the user's audio directory. /// /// |Platform | Value | Example | /// | ------- | ------------------ | -------------------- | /// | Linux | `XDG_MUSIC_DIR` | /home/alice/Music | /// | macOS | `$HOME`/Music | /Users/Alice/Music | /// | Windows | `{FOLDERID_Music}` | C:\Users\Alice\Music | pub fn audio_dir(&self) -> Option<&Path> { self.audio_dir.as_ref().map(|p| p.as_path()) } /// Returns the path to the user's desktop directory. /// /// |Platform | Value | Example | /// | ------- | -------------------- | ---------------------- | /// | Linux | `XDG_DESKTOP_DIR` | /home/alice/Desktop | /// | macOS | `$HOME`/Desktop | /Users/Alice/Desktop | /// | Windows | `{FOLDERID_Desktop}` | C:\Users\Alice\Desktop | pub fn desktop_dir(&self) -> Option<&Path> { self.desktop_dir.as_ref().map(|p| p.as_path()) } /// Returns the path to the user's document directory. /// /// |Platform | Value | Example | /// | ------- | ---------------------- | ------------------------ | /// | Linux | `XDG_DOCUMENTS_DIR` | /home/alice/Documents | /// | macOS | `$HOME`/Documents | /Users/Alice/Documents | /// | Windows | `{FOLDERID_Documents}` | C:\Users\Alice\Documents | pub fn document_dir(&self) -> Option<&Path> { self.document_dir.as_ref().map(|p| p.as_path()) } /// Returns the path to the user's download directory. /// /// |Platform | Value | Example | /// | ------- | ---------------------- | ------------------------ | /// | Linux | `XDG_DOWNLOAD_DIR` | /home/alice/Downloads | /// | macOS | `$HOME`/Downloads | /Users/Alice/Downloads | /// | Windows | `{FOLDERID_Downloads}` | C:\Users\Alice\Downloads | pub fn download_dir(&self) -> Option<&Path> { self.download_dir.as_ref().map(|p| p.as_path()) } /// Returns the path to the user's font directory. /// /// |Platform | Value | Example | /// | ------- | ---------------------------------------------------- | ------------------------------ | /// | Linux | `$XDG_DATA_HOME`/fonts or `$HOME`/.local/share/fonts | /home/alice/.local/share/fonts | /// | macOS | `$HOME`/Library/Fonts | /Users/Alice/Library/Fonts | /// | Windows | – | – | pub fn font_dir(&self) -> Option<&Path> { self.font_dir.as_ref().map(|p| p.as_path()) } /// Returns the path to the user's picture directory. /// /// |Platform | Value | Example | /// | ------- | --------------------- | ----------------------- | /// | Linux | `XDG_PICTURES_DIR` | /home/alice/Pictures | /// | macOS | `$HOME`/Pictures | /Users/Alice/Pictures | /// | Windows | `{FOLDERID_Pictures}` | C:\Users\Alice\Pictures | pub fn picture_dir(&self) -> Option<&Path> { self.picture_dir.as_ref().map(|p| p.as_path()) } /// Returns the path to the user's public directory. /// /// |Platform | Value | Example | /// | ------- | --------------------- | ------------------- | /// | Linux | `XDG_PUBLICSHARE_DIR` | /home/alice/Public | /// | macOS | `$HOME`/Public | /Users/Alice/Public | /// | Windows | `{FOLDERID_Public}` | C:\Users\Public | pub fn public_dir(&self) -> Option<&Path> { self.public_dir.as_ref().map(|p| p.as_path()) } /// Returns the path to the user's template directory. /// /// |Platform | Value | Example | /// | ------- | ---------------------- | ---------------------------------------------------------- | /// | Linux | `XDG_TEMPLATES_DIR` | /home/alice/Templates | /// | macOS | – | – | /// | Windows | `{FOLDERID_Templates}` | C:\Users\Alice\AppData\Roaming\Microsoft\Windows\Templates | pub fn template_dir(&self) -> Option<&Path> { self.template_dir.as_ref().map(|p| p.as_path()) } /// Returns the path to the user's video directory. /// /// |Platform | Value | Example | /// | ------- | ------------------- | --------------------- | /// | Linux | `XDG_VIDEOS_DIR` | /home/alice/Videos | /// | macOS | `$HOME`/Movies | /Users/Alice/Movies | /// | Windows | `{FOLDERID_Videos}` | C:\Users\Alice\Videos | pub fn video_dir(&self) -> Option<&Path> { self.video_dir.as_ref().map(|p| p.as_path()) } } impl ProjectDirs { /// Creates a `ProjectDirs` struct directly from a `PathBuf` value. /// The argument is used verbatim and is not adapted to operating system standards. /// /// The use of `ProjectDirs::from_path` is strongly discouraged, as its results will /// not follow operating system standards on at least two of three platforms. /// /// Use [`ProjectDirs::from`] instead. pub fn from_path(project_path: PathBuf) -> Option { sys::project_dirs_from_path(project_path) } /// Creates a `ProjectDirs` struct from values describing the project. /// /// The returned value depends on the operating system and is either /// - `Some`, containing project directory paths based on the state of the system's paths at the time `new()` was invoked, or /// - `None`, if no valid home directory path could be retrieved from the operating system. /// /// To determine whether a system provides a valid `$HOME` path, please refer to [`BaseDirs::new`] /// /// The use of `ProjectDirs::from` (instead of `ProjectDirs::from_path`) is strongly encouraged, /// as its results will follow operating system standards on Linux, macOS and Windows. /// /// # Parameters /// /// - `qualifier` – The reverse domain name notation of the application, excluding the organization or application name itself.
/// An empty string can be passed if no qualifier should be used (only affects macOS).
/// Example values: `"com.example"`, `"org"`, `"uk.co"`, `"io"`, `""` /// - `organization` – The name of the organization that develops this application, or for which the application is developed.
/// An empty string can be passed if no organization should be used (only affects macOS and Windows).
/// Example values: `"Foo Corp"`, `"Alice and Bob Inc"`, `""` /// - `application` – The name of the application itself.
/// Example values: `"Bar App"`, `"ExampleProgram"`, `"Unicorn-Programme"` /// /// # Panics /// /// Panics if the home directory cannot be determined. See [`BaseDirs::home_dir`]. /// /// [`BaseDirs::home_dir`]: struct.BaseDirs.html#method.home_dir pub fn from(qualifier: &str, organization: &str, application: &str) -> Option { sys::project_dirs_from(qualifier, organization, application) } /// Returns the project path fragment used to compute the project's cache/config/data directories. /// The value is derived from the `ProjectDirs::from` call and is platform-dependent. pub fn project_path(&self) -> &Path { self.project_path.as_path() } /// Returns the path to the project's cache directory. /// /// |Platform | Value | Example | /// | ------- | --------------------------------------------------------------------- | --------------------------------------------------- | /// | Linux | `$XDG_CACHE_HOME`/`_project_path_` or `$HOME`/.cache/`_project_path_` | /home/alice/.cache/barapp | /// | macOS | `$HOME`/Library/Caches/`_project_path_` | /Users/Alice/Library/Caches/com.Foo-Corp.Bar-App | /// | Windows | `{FOLDERID_LocalAppData}`\`_project_path_`\cache | C:\Users\Alice\AppData\Local\Foo Corp\Bar App\cache | pub fn cache_dir(&self) -> &Path { self.cache_dir.as_path() } /// Returns the path to the project's config directory. /// /// |Platform | Value | Example | /// | ------- | ----------------------------------------------------------------------- | ------------------------------------------------------ | /// | Linux | `$XDG_CONFIG_HOME`/`_project_path_` or `$HOME`/.config/`_project_path_` | /home/alice/.config/barapp | /// | macOS | `$HOME`/Library/Preferences/`_project_path_` | /Users/Alice/Library/Preferences/com.Foo-Corp.Bar-App | /// | Windows | `{FOLDERID_RoamingAppData}`\`_project_path_`\config | C:\Users\Alice\AppData\Roaming\Foo Corp\Bar App\config | pub fn config_dir(&self) -> &Path { self.config_dir.as_path() } /// Returns the path to the project's data directory. /// /// |Platform | Value | Example | /// | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------- | /// | Linux | `$XDG_DATA_HOME`/`_project_path_` or `$HOME`/.local/share/`_project_path_` | /home/alice/.local/share/barapp | /// | macOS | `$HOME`/Library/Application Support/`_project_path_` | /Users/Alice/Library/Application Support/com.Foo-Corp.Bar-App | /// | Windows | `{FOLDERID_RoamingAppData}`\`_project_path_`\data | C:\Users\Alice\AppData\Roaming\Foo Corp\Bar App\data | pub fn data_dir(&self) -> &Path { self.data_dir.as_path() } /// Returns the path to the project's local data directory. /// /// |Platform | Value | Example | /// | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------- | /// | Linux | `$XDG_DATA_HOME`/`_project_path_` or `$HOME`/.local/share/`_project_path_` | /home/alice/.local/share/barapp | /// | macOS | `$HOME`/Library/Application Support/`_project_path_` | /Users/Alice/Library/Application Support/com.Foo-Corp.Bar-App | /// | Windows | `{FOLDERID_LocalAppData}`\`_project_path_`\data | C:\Users\Alice\AppData\Local\Foo Corp\Bar App\data | pub fn data_local_dir(&self) -> &Path { self.data_local_dir.as_path() } /// Returns the path to the project's runtime directory. /// /// |Platform | Value | Example | /// | ------- | ----------------------------------- | --------------------- | /// | Linux | `$XDG_RUNTIME_DIR`/`_project_path_` | /run/user/1001/barapp | /// | macOS | – | – | /// | Windows | – | – | pub fn runtime_dir(&self) -> Option<&Path> { self.runtime_dir.as_ref().map(|p| p.as_path()) } } #[cfg(test)] mod tests { #[test] fn test_base_dirs() { println!("BaseDirs::new())\n{:?}", ::BaseDirs::new()); } #[test] fn test_user_dirs() { println!("UserDirs::new())\n{:?}", ::UserDirs::new()); } #[test] fn test_project_dirs() { let proj_dirs = ::ProjectDirs::from("qux", "FooCorp", "BarApp"); println!("ProjectDirs::from(\"qux\", \"FooCorp\", \"BarApp\")\n{:?}", proj_dirs); let proj_dirs = ::ProjectDirs::from("qux.zoo", "Foo Corp", "Bar-App"); println!("ProjectDirs::from(\"qux.zoo\", \"Foo Corp\", \"Bar-App\")\n{:?}", proj_dirs); let proj_dirs = ::ProjectDirs::from("com", "Foo Corp.", "Bar App"); println!("ProjectDirs::from(\"com\", \"Foo Corp.\", \"Bar App\")\n{:?}", proj_dirs); } } directories-1.0.2/src/lin.rs010066400017510001751000000136711335175400600142060ustar0000000000000000use std::env; use std::ffi::OsString; use std::path::PathBuf; use std::process::Command; use BaseDirs; use UserDirs; use ProjectDirs; use unix; pub fn base_dirs() -> Option { if let Some(home_dir) = unix::home_dir() { let cache_dir = env::var_os("XDG_CACHE_HOME") .and_then(is_absolute_path).unwrap_or_else(|| home_dir.join(".cache")); let config_dir = env::var_os("XDG_CONFIG_HOME").and_then(is_absolute_path).unwrap_or_else(|| home_dir.join(".config")); let data_dir = env::var_os("XDG_DATA_HOME") .and_then(is_absolute_path).unwrap_or_else(|| home_dir.join(".local/share")); let data_local_dir = data_dir.clone(); let runtime_dir = env::var_os("XDG_RUNTIME_DIR").and_then(is_absolute_path); let executable_dir = env::var_os("XDG_BIN_HOME").and_then(is_absolute_path).unwrap_or_else(|| { let mut new_dir = data_dir.clone(); new_dir.pop(); new_dir.push("bin"); new_dir }); let base_dirs = BaseDirs { home_dir: home_dir, cache_dir: cache_dir, config_dir: config_dir, data_dir: data_dir, data_local_dir: data_local_dir, executable_dir: Some(executable_dir), runtime_dir: runtime_dir }; Some(base_dirs) } else { None } } pub fn user_dirs() -> Option { if let Some(home_dir) = unix::home_dir() { let data_dir = env::var_os("XDG_DATA_HOME").and_then(is_absolute_path).unwrap_or_else(|| home_dir.join(".local/share")); let font_dir = data_dir.join("fonts"); let user_dirs = UserDirs { home_dir: home_dir, audio_dir: run_xdg_user_dir_command("MUSIC"), desktop_dir: run_xdg_user_dir_command("DESKTOP"), document_dir: run_xdg_user_dir_command("DOCUMENTS"), download_dir: run_xdg_user_dir_command("DOWNLOAD"), font_dir: Some(font_dir), picture_dir: run_xdg_user_dir_command("PICTURES"), public_dir: run_xdg_user_dir_command("PUBLICSHARE"), template_dir: run_xdg_user_dir_command("TEMPLATES"), video_dir: run_xdg_user_dir_command("VIDEOS") }; Some(user_dirs) } else { None } } pub fn project_dirs_from_path(project_path: PathBuf) -> Option { if let Some(home_dir) = unix::home_dir() { let cache_dir = env::var_os("XDG_CACHE_HOME") .and_then(is_absolute_path).unwrap_or_else(|| home_dir.join(".cache")).join(&project_path); let config_dir = env::var_os("XDG_CONFIG_HOME").and_then(is_absolute_path).unwrap_or_else(|| home_dir.join(".config")).join(&project_path); let data_dir = env::var_os("XDG_DATA_HOME") .and_then(is_absolute_path).unwrap_or_else(|| home_dir.join(".local/share")).join(&project_path); let data_local_dir = data_dir.clone(); let runtime_dir = env::var_os("XDG_RUNTIME_DIR").and_then(is_absolute_path).map(|o| o.join(&project_path)); let project_dirs = ProjectDirs { project_path: project_path, cache_dir: cache_dir, config_dir: config_dir, data_dir: data_dir, data_local_dir: data_local_dir, runtime_dir: runtime_dir }; Some(project_dirs) } else { None } } pub fn project_dirs_from(_qualifier: &str, _organization: &str, application: &str) -> Option { ProjectDirs::from_path(PathBuf::from(&trim_and_lowercase_then_replace_spaces(application, ""))) } // we don't need to explicitly handle empty strings in the code above, // because an empty string is not considered to be a absolute path here. fn is_absolute_path(path: OsString) -> Option { let path = PathBuf::from(path); if path.is_absolute() { Some(path) } else { None } } fn run_xdg_user_dir_command(arg: &str) -> Option { use std::os::unix::ffi::OsStringExt; let mut out = match Command::new("xdg-user-dir").arg(arg).output() { Ok(output) => output.stdout, Err(_) => return None, }; let out_len = out.len(); out.truncate(out_len - 1); Some(PathBuf::from(OsString::from_vec(out))) } fn trim_and_lowercase_then_replace_spaces(name: &str, replacement: &str) -> String { let mut buf = String::with_capacity(name.len()); let mut parts = name.split_whitespace(); let mut current_part = parts.next(); let replace = !replacement.is_empty(); while current_part.is_some() { let value = current_part.unwrap().to_lowercase(); buf.push_str(&value); current_part = parts.next(); if replace && current_part.is_some() { buf.push_str(replacement); } } buf } #[cfg(test)] mod tests { use lin::trim_and_lowercase_then_replace_spaces; #[test] fn test_trim_and_lowercase_then_replace_spaces() { let input1 = "Bar App"; let actual1 = trim_and_lowercase_then_replace_spaces(input1, "-"); let expected1 = "bar-app"; assert_eq!(expected1, actual1); let input2 = "BarApp-Foo"; let actual2 = trim_and_lowercase_then_replace_spaces(input2, "-"); let expected2 = "barapp-foo"; assert_eq!(expected2, actual2); let input3 = " Bar App "; let actual3 = trim_and_lowercase_then_replace_spaces(input3, "-"); let expected3 = "bar-app"; assert_eq!(expected3, actual3); let input4 = " Bar App "; let actual4 = trim_and_lowercase_then_replace_spaces(input4, "-"); let expected4 = "bar-app"; assert_eq!(expected4, actual4); } #[test] fn test_file_user_dirs_exists() { let base_dirs = ::BaseDirs::new(); let user_dirs_file = base_dirs.unwrap().config_dir().join("user-dirs.dirs"); println!("{:?} exists: {:?}", user_dirs_file, user_dirs_file.exists()); } } directories-1.0.2/src/mac.rs010066400017510001751000000060711335175400600141600ustar0000000000000000use std::path::PathBuf; use BaseDirs; use UserDirs; use ProjectDirs; use unix; pub fn base_dirs() -> Option { if let Some(home_dir) = unix::home_dir() { let cache_dir = home_dir.join("Library/Caches"); let config_dir = home_dir.join("Library/Preferences"); let data_dir = home_dir.join("Library/Application Support"); let data_local_dir = data_dir.clone(); let base_dirs = BaseDirs { home_dir: home_dir, cache_dir: cache_dir, config_dir: config_dir, data_dir: data_dir, data_local_dir: data_local_dir, executable_dir: None, runtime_dir: None }; Some(base_dirs) } else { None } } pub fn user_dirs() -> Option { if let Some(home_dir) = unix::home_dir() { let audio_dir = home_dir.join("Music"); let desktop_dir = home_dir.join("Desktop"); let document_dir = home_dir.join("Documents"); let download_dir = home_dir.join("Downloads"); let picture_dir = home_dir.join("Pictures"); let public_dir = home_dir.join("Public"); let video_dir = home_dir.join("Movies"); let font_dir = home_dir.join("Library/Fonts"); let user_dirs = UserDirs { home_dir: home_dir, audio_dir: Some(audio_dir), desktop_dir: Some(desktop_dir), document_dir: Some(document_dir), download_dir: Some(download_dir), font_dir: Some(font_dir), picture_dir: Some(picture_dir), public_dir: Some(public_dir), template_dir: None, video_dir: Some(video_dir) }; Some(user_dirs) } else { None } } pub fn project_dirs_from_path(project_path: PathBuf) -> Option { if let Some(home_dir) = unix::home_dir() { let cache_dir = home_dir.join("Library/Caches").join(&project_path); let config_dir = home_dir.join("Library/Preferences").join(&project_path); let data_dir = home_dir.join("Library/Application Support").join(&project_path); let data_local_dir = data_dir.clone(); let project_dirs = ProjectDirs { project_path: project_path, cache_dir: cache_dir, config_dir: config_dir, data_dir: data_dir, data_local_dir: data_local_dir, runtime_dir: None, }; Some(project_dirs) } else { None } } pub fn project_dirs_from(qualifier: &str, organization: &str, application: &str) -> Option { // we should replace more characters, according to RFC1034 identifier rules let organization = organization.replace(" ", "-"); let application = application.replace(" ", "-"); let mut parts = vec![qualifier, &organization, &application]; parts.retain(|e| !e.is_empty()); let bundle_id = parts.join("."); ProjectDirs::from_path(PathBuf::from(bundle_id)) } directories-1.0.2/src/unix.rs010066400017510001751000000031121335175400600143740ustar0000000000000000#![cfg(unix)] use std::env; use std::path::PathBuf; use std::mem; use std::ptr; use std::ffi::CStr; use std::ffi::OsString; use std::os::unix::ffi::OsStringExt; extern crate libc; // https://github.com/rust-lang/rust/blob/master/src/libstd/sys/unix/os.rs#L498 pub fn home_dir() -> Option { return env::var_os("HOME").and_then(|h| { if h.is_empty() { None } else { Some(h) } } ).or_else(|| unsafe { fallback() }).map(PathBuf::from); #[cfg(any(target_os = "android", target_os = "ios", target_os = "emscripten"))] unsafe fn fallback() -> Option { None } #[cfg(not(any(target_os = "android", target_os = "ios", target_os = "emscripten")))] unsafe fn fallback() -> Option { let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) { n if n < 0 => 512 as usize, n => n as usize, }; let mut buf = Vec::with_capacity(amt); let mut passwd: libc::passwd = mem::zeroed(); let mut result = ptr::null_mut(); match libc::getpwuid_r(libc::getuid(), &mut passwd, buf.as_mut_ptr(), buf.capacity(), &mut result) { 0 if !result.is_null() => { let ptr = passwd.pw_dir as *const _; let bytes = CStr::from_ptr(ptr).to_bytes(); if bytes.is_empty() { None } else { Some(OsStringExt::from_vec(bytes.to_vec())) } }, _ => None, } } } directories-1.0.2/src/win.rs010066400017510001751000000103651335175400600142160ustar0000000000000000use std; use std::path::PathBuf; use std::iter::FromIterator; extern crate winapi; use self::winapi::shared::winerror; use self::winapi::um::knownfolders; use self::winapi::um::combaseapi; use self::winapi::um::shlobj; use self::winapi::um::shtypes; use self::winapi::um::winbase; use self::winapi::um::winnt; use BaseDirs; use UserDirs; use ProjectDirs; pub fn base_dirs() -> Option { let home_dir = known_folder(&knownfolders::FOLDERID_Profile); let data_dir = known_folder(&knownfolders::FOLDERID_RoamingAppData); let data_local_dir = known_folder(&knownfolders::FOLDERID_LocalAppData); if let (Some(home_dir), Some(data_dir), Some(data_local_dir)) = (home_dir, data_dir, data_local_dir) { let cache_dir = data_local_dir.clone(); let config_dir = data_dir.clone(); let base_dirs = BaseDirs { home_dir: home_dir, cache_dir: cache_dir, config_dir: config_dir, data_dir: data_dir, data_local_dir: data_local_dir, executable_dir: None, runtime_dir: None }; Some(base_dirs) } else { None } } pub fn user_dirs() -> Option { if let Some(home_dir) = known_folder(&knownfolders::FOLDERID_Profile) { let audio_dir = known_folder(&knownfolders::FOLDERID_Music); let desktop_dir = known_folder(&knownfolders::FOLDERID_Desktop); let document_dir = known_folder(&knownfolders::FOLDERID_Documents); let download_dir = known_folder(&knownfolders::FOLDERID_Downloads); let picture_dir = known_folder(&knownfolders::FOLDERID_Pictures); let public_dir = known_folder(&knownfolders::FOLDERID_Public); let template_dir = known_folder(&knownfolders::FOLDERID_Templates); let video_dir = known_folder(&knownfolders::FOLDERID_Videos); let user_dirs = UserDirs { home_dir: home_dir, audio_dir: audio_dir, desktop_dir: desktop_dir, document_dir: document_dir, download_dir: download_dir, font_dir: None, picture_dir: picture_dir, public_dir: public_dir, template_dir: template_dir, video_dir: video_dir }; Some(user_dirs) } else { None } } pub fn project_dirs_from_path(project_path: PathBuf) -> Option { let app_data_local = known_folder(&knownfolders::FOLDERID_LocalAppData); let app_data_roaming = known_folder(&knownfolders::FOLDERID_RoamingAppData); if let (Some(app_data_local), Some(app_data_roaming)) = (app_data_local, app_data_roaming) { let app_data_local = app_data_local.join(&project_path); let app_data_roaming = app_data_roaming.join(&project_path); let cache_dir = app_data_local.join("cache"); let data_local_dir = app_data_local.join("data"); let config_dir = app_data_roaming.join("config"); let data_dir = app_data_roaming.join("data"); let project_dirs = ProjectDirs { project_path: project_path, cache_dir: cache_dir, config_dir: config_dir, data_dir: data_dir, data_local_dir: data_local_dir, runtime_dir: None }; Some(project_dirs) } else { None } } pub fn project_dirs_from(_qualifier: &str, organization: &str, application: &str) -> Option { ProjectDirs::from_path(PathBuf::from_iter(&[organization, application])) } fn known_folder(folder_id: shtypes::REFKNOWNFOLDERID) -> Option { unsafe { let mut path_ptr: winnt::PWSTR = std::ptr::null_mut(); let result = shlobj::SHGetKnownFolderPath(folder_id, 0, std::ptr::null_mut(), &mut path_ptr); if result == winerror::S_OK { let len = winbase::lstrlenW(path_ptr) as usize; let path = std::slice::from_raw_parts(path_ptr, len); let ostr: std::ffi::OsString = std::os::windows::ffi::OsStringExt::from_wide(path); combaseapi::CoTaskMemFree(path_ptr as *mut winapi::ctypes::c_void); Some(PathBuf::from(ostr)) } else { None } } }directories-1.0.2/.cargo_vcs_info.json0000644000000001120000000000000134010ustar00{ "git": { "sha1": "942bc3fc755e44b8dbc91e94d092b539ffac2297" } }