gix-path-0.10.21/.cargo_vcs_info.json0000644000000001460000000000100127170ustar { "git": { "sha1": "89fb308f1283b404b55916304f7d161fbf13fe10" }, "path_in_vcs": "gix-path" }gix-path-0.10.21/Cargo.lock0000644000000274130000000000100107000ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "autocfg" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "bitflags" version = "2.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394" [[package]] name = "bstr" version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "234113d19d0d7d613b40e86fb654acf958910802bcceab913a4f9e7cda03b1a4" dependencies = [ "memchr", "serde", ] [[package]] name = "cfg-if" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" [[package]] name = "gix-path" version = "0.10.21" dependencies = [ "bstr", "gix-trace", "gix-validate", "home", "serial_test", "thiserror", "windows", "winreg", ] [[package]] name = "gix-trace" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d35bf1c8c1a883bdbb17ed1fef49be8c751a50dc3a28a2deb4234d826eddb4bb" [[package]] name = "gix-validate" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b1e63a5b516e970a594f870ed4571a8fdcb8a344e7bd407a20db8bd61dbfde4" dependencies = [ "bstr", "thiserror", ] [[package]] name = "home" version = "0.5.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf" dependencies = [ "windows-sys", ] [[package]] name = "libc" version = "0.2.176" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174" [[package]] name = "lock_api" version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765" dependencies = [ "autocfg", "scopeguard", ] [[package]] name = "memchr" version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" [[package]] name = "once_cell" version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] name = "parking_lot" version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13" dependencies = [ "lock_api", "parking_lot_core", ] [[package]] name = "parking_lot_core" version = "0.9.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5" dependencies = [ "cfg-if", "libc", "redox_syscall", "smallvec", "windows-targets", ] [[package]] name = "proc-macro2" version = "1.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1" dependencies = [ "proc-macro2", ] [[package]] name = "redox_syscall" version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5407465600fb0548f1442edf71dd20683c6ed326200ace4b1ef0763521bb3b77" dependencies = [ "bitflags", ] [[package]] name = "scc" version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46e6f046b7fef48e2660c57ed794263155d713de679057f2d0c169bfc6e756cc" dependencies = [ "sdd", ] [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sdd" version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "490dcfcbfef26be6800d11870ff2df8774fa6e86d047e3e8c8a76b25655e41ca" [[package]] name = "serde" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", ] [[package]] name = "serde_core" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serial_test" version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b258109f244e1d6891bf1053a55d63a5cd4f8f4c30cf9a1280989f80e7a1fa9" dependencies = [ "once_cell", "parking_lot", "scc", "serial_test_derive", ] [[package]] name = "serial_test_derive" version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d69265a08751de7844521fd15003ae0a888e035773ba05695c5c759a6f89eef" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "smallvec" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] name = "syn" version = "2.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "thiserror" version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "unicode-ident" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" [[package]] name = "windows" version = "0.62.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49e6c4a1f363c8210c6f77ba24f645c61c6fb941eccf013da691f7e09515b8ac" dependencies = [ "windows-collections", "windows-core", "windows-future", "windows-numerics", ] [[package]] name = "windows-collections" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "123e712f464a8a60ce1a13f4c446d2d43ab06464cb5842ff68f5c71b6fb7852e" dependencies = [ "windows-core", ] [[package]] name = "windows-core" version = "0.62.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6844ee5416b285084d3d3fffd743b925a6c9385455f64f6d4fa3031c4c2749a9" dependencies = [ "windows-implement", "windows-interface", "windows-link", "windows-result", "windows-strings", ] [[package]] name = "windows-future" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68f3db6b24b120200d649cd4811b4947188ed3a8d2626f7075146c5d178a9a4a" dependencies = [ "windows-core", "windows-link", "windows-threading", ] [[package]] name = "windows-implement" version = "0.60.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "edb307e42a74fb6de9bf3a02d9712678b22399c87e6fa869d6dfcd8c1b7754e0" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "windows-interface" version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0abd1ddbc6964ac14db11c7213d6532ef34bd9aa042c2e5935f59d7908b46a5" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "windows-link" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65" [[package]] name = "windows-numerics" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ce3498fe0aba81e62e477408383196b4b0363db5e0c27646f932676283b43d8" dependencies = [ "windows-core", "windows-link", ] [[package]] name = "windows-result" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7084dcc306f89883455a206237404d3eaf961e5bd7e0f312f7c91f57eb44167f" dependencies = [ "windows-link", ] [[package]] name = "windows-strings" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7218c655a553b0bed4426cf54b20d7ba363ef543b52d515b3e48d7fd55318dda" dependencies = [ "windows-link", ] [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows-threading" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab47f085ad6932defa48855254c758cdd0e2f2d48e62a34118a268d8f345e118" dependencies = [ "windows-link", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winreg" version = "0.55.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" dependencies = [ "cfg-if", "windows-sys", ] gix-path-0.10.21/Cargo.toml0000644000000073320000000000100107210ustar # 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.82" name = "gix-path" version = "0.10.21" authors = ["Sebastian Thiel "] build = false include = [ "src/**/*", "LICENSE-*", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A crate of the gitoxide project dealing paths and their conversions" readme = false license = "MIT OR Apache-2.0" repository = "https://github.com/GitoxideLabs/gitoxide" [lib] name = "gix_path" path = "src/lib.rs" doctest = true [dependencies.bstr] version = "1.12.0" features = ["std"] default-features = false [dependencies.gix-trace] version = "^0.1.14" [dependencies.gix-validate] version = "^0.10.1" [dependencies.thiserror] version = "2.0.17" [dev-dependencies.serial_test] version = "3.1.0" default-features = false [target.'cfg(not(target_family = "wasm"))'.dependencies.home] version = "0.5.5" [target."cfg(windows)".dev-dependencies.windows] version = "0.62.1" features = [ "Win32_System_Com", "Win32_System_Threading", "Win32_UI_Shell", ] [target."cfg(windows)".dev-dependencies.winreg] version = "0.55.0" [lints.clippy] bool_to_int_with_if = "allow" borrow_as_ptr = "allow" cast_lossless = "allow" cast_possible_truncation = "allow" cast_possible_wrap = "allow" cast_precision_loss = "allow" cast_sign_loss = "allow" checked_conversions = "allow" copy_iterator = "allow" default_trait_access = "allow" doc_markdown = "allow" empty_docs = "allow" enum_glob_use = "allow" explicit_deref_methods = "allow" explicit_into_iter_loop = "allow" explicit_iter_loop = "allow" filter_map_next = "allow" fn_params_excessive_bools = "allow" from_iter_instead_of_collect = "allow" if_not_else = "allow" ignored_unit_patterns = "allow" implicit_clone = "allow" inconsistent_struct_constructor = "allow" inefficient_to_string = "allow" inline_always = "allow" items_after_statements = "allow" iter_not_returning_iterator = "allow" iter_without_into_iter = "allow" large_enum_variant = "allow" large_stack_arrays = "allow" manual_assert = "allow" manual_is_variant_and = "allow" manual_let_else = "allow" manual_string_new = "allow" many_single_char_names = "allow" match_bool = "allow" match_same_arms = "allow" match_wild_err_arm = "allow" match_wildcard_for_single_variants = "allow" missing_errors_doc = "allow" missing_panics_doc = "allow" module_name_repetitions = "allow" must_use_candidate = "allow" mut_mut = "allow" naive_bytecount = "allow" needless_continue = "allow" needless_for_each = "allow" needless_pass_by_value = "allow" needless_raw_string_hashes = "allow" no_effect_underscore_binding = "allow" option_option = "allow" range_plus_one = "allow" redundant_else = "allow" result_large_err = "allow" return_self_not_must_use = "allow" should_panic_without_expect = "allow" similar_names = "allow" single_match_else = "allow" stable_sort_primitive = "allow" struct_excessive_bools = "allow" struct_field_names = "allow" too_long_first_doc_paragraph = "allow" too_many_lines = "allow" transmute_ptr_to_ptr = "allow" trivially_copy_pass_by_ref = "allow" unnecessary_join = "allow" unnecessary_wraps = "allow" unreadable_literal = "allow" unused_self = "allow" used_underscore_binding = "allow" wildcard_imports = "allow" [lints.clippy.pedantic] level = "warn" priority = -1 [lints.rust] gix-path-0.10.21/Cargo.toml.orig000064400000000000000000000017731046102023000144050ustar 00000000000000lints.workspace = true [package] name = "gix-path" version = "0.10.21" repository = "https://github.com/GitoxideLabs/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.82" [lib] doctest = true [dependencies] gix-trace = { version = "^0.1.14", path = "../gix-trace" } gix-validate = { version = "^0.10.1", path = "../gix-validate" } bstr = { version = "1.12.0", default-features = false, features = ["std"] } thiserror = "2.0.17" [target.'cfg(not(target_family = "wasm"))'.dependencies] home = "0.5.5" [dev-dependencies] gix-testtools = { path = "../tests/tools" } serial_test = { version = "3.1.0", default-features = false } [target.'cfg(windows)'.dev-dependencies] windows = { version = "0.62.1", features = [ "Win32_System_Com", "Win32_System_Threading", "Win32_UI_Shell", ] } winreg = "0.55.0" gix-path-0.10.21/LICENSE-APACHE000064400000000000000000000236761046102023000134500ustar 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 gix-path-0.10.21/LICENSE-MIT000064400000000000000000000017771046102023000131560ustar 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.21/src/convert.rs000064400000000000000000000313131046102023000143240ustar 00000000000000use std::{ borrow::Cow, ffi::{OsStr, OsString}, path::{Component, 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), } } /// Like [`into_bstr()`], but takes `Cow` as input for a lossless, but fallible, conversion. pub fn try_os_str_into_bstr(path: Cow<'_, OsStr>) -> Result, Utf8Error> { match path { Cow::Borrowed(path) => os_str_into_bstr(path).map(Cow::Borrowed), Cow::Owned(path) => os_string_into_bstring(path).map(Cow::Owned), } } /// Convert the given path either into its raw bytes on Unix or its UTF-8 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 installations which produce malformed UTF-16 /// if certain emojis 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 **panic** if unpaired 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)) } } /// Replace 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)] { to_unix_separators(path) } #[cfg(not(windows))] { path.into() } } /// Replace Windows path separators with slashes, which typically resembles a Unix path, unconditionally. /// /// **Note** Do not use these and prefer the conditional versions of this method. pub fn to_unix_separators<'a>(path: impl Into>) -> Cow<'a, BStr> { replace(path, b'\\', b'/') } /// Find slashes and replace them with backslashes, unconditionally. /// /// **Note** Do not use these and prefer the conditional versions of this method. pub fn to_windows_separators<'a>(path: impl Into>) -> Cow<'a, BStr> { replace(path, b'/', b'\\') } /// Resolve relative components virtually, eliminating intermediate `..` without accessing the filesystem. /// /// For example, this turns `a/./b/c/.././..` into `a`, and turns `/a/../b/..` into `/`. /// /// ``` /// # fn main() { /// # use std::path::Path; /// # use gix_path::normalize; /// for (input, expected) in [ /// ("a/./b/c/.././..", "a"), /// ("/a/../b/..", "/"), /// ("/base/a/..", "/base"), /// ("./a/..", "."), /// ("./a/../..", "/"), /// (".///", ".///"), /// ("a//b", "a//b"), /// ("/base/../base", "/base"), /// ] { /// let input = Path::new(input); /// let expected = Path::new(expected); /// assert_eq!(normalize(input.into(), Path::new("/cwd")), Some(expected.into())); /// } /// # } /// ``` /// /// Leading `.` 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 will use 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() } /// Rebuild the worktree-relative `relative_path` to be relative to `prefix`, which is the /// worktree-relative path equivalent to the position of the user, or current working directory. /// /// This is a no-op if `prefix` is empty. /// /// Note that both `relative_path` and `prefix` are assumed to be [normalized](normalize()), and /// failure to do so will lead to incorrect results. /// /// Note that both input paths are expected to be equal in terms of case too, as comparisons will /// be case-sensitive. pub fn relativize_with_prefix<'a>(relative_path: &'a Path, prefix: &Path) -> Cow<'a, Path> { if prefix.as_os_str().is_empty() { return Cow::Borrowed(relative_path); } debug_assert!( relative_path.components().all(|c| matches!(c, Component::Normal(_))), "BUG: all input is expected to be normalized, but relative_path was not" ); debug_assert!( prefix.components().all(|c| matches!(c, Component::Normal(_))), "BUG: all input is expected to be normalized, but prefix was not" ); let mut buf = PathBuf::new(); let mut rpc = relative_path.components().peekable(); let mut equal_thus_far = true; for pcomp in prefix.components() { if equal_thus_far { if let (Component::Normal(pname), Some(Component::Normal(rpname))) = (pcomp, rpc.peek()) { if &pname == rpname { rpc.next(); continue; } else { equal_thus_far = false; } } } buf.push(Component::ParentDir); } buf.extend(rpc); if buf.as_os_str().is_empty() { Cow::Borrowed(Path::new(".")) } else { Cow::Owned(buf) } } gix-path-0.10.21/src/env/auxiliary.rs000064400000000000000000000222671046102023000154530ustar 00000000000000use std::{ ffi::OsString, path::{Path, PathBuf}, }; use std::sync::LazyLock; /// `usr`-like directory component names that MSYS2 may provide, other than for `/usr` itself. /// /// These are the values of the "Prefix" column of the "Environments" and "Legacy Environments" /// tables in the [MSYS2 Environments](https://www.msys2.org/docs/environments/) documentation, /// with the leading `/` separator removed, except that this does not list `usr` itself. /// /// On Windows, we prefer to use `sh` as provided by Git for Windows, when present. To find it, we /// run `git --exec-path` to get a path that is usually `/libexec/git-core` in the Git /// for Windows installation, where `` is something like `mingw64`. It is also acceptable /// to find `sh` in an environment not provided by Git for Windows, such as an independent MSYS2 /// environment in which a `git` package has been installed. However, in an unusual installation, /// or if the user has set a custom value of `GIT_EXEC_PATH`, the output of `git --exec-path` may /// take a form other than `/libexec/git-core`, such that finding shell at a location /// like `../../../bin/sh.exe` relative to it should not be attempted. We lower the risk by /// checking that `` is a plausible value that is not likely to have any other meaning. /// /// This involves two tradeoffs. First, it may be reasonable to find `sh.exe` in an environment /// that is not MSYS2 at all, for which in principle the prefix could be different. But listing /// more prefixes or matching a broad pattern of platform-like strings might be too broad. So only /// prefixes that have been used in MSYS2 are considered. /// /// Second, we don't recognize `usr` itself here, even though it is a plausible prefix. In MSYS2, /// it is the prefix for MSYS2 non-native programs, i.e. those that use `msys-2.0.dll`. But unlike /// the `` names we recognize, `usr` also has an effectively unbounded range of plausible /// meanings on non-Unix systems (for example, what should we take `Z:\usr` to mean?), which might /// occasionally relate to subdirectories with contents controlled by different *user accounts*. /// /// If we start with a `libexec/git-core` directory that we already use and trust, and it is in a /// directory with a name like `mingw64`, we infer that this `mingw64` directory has the expected /// meaning and accordingly infer that its `usr` sibling, if present, is acceptable to treat as /// though it is a first-level directory inside an MSYS2-like tree. So we are willing to traverse /// down to `usr/sh.exe` and try to use it. But if the `libexec/git-core` we use and trust is in a /// directory named `usr`, that `usr` directory may still not have the meaning we expect of `usr`. /// /// Conditions for a privilege escalation attack or other serious malfunction seem far-fetched. If /// further research finds the risk is low enough, `usr` may be added. But for now it is omitted. const MSYS_USR_VARIANTS: &[&str] = &["mingw64", "mingw32", "clangarm64", "clang64", "clang32", "ucrt64"]; /// Find a Git for Windows installation directory based on `git --exec-path` output. /// /// Currently this is used only for finding the path to an `sh.exe` associated with Git. This is /// separate from `installation_config()` and `installation_config_prefix()` in `gix_path::env`. /// This is *not* suitable for finding the highest-scoped configuration file, because that could be /// installed in an unusual place, or customized via `GIT_CONFIG_SYSTEM` or `GIT_CONFIG_NOSYSTEM`, /// all of which `installation_config()` should reflect. Likewise, `installation_config_prefix()` /// has strong uses, such as to find a directory inside `ProgramData` containing configuration. /// But it is possible that some marginal uses of `installation_config_prefix()`, if they do not /// really relate to configuration, could be replaced with `git_for_windows_root()` in the future. fn git_for_windows_root() -> Option<&'static Path> { static GIT_ROOT: LazyLock> = LazyLock::new(|| { super::core_dir() .filter(|core| { // Only use this if the directory structure resembles a Git installation. This // accepts installations of common types that are not broken when `GIT_EXEC_PATH` // is unset, as well as values of `GIT_EXEC_PATH` that are likely to be usable. core.is_absolute() && core.ends_with("libexec/git-core") }) .and_then(|core| core.ancestors().nth(2)) .filter(|prefix| { // Only use `libexec/git-core` from inside something `usr`-like, such as `mingw64`. // See `MSYS_USR_VARIANTS` for details and the rationale for this restriction. MSYS_USR_VARIANTS.iter().any(|name| prefix.ends_with(name)) }) .and_then(|prefix| prefix.parent()) .map(Into::into) }); GIT_ROOT.as_deref() } /// `bin` directory paths to try relative to the root of a Git for Windows or MSYS2 installation. /// /// These are ordered so that a shim is preferred over a non-shim when they are tried in order. const BIN_DIR_FRAGMENTS: &[&str] = &["bin", "usr/bin"]; /// Obtain a path to an executable command on Windows associated with Git, if one can be found. /// /// The resulting path uses only `/` separators so long as the path obtained from `git --exec-path` /// does, which is the case unless it is overridden by setting `GIT_EXEC_PATH` to an unusual value. /// /// This is currently only used (and only heavily exercised in tests) for finding `sh.exe`. It may /// be used to find other executables in the future, but may need adjustment. In particular, /// depending on desired semantics, it should possibly also check a `cmd` directory; directories /// like `/bin`, for any applicable variants (such as `mingw64`); and `super::core_dir()` /// itself, which it could safely check even if its value is not safe for inferring other paths. fn find_git_associated_windows_executable(stem: &str) -> Option { let git_root = git_for_windows_root()?; BIN_DIR_FRAGMENTS .iter() .map(|bin_dir_fragment| { // Perform explicit raw concatenation with `/` to avoid introducing any `\` separators. let mut raw_path = OsString::from(git_root); raw_path.push("/"); raw_path.push(bin_dir_fragment); raw_path.push("/"); raw_path.push(stem); raw_path.push(".exe"); raw_path }) .find(|raw_path| Path::new(raw_path).is_file()) } /// Like `find_associated_windows_executable`, but if not found, fall back to a simple filename. pub(super) fn find_git_associated_windows_executable_with_fallback(stem: &str) -> OsString { find_git_associated_windows_executable(stem).unwrap_or_else(|| { let mut raw_path = OsString::from(stem); raw_path.push(".exe"); raw_path }) } #[cfg(test)] mod tests { use std::path::Path; /// Some commands with `.exe` files in `bin` and `usr/bin` that should be found. /// /// Tests are expected to run with a full Git for Windows installation (not MinGit). const SHOULD_FIND: &[&str] = &[ "sh", "bash", "dash", "diff", "tar", "less", "sed", "awk", "perl", "cygpath", ]; /// Shouldn't find anything nonexistent, or only in PATH or in `bin`s we don't mean to search. /// /// If dirs like `mingsw64/bin` are added, `git-credential-manager` should be moved to `SHOULD_FIND`. /// Likewise, if `super::core_dir()` is added, `git-daemon` should be moved to `SHOULD_FIND`. const SHOULD_NOT_FIND: &[&str] = &[ "nonexistent-command", "cmd", "powershell", "explorer", "git-credential-manager", "git-daemon", ]; #[test] #[cfg_attr(not(windows), ignore = "only meaningful on Windows")] fn find_git_associated_windows_executable() { for stem in SHOULD_FIND { let path = super::find_git_associated_windows_executable(stem); assert!(path.is_some(), "should find {stem:?}"); } } #[test] #[cfg_attr(not(windows), ignore = "only meaningful on Windows")] fn find_git_associated_windows_executable_no_extra() { for stem in SHOULD_NOT_FIND { let path = super::find_git_associated_windows_executable(stem); assert_eq!(path, None, "should not find {stem:?}"); } } #[test] #[cfg_attr(not(windows), ignore = "only meaningful on Windows")] fn find_git_associated_windows_executable_with_fallback() { for stem in SHOULD_FIND { let path = super::find_git_associated_windows_executable_with_fallback(stem); assert!(Path::new(&path).is_absolute(), "should find {stem:?}"); } } #[test] #[cfg_attr(not(windows), ignore = "only meaningful on Windows")] fn find_git_associated_windows_executable_with_fallback_falls_back() { for stem in SHOULD_NOT_FIND { let path = super::find_git_associated_windows_executable_with_fallback(stem) .to_str() .expect("valid Unicode") .to_owned(); assert_eq!(path, format!("{stem}.exe"), "should fall back for {stem:?}"); } } } gix-path-0.10.21/src/env/git/mod.rs000064400000000000000000000240571046102023000150050ustar 00000000000000use std::{ env, path::{Path, PathBuf}, process::{Command, Stdio}, }; use bstr::{BStr, BString, ByteSlice}; use std::sync::LazyLock; /// Other places to find Git in. #[cfg(windows)] pub(super) static ALTERNATIVE_LOCATIONS: LazyLock> = LazyLock::new(|| locations_under_program_files(|key| std::env::var_os(key))); #[cfg(not(windows))] pub(super) static ALTERNATIVE_LOCATIONS: LazyLock> = LazyLock::new(Vec::new); #[cfg(windows)] fn locations_under_program_files(var_os_func: F) -> Vec where F: Fn(&str) -> Option, { // Should give a 64-bit program files path from a 32-bit or 64-bit process on a 64-bit system. let varname_64bit = "ProgramW6432"; // Should give a 32-bit program files path from a 32-bit or 64-bit process on a 64-bit system. // This variable is x86-specific, but neither Git nor Rust target 32-bit ARM on Windows. let varname_x86 = "ProgramFiles(x86)"; // Should give a 32-bit program files path on a 32-bit system. We also check this on a 64-bit // system, even though it *should* equal the process's architecture-specific variable, so that // we cover the case of a parent process that passes down an overly sanitized environment that // lacks the architecture-specific variable. On a 64-bit system, because parent and child // processes' architectures can be different, Windows sets the child's `ProgramFiles` variable // from whichever of the `ProgramW6432` or `ProgramFiles(x86)` variable corresponds to the // child's architecture. Only if the parent does not pass down the architecture-specific // variable corresponding to the child's architecture does the child receive its `ProgramFiles` // variable from `ProgramFiles` as passed down by the parent. But this behavior is not well // known. So the situation where a process only passes down `ProgramFiles` sometimes happens. let varname_current = "ProgramFiles"; // Should give the user's local application data path on any system. If a user program files // directory exists for this user, then it should be the `Programs` subdirectory of this. If it // doesn't exist, or on a future or extremely strangely configured Windows setup where it is // somewhere else, it should still be safe to attempt to use it. (This differs from global // program files paths, which are usually subdirectories of the root of the system drive, which // limited user accounts can usually create their own arbitrarily named directories inside.) let varname_user_appdata_local = "LocalAppData"; // 64-bit relative bin dirs. So far, this is always `mingw64` or `clangarm64`, not `urct64` or // `clang64`. We check `clangarm64` before `mingw64`, because in the strange case that both are // available, we don't want to skip over a native ARM64 executable for an emulated x86_64 one. let suffixes_64 = &[r"Git\clangarm64\bin", r"Git\mingw64\bin"][..]; // 32-bit relative bin dirs. So far, this is only ever `mingw32`, not `clang32`. let suffixes_32 = &[r"Git\mingw32\bin"][..]; // Whichever of the 64-bit or 32-bit relative bin better matches this process's architecture. // Unlike the system architecture, the process architecture is always known at compile time. #[cfg(target_pointer_width = "64")] let suffixes_current = suffixes_64; #[cfg(target_pointer_width = "32")] let suffixes_current = suffixes_32; // Bin dirs relative to a user's local application data directory. We try each architecture. let suffixes_user = &[ r"Programs\Git\clangarm64\bin", r"Programs\Git\mingw64\bin", r"Programs\Git\mingw32\bin", ][..]; let rules = [ (varname_user_appdata_local, suffixes_user), (varname_64bit, suffixes_64), (varname_x86, suffixes_32), (varname_current, suffixes_current), ]; let mut locations = vec![]; for (varname, suffixes) in rules { let Some(program_files_dir) = var_os_func(varname).map(PathBuf::from).filter(|p| p.is_absolute()) else { // The environment variable is unset or somehow not an absolute path (e.g. an empty string). continue; }; for suffix in suffixes { let location = program_files_dir.join(suffix); if !locations.contains(&location) { locations.push(location); } } } locations } #[cfg(windows)] pub(super) const EXE_NAME: &str = "git.exe"; #[cfg(not(windows))] pub(super) const EXE_NAME: &str = "git"; /// Invoke the git executable to obtain the origin configuration, which is cached and returned. /// /// The git executable is the one found in `PATH` or an alternative location. pub(super) static GIT_HIGHEST_SCOPE_CONFIG_PATH: LazyLock> = LazyLock::new(exe_info); // There are a number of ways to refer to the null device on Windows, but they are not all equally // well supported. Git for Windows rejects `\\.\NUL` and `\\.\nul`. On Windows 11 ARM64 (and maybe // some others), it rejects even the legacy name `NUL`, when capitalized. But it always accepts the // lower-case `nul`, handling it in various path checks, some of which are done case-sensitively. #[cfg(windows)] const NULL_DEVICE: &str = "nul"; #[cfg(not(windows))] const NULL_DEVICE: &str = "/dev/null"; fn exe_info() -> Option { let mut cmd = git_cmd(EXE_NAME.into()); gix_trace::debug!(cmd = ?cmd, "invoking git for installation config path"); let cmd_output = match cmd.output() { Ok(out) => out.stdout, #[cfg(windows)] Err(err) if err.kind() == std::io::ErrorKind::NotFound => { let executable = ALTERNATIVE_LOCATIONS.iter().find_map(|prefix| { let candidate = prefix.join(EXE_NAME); candidate.is_file().then_some(candidate) })?; gix_trace::debug!(cmd = ?cmd, "invoking git for installation config path in alternate location"); git_cmd(executable).output().ok()?.stdout } Err(_) => return None, }; first_file_from_config_with_origin(cmd_output.as_slice().into()).map(ToOwned::to_owned) } fn git_cmd(executable: PathBuf) -> Command { let mut cmd = Command::new(executable); #[cfg(windows)] { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x08000000; cmd.creation_flags(CREATE_NO_WINDOW); } // We will try to run `git` from a location fairly high in the filesystem, in the hope it may // be faster if we are deeply nested, on a slow disk, or in a directory that has been deleted. let cwd = if cfg!(windows) { // We try the Windows directory (usually `C:\Windows`) first. It is given by `SystemRoot`, // except in rare cases where our own parent has not passed down that environment variable. env::var_os("SystemRoot") .or_else(|| env::var_os("windir")) .map(PathBuf::from) .filter(|p| p.is_absolute()) .unwrap_or_else(env::temp_dir) } else { "/".into() }; // Git 2.8.0 and higher support `--show-origin`. The `-l`, `-z`, and `--name-only` options were // supported even before that. In contrast, `--show-scope` was introduced later, in Git 2.26.0. // Low versions of Git are still sometimes used, and this is sometimes reasonable because // downstream distributions often backport security patches without adding most new features. // So for now, we forgo the convenience of `--show-scope` for greater backward compatibility. // // Separately from that, we can't use `--system` here, because scopes treated higher than the // system scope are possible. This commonly happens on macOS with Apple Git, where the config // file under `/Library` or `/Applications` is shown as an "unknown" scope but takes precedence // over the system scope. Although `GIT_CONFIG_NOSYSTEM` suppresses this scope along with the // system scope, passing `--system` selects only the system scope and not this "unknown" scope. cmd.args(["config", "-lz", "--show-origin", "--name-only"]) .current_dir(cwd) .env_remove("GIT_CONFIG") .env_remove("GIT_DISCOVERY_ACROSS_FILESYSTEM") .env_remove("GIT_OBJECT_DIRECTORY") .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES") .env_remove("GIT_COMMON_DIR") .env("GIT_DIR", NULL_DEVICE) // Avoid getting local-scope config. .env("GIT_WORK_TREE", NULL_DEVICE) // Avoid confusion when debugging. .stdin(Stdio::null()) .stderr(Stdio::null()); cmd } 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'\0')?; file[..end_pos].as_bstr().into() } /// Try to find the file that contains Git configuration coming with the Git installation. /// /// This returns the configuration associated with the `git` executable found in the current `PATH` /// or an alternative location, or `None` if no `git` executable was found or there were other /// errors during execution. pub(super) fn install_config_path() -> Option<&'static BStr> { let _span = gix_trace::detail!("gix_path::git::install_config_path()"); static PATH: LazyLock> = LazyLock::new(|| { // Shortcut: Specifically in Git for Windows 'Git Bash' shells, this variable is set. It // may let us 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(PathBuf::from) { exec_path.push("etc"); exec_path.push("gitconfig"); return crate::os_string_into_bstring(exec_path.into()).ok(); } GIT_HIGHEST_SCOPE_CONFIG_PATH.clone() }); PATH.as_ref().map(AsRef::as_ref) } /// Given `config_path` as obtained from `install_config_path()`, return the path of the git installation base. pub(super) 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; gix-path-0.10.21/src/env/git/tests.rs000064400000000000000000001153171046102023000153700ustar 00000000000000use std::path::Path; #[cfg(windows)] mod locations { use std::{ ffi::{c_void, OsStr, OsString}, io::ErrorKind, os::windows::ffi::OsStringExt, path::{Path, PathBuf}, }; use windows::{ core::{Result as WindowsResult, BOOL, GUID, PWSTR}, Win32::{ System::{ Com::CoTaskMemFree, Threading::{GetCurrentProcess, IsWow64Process}, }, UI::Shell::{ FOLDERID_LocalAppData, FOLDERID_ProgramFiles, FOLDERID_ProgramFilesX86, FOLDERID_UserProgramFiles, SHGetKnownFolderPath, KF_FLAG_DEFAULT, KF_FLAG_DONT_VERIFY, KNOWN_FOLDER_FLAG, }, }, }; use winreg::{ enums::{HKEY_LOCAL_MACHINE, KEY_QUERY_VALUE}, RegKey, }; macro_rules! var_os_stub { { $($name:expr => $value:expr),* $(,)? } => { |key| { match key { $( $name => Some(OsString::from($value)), )* _ => None, } } } } macro_rules! locations_from { ($($name:expr => $value:expr),* $(,)?) => { super::super::locations_under_program_files(var_os_stub! { $( $name => $value, )* }) } } macro_rules! pathbuf_vec { [$($path:expr),* $(,)?] => { vec![$( PathBuf::from($path), )*] } } #[test] fn locations_under_program_files_no_vars() { assert_eq!(locations_from!(), Vec::::new()); } #[test] fn locations_under_program_files_global_only_ordinary_values_current_var_only() { assert_eq!( locations_from!( "ProgramFiles" => r"C:\Program Files", ), if cfg!(target_pointer_width = "64") { pathbuf_vec![ r"C:\Program Files\Git\clangarm64\bin", r"C:\Program Files\Git\mingw64\bin", ] } else { pathbuf_vec![r"C:\Program Files\Git\mingw32\bin"] }, ); } #[test] fn locations_under_program_files_global_only_ordinary_values_all_vars() { assert_eq!( locations_from!( "ProgramFiles" => { if cfg!(target_pointer_width = "64") { r"C:\Program Files" } else { r"C:\Program Files (x86)" } }, "ProgramFiles(x86)" => r"C:\Program Files (x86)", "ProgramW6432" => r"C:\Program Files", ), pathbuf_vec![ r"C:\Program Files\Git\clangarm64\bin", r"C:\Program Files\Git\mingw64\bin", r"C:\Program Files (x86)\Git\mingw32\bin", ], ); } #[test] fn locations_under_program_files_global_only_strange_values_all_vars_distinct() { assert_eq!( locations_from!( "ProgramFiles" => r"X:\cur\rent", "ProgramFiles(x86)" => r"Y:\nar\row", "ProgramW6432" => r"Z:\wi\de", ), if cfg!(target_pointer_width = "64") { pathbuf_vec![ r"Z:\wi\de\Git\clangarm64\bin", r"Z:\wi\de\Git\mingw64\bin", r"Y:\nar\row\Git\mingw32\bin", r"X:\cur\rent\Git\clangarm64\bin", r"X:\cur\rent\Git\mingw64\bin", ] } else { pathbuf_vec![ r"Z:\wi\de\Git\clangarm64\bin", r"Z:\wi\de\Git\mingw64\bin", r"Y:\nar\row\Git\mingw32\bin", r"X:\cur\rent\Git\mingw32\bin", ] }, ); } #[test] fn locations_under_program_files_global_only_strange_values_64bit_var_only() { assert_eq!( locations_from!( "ProgramW6432" => r"Z:\wi\de", ), pathbuf_vec![r"Z:\wi\de\Git\clangarm64\bin", r"Z:\wi\de\Git\mingw64\bin"], ); } #[test] fn locations_under_program_files_global_only_strange_values_all_vars_path_cruft() { assert_eq!( locations_from!( "ProgramFiles" => r"Z:/wi//de/", "ProgramFiles(x86)" => r"Y:/\nar\/row", "ProgramW6432" => r"Z:\wi\.\de", ), if cfg!(target_pointer_width = "64") { pathbuf_vec![ r"Z:\wi\de\Git\clangarm64\bin", r"Z:\wi\de\Git\mingw64\bin", r"Y:\nar\row\Git\mingw32\bin", ] } else { pathbuf_vec![ r"Z:\wi\de\Git\clangarm64\bin", r"Z:\wi\de\Git\mingw64\bin", r"Y:\nar\row\Git\mingw32\bin", r"Z:\wi\de\Git\mingw32\bin", ] }, ); } #[test] fn locations_under_program_files_global_only_strange_values_some_relative() { assert_eq!( locations_from!( "ProgramFiles" => r"foo\bar", "ProgramFiles(x86)" => r"\\host\share\subdir", "ProgramW6432" => r"", ), pathbuf_vec![r"\\host\share\subdir\Git\mingw32\bin"], ); } #[test] fn locations_under_program_files_local_only_ordinary_value() { assert_eq!( locations_from!( "LocalAppData" => r"C:\Users\alice\AppData\Local", ), pathbuf_vec![ r"C:\Users\alice\AppData\Local\Programs\Git\clangarm64\bin", r"C:\Users\alice\AppData\Local\Programs\Git\mingw64\bin", r"C:\Users\alice\AppData\Local\Programs\Git\mingw32\bin", ], ); } #[test] fn locations_under_program_files_local_only_strange_value_path_cruft() { assert_eq!( locations_from!( "LocalAppData" => r"\\.\Q:\Documents and Settings/bob\/weird\.\sub//dir", ), pathbuf_vec![ r"\\.\Q:\Documents and Settings\bob\weird\sub\dir\Programs\Git\clangarm64\bin", r"\\.\Q:\Documents and Settings\bob\weird\sub\dir\Programs\Git\mingw64\bin", r"\\.\Q:\Documents and Settings\bob\weird\sub\dir\Programs\Git\mingw32\bin", ], ); } #[test] fn locations_under_program_files_local_only_strange_value_empty() { assert_eq!( locations_from!( "LocalAppData" => "", ), Vec::::new(), ); } #[test] fn locations_under_program_files_local_only_strange_value_relative_nonempty() { assert_eq!( locations_from!( "LocalAppData" => r"AppData\Local", ), Vec::::new(), ); } #[test] fn locations_under_program_files_local_and_global_ordinary_values_limited_vars() { assert_eq!( locations_from!( "LocalAppData" => r"C:\Users\alice\AppData\Local", "ProgramFiles" => r"C:\Program Files", ), if cfg!(target_pointer_width = "64") { pathbuf_vec![ r"C:\Users\alice\AppData\Local\Programs\Git\clangarm64\bin", r"C:\Users\alice\AppData\Local\Programs\Git\mingw64\bin", r"C:\Users\alice\AppData\Local\Programs\Git\mingw32\bin", r"C:\Program Files\Git\clangarm64\bin", r"C:\Program Files\Git\mingw64\bin", ] } else { pathbuf_vec![ r"C:\Users\alice\AppData\Local\Programs\Git\clangarm64\bin", r"C:\Users\alice\AppData\Local\Programs\Git\mingw64\bin", r"C:\Users\alice\AppData\Local\Programs\Git\mingw32\bin", r"C:\Program Files\Git\mingw32\bin", ] }, ); } #[test] fn locations_under_program_files_local_and_global_ordinary_values_all_vars() { assert_eq!( locations_from!( "LocalAppData" => r"C:\Users\bob\AppData\Local", "ProgramFiles" => { if cfg!(target_pointer_width = "64") { r"C:\Program Files" } else { r"C:\Program Files (x86)" } }, "ProgramFiles(x86)" => r"C:\Program Files (x86)", "ProgramW6432" => r"C:\Program Files", ), pathbuf_vec![ r"C:\Users\bob\AppData\Local\Programs\Git\clangarm64\bin", r"C:\Users\bob\AppData\Local\Programs\Git\mingw64\bin", r"C:\Users\bob\AppData\Local\Programs\Git\mingw32\bin", r"C:\Program Files\Git\clangarm64\bin", r"C:\Program Files\Git\mingw64\bin", r"C:\Program Files (x86)\Git\mingw32\bin", ], ); } #[test] fn locations_under_program_files_local_and_global_strange_values_all_vars_distinct() { assert_eq!( locations_from!( "LocalAppData" => r"W:\us\er", "ProgramFiles" => r"X:\cur\rent", "ProgramFiles(x86)" => r"Y:\nar\row", "ProgramW6432" => r"Z:\wi\de", ), if cfg!(target_pointer_width = "64") { pathbuf_vec![ r"W:\us\er\Programs\Git\clangarm64\bin", r"W:\us\er\Programs\Git\mingw64\bin", r"W:\us\er\Programs\Git\mingw32\bin", r"Z:\wi\de\Git\clangarm64\bin", r"Z:\wi\de\Git\mingw64\bin", r"Y:\nar\row\Git\mingw32\bin", r"X:\cur\rent\Git\clangarm64\bin", r"X:\cur\rent\Git\mingw64\bin", ] } else { pathbuf_vec![ r"W:\us\er\Programs\Git\clangarm64\bin", r"W:\us\er\Programs\Git\mingw64\bin", r"W:\us\er\Programs\Git\mingw32\bin", r"Z:\wi\de\Git\clangarm64\bin", r"Z:\wi\de\Git\mingw64\bin", r"Y:\nar\row\Git\mingw32\bin", r"X:\cur\rent\Git\mingw32\bin", ] }, ); } #[test] fn locations_under_program_files_local_and_global_strange_values_limited_64bit_var() { assert_eq!( locations_from!( "LocalAppData" => r"W:\us\er", "ProgramW6432" => r"Z:\wi\de", ), pathbuf_vec![ r"W:\us\er\Programs\Git\clangarm64\bin", r"W:\us\er\Programs\Git\mingw64\bin", r"W:\us\er\Programs\Git\mingw32\bin", r"Z:\wi\de\Git\clangarm64\bin", r"Z:\wi\de\Git\mingw64\bin", ], ); } #[test] fn locations_under_program_files_local_and_global_strange_values_crufty_cross_clash() { assert_eq!( locations_from!( "LocalAppData" => r"Y:\nar\row", "ProgramFiles" => r"Z:/wi//de/", "ProgramFiles(x86)" => r"Y:/\nar/row\Programs", "ProgramW6432" => r"Z:\wi\.\de", ), if cfg!(target_pointer_width = "64") { pathbuf_vec![ r"Y:\nar\row\Programs\Git\clangarm64\bin", r"Y:\nar\row\Programs\Git\mingw64\bin", r"Y:\nar\row\Programs\Git\mingw32\bin", r"Z:\wi\de\Git\clangarm64\bin", r"Z:\wi\de\Git\mingw64\bin", ] } else { pathbuf_vec![ r"Y:\nar\row\Programs\Git\clangarm64\bin", r"Y:\nar\row\Programs\Git\mingw64\bin", r"Y:\nar\row\Programs\Git\mingw32\bin", r"Z:\wi\de\Git\clangarm64\bin", r"Z:\wi\de\Git\mingw64\bin", r"Z:\wi\de\Git\mingw32\bin", ] }, ); } #[test] fn locations_under_program_files_local_and_global_strange_values_some_relative() { assert_eq!( locations_from!( "LocalAppData" => "dir", "ProgramFiles" => r"foo\bar", "ProgramFiles(x86)" => r"\\host\share\subdir", "ProgramW6432" => r"", ), pathbuf_vec![r"\\host\share\subdir\Git\mingw32\bin"], ); } /// Owner of a null-terminated `PWSTR` that must be freed with `CoTaskMemFree`. struct CoStr { pwstr: PWSTR, } impl CoStr { /// SAFETY: The caller must ensure `pwstr` is a non-null pointer to the beginning of a /// null-terminated (zero-codepoint-terminated) wide string releasable by `CoTaskMemFree`. unsafe fn new(pwstr: PWSTR) -> Self { Self { pwstr } } fn to_os_string(&self) -> OsString { // SAFETY: We know `pwstr` is derefrenceable and the string is null-terminated. let wide = unsafe { self.pwstr.as_wide() }; OsString::from_wide(wide) } } impl Drop for CoStr { fn drop(&mut self) { // SAFETY: `pwstr` is allowed to be passed to `CoTaskMemFree`. (We happen to know it's // non-null, but `CoTaskMemFree` permits null as well, so the cast is doubly safe.) unsafe { CoTaskMemFree(Some(self.pwstr.as_ptr().cast::())) }; } } fn get_known_folder_path_with_flag(id: GUID, flag: KNOWN_FOLDER_FLAG) -> WindowsResult { // SAFETY: `SHGetKnownFolderPath` in the `windows` crate wraps the API function and returns // a non-null pointer to a null-terminated wide string, or an error, not a null pointer. // As in the wrapped API function, the pointer it returns can be passed to `CoTaskMemFree`. let costr = unsafe { CoStr::new(SHGetKnownFolderPath(&id, flag, None)?) }; Ok(PathBuf::from(costr.to_os_string())) } #[derive(Clone, Copy, Debug)] enum PlatformBitness { Is32on32, Is32on64, Is64on64, } impl PlatformBitness { fn current() -> WindowsResult { // Ordinarily, we would check the target pointer width first to avoid doing extra work, // because if this is a 64-bit executable then the operating system is 64-bit. But this // is for the test suite, and doing it this way allows problems to be caught earlier if // a change made on a 64-bit development machine breaks the IsWow64Process() call. let mut wow64process = BOOL::default(); unsafe { // SAFETY: `GetCurrentProcess` always succeeds, and the handle it returns is a // valid process handle to pass to `IsWow64Process`. IsWow64Process(GetCurrentProcess(), &mut wow64process)?; } let platform_bitness = if wow64process.as_bool() { Self::Is32on64 } else if cfg!(target_pointer_width = "32") { Self::Is32on32 } else { assert!(cfg!(target_pointer_width = "64")); Self::Is64on64 }; Ok(platform_bitness) } } fn ends_with_case_insensitive(full_text: &OsStr, literal_pattern: &str) -> Option { let folded_text = full_text.to_str()?.to_lowercase(); let folded_pattern = literal_pattern.to_lowercase(); Some(folded_text.ends_with(&folded_pattern)) } /// The most common program files paths, as they are available in this environment. /// /// This omits the global 32-bit ARM program files directory, because Git for Windows is never /// installed there. #[derive(Clone, Debug)] struct ProgramFilesPaths { /// The program files directory used for whatever architecture this program was built for. current: PathBuf, /// The 32-bit x86 program files directory regardless of the architecture of the program. /// /// If Rust gains Windows targets like ARMv7 where this is unavailable, this could fail. x86: PathBuf, /// The 64-bit program files directory if there is one. /// /// This is present on x64 (AMD64) and also ARM64 systems. On an ARM64 system, ARM64 and /// AMD64 programs use the same program files directory while 32-bit x86 and 32-bit ARM /// programs use two others. Only a 32-bit system has no 64-bit program files directory. maybe_64bit: Option, /// The per-user `Programs` subdirectory of the user's local application data directory. user: PathBuf, } impl ProgramFilesPaths { /// Get the four most common kinds of program files paths without environment variables. /// /// The idea here is to obtain this information, which the `alternative_locations()` unit /// test uses to learn the expected alternative locations, without duplicating *any* of the /// approach used for `ALTERNATIVE_LOCATIONS`, so it can be used to test that. The approach /// here is also more reliable than using environment variables, but it is a bit more /// complex, and it requires either additional dependencies or the use of unsafe code. /// /// This gets `pf_user`, `pf_current`, and `pf_x86` by the [known folders][known-folders] /// system. But it gets `maybe_pf_64bit` from the registry, as the corresponding known /// folder is not available to 32-bit processes. See the [`KNOWNFOLDDERID`][knownfolderid] /// documentation. /// /// If in the future the implementation of `ALTERNATIVE_LOCATIONS` uses these techniques, /// then this function can be changed to use environment variables and renamed accordingly. /// /// [known-folders]: https://learn.microsoft.com/en-us/windows/win32/shell/known-folders /// [knownfolderid]: https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid#remarks fn obtain_envlessly() -> Self { let pf_current = get_known_folder_path_with_flag(FOLDERID_ProgramFiles, KF_FLAG_DEFAULT) .expect("The process architecture specific program files folder is always available"); let pf_x86 = get_known_folder_path_with_flag(FOLDERID_ProgramFilesX86, KF_FLAG_DEFAULT) .expect("The x86 program files folder will in practice always be available"); let maybe_pf_64bit = RegKey::predef(HKEY_LOCAL_MACHINE) .open_subkey_with_flags(r"SOFTWARE\Microsoft\Windows\CurrentVersion", KEY_QUERY_VALUE) .expect("The `CurrentVersion` registry key exists and allows reading") .get_value::("ProgramW6432Dir") .map(PathBuf::from) .map_err(|error| { assert_eq!(error.kind(), ErrorKind::NotFound); error }) .ok(); let pf_user = get_known_folder_path_with_flag(FOLDERID_UserProgramFiles, KF_FLAG_DONT_VERIFY) .expect("The path where the user's local Programs folder is, or would be created, is known"); Self { current: pf_current, x86: pf_x86, maybe_64bit: maybe_pf_64bit, user: pf_user, } } /// Check that the paths we got for testing are reasonable. /// /// This checks that `obtain_envlessly()` returned paths that are likely to be correct and /// that satisfy the most important properties based on the current system and process. fn validated(self) -> Self { self.validate_global_folders(); self.validate_user_folder(); self } fn validate_global_folders(&self) { match PlatformBitness::current().expect("Process and system 'bitness' should be available") { PlatformBitness::Is32on32 => { assert_eq!( self.current.as_os_str(), self.x86.as_os_str(), "Our program files path is exactly identical to the 32-bit one.", ); for trailing_arch in [" (x86)", " (Arm)"] { let is_adorned = ends_with_case_insensitive(self.current.as_os_str(), trailing_arch) .expect("Assume the test system's important directories are valid Unicode"); assert!( !is_adorned, "The 32-bit program files directory name on a 32-bit system mentions no architecture.", ); } assert_eq!( self.maybe_64bit, None, "A 32-bit system has no 64-bit program files directory.", ); } PlatformBitness::Is32on64 => { assert_eq!( self.current.as_os_str(), self.x86.as_os_str(), "Our program files path is exactly identical to the 32-bit one.", ); let pf_64bit = self .maybe_64bit .as_ref() .expect("The 64-bit program files directory exists"); assert_ne!( &self.x86, pf_64bit, "The 32-bit and 64-bit program files directories have different locations.", ); } PlatformBitness::Is64on64 => { let pf_64bit = self .maybe_64bit .as_ref() .expect("The 64-bit program files directory exists"); assert_eq!( self.current.as_os_str(), pf_64bit.as_os_str(), "Our program files path is exactly identical to the 64-bit one.", ); assert_ne!( &self.x86, pf_64bit, "The 32-bit and 64-bit program files directories have different locations.", ); } } } fn validate_user_folder(&self) { let expected = get_known_folder_path_with_flag(FOLDERID_LocalAppData, KF_FLAG_DEFAULT) .expect("The user's local application data directory is available") .join("Programs"); assert_eq!( self.user, expected, "The user program files directory is Programs in the local application data directory.", ); } } /// Architecture-specific Git for Windows paths relative to the user program files directory. #[derive(Clone, Debug)] struct RelativeUserGitBinPaths<'a> { x86: &'a Path, x64: &'a Path, arm64: &'a Path, } impl<'a> RelativeUserGitBinPaths<'a> { /// Assert that `locations` leads with the given user path prefix, and extract the suffixes. fn assert_from(pf_user: &'a Path, locations: &'static [PathBuf]) -> Self { match locations { [path1, path2, path3, ..] => { let suffix_user_arm64 = path1 .strip_prefix(pf_user) .expect("It gives a per-user 64-bit ARM64 path and lists it first"); let suffix_user_x64 = path2 .strip_prefix(pf_user) .expect("It gives a per-user 64-bit x86 path and lists it second"); let suffix_user_x86 = path3 .strip_prefix(pf_user) .expect("It gives a per-user 32-bit x86 path and lists it third"); Self { x86: suffix_user_x86, x64: suffix_user_x64, arm64: suffix_user_arm64, } } other => panic!( "{:?} has length {}, so some expected leading user program files paths are absent", other, other.len() ), } } /// Assert that suffixes are common Git install locations relative to a program files directory. fn assert_architectures(&self) { assert_eq!(self.x86, Path::new("Git/mingw32/bin")); assert_eq!(self.x64, Path::new("Git/mingw64/bin")); assert_eq!(self.arm64, Path::new("Git/clangarm64/bin")); } } /// Architecture-specific Git for Windows paths relative to global program files directories. #[derive(Clone, Debug)] struct RelativeGlobalGitBinPaths<'a> { x86: &'a Path, maybe_x64: Option<&'a Path>, maybe_arm64: Option<&'a Path>, } impl<'a> RelativeGlobalGitBinPaths<'a> { /// Assert that `locations` trails with the given global path prefixes, and extract the suffixes. fn assert_from(pf: &'a ProgramFilesPaths, locations: &'static [PathBuf]) -> Self { match locations { [_, _, _, path4, path5, path6] => { let prefix_64bit = pf .maybe_64bit .as_ref() .expect("It gives 6 paths only if some global paths can be 64-bit"); let suffix_global_arm64 = path4 .strip_prefix(prefix_64bit) .expect("It gives a global 64-bit ARM64 path and lists it fourth"); let suffix_global_x64 = path5 .strip_prefix(prefix_64bit) .expect("It gives a global 64-bit x86 path and lists it fifth"); let suffix_global_x86 = path6 .strip_prefix(&pf.x86) .expect("It gives a global 32-bit path and lists it sixth"); Self { x86: suffix_global_x86, maybe_x64: Some(suffix_global_x64), maybe_arm64: Some(suffix_global_arm64), } } [_, _, _, path4] => { assert_eq!( pf.maybe_64bit, None, "It gives 4 paths only if no global paths can be 64-bit.", ); let suffix_global_x86 = path4 .strip_prefix(&pf.x86) .expect("It gives a global 32-bit path and lists it fourth"); Self { x86: suffix_global_x86, maybe_x64: None, maybe_arm64: None, } } other => panic!("{:?} has length {}, expected 4 or 6.", other, other.len()), } } /// Assert that suffixes are common Git install locations relative to a program files directory. fn assert_architectures(&self) { assert_eq!(self.x86, Path::new("Git/mingw32/bin")); if let Some(suffix_x64) = self.maybe_x64 { assert_eq!(suffix_x64, Path::new("Git/mingw64/bin")); } if let Some(suffix_arm64) = self.maybe_arm64 { assert_eq!(suffix_arm64, Path::new("Git/clangarm64/bin")); } } } /// Architecture-specific Git for Windows paths relative to particular program files directories. #[derive(Clone, Debug)] struct RelativeGitBinPaths<'a> { global: RelativeGlobalGitBinPaths<'a>, user: RelativeUserGitBinPaths<'a>, } impl<'a> RelativeGitBinPaths<'a> { /// Assert that `locations` has the given path prefixes, and extract the suffixes. fn assert_from(pf: &'a ProgramFilesPaths, locations: &'static [PathBuf]) -> Self { let user = RelativeUserGitBinPaths::assert_from(&pf.user, locations); let global = RelativeGlobalGitBinPaths::assert_from(pf, locations); Self { global, user } } /// Assert that global and user suffixes (relative subdirectories) are common Git install locations. fn assert_architectures(&self) { self.global.assert_architectures(); self.user.assert_architectures(); } } #[test] fn alternative_locations() { // Obtain program files directory paths by other means and check that they seem correct. let pf = ProgramFilesPaths::obtain_envlessly().validated(); // Check that `ALTERNATIVE_LOCATIONS` correspond to them, with the correct subdirectories. let locations = super::super::ALTERNATIVE_LOCATIONS.as_slice(); RelativeGitBinPaths::assert_from(&pf, locations).assert_architectures(); } } #[cfg(not(windows))] mod locations { #[test] fn alternative_locations() { assert!(super::super::ALTERNATIVE_LOCATIONS.is_empty()); } } mod exe_info { use std::path::{Path, PathBuf}; use gix_testtools::tempfile; use serial_test::serial; use crate::env::git::{exe_info, NULL_DEVICE}; /// Wrapper for a valid path to a plausible location, kept from accidentally existing (until drop). #[derive(Debug)] struct NonexistentLocation { _empty: tempfile::TempDir, nonexistent: PathBuf, } impl NonexistentLocation { fn new() -> Self { let empty = tempfile::tempdir().expect("can create new temporary subdirectory"); let nonexistent = empty .path() .canonicalize() .expect("path to the new directory works") .join("nonexistent"); assert!(!nonexistent.exists(), "Test bug: Need nonexistent directory"); Self { _empty: empty, nonexistent, } } fn path(&self) -> &Path { &self.nonexistent } } fn set_temp_env_vars<'a>(path: &Path) -> gix_testtools::Env<'a> { let path_str = path.to_str().expect("valid Unicode"); let env = gix_testtools::Env::new() .set("TMPDIR", path_str) // Mainly for Unix. .set("TMP", path_str) // Mainly for Windows. .set("TEMP", path_str); // Mainly for Windows, too. assert_eq!( std::env::temp_dir(), path, "Possible test bug: Temp dir path may not have been customized successfully" ); env } fn unset_windows_directory_vars<'a>() -> gix_testtools::Env<'a> { gix_testtools::Env::new().unset("windir").unset("SystemRoot") } fn check_exe_info() { let path = exe_info() .map(crate::from_bstring) .expect("It is present in the test environment (nonempty config)"); assert!( path.is_absolute(), "It is absolute (unless overridden such as with GIT_CONFIG_SYSTEM)" ); assert!( path.exists(), "It should exist on disk, since `git config` just found an entry there" ); } #[test] #[serial] fn with_unmodified_environment() { check_exe_info(); } #[test] #[serial] fn tolerates_broken_temp() { let non = NonexistentLocation::new(); let _env = set_temp_env_vars(non.path()); check_exe_info(); } #[test] #[serial] fn tolerates_oversanitized_env() { // This test runs on all systems, but it is only checking for a Windows regression. Also, on // Windows, having both a broken temp dir and an over-sanitized environment is not supported. let _env = unset_windows_directory_vars(); check_exe_info(); } #[test] #[serial] fn tolerates_git_config_env_var() { let _env = gix_testtools::Env::new().set("GIT_CONFIG", NULL_DEVICE); check_exe_info(); } #[test] #[serial] fn same_result_with_broken_temp() { let with_unmodified_temp = exe_info(); let with_nonexistent_temp = { let non = NonexistentLocation::new(); let _env = set_temp_env_vars(non.path()); exe_info() }; assert_eq!(with_unmodified_temp, with_nonexistent_temp); } #[test] #[serial] fn same_result_with_oversanitized_env() { let with_unmodified_env = exe_info(); let with_oversanitized_env = { let _env = unset_windows_directory_vars(); exe_info() }; assert_eq!(with_unmodified_env, with_oversanitized_env); } #[test] #[serial] fn same_result_with_git_config_env_var() { let with_unmodified_env = exe_info(); let with_git_config_env_var = { let _env = gix_testtools::Env::new().set("GIT_CONFIG", NULL_DEVICE); exe_info() }; assert_eq!(with_unmodified_env, with_git_config_env_var); } #[test] #[serial] #[cfg(not(target_os = "macos"))] // Assumes no higher "unknown" scope. The `nosystem` case works. fn never_from_local_scope() { let repo = gix_testtools::scripted_fixture_read_only("local_config.sh").expect("script succeeds"); let _cwd = gix_testtools::set_current_dir(repo).expect("can change to repo dir"); let _env = gix_testtools::Env::new() .set("GIT_CONFIG_SYSTEM", NULL_DEVICE) .set("GIT_CONFIG_GLOBAL", NULL_DEVICE); let maybe_path = exe_info(); assert_eq!( maybe_path, None, "Should find no config path if the config would be local (empty system config)" ); } #[test] #[serial] fn never_from_local_scope_nosystem() { let repo = gix_testtools::scripted_fixture_read_only("local_config.sh").expect("script succeeds"); let _cwd = gix_testtools::set_current_dir(repo).expect("can change to repo dir"); let _env = gix_testtools::Env::new() .set("GIT_CONFIG_NOSYSTEM", "1") .set("GIT_CONFIG_GLOBAL", NULL_DEVICE); let maybe_path = exe_info(); assert_eq!( maybe_path, None, "Should find no config path if the config would be local (suppressed system config)" ); } #[test] #[serial] #[cfg(not(target_os = "macos"))] // Assumes no higher "unknown" scope. The `nosystem` case works. fn never_from_local_scope_even_if_temp_is_here() { let repo = gix_testtools::scripted_fixture_read_only("local_config.sh") .expect("script succeeds") .canonicalize() .expect("repo path is valid and exists"); let _cwd = gix_testtools::set_current_dir(&repo).expect("can change to repo dir"); let _env = set_temp_env_vars(&repo) .set("GIT_CONFIG_SYSTEM", NULL_DEVICE) .set("GIT_CONFIG_GLOBAL", NULL_DEVICE); let maybe_path = exe_info(); assert_eq!( maybe_path, None, "Should find no config path if the config would be local even in a `/tmp`-like dir (empty system config)" ); } #[test] #[serial] fn never_from_local_scope_even_if_temp_is_here_nosystem() { let repo = gix_testtools::scripted_fixture_read_only("local_config.sh") .expect("script succeeds") .canonicalize() .expect("repo path is valid and exists"); let _cwd = gix_testtools::set_current_dir(&repo).expect("can change to repo dir"); let _env = set_temp_env_vars(&repo) .set("GIT_CONFIG_NOSYSTEM", "1") .set("GIT_CONFIG_GLOBAL", NULL_DEVICE); let maybe_path = exe_info(); assert_eq!( maybe_path, None, "Should find no config path if the config would be local even in a `/tmp`-like dir (suppressed system config)" ); } #[test] #[serial] fn never_from_git_config_env_var() { let repo = gix_testtools::scripted_fixture_read_only("local_config.sh").expect("script succeeds"); // Get an absolute path to a config file that is non-UNC if possible so any Git accepts it. let config_path = std::env::current_dir() .expect("got CWD") .join(repo) .join(".git") .join("config") .to_str() .expect("valid UTF-8") .to_owned(); let _env = gix_testtools::Env::new() .set("GIT_CONFIG_NOSYSTEM", "1") .set("GIT_CONFIG_GLOBAL", NULL_DEVICE) .set("GIT_CONFIG", config_path); let maybe_path = exe_info(); assert_eq!( maybe_path, None, "Should find no config path from GIT_CONFIG (even if nonempty)" ); } #[test] fn first_file_from_config_with_origin() { let macos = "file:/Applications/Xcode.app/Contents/Developer/usr/share/git-core/gitconfig\0credential.helper\0file:/Users/byron/.gitconfig\0push.default\0"; let win_msys = "file:C:/git-sdk-64/etc/gitconfig\0core.symlinks\0file:C:/git-sdk-64/etc/gitconfig\0core.autocrlf\0"; let win_cmd = "file:C:/Program Files/Git/etc/gitconfig\0diff.astextplain.textconv\0file:C:/Program Files/Git/etc/gitconfig\0filter.lfs.clean\0"; let win_msys_old = "file:C:\\ProgramData/Git/config\0diff.astextplain.textconv\0file:C:\\ProgramData/Git/config\0filter.lfs.clean\0"; let linux = "file:/home/parallels/.gitconfig\0core.excludesfile\0"; 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(r"C:\ProgramData/Git/config")), (win_cmd, Some("C:/Program Files/Git/etc/gitconfig")), (linux, Some("/home/parallels/.gitconfig")), (bogus, None), (empty, None), ] { assert_eq!( crate::env::git::first_file_from_config_with_origin(source.into()), expected.map(Into::into) ); } } } #[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"), (r"C:\ProgramData/Git/config", r"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)); } } gix-path-0.10.21/src/env/mod.rs000064400000000000000000000177701046102023000142260ustar 00000000000000use std::{ ffi::{OsStr, OsString}, path::{Path, PathBuf}, }; use bstr::{BString, ByteSlice}; use std::sync::LazyLock; use crate::env::git::EXE_NAME; mod auxiliary; 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) } /// Return the shell that Git would use, the shell to execute commands from. /// /// On Windows, this is the full path to `sh.exe` bundled with Git for Windows if we can find it. /// If the bundled shell on Windows cannot be found, `sh.exe` is returned as the name of a shell, /// as it could possibly be found in `PATH`. On Unix it's `/bin/sh` as the POSIX-compatible shell. /// /// Note that the returned path might not be a path on disk, if it is a fallback path or if the /// file was moved or deleted since the first time this function is called. pub fn shell() -> &'static OsStr { static PATH: LazyLock = LazyLock::new(|| { if cfg!(windows) { auxiliary::find_git_associated_windows_executable_with_fallback("sh") } else { "/bin/sh".into() } }); PATH.as_ref() } /// Return the name of the Git executable to invoke it. /// /// If it's in the `PATH`, it will always be a short name. /// /// Note that on Windows, we will find the executable in the `PATH` if it exists there, or search it /// in alternative locations which when found yields the full path to it. pub fn exe_invocation() -> &'static Path { if cfg!(windows) { /// The path to the Git executable as located in the `PATH` or in other locations that it's /// known to be installed to. It's `None` if environment variables couldn't be read or if /// no executable could be found. static EXECUTABLE_PATH: LazyLock> = LazyLock::new(|| { std::env::split_paths(&std::env::var_os("PATH")?) .chain(git::ALTERNATIVE_LOCATIONS.iter().map(Into::into)) .find_map(|prefix| { let full_path = prefix.join(EXE_NAME); full_path.is_file().then_some(full_path) }) .map(|exe_path| { let is_in_alternate_location = git::ALTERNATIVE_LOCATIONS .iter() .any(|prefix| exe_path.strip_prefix(prefix).is_ok()); if is_in_alternate_location { exe_path } else { EXE_NAME.into() } }) }); EXECUTABLE_PATH.as_deref().unwrap_or(Path::new(git::EXE_NAME)) } else { Path::new("git") } } /// 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 }) }) } static GIT_CORE_DIR: LazyLock> = LazyLock::new(|| { let mut cmd = std::process::Command::new(exe_invocation()); #[cfg(windows)] { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x08000000; cmd.creation_flags(CREATE_NO_WINDOW); } let output = cmd.arg("--exec-path").output().ok()?; if !output.status.success() { return None; } BString::new(output.stdout) .strip_suffix(b"\n")? .to_path() .ok()? .to_owned() .into() }); /// Return the directory obtained by calling `git --exec-path`. /// /// Returns `None` if Git could not be found or if it returned an error. pub fn core_dir() -> Option<&'static Path> { GIT_CORE_DIR.as_deref() } fn system_prefix_from_core_dir(core_dir_func: F) -> Option where F: Fn() -> Option<&'static Path>, { let path = core_dir_func()?; 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()) } fn system_prefix_from_exepath_var(var_os_func: F) -> Option where F: Fn(&str) -> Option, { // Only attempt this optimization if the `EXEPATH` variable is set to an absolute path. let root = var_os_func("EXEPATH").map(PathBuf::from).filter(|r| r.is_absolute())?; let mut candidates = ["clangarm64", "mingw64", "mingw32"] .iter() .map(|component| root.join(component)) .filter(|candidate| candidate.is_dir()); let path = candidates.next()?; match candidates.next() { Some(_) => None, // Multiple plausible candidates, so don't use the `EXEPATH` optimization. None => Some(path), } } /// 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 executable in the PATH. This is often /// avoided by inspecting the environment, when launched from inside a Git Bash 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: LazyLock> = LazyLock::new(|| { system_prefix_from_exepath_var(|key| std::env::var_os(key)) .or_else(|| system_prefix_from_core_dir(core_dir)) }); 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() } /// Tries to obtain the home directory from `HOME` on all platforms, but falls back to /// [`home::home_dir()`] for more complex ways of obtaining a home directory, particularly useful /// on Windows. /// /// The reason `HOME` is tried first is to allow Windows users to have a custom location for their /// linux-style home, as otherwise they would have to accumulate dot files in a directory these are /// inconvenient and perceived as clutter. #[cfg(not(target_family = "wasm"))] pub fn home_dir() -> Option { std::env::var_os("HOME").map(Into::into).or_else(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) } } #[cfg(test)] mod tests; gix-path-0.10.21/src/env/tests.rs000064400000000000000000000112711046102023000145770ustar 00000000000000mod system_prefix { use super::super::system_prefix_from_exepath_var; use gix_testtools::tempfile; use serial_test::serial; use std::{ffi::OsString, path::PathBuf}; fn if_exepath(key: &str, value: impl Into) -> Option { match key { "EXEPATH" => Some(value.into()), _ => None, } } struct ExePath { _tempdir: tempfile::TempDir, path: PathBuf, } impl ExePath { fn new() -> Self { let tempdir = tempfile::tempdir().expect("can create new temporary directory"); // This is just `tempdir.path()` unless it is relative, in which case it is resolved. let path = std::env::current_dir() .expect("can get current directory") .join(tempdir.path()); Self { _tempdir: tempdir, path, } } fn create_subdir(&self, name: &str) -> PathBuf { let child = self.path.join(name); std::fs::create_dir(&child).expect("can create subdirectory"); child } fn create_separate_subdirs(&self, names: &[&str]) { for name in names { self.create_subdir(name); } } fn create_separate_regular_files(&self, names: &[&str]) { for name in names { std::fs::File::create_new(self.path.join(name)).expect("can create new file"); } } fn var_os_func(&self, key: &str) -> Option { if_exepath(key, self.path.as_os_str()) } } #[test] fn exepath_unset() { let outcome = system_prefix_from_exepath_var(|_| None); assert_eq!(outcome, None); } #[test] fn exepath_no_relevant_subdir() { for names in [&[][..], &["ucrt64"][..]] { let exepath = ExePath::new(); exepath.create_separate_subdirs(names); let outcome = system_prefix_from_exepath_var(|key| exepath.var_os_func(key)); assert_eq!(outcome, None); } } #[test] fn exepath_unambiguous_subdir() { for name in ["mingw32", "mingw64", "clangarm64"] { let exepath = ExePath::new(); let subdir = exepath.create_subdir(name); let outcome = system_prefix_from_exepath_var(|key| exepath.var_os_func(key)); assert_eq!(outcome, Some(subdir)); } } #[test] fn exepath_unambiguous_subdir_beside_strange_files() { for (dirname, filename1, filename2) in [ ("mingw32", "mingw64", "clangarm64"), ("mingw64", "mingw32", "clangarm64"), ("clangarm64", "mingw32", "mingw64"), ] { let exepath = ExePath::new(); let subdir = exepath.create_subdir(dirname); exepath.create_separate_regular_files(&[filename1, filename2]); let outcome = system_prefix_from_exepath_var(|key| exepath.var_os_func(key)); assert_eq!(outcome, Some(subdir)); } } #[test] fn exepath_ambiguous_subdir() { for names in [ &["mingw32", "mingw64"][..], &["mingw32", "clangarm64"][..], &["mingw64", "clangarm64"][..], &["mingw32", "mingw64", "clangarm64"][..], ] { let exepath = ExePath::new(); exepath.create_separate_subdirs(names); let outcome = system_prefix_from_exepath_var(|key| exepath.var_os_func(key)); assert_eq!(outcome, None); } } #[test] #[serial] fn exepath_empty_string() { for name in ["mingw32", "mingw64", "clangarm64"] { let exepath = ExePath::new(); exepath.create_subdir(name); let _cwd = gix_testtools::set_current_dir(&exepath.path).expect("can change to test dir"); let outcome = system_prefix_from_exepath_var(|key| if_exepath(key, "")); assert_eq!(outcome, None); } } #[test] #[serial] fn exepath_nonempty_relative() { for name in ["mingw32", "mingw64", "clangarm64"] { let grandparent = tempfile::tempdir().expect("can create new temporary directory"); let parent = grandparent .path() .canonicalize() .expect("path to the new directory works") .join("dir"); std::fs::create_dir_all(parent.join(name)).expect("can create directories"); let _cwd = gix_testtools::set_current_dir(grandparent.path()).expect("can change to test dir"); let outcome = system_prefix_from_exepath_var(|key| if_exepath(key, "dir")); assert_eq!(outcome, None); } } } gix-path-0.10.21/src/lib.rs000064400000000000000000000105231046102023000134120ustar 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)] #![cfg_attr(not(test), deny(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; /// pub mod relative_path; pub use relative_path::types::RelativePath; gix-path-0.10.21/src/realpath.rs000064400000000000000000000102631046102023000144450ustar 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.21/src/relative_path.rs000064400000000000000000000061701046102023000154760ustar 00000000000000use std::path::Path; use bstr::{BStr, BString, ByteSlice}; use gix_validate::path::component::Options; use crate::{os_str_into_bstr, try_from_bstr, try_from_byte_slice}; pub(super) mod types { use bstr::{BStr, ByteSlice}; /// A wrapper for `BStr`. It is used to enforce the following constraints: /// /// - The path separator always is `/`, independent of the platform. /// - Only normal components are allowed. /// - It is always represented as a bunch of bytes. #[derive()] pub struct RelativePath { inner: BStr, } impl AsRef<[u8]> for RelativePath { #[inline] fn as_ref(&self) -> &[u8] { self.inner.as_bytes() } } } use types::RelativePath; impl RelativePath { fn new_unchecked(value: &BStr) -> Result<&RelativePath, Error> { // SAFETY: `RelativePath` is transparent and equivalent to a `&BStr` if provided as reference. #[allow(unsafe_code)] unsafe { std::mem::transmute(value) } } } /// The error used in [`RelativePath`]. #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("A RelativePath is not allowed to be absolute")] IsAbsolute, #[error(transparent)] ContainsInvalidComponent(#[from] gix_validate::path::component::Error), #[error(transparent)] IllegalUtf8(#[from] crate::Utf8Error), } fn relative_path_from_value_and_path<'a>(path_bstr: &'a BStr, path: &Path) -> Result<&'a RelativePath, Error> { if path.is_absolute() { return Err(Error::IsAbsolute); } let options = Options::default(); for component in path.components() { let component = os_str_into_bstr(component.as_os_str())?; gix_validate::path::component(component, None, options)?; } RelativePath::new_unchecked(BStr::new(path_bstr.as_bytes())) } impl<'a> TryFrom<&'a str> for &'a RelativePath { type Error = Error; fn try_from(value: &'a str) -> Result { relative_path_from_value_and_path(value.into(), Path::new(value)) } } impl<'a> TryFrom<&'a BStr> for &'a RelativePath { type Error = Error; fn try_from(value: &'a BStr) -> Result { let path = try_from_bstr(value)?; relative_path_from_value_and_path(value, &path) } } impl<'a> TryFrom<&'a [u8]> for &'a RelativePath { type Error = Error; #[inline] fn try_from(value: &'a [u8]) -> Result { let path = try_from_byte_slice(value)?; relative_path_from_value_and_path(value.as_bstr(), path) } } impl<'a, const N: usize> TryFrom<&'a [u8; N]> for &'a RelativePath { type Error = Error; #[inline] fn try_from(value: &'a [u8; N]) -> Result { let path = try_from_byte_slice(value.as_bstr())?; relative_path_from_value_and_path(value.as_bstr(), path) } } impl<'a> TryFrom<&'a BString> for &'a RelativePath { type Error = Error; fn try_from(value: &'a BString) -> Result { let path = try_from_bstr(value.as_bstr())?; relative_path_from_value_and_path(value.as_bstr(), &path) } } gix-path-0.10.21/src/util.rs000064400000000000000000000005271046102023000136240ustar 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('/') }