gix-path-0.10.4/.cargo_vcs_info.json0000644000000001460000000000100126400ustar { "git": { "sha1": "eb6aa8f502314f886fc4ea3d52ab220763968208" }, "path_in_vcs": "gix-path" }gix-path-0.10.4/Cargo.toml0000644000000022510000000000100106350ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.65" name = "gix-path" version = "0.10.4" authors = ["Sebastian Thiel "] include = [ "src/**/*", "LICENSE-*", ] description = "A crate of the gitoxide project dealing paths and their conversions" license = "MIT OR Apache-2.0" repository = "https://github.com/Byron/gitoxide" [lib] doctest = false [dependencies.bstr] version = "1.3.0" features = ["std"] default-features = false [dependencies.gix-trace] version = "^0.1.7" [dependencies.once_cell] version = "1.17.1" [dependencies.thiserror] version = "1.0.26" [dev-dependencies.tempfile] version = "3.3.0" [target."cfg(not(target_family = \"wasm\"))".dependencies.home] version = "0.5.5" gix-path-0.10.4/Cargo.toml.orig000064400000000000000000000012361046102023000143200ustar 00000000000000[package] name = "gix-path" version = "0.10.4" repository = "https://github.com/Byron/gitoxide" license = "MIT OR Apache-2.0" description = "A crate of the gitoxide project dealing paths and their conversions" authors = ["Sebastian Thiel "] edition = "2021" include = ["src/**/*", "LICENSE-*"] rust-version = "1.65" [lib] doctest = false [dependencies] gix-trace = { version = "^0.1.7", path = "../gix-trace" } bstr = { version = "1.3.0", default-features = false, features = ["std"] } thiserror = "1.0.26" once_cell = "1.17.1" [target.'cfg(not(target_family = "wasm"))'.dependencies] home = "0.5.5" [dev-dependencies] tempfile = "3.3.0" gix-path-0.10.4/LICENSE-APACHE000064400000000000000000000247461046102023000133700ustar 00000000000000 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. END OF TERMS AND CONDITIONS Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. gix-path-0.10.4/LICENSE-MIT000064400000000000000000000017771046102023000130770ustar 00000000000000Permission 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. gix-path-0.10.4/src/convert.rs000064400000000000000000000245121046102023000142500ustar 00000000000000use std::{ borrow::Cow, ffi::{OsStr, OsString}, path::{Path, PathBuf}, }; use bstr::{BStr, BString}; #[derive(Debug)] /// The error type returned by [`into_bstr()`] and others may suffer from failed conversions from or to bytes. pub struct Utf8Error; impl std::fmt::Display for Utf8Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Could not convert to UTF8 or from UTF8 due to ill-formed input") } } impl std::error::Error for Utf8Error {} /// Like [`into_bstr()`], but takes `OsStr` as input for a lossless, but fallible, conversion. pub fn os_str_into_bstr(path: &OsStr) -> Result<&BStr, Utf8Error> { let path = try_into_bstr(Cow::Borrowed(path.as_ref()))?; match path { Cow::Borrowed(path) => Ok(path), Cow::Owned(_) => unreachable!("borrowed cows stay borrowed"), } } /// Like [`into_bstr()`], but takes `OsString` as input for a lossless, but fallible, conversion. pub fn os_string_into_bstring(path: OsString) -> Result { let path = try_into_bstr(Cow::Owned(path.into()))?; match path { Cow::Borrowed(_path) => unreachable!("borrowed cows stay borrowed"), Cow::Owned(path) => Ok(path), } } /// Convert the given path either into its raw bytes on unix or its UTF8 encoded counterpart on windows. /// /// On windows, if the source Path contains ill-formed, lone surrogates, the UTF-8 conversion will fail /// causing `Utf8Error` to be returned. pub fn try_into_bstr<'a>(path: impl Into>) -> Result, Utf8Error> { let path = path.into(); let path_str = match path { Cow::Owned(path) => Cow::Owned({ #[cfg(unix)] let p: BString = { use std::os::unix::ffi::OsStringExt; path.into_os_string().into_vec().into() }; #[cfg(target_os = "wasi")] let p: BString = { use std::os::wasi::ffi::OsStringExt; path.into_os_string().into_vec().into() }; #[cfg(not(any(unix, target_os = "wasi")))] let p: BString = path.into_os_string().into_string().map_err(|_| Utf8Error)?.into(); p }), Cow::Borrowed(path) => Cow::Borrowed({ #[cfg(unix)] let p: &BStr = { use std::os::unix::ffi::OsStrExt; path.as_os_str().as_bytes().into() }; #[cfg(target_os = "wasi")] let p: &BStr = { use std::os::wasi::ffi::OsStrExt; path.as_os_str().as_bytes().into() }; #[cfg(not(any(unix, target_os = "wasi")))] let p: &BStr = path.to_str().ok_or(Utf8Error)?.as_bytes().into(); p }), }; Ok(path_str) } /// Similar to [`try_into_bstr()`] but **panics** if malformed surrogates are encountered on windows. pub fn into_bstr<'a>(path: impl Into>) -> Cow<'a, BStr> { try_into_bstr(path).expect("prefix path doesn't contain ill-formed UTF-8") } /// Join `path` to `base` such that they are separated with a `/`, i.e. `base/path`. pub fn join_bstr_unix_pathsep<'a, 'b>(base: impl Into>, path: impl Into<&'b BStr>) -> Cow<'a, BStr> { let mut base = base.into(); if !base.is_empty() && base.last() != Some(&b'/') { base.to_mut().push(b'/'); } base.to_mut().extend_from_slice(path.into()); base } /// Given `input` bytes, produce a `Path` from them ignoring encoding entirely if on unix. /// /// On windows, the input is required to be valid UTF-8, which is guaranteed if we wrote it before. There are some potential /// git versions and windows installation which produce mal-formed UTF-16 if certain emojies are in the path. It's as rare as /// it sounds, but possible. pub fn try_from_byte_slice(input: &[u8]) -> Result<&Path, Utf8Error> { #[cfg(unix)] let p = { use std::os::unix::ffi::OsStrExt; OsStr::from_bytes(input).as_ref() }; #[cfg(target_os = "wasi")] let p: &Path = { use std::os::wasi::ffi::OsStrExt; OsStr::from_bytes(input).as_ref() }; #[cfg(not(any(unix, target_os = "wasi")))] let p = Path::new(std::str::from_utf8(input).map_err(|_| Utf8Error)?); Ok(p) } /// Similar to [`from_byte_slice()`], but takes either borrowed or owned `input`. pub fn try_from_bstr<'a>(input: impl Into>) -> Result, Utf8Error> { let input = input.into(); match input { Cow::Borrowed(input) => try_from_byte_slice(input).map(Cow::Borrowed), Cow::Owned(input) => try_from_bstring(input).map(Cow::Owned), } } /// Similar to [`try_from_bstr()`], but **panics** if malformed surrogates are encountered on windows. pub fn from_bstr<'a>(input: impl Into>) -> Cow<'a, Path> { try_from_bstr(input).expect("prefix path doesn't contain ill-formed UTF-8") } /// Similar to [`try_from_bstr()`], but takes and produces owned data. pub fn try_from_bstring(input: impl Into) -> Result { let input = input.into(); #[cfg(unix)] let p = { use std::os::unix::ffi::OsStringExt; std::ffi::OsString::from_vec(input.into()).into() }; #[cfg(target_os = "wasi")] let p: PathBuf = { use std::os::wasi::ffi::OsStringExt; std::ffi::OsString::from_vec(input.into()).into() }; #[cfg(not(any(unix, target_os = "wasi")))] let p = { use bstr::ByteVec; PathBuf::from( { let v: Vec<_> = input.into(); v } .into_string() .map_err(|_| Utf8Error)?, ) }; Ok(p) } /// Similar to [`try_from_bstring()`], but will **panic** if there is ill-formed UTF-8 in the `input`. pub fn from_bstring(input: impl Into) -> PathBuf { try_from_bstring(input).expect("well-formed UTF-8 on windows") } /// Similar to [`try_from_byte_slice()`], but will **panic** if there is ill-formed UTF-8 in the `input`. pub fn from_byte_slice(input: &[u8]) -> &Path { try_from_byte_slice(input).expect("well-formed UTF-8 on windows") } fn replace<'a>(path: impl Into>, find: u8, replace: u8) -> Cow<'a, BStr> { let path = path.into(); match path { Cow::Owned(mut path) => { for b in path.iter_mut().filter(|b| **b == find) { *b = replace; } path.into() } Cow::Borrowed(path) => { if !path.contains(&find) { return path.into(); } let mut path = path.to_owned(); for b in path.iter_mut().filter(|b| **b == find) { *b = replace; } path.into() } } } /// Assures the given bytes use the native path separator. pub fn to_native_separators<'a>(path: impl Into>) -> Cow<'a, BStr> { #[cfg(not(windows))] let p = to_unix_separators(path); #[cfg(windows)] let p = to_windows_separators(path); p } /// Convert paths with slashes to backslashes on windows and do nothing on unix, but **panics** if malformed surrogates are encountered on windows. pub fn to_native_path_on_windows<'a>(path: impl Into>) -> Cow<'a, std::path::Path> { #[cfg(not(windows))] { crate::from_bstr(path) } #[cfg(windows)] { crate::from_bstr(to_windows_separators(path)) } } /// Replaces windows path separators with slashes, but only do so on windows. pub fn to_unix_separators_on_windows<'a>(path: impl Into>) -> Cow<'a, BStr> { #[cfg(windows)] { replace(path, b'\\', b'/') } #[cfg(not(windows))] { path.into() } } /// Replaces windows path separators with slashes, unconditionally. /// /// **Note** Do not use these and prefer the conditional versions of this method. // TODO: use https://lib.rs/crates/path-slash to handle escapes pub fn to_unix_separators<'a>(path: impl Into>) -> Cow<'a, BStr> { replace(path, b'\\', b'/') } /// Find backslashes and replace them with slashes, which typically resembles a unix path, unconditionally. /// /// **Note** Do not use these and prefer the conditional versions of this method. // TODO: use https://lib.rs/crates/path-slash to handle escapes pub fn to_windows_separators<'a>(path: impl Into>) -> Cow<'a, BStr> { replace(path, b'/', b'\\') } /// Resolve relative components virtually without accessing the file system, e.g. turn `a/./b/c/.././..` into `a`, /// without keeping intermediate `..` and `/a/../b/..` becomes `/`. /// If the input path was relative and ends up being the `current_dir`, `.` is returned instead of the full path to `current_dir`. /// Note that single `.` components as well as duplicate separators are left untouched. /// /// This is particularly useful when manipulating paths that are based on user input, and not resolving intermediate /// symlinks keeps the path similar to what the user provided. If that's not desirable, use `[realpath()][crate::realpath()` /// instead. /// /// Note that we might access the `current_dir` if we run out of path components to pop off, which is expected to be absolute /// as typical return value of `std::env::current_dir()` or `gix_fs::current_dir(…)` when `core.precomposeUnicode` is known. /// As a `current_dir` like `/c` can be exhausted by paths like `../../r`, `None` will be returned to indicate the inability /// to produce a logically consistent path. pub fn normalize<'a>(path: Cow<'a, Path>, current_dir: &Path) -> Option> { use std::path::Component::ParentDir; if !path.components().any(|c| matches!(c, ParentDir)) { return Some(path); } let mut current_dir_opt = Some(current_dir); let was_relative = path.is_relative(); let components = path.components(); let mut path = PathBuf::new(); for component in components { if let ParentDir = component { let path_was_dot = path == Path::new("."); if path.as_os_str().is_empty() || path_was_dot { path.push(current_dir_opt.take()?); } if !path.pop() { return None; } } else { path.push(component) } } if (path.as_os_str().is_empty() || path == current_dir) && was_relative { Cow::Borrowed(Path::new(".")) } else { path.into() } .into() } gix-path-0.10.4/src/env/git.rs000064400000000000000000000101271046102023000141400ustar 00000000000000use std::{ path::Path, process::{Command, Stdio}, }; use bstr::{BStr, BString, ByteSlice}; /// Returns the file that contains git configuration coming with the installation of the `git` file in the current `PATH`, or `None` /// if no `git` executable was found or there were other errors during execution. pub(crate) fn install_config_path() -> Option<&'static BStr> { let _span = gix_trace::detail!("gix_path::git::install_config_path()"); static PATH: once_cell::sync::Lazy> = once_cell::sync::Lazy::new(|| { // Shortcut: in Msys shells this variable is set which allows to deduce the installation directory // so we can save the `git` invocation. #[cfg(windows)] if let Some(mut exec_path) = std::env::var_os("EXEPATH").map(std::path::PathBuf::from) { exec_path.push("etc"); exec_path.push("gitconfig"); return crate::os_string_into_bstring(exec_path.into()).ok(); } let mut cmd = Command::new(if cfg!(windows) { "git.exe" } else { "git" }); cmd.args(["config", "-l", "--show-origin"]) .stdin(Stdio::null()) .stderr(Stdio::null()); gix_trace::debug!(cmd = ?cmd, "invoking git for installation config path"); first_file_from_config_with_origin(cmd.output().ok()?.stdout.as_slice().into()).map(ToOwned::to_owned) }); PATH.as_ref().map(AsRef::as_ref) } fn first_file_from_config_with_origin(source: &BStr) -> Option<&BStr> { let file = source.strip_prefix(b"file:")?; let end_pos = file.find_byte(b'\t')?; file[..end_pos].trim_with(|c| c == '"').as_bstr().into() } /// Given `config_path` as obtained from `install_config_path()`, return the path of the git installation base. pub(crate) fn config_to_base_path(config_path: &Path) -> &Path { config_path .parent() .expect("config file paths always have a file name to pop") } #[cfg(test)] mod tests { use std::path::Path; #[test] fn config_to_base_path() { for (input, expected) in [ ( "/Applications/Xcode.app/Contents/Developer/usr/share/git-core/gitconfig", "/Applications/Xcode.app/Contents/Developer/usr/share/git-core", ), ("C:/git-sdk-64/etc/gitconfig", "C:/git-sdk-64/etc"), ("C:\\ProgramData/Git/config", "C:\\ProgramData/Git"), ("C:/Program Files/Git/etc/gitconfig", "C:/Program Files/Git/etc"), ] { assert_eq!(super::config_to_base_path(Path::new(input)), Path::new(expected)); } } #[test] fn first_file_from_config_with_origin() { let macos = "file:/Applications/Xcode.app/Contents/Developer/usr/share/git-core/gitconfig credential.helper=osxkeychain\nfile:/Users/byron/.gitconfig push.default=simple\n"; let win_msys = "file:C:/git-sdk-64/etc/gitconfig core.symlinks=false\r\nfile:C:/git-sdk-64/etc/gitconfig core.autocrlf=true"; let win_cmd = "file:C:/Program Files/Git/etc/gitconfig diff.astextplain.textconv=astextplain\r\nfile:C:/Program Files/Git/etc/gitconfig filter.lfs.clean=gix-lfs clean -- %f\r\n"; let win_msys_old = "file:\"C:\\ProgramData/Git/config\" diff.astextplain.textconv=astextplain\r\nfile:\"C:\\ProgramData/Git/config\" filter.lfs.clean=git-lfs clean -- %f\r\n"; let linux = "file:/home/parallels/.gitconfig core.excludesfile=~/.gitignore\n"; let bogus = "something unexpected"; let empty = ""; for (source, expected) in [ ( macos, Some("/Applications/Xcode.app/Contents/Developer/usr/share/git-core/gitconfig"), ), (win_msys, Some("C:/git-sdk-64/etc/gitconfig")), (win_msys_old, Some("C:\\ProgramData/Git/config")), (win_cmd, Some("C:/Program Files/Git/etc/gitconfig")), (linux, Some("/home/parallels/.gitconfig")), (bogus, None), (empty, None), ] { assert_eq!( super::first_file_from_config_with_origin(source.into()), expected.map(Into::into) ); } } } gix-path-0.10.4/src/env/mod.rs000064400000000000000000000102241046102023000141320ustar 00000000000000use std::{ ffi::OsString, path::{Path, PathBuf}, }; use bstr::{BString, ByteSlice}; mod git; /// Return the location at which installation specific git configuration file can be found, or `None` /// if the binary could not be executed or its results could not be parsed. /// /// ### Performance /// /// This invokes the git binary which is slow on windows. pub fn installation_config() -> Option<&'static Path> { git::install_config_path().and_then(|p| crate::try_from_byte_slice(p).ok()) } /// Return the location at which git installation specific configuration files are located, or `None` if the binary /// could not be executed or its results could not be parsed. /// /// ### Performance /// /// This invokes the git binary which is slow on windows. pub fn installation_config_prefix() -> Option<&'static Path> { installation_config().map(git::config_to_base_path) } /// Returns the fully qualified path in the *xdg-home* directory (or equivalent in the home dir) to `file`, /// accessing `env_var()` to learn where these bases are. /// /// Note that the `HOME` directory should ultimately come from [`home_dir()`] as it handles windows correctly. /// The same can be achieved by using [`var()`] as `env_var`. pub fn xdg_config(file: &str, env_var: &mut dyn FnMut(&str) -> Option) -> Option { env_var("XDG_CONFIG_HOME") .map(|home| { let mut p = PathBuf::from(home); p.push("git"); p.push(file); p }) .or_else(|| { env_var("HOME").map(|home| { let mut p = PathBuf::from(home); p.push(".config"); p.push("git"); p.push(file); p }) }) } /// Returns the platform dependent system prefix or `None` if it cannot be found (right now only on windows). /// /// ### Performance /// /// On windows, the slowest part is the launch of the `git.exe` executable in the PATH, which only happens when launched /// from outside of the `msys2` shell. /// /// ### When `None` is returned /// /// This happens only windows if the git binary can't be found at all for obtaining its executable path, or if the git binary /// wasn't built with a well-known directory structure or environment. pub fn system_prefix() -> Option<&'static Path> { if cfg!(windows) { static PREFIX: once_cell::sync::Lazy> = once_cell::sync::Lazy::new(|| { if let Some(root) = std::env::var_os("EXEPATH").map(PathBuf::from) { for candidate in ["mingw64", "mingw32"] { let candidate = root.join(candidate); if candidate.is_dir() { return Some(candidate); } } } let mut cmd = std::process::Command::new("git.exe"); cmd.arg("--exec-path").stderr(std::process::Stdio::null()); gix_trace::debug!(cmd = ?cmd, "invoking git to get system prefix/exec path"); let path = cmd.output().ok()?.stdout; let path = BString::new(path) .trim_with(|b| b.is_ascii_whitespace()) .to_path() .ok()? .to_owned(); let one_past_prefix = path.components().enumerate().find_map(|(idx, c)| { matches!(c,std::path::Component::Normal(name) if name.to_str() == Some("libexec")).then_some(idx) })?; Some(path.components().take(one_past_prefix.checked_sub(1)?).collect()) }); PREFIX.as_deref() } else { Path::new("/").into() } } /// Returns `$HOME` or `None` if it cannot be found. #[cfg(target_family = "wasm")] pub fn home_dir() -> Option { std::env::var("HOME").map(PathBuf::from).ok() } #[cfg(not(target_family = "wasm"))] pub use home::home_dir; /// Returns the contents of an environment variable of `name` with some special handling /// for certain environment variables (like `HOME`) for platform compatibility. pub fn var(name: &str) -> Option { if name == "HOME" { home_dir().map(PathBuf::into_os_string) } else { std::env::var_os(name) } } gix-path-0.10.4/src/lib.rs000064400000000000000000000103721046102023000133350ustar 00000000000000//! This crate contains an assortment of utilities to deal with paths and their conversions. //! //! Generally `git` treats paths as bytes, but inherently assumes non-illformed UTF-8 as encoding on windows. Internally, it expects //! slashes to be used as path separators and paths in files must have slashes, with conversions being performed on windows accordingly. //! //!
//! //! ### Research //! //! * **windows** //! - [`dirent.c`](https://github.com/git/git/blob/main/compat/win32/dirent.c#L31:L31) contains all implementation (seemingly) of opening directories and reading their entries, along with all path conversions (UTF-16 for windows). This is done on the fly so git can work with [in UTF-8](https://github.com/git/git/blob/main/compat/win32/dirent.c#L12:L12). //! - mingw [is used for the conversion](https://github.com/git/git/blob/main/compat/mingw.h#L579:L579) and it appears they handle surrogates during the conversion, maybe some sort of non-strict UTF-8 converter? Actually it uses [WideCharToMultiByte](https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-widechartomultibyte) //! under the hood which by now does fail if the UTF-8 would be invalid unicode, i.e. unicode pairs. //! - `OsString` on windows already stores strings as WTF-8, which supports [surrogate pairs](https://unicodebook.readthedocs.io/unicode_encodings.html), //! something that UTF-8 isn't allowed do it for security reasons, after all it's UTF-16 specific and exists only to extend //! the encodable code-points. //! - informative reading on [WTF-8](https://simonsapin.github.io/wtf-8/#motivation) which is the encoding used by Rust //! internally that deals with surrogates and non-wellformed surrogates (those that aren't in pairs). //! * **unix** //! - It uses [opendir](https://man7.org/linux/man-pages/man3/opendir.3.html) and [readdir](https://man7.org/linux/man-pages/man3/readdir.3.html) //! respectively. There is no encoding specified, except that these paths are null-terminated. //! //! ### Learnings //! //! Surrogate pairs are a way to extend the encodable value range in UTF-16 encodings, used primarily on windows and in Javascript. //! For a long time these codepoints used for surrogates, always to be used in pairs, were not assigned, until…they were for rare //! emojies and the likes. The unicode standard does not require surrogates to happen in pairs, even though by now unpaired surrogates //! in UTF-16 are considered ill-formed, which aren't supposed to be converted to UTF-8 for example. //! //! This is the reason we have to deal with `to_string_lossy()`, it's _just_ for that quirk. //! //! This also means the only platform ever eligible to see conversion errors is windows, and there it's only older pre-vista //! windows versions which incorrectly allow ill-formed UTF-16 strings. Newer versions don't perform such conversions anymore, for //! example when going from UTF-16 to UTF-8, they will trigger an error. //! //! ### Conclusions //! //! Since [WideCharToMultiByte](https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-widechartomultibyte) by now is //! fixed (Vista onward) to produce valid UTF-8, lone surrogate codepoints will cause failure, which `git` //! [doesn't care about](https://github.com/git/git/blob/main/compat/win32/dirent.c#L12:L12). //! //! We will, though, which means from now on we can just convert to UTF-8 on windows and bubble up errors where necessary, //! preventing potential mismatched surrogate pairs to ever be saved on disk by gitoxide. //! //! Even though the error only exists on older windows versions, we will represent it in the type system through fallible function calls. //! Callers may `.expect()` on the result to indicate they don't wish to handle this special and rare case. Note that servers should not //! ever get into a code-path which does panic though. //!
#![deny(missing_docs, rust_2018_idioms)] #![forbid(unsafe_code)] /// A dummy type to represent path specs and help finding all spots that take path specs once it is implemented. mod convert; pub use convert::*; mod util; pub use util::is_absolute; /// pub mod realpath; pub use realpath::function::{realpath, realpath_opts}; /// Information about the environment in terms of locations of resources. pub mod env; gix-path-0.10.4/src/realpath.rs000064400000000000000000000102631046102023000143660ustar 00000000000000/// The error returned by [`realpath()`][super::realpath()]. #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("The maximum allowed number {} of symlinks in path is exceeded", .max_symlinks)] MaxSymlinksExceeded { max_symlinks: u8 }, #[error("Cannot resolve symlinks in path with more than {max_symlink_checks} components (takes too long)")] ExcessiveComponentCount { max_symlink_checks: usize }, #[error(transparent)] ReadLink(std::io::Error), #[error(transparent)] CurrentWorkingDir(std::io::Error), #[error("Empty is not a valid path")] EmptyPath, #[error("Ran out of path components while following parent component '..'")] MissingParent, } /// The default amount of symlinks we may follow when resolving a path in [`realpath()`][crate::realpath()]. pub const MAX_SYMLINKS: u8 = 32; pub(crate) mod function { use std::path::{ Component::{CurDir, Normal, ParentDir, Prefix, RootDir}, Path, PathBuf, }; use super::Error; use crate::realpath::MAX_SYMLINKS; /// Check each component of `path` and see if it is a symlink. If so, resolve it. /// Do not fail for non-existing components, but assume these are as is. /// /// If `path` is relative, the current working directory be used to make it absolute. /// Note that the returned path will be verbatim, and repositories with `core.precomposeUnicode` /// set will probably want to precompose the paths unicode. pub fn realpath(path: impl AsRef) -> Result { let path = path.as_ref(); let cwd = path .is_relative() .then(std::env::current_dir) .unwrap_or_else(|| Ok(PathBuf::default())) .map_err(Error::CurrentWorkingDir)?; realpath_opts(path, &cwd, MAX_SYMLINKS) } /// The same as [`realpath()`], but allow to configure `max_symlinks` to configure how many symbolic links we are going to follow. /// This serves to avoid running into cycles or doing unreasonable amounts of work. pub fn realpath_opts(path: &Path, cwd: &Path, max_symlinks: u8) -> Result { if path.as_os_str().is_empty() { return Err(Error::EmptyPath); } let mut real_path = PathBuf::new(); if path.is_relative() { real_path.push(cwd); } let mut num_symlinks = 0; let mut path_backing: PathBuf; let mut components = path.components(); const MAX_SYMLINK_CHECKS: usize = 2048; let mut symlink_checks = 0; while let Some(component) = components.next() { match component { part @ (RootDir | Prefix(_)) => real_path.push(part), CurDir => {} ParentDir => { if !real_path.pop() { return Err(Error::MissingParent); } } Normal(part) => { real_path.push(part); symlink_checks += 1; if real_path.is_symlink() { num_symlinks += 1; if num_symlinks > max_symlinks { return Err(Error::MaxSymlinksExceeded { max_symlinks }); } let mut link_destination = std::fs::read_link(real_path.as_path()).map_err(Error::ReadLink)?; if link_destination.is_absolute() { // pushing absolute path to real_path resets it to the pushed absolute path } else { assert!(real_path.pop(), "we just pushed a component"); } link_destination.extend(components); path_backing = link_destination; components = path_backing.components(); } if symlink_checks > MAX_SYMLINK_CHECKS { return Err(Error::ExcessiveComponentCount { max_symlink_checks: MAX_SYMLINK_CHECKS, }); } } } } Ok(real_path) } } gix-path-0.10.4/src/util.rs000064400000000000000000000005271046102023000135450ustar 00000000000000use std::path::Path; /// return true if `path` is absolute, which depends on the platform but is always true if it starts with a `slash`, hence looks like /// a linux path. pub fn is_absolute(path: impl AsRef) -> bool { let path = path.as_ref(); path.is_absolute() || path.to_str().and_then(|s| s.chars().next()) == Some('/') }