├── .github └── workflows │ ├── check.yml │ ├── scheduled.yml │ └── test.yml ├── .gitignore ├── .rustfmt.toml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── env.rs ├── lib.rs └── windows.rs /.github/workflows/check.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: [main] 4 | pull_request: 5 | name: check 6 | jobs: 7 | fmt: 8 | runs-on: ubuntu-latest 9 | name: stable / fmt 10 | steps: 11 | - uses: actions/checkout@v3 12 | with: 13 | submodules: true 14 | - name: Install stable 15 | uses: actions-rs/toolchain@v1 16 | with: 17 | profile: minimal 18 | toolchain: stable 19 | components: rustfmt 20 | - name: cargo fmt --check 21 | uses: actions-rs/cargo@v1 22 | with: 23 | command: fmt 24 | args: --check 25 | clippy: 26 | runs-on: ubuntu-latest 27 | name: ${{ matrix.toolchain }} / clippy 28 | strategy: 29 | fail-fast: false 30 | matrix: 31 | toolchain: [stable, beta] 32 | steps: 33 | - uses: actions/checkout@v3 34 | with: 35 | submodules: true 36 | - name: Install ${{ matrix.toolchain }} 37 | uses: actions-rs/toolchain@v1 38 | with: 39 | profile: minimal 40 | toolchain: ${{ matrix.toolchain }} 41 | default: true 42 | components: clippy 43 | - name: cargo clippy 44 | uses: actions-rs/clippy-check@v1 45 | with: 46 | token: ${{ secrets.GITHUB_TOKEN }} 47 | doc: 48 | runs-on: ubuntu-latest 49 | name: nightly / doc 50 | steps: 51 | - uses: actions/checkout@v3 52 | with: 53 | submodules: true 54 | - name: Install nightly 55 | uses: actions-rs/toolchain@v1 56 | with: 57 | profile: minimal 58 | toolchain: nightly 59 | default: true 60 | - name: cargo doc 61 | uses: actions-rs/cargo@v1 62 | with: 63 | command: doc 64 | args: --no-deps --all-features 65 | env: 66 | RUSTDOCFLAGS: --cfg docsrs 67 | hack: 68 | runs-on: ubuntu-latest 69 | name: ubuntu / stable / features 70 | steps: 71 | - uses: actions/checkout@v3 72 | with: 73 | submodules: true 74 | - name: Install stable 75 | uses: actions-rs/toolchain@v1 76 | with: 77 | profile: minimal 78 | toolchain: stable 79 | - name: cargo install cargo-hack 80 | uses: taiki-e/install-action@cargo-hack 81 | - name: cargo hack 82 | uses: actions-rs/cargo@v1 83 | with: 84 | command: hack 85 | args: --feature-powerset check --lib --tests 86 | msrv: 87 | runs-on: ubuntu-latest 88 | # we use a matrix here just because env can't be used in job names 89 | # https://docs.github.com/en/actions/learn-github-actions/contexts#context-availability 90 | strategy: 91 | matrix: 92 | msrv: [1.36.0] 93 | name: ubuntu / ${{ matrix.msrv }} 94 | steps: 95 | - uses: actions/checkout@v3 96 | with: 97 | submodules: true 98 | - name: Install ${{ matrix.toolchain }} 99 | uses: actions-rs/toolchain@v1 100 | with: 101 | profile: minimal 102 | toolchain: ${{ matrix.msrv }} 103 | default: true 104 | - name: cargo +${{ matrix.msrv }} check 105 | uses: actions-rs/cargo@v1 106 | with: 107 | command: check 108 | -------------------------------------------------------------------------------- /.github/workflows/scheduled.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: [main] 4 | pull_request: 5 | schedule: 6 | - cron: '7 7 * * *' 7 | name: rolling 8 | jobs: 9 | # https://twitter.com/mycoliza/status/1571295690063753218 10 | nightly: 11 | runs-on: ubuntu-latest 12 | name: ubuntu / nightly 13 | steps: 14 | - uses: actions/checkout@v3 15 | with: 16 | submodules: true 17 | - name: Install nightly 18 | uses: actions-rs/toolchain@v1 19 | with: 20 | profile: minimal 21 | toolchain: nightly 22 | default: true 23 | - name: cargo generate-lockfile 24 | if: hashFiles('Cargo.lock') == '' 25 | uses: actions-rs/cargo@v1 26 | with: 27 | command: generate-lockfile 28 | - name: cargo test --locked 29 | uses: actions-rs/cargo@v1 30 | with: 31 | command: test 32 | args: --locked --all-features --all-targets 33 | # https://twitter.com/alcuadrado/status/1571291687837732873 34 | update: 35 | runs-on: ubuntu-latest 36 | name: ubuntu / beta / updated 37 | # There's no point running this if no Cargo.lock was checked in in the 38 | # first place, since we'd just redo what happened in the regular test job. 39 | # Unfortunately, hashFiles only works in if on steps, so we reepeat it. 40 | # if: hashFiles('Cargo.lock') != '' 41 | steps: 42 | - uses: actions/checkout@v3 43 | with: 44 | submodules: true 45 | - name: Install beta 46 | if: hashFiles('Cargo.lock') != '' 47 | uses: actions-rs/toolchain@v1 48 | with: 49 | profile: minimal 50 | toolchain: beta 51 | default: true 52 | - name: cargo update 53 | if: hashFiles('Cargo.lock') != '' 54 | uses: actions-rs/cargo@v1 55 | with: 56 | command: update 57 | - name: cargo test 58 | if: hashFiles('Cargo.lock') != '' 59 | uses: actions-rs/cargo@v1 60 | with: 61 | command: test 62 | args: --locked --all-features --all-targets 63 | env: 64 | RUSTFLAGS: -D deprecated 65 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: [main] 4 | pull_request: 5 | name: test 6 | jobs: 7 | required: 8 | runs-on: ubuntu-latest 9 | name: ubuntu / ${{ matrix.toolchain }} 10 | strategy: 11 | matrix: 12 | toolchain: [stable, beta] 13 | steps: 14 | - uses: actions/checkout@v3 15 | with: 16 | submodules: true 17 | - name: Install ${{ matrix.toolchain }} 18 | uses: actions-rs/toolchain@v1 19 | with: 20 | profile: minimal 21 | toolchain: ${{ matrix.toolchain }} 22 | default: true 23 | - name: cargo generate-lockfile 24 | if: hashFiles('Cargo.lock') == '' 25 | uses: actions-rs/cargo@v1 26 | with: 27 | command: generate-lockfile 28 | # https://twitter.com/jonhoo/status/1571290371124260865 29 | - name: cargo test --locked 30 | uses: actions-rs/cargo@v1 31 | with: 32 | command: test 33 | args: --locked --all-features --all-targets 34 | minimal: 35 | runs-on: ubuntu-latest 36 | name: ubuntu / stable / minimal-versions 37 | steps: 38 | - uses: actions/checkout@v3 39 | with: 40 | submodules: true 41 | - name: Install stable 42 | uses: actions-rs/toolchain@v1 43 | with: 44 | profile: minimal 45 | toolchain: stable 46 | - name: Install nightly for -Zminimal-versions 47 | uses: actions-rs/toolchain@v1 48 | with: 49 | profile: minimal 50 | toolchain: nightly 51 | - name: cargo update -Zminimal-versions 52 | uses: actions-rs/cargo@v1 53 | with: 54 | command: update 55 | toolchain: nightly 56 | args: -Zminimal-versions 57 | - name: cargo test 58 | uses: actions-rs/cargo@v1 59 | with: 60 | command: test 61 | args: --locked --all-features --all-targets 62 | os-check: 63 | runs-on: ${{ matrix.os }} 64 | name: ${{ matrix.os }} / stable 65 | strategy: 66 | fail-fast: false 67 | matrix: 68 | os: [macos-latest, windows-latest] 69 | steps: 70 | - uses: actions/checkout@v3 71 | with: 72 | submodules: true 73 | - name: Install stable 74 | uses: actions-rs/toolchain@v1 75 | with: 76 | profile: minimal 77 | toolchain: stable 78 | - name: cargo generate-lockfile 79 | if: hashFiles('Cargo.lock') == '' 80 | uses: actions-rs/cargo@v1 81 | with: 82 | command: generate-lockfile 83 | - name: cargo test 84 | uses: actions-rs/cargo@v1 85 | with: 86 | command: test 87 | args: --locked --all-features --all-targets 88 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 120 2 | edition = "2018" 3 | merge_derives = false 4 | use_field_init_shorthand = true 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | 8 | 9 | ## [0.5.4] - 2022-10-10 10 | - Add `_with_env` variants of functions to support in-process threaded tests for 11 | rustup. 12 | 13 | ## [0.5.3] - 2020-01-07 14 | 15 | Use Rust 1.36.0 as minimum Rust version. 16 | 17 | ## [0.5.2] - 2020-01-05 18 | 19 | *YANKED since it cannot be built on Rust 1.36.0* 20 | 21 | ### Changed 22 | - Check for emptiness of `CARGO_HOME` and `RUSTUP_HOME` environment variables. 23 | - Windows: Use `SHGetFolderPath` to replace `GetUserProfileDirectory` syscall. 24 | * Remove `scopeguard` dependency. 25 | 26 | ## [0.5.1] - 2019-10-12 27 | ### Changed 28 | - Disable unnecessary features for `scopeguard`. Thanks @mati865. 29 | 30 | ## [0.5.0] - 2019-08-21 31 | ### Added 32 | - Add `home_dir` implementation for Windows UWP platforms. 33 | 34 | ### Fixed 35 | - Fix `rustup_home` implementation when `RUSTUP_HOME` is an absolute directory. 36 | - Fix `cargo_home` implementation when `CARGO_HOME` is an absolute directory. 37 | 38 | ### Removed 39 | - Remove support for `multirust` folder used in old version of `rustup`. 40 | 41 | [Unreleased]: https://github.com/brson/home/compare/v0.5.4...HEAD 42 | [0.5.4]: https://github.com/brson/home/compare/v0.5.3...v0.5.4 43 | [0.5.3]: https://github.com/brson/home/compare/v0.5.2...v0.5.3 44 | [0.5.2]: https://github.com/brson/home/compare/v0.5.1...v0.5.2 45 | [0.5.1]: https://github.com/brson/home/compare/v0.5.0...v0.5.1 46 | [0.5.0]: https://github.com/brson/home/compare/0.4.2...v0.5.0 47 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "home" 3 | version = "0.5.4" # also update `html_root_url` in `src/lib.rs` 4 | authors = [ "Brian Anderson " ] 5 | documentation = "https://docs.rs/home" 6 | edition = "2018" 7 | include = [ 8 | "/src", 9 | "/Cargo.toml", 10 | "/CHANGELOG", 11 | "/LICENSE-*", 12 | "/README.md", 13 | ] 14 | license = "MIT OR Apache-2.0" 15 | readme = "README.md" 16 | repository = "https://github.com/brson/home" 17 | description = "Shared definitions of home directories" 18 | 19 | [target."cfg(windows)".dependencies.winapi] 20 | version = "0.3" 21 | features = [ 22 | "shlobj", 23 | "std", 24 | "winerror", 25 | ] 26 | -------------------------------------------------------------------------------- /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 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Brian Anderson 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Brian Anderson 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Documentation](https://docs.rs/home/badge.svg)](https://docs.rs/home) 2 | [![Crates.io](https://img.shields.io/crates/v/home.svg)](https://crates.io/crates/home) 3 | 4 | __NOTE:__ This repository has been moved into [rust-lang/cargo]. 5 | 6 | [rust-lang/cargo]: https://github.com/rust-lang/cargo/tree/master/crates/home 7 | 8 | Canonical definitions of `home_dir`, `cargo_home`, and `rustup_home`. 9 | 10 | This provides the definition of `home_dir` used by Cargo and rustup, 11 | as well functions to find the correct value of `CARGO_HOME` and 12 | `RUSTUP_HOME`. 13 | 14 | The definition of `home_dir` provided by the standard library is 15 | incorrect because it considers the `HOME` environment variable on 16 | Windows. This causes surprising situations where a Rust program will 17 | behave differently depending on whether it is run under a Unix 18 | emulation environment like Cygwin or MinGW. Neither Cargo nor rustup 19 | use the standard libraries definition - they use the definition here. 20 | 21 | This crate further provides two functions, `cargo_home` and 22 | `rustup_home`, which are the canonical way to determine the location 23 | that Cargo and rustup store their data. 24 | 25 | See [rust-lang/rust#43321]. 26 | 27 | [rust-lang/rust#43321]: https://github.com/rust-lang/rust/issues/43321 28 | 29 | ## License 30 | 31 | MIT OR Apache-2.0 32 | -------------------------------------------------------------------------------- /src/env.rs: -------------------------------------------------------------------------------- 1 | //! Lower-level utilities for mocking the process environment. 2 | 3 | use std::{ 4 | ffi::OsString, 5 | io, 6 | path::{Path, PathBuf}, 7 | }; 8 | 9 | /// Permits parameterizing the home functions via the _from variants - used for 10 | /// in-process unit testing by rustup. 11 | pub trait Env { 12 | /// Return the path to the the users home dir, or None if any error occurs: 13 | /// see home_inner. 14 | fn home_dir(&self) -> Option; 15 | /// Return the current working directory. 16 | fn current_dir(&self) -> io::Result; 17 | /// Get an environment variable, as per std::env::var_os. 18 | fn var_os(&self, key: &str) -> Option; 19 | } 20 | 21 | /// Implements Env for the OS context, both Unix style and Windows. 22 | /// 23 | /// This is trait permits in-process testing by providing a control point to 24 | /// allow in-process divergence on what is normally process wide state. 25 | /// 26 | /// Implementations should be provided by whatever testing framework the caller 27 | /// is using. Code that is not performing in-process threaded testing requiring 28 | /// isolated rustup/cargo directories does not need this trait or the _from 29 | /// functions. 30 | pub struct OsEnv; 31 | impl Env for OsEnv { 32 | fn home_dir(&self) -> Option { 33 | crate::home_dir_inner() 34 | } 35 | fn current_dir(&self) -> io::Result { 36 | std::env::current_dir() 37 | } 38 | fn var_os(&self, key: &str) -> Option { 39 | std::env::var_os(key) 40 | } 41 | } 42 | 43 | pub const OS_ENV: OsEnv = OsEnv {}; 44 | 45 | /// Returns the path of the current user's home directory from [`Env::home_dir`]. 46 | pub fn home_dir_with_env(env: &dyn Env) -> Option { 47 | env.home_dir() 48 | } 49 | 50 | /// Variant of cargo_home where the environment source is parameterized. This is 51 | /// specifically to support in-process testing scenarios as environment 52 | /// variables and user home metadata are normally process global state. See the 53 | /// [`Env`] trait. 54 | pub fn cargo_home_with_env(env: &dyn Env) -> io::Result { 55 | let cwd = env.current_dir()?; 56 | cargo_home_with_cwd_env(env, &cwd) 57 | } 58 | 59 | /// Variant of cargo_home_with_cwd where the environment source is 60 | /// parameterized. This is specifically to support in-process testing scenarios 61 | /// as environment variables and user home metadata are normally process global 62 | /// state. See the OsEnv trait. 63 | pub fn cargo_home_with_cwd_env(env: &dyn Env, cwd: &Path) -> io::Result { 64 | match env.var_os("CARGO_HOME").filter(|h| !h.is_empty()) { 65 | Some(home) => { 66 | let home = PathBuf::from(home); 67 | if home.is_absolute() { 68 | Ok(home) 69 | } else { 70 | Ok(cwd.join(&home)) 71 | } 72 | } 73 | _ => home_dir_with_env(env) 74 | .map(|p| p.join(".cargo")) 75 | .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "could not find cargo home dir")), 76 | } 77 | } 78 | 79 | /// Variant of cargo_home_with_cwd where the environment source is 80 | /// parameterized. This is specifically to support in-process testing scenarios 81 | /// as environment variables and user home metadata are normally process global 82 | /// state. See the OsEnv trait. 83 | pub fn rustup_home_with_env(env: &dyn Env) -> io::Result { 84 | let cwd = env.current_dir()?; 85 | rustup_home_with_cwd_env(env, &cwd) 86 | } 87 | 88 | /// Variant of cargo_home_with_cwd where the environment source is 89 | /// parameterized. This is specifically to support in-process testing scenarios 90 | /// as environment variables and user home metadata are normally process global 91 | /// state. See the OsEnv trait. 92 | pub fn rustup_home_with_cwd_env(env: &dyn Env, cwd: &Path) -> io::Result { 93 | match env.var_os("RUSTUP_HOME").filter(|h| !h.is_empty()) { 94 | Some(home) => { 95 | let home = PathBuf::from(home); 96 | if home.is_absolute() { 97 | Ok(home) 98 | } else { 99 | Ok(cwd.join(&home)) 100 | } 101 | } 102 | _ => home_dir_with_env(env) 103 | .map(|d| d.join(".rustup")) 104 | .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "could not find rustup home dir")), 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Canonical definitions of `home_dir`, `cargo_home`, and `rustup_home`. 2 | //! 3 | //! This provides the definition of `home_dir` used by Cargo and 4 | //! rustup, as well functions to find the correct value of 5 | //! `CARGO_HOME` and `RUSTUP_HOME`. 6 | //! 7 | //! See also the [`dirs`](https://docs.rs/dirs) crate. 8 | //! 9 | //! _Note that as of 2019/08/06 it appears that cargo uses this crate. And 10 | //! rustup has used this crate since 2019/08/21._ 11 | //! 12 | //! The definition of `home_dir` provided by the standard library is 13 | //! incorrect because it considers the `HOME` environment variable on 14 | //! Windows. This causes surprising situations where a Rust program 15 | //! will behave differently depending on whether it is run under a 16 | //! Unix emulation environment like Cygwin or MinGW. Neither Cargo nor 17 | //! rustup use the standard libraries definition - they use the 18 | //! definition here. 19 | //! 20 | //! This crate further provides two functions, `cargo_home` and 21 | //! `rustup_home`, which are the canonical way to determine the 22 | //! location that Cargo and rustup store their data. 23 | //! 24 | //! See also this [discussion]. 25 | //! 26 | //! [discussion]: https://github.com/rust-lang/rust/pull/46799#issuecomment-361156935 27 | 28 | #![doc(html_root_url = "https://docs.rs/home/0.5.4")] 29 | #![deny(rust_2018_idioms)] 30 | 31 | pub mod env; 32 | 33 | #[cfg(windows)] 34 | mod windows; 35 | 36 | use std::io; 37 | use std::path::{Path, PathBuf}; 38 | 39 | /// Returns the path of the current user's home directory if known. 40 | /// 41 | /// # Unix 42 | /// 43 | /// Returns the value of the `HOME` environment variable if it is set 44 | /// and not equal to the empty string. Otherwise, it tries to determine the 45 | /// home directory by invoking the `getpwuid_r` function on the UID of the 46 | /// current user. 47 | /// 48 | /// # Windows 49 | /// 50 | /// Returns the value of the `USERPROFILE` environment variable if it 51 | /// is set and not equal to the empty string. If both do not exist, 52 | /// [`SHGetFolderPathW`][msdn] is used to return the appropriate path. 53 | /// 54 | /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetfolderpathw 55 | /// 56 | /// # Examples 57 | /// 58 | /// ``` 59 | /// match home::home_dir() { 60 | /// Some(path) => println!("{}", path.display()), 61 | /// None => println!("Impossible to get your home dir!"), 62 | /// } 63 | /// ``` 64 | pub fn home_dir() -> Option { 65 | env::home_dir_with_env(&env::OS_ENV) 66 | } 67 | 68 | #[cfg(windows)] 69 | use windows::home_dir_inner; 70 | 71 | #[cfg(any(unix, target_os = "redox"))] 72 | fn home_dir_inner() -> Option { 73 | #[allow(deprecated)] 74 | std::env::home_dir() 75 | } 76 | 77 | /// Returns the storage directory used by Cargo, often knowns as 78 | /// `.cargo` or `CARGO_HOME`. 79 | /// 80 | /// It returns one of the following values, in this order of 81 | /// preference: 82 | /// 83 | /// - The value of the `CARGO_HOME` environment variable, if it is 84 | /// an absolute path. 85 | /// - The value of the current working directory joined with the value 86 | /// of the `CARGO_HOME` environment variable, if `CARGO_HOME` is a 87 | /// relative directory. 88 | /// - The `.cargo` directory in the user's home directory, as reported 89 | /// by the `home_dir` function. 90 | /// 91 | /// # Errors 92 | /// 93 | /// This function fails if it fails to retrieve the current directory, 94 | /// or if the home directory cannot be determined. 95 | /// 96 | /// # Examples 97 | /// 98 | /// ``` 99 | /// match home::cargo_home() { 100 | /// Ok(path) => println!("{}", path.display()), 101 | /// Err(err) => eprintln!("Cannot get your cargo home dir: {:?}", err), 102 | /// } 103 | /// ``` 104 | pub fn cargo_home() -> io::Result { 105 | env::cargo_home_with_env(&env::OS_ENV) 106 | } 107 | 108 | /// Returns the storage directory used by Cargo within `cwd`. 109 | /// For more details, see [`cargo_home`](fn.cargo_home.html). 110 | pub fn cargo_home_with_cwd(cwd: &Path) -> io::Result { 111 | env::cargo_home_with_cwd_env(&env::OS_ENV, cwd) 112 | } 113 | 114 | /// Returns the storage directory used by rustup, often knowns as 115 | /// `.rustup` or `RUSTUP_HOME`. 116 | /// 117 | /// It returns one of the following values, in this order of 118 | /// preference: 119 | /// 120 | /// - The value of the `RUSTUP_HOME` environment variable, if it is 121 | /// an absolute path. 122 | /// - The value of the current working directory joined with the value 123 | /// of the `RUSTUP_HOME` environment variable, if `RUSTUP_HOME` is a 124 | /// relative directory. 125 | /// - The `.rustup` directory in the user's home directory, as reported 126 | /// by the `home_dir` function. 127 | /// 128 | /// # Errors 129 | /// 130 | /// This function fails if it fails to retrieve the current directory, 131 | /// or if the home directory cannot be determined. 132 | /// 133 | /// # Examples 134 | /// 135 | /// ``` 136 | /// match home::rustup_home() { 137 | /// Ok(path) => println!("{}", path.display()), 138 | /// Err(err) => eprintln!("Cannot get your rustup home dir: {:?}", err), 139 | /// } 140 | /// ``` 141 | pub fn rustup_home() -> io::Result { 142 | env::rustup_home_with_env(&env::OS_ENV) 143 | } 144 | 145 | /// Returns the storage directory used by rustup within `cwd`. 146 | /// For more details, see [`rustup_home`](fn.rustup_home.html). 147 | pub fn rustup_home_with_cwd(cwd: &Path) -> io::Result { 148 | env::rustup_home_with_cwd_env(&env::OS_ENV, cwd) 149 | } 150 | -------------------------------------------------------------------------------- /src/windows.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::ffi::OsString; 3 | use std::os::windows::ffi::OsStringExt; 4 | use std::path::PathBuf; 5 | use std::ptr; 6 | 7 | use winapi::shared::minwindef::MAX_PATH; 8 | use winapi::shared::winerror::S_OK; 9 | use winapi::um::shlobj::{SHGetFolderPathW, CSIDL_PROFILE}; 10 | 11 | pub fn home_dir_inner() -> Option { 12 | env::var_os("USERPROFILE") 13 | .filter(|s| !s.is_empty()) 14 | .map(PathBuf::from) 15 | .or_else(home_dir_crt) 16 | } 17 | 18 | #[cfg(not(target_vendor = "uwp"))] 19 | fn home_dir_crt() -> Option { 20 | unsafe { 21 | let mut path: Vec = Vec::with_capacity(MAX_PATH); 22 | match SHGetFolderPathW(ptr::null_mut(), CSIDL_PROFILE, ptr::null_mut(), 0, path.as_mut_ptr()) { 23 | S_OK => { 24 | let len = wcslen(path.as_ptr()); 25 | path.set_len(len); 26 | let s = OsString::from_wide(&path); 27 | Some(PathBuf::from(s)) 28 | } 29 | _ => None, 30 | } 31 | } 32 | } 33 | 34 | #[cfg(target_vendor = "uwp")] 35 | fn home_dir_crt() -> Option { 36 | None 37 | } 38 | 39 | extern "C" { 40 | fn wcslen(buf: *const u16) -> usize; 41 | } 42 | 43 | #[cfg(not(target_vendor = "uwp"))] 44 | #[cfg(test)] 45 | mod tests { 46 | use super::home_dir_inner; 47 | use std::env; 48 | use std::ops::Deref; 49 | use std::path::{Path, PathBuf}; 50 | 51 | #[test] 52 | fn test_with_without() { 53 | let olduserprofile = env::var_os("USERPROFILE").unwrap(); 54 | 55 | env::remove_var("HOME"); 56 | env::remove_var("USERPROFILE"); 57 | 58 | assert_eq!(home_dir_inner(), Some(PathBuf::from(olduserprofile))); 59 | 60 | let home = Path::new(r"C:\Users\foo tar baz"); 61 | 62 | env::set_var("HOME", home.as_os_str()); 63 | assert_ne!(home_dir_inner().as_ref().map(Deref::deref), Some(home)); 64 | 65 | env::set_var("USERPROFILE", home.as_os_str()); 66 | assert_eq!(home_dir_inner().as_ref().map(Deref::deref), Some(home)); 67 | } 68 | } 69 | --------------------------------------------------------------------------------