normpath-1.5.0/.cargo_vcs_info.json0000644000000001360000000000100126670ustar { "git": { "sha1": "866a61ddf57ba6f3c764d3b90d72a46ff05a1421" }, "path_in_vcs": "" }normpath-1.5.0/COPYRIGHT000064400000000000000000000005031046102023000127500ustar 00000000000000Copyright (c) 2020 dylni (https://github.com/dylni) Some files also include explicit copyright notices. Licensed under the Apache License, Version 2.0 or the MIT license , at your option. All files in this project may not be copied, modified, or distributed except according to those terms. normpath-1.5.0/Cargo.lock0000644000000144750000000000100106550ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bincode" version = "1.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" dependencies = [ "serde", ] [[package]] name = "bitflags" version = "2.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394" [[package]] name = "cfg-if" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" [[package]] name = "errno" version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", "windows-sys", ] [[package]] name = "fastrand" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "getrandom" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ "cfg-if", "libc", "r-efi", "wasi", ] [[package]] name = "libc" version = "0.2.175" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a82ae493e598baaea5209805c49bbf2ea7de956d50d7da0da1164f9c6d28543" [[package]] name = "linux-raw-sys" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" [[package]] name = "normpath" version = "1.5.0" dependencies = [ "bincode", "libc", "normpath_macros", "print_bytes", "serde", "tempfile", "uniquote", "windows-sys", ] [[package]] name = "normpath_macros" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4d19bb753bec436b65927a36aee83864f1369385e18315afe016b9bbc157cac" dependencies = [ "windows-sys", ] [[package]] name = "once_cell" version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] name = "os_str_bytes" version = "7.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63eceb7b5d757011a87d08eb2123db15d87fb0c281f65d101ce30a1e96c3ad5c" [[package]] name = "print_bytes" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f79d99e0015e3634241b5f40058836891f4ced507ec7c9b336cd51bc510f4089" dependencies = [ "os_str_bytes", "windows-sys", ] [[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.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] name = "r-efi" version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] name = "rustix" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "serde" version = "1.0.226" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dca6411025b24b60bfa7ec1fe1f8e710ac09782dca409ee8237ba74b51295fd" dependencies = [ "serde_core", ] [[package]] name = "serde_core" version = "1.0.226" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba2ba63999edb9dac981fb34b3e5c0d111a69b0924e253ed29d83f7c99e966a4" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.226" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8db53ae22f34573731bafa1db20f04027b2d25e02d8205921b569171699cdb33" dependencies = [ "proc-macro2", "quote", "syn", ] [[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 = "tempfile" version = "3.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84fa4d11fadde498443cca10fd3ac23c951f0dc59e080e9f4b93d4df4e4eea53" dependencies = [ "fastrand", "getrandom", "once_cell", "rustix", "windows-sys", ] [[package]] name = "unicode-ident" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" [[package]] name = "uniquote" version = "4.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd76d314b2276c3efba1c90e48135f1b8b8bd7f9fca39dd5e7425c0cef74c79" [[package]] name = "wasi" version = "0.14.7+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" dependencies = [ "wasip2", ] [[package]] name = "wasip2" version = "1.0.1+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" dependencies = [ "wit-bindgen", ] [[package]] name = "windows-link" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65" [[package]] name = "windows-sys" version = "0.61.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e201184e40b2ede64bc2ea34968b28e33622acdbbf37104f0e4a33f7abe657aa" dependencies = [ "windows-link", ] [[package]] name = "wit-bindgen" version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" normpath-1.5.0/Cargo.toml0000644000000040060000000000100106650ustar # 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.81.0" name = "normpath" version = "1.5.0" authors = ["dylni"] build = false exclude = [ ".*", "tests.rs", "/rustfmt.toml", "/src/bin", "/tests", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = """ More reliable path manipulation """ readme = "README.md" keywords = [ "absolute", "canonicalize", "path", "normalize", "windows", ] categories = [ "command-line-interface", "filesystem", "os", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dylni/normpath" [package.metadata.docs.rs] all-features = true rustc-args = [ "--cfg", "normpath_docs_rs", ] rustdoc-args = [ "--cfg", "normpath_docs_rs", ] [features] localization = [ "windows-sys/Win32_UI_Shell", "windows-sys/Win32_UI_WindowsAndMessaging", ] [lib] name = "normpath" path = "src/lib.rs" [dependencies.print_bytes] version = "2.0" features = ["os_str_bytes"] optional = true [dependencies.serde] version = "1.0" optional = true [dependencies.uniquote] version = "4.0" optional = true [dev-dependencies.bincode] version = "1.0" [dev-dependencies.tempfile] version = "3.0" [target."cfg(not(windows))".dev-dependencies.libc] version = "0.2" [target."cfg(windows)".dependencies.windows-sys] version = "0.61" features = ["Win32_Storage_FileSystem"] [target."cfg(windows)".dev-dependencies.normpath_macros] version = "=1.5.0" [target."cfg(windows)".dev-dependencies.windows-sys] version = "0.61" features = ["Win32_Foundation"] normpath-1.5.0/Cargo.toml.orig000064400000000000000000000026771046102023000143620ustar 00000000000000[package] name = "normpath" version.workspace = true authors = ["dylni"] edition.workspace = true rust-version.workspace = true description = """ More reliable path manipulation """ readme = "README.md" repository.workspace = true license.workspace = true keywords = ["absolute", "canonicalize", "path", "normalize", "windows"] categories = ["command-line-interface", "filesystem", "os"] exclude = [".*", "tests.rs", "/rustfmt.toml", "/src/bin", "/tests"] [package.metadata.docs.rs] all-features = true rustc-args = ["--cfg", "normpath_docs_rs"] rustdoc-args = ["--cfg", "normpath_docs_rs"] [dependencies] print_bytes = { version = "2.0", features = ["os_str_bytes"], optional = true } serde = { version = "1.0", optional = true } uniquote = { version = "4.0", optional = true } [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] } [dev-dependencies] bincode = "1.0" tempfile = "3.0" [target.'cfg(windows)'.dev-dependencies] normpath_macros = { version = "=1.5.0", path = "macros" } windows-sys = { version = "0.61", features = ["Win32_Foundation"] } [target.'cfg(not(windows))'.dev-dependencies] libc = "0.2" [features] localization = ["windows-sys/Win32_UI_Shell", "windows-sys/Win32_UI_WindowsAndMessaging"] [workspace] members = ["macros"] [workspace.package] version = "1.5.0" edition = "2021" rust-version = "1.81.0" repository = "https://github.com/dylni/normpath" license = "MIT OR Apache-2.0" normpath-1.5.0/LICENSE-APACHE000064400000000000000000000236751046102023000134200ustar 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 normpath-1.5.0/LICENSE-MIT000064400000000000000000000021011046102023000131050ustar 00000000000000MIT License Copyright (c) 2020 dylni (https://github.com/dylni) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. normpath-1.5.0/LICENSE-THIRD-PARTY000064400000000000000000000566161046102023000142470ustar 00000000000000=============================================================================== The Rust Programming Language https://github.com/rust-lang/rust/blob/b1277d04db0dc8009037e872a1be7cdc2bd74a43/LICENSE-MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================== The Rust Programming Language https://github.com/rust-lang/rust/blob/b1277d04db0dc8009037e872a1be7cdc2bd74a43/LICENSE-APACHE 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 =============================================================================== Fruity https://github.com/nvzqz/fruity/blob/320efcf715c2c5fbd2f3084f671f2be2e03a6f2b/LICENSE-MIT MIT License Copyright (c) 2020 Nikolai Vazquez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================== Fruity https://github.com/nvzqz/fruity/blob/320efcf715c2c5fbd2f3084f671f2be2e03a6f2b/LICENSE-APACHE 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. normpath-1.5.0/README.md000064400000000000000000000057031046102023000127430ustar 00000000000000# NormPath This crate provides methods to normalize paths in the recommended way for the operating system. It was made to fix a recurring bug caused by using [`fs::canonicalize`] on Windows: [#45067], [#48249], [#52440], [#55812], [#58613], [#59107], [#74327]. Normalization is usually a better choice unless you specifically need a canonical path. [![GitHub Build Status](https://github.com/dylni/normpath/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/dylni/normpath/actions/workflows/build.yml?query=branch%3Amaster) ## Usage Add the following lines to your "Cargo.toml" file: ```toml [dependencies] normpath = "1.5" ``` See the [documentation] for available functionality and examples. ## Rust version support The minimum supported Rust toolchain version is currently Rust 1.81.0. Minor version updates may increase this version requirement. However, the previous two Rust releases will always be supported. If the minimum Rust version must not be increased, use a tilde requirement to prevent updating this crate's minor version: ```toml [dependencies] normpath = "~1.5" ``` ## License Licensing terms are specified in [COPYRIGHT]. Unless you explicitly state otherwise, any contribution submitted for inclusion in this crate, as defined in [LICENSE-APACHE], shall be licensed according to [COPYRIGHT], without any additional terms or conditions. ### Third-party content This crate includes copies and modifications of content developed by third parties: - [src/cmp.rs] and [tests/rust.rs] contain modifications of code from The Rust Programming Language, licensed under the MIT License or the Apache License, Version 2.0. - [src/common/localize/macos/fruity.rs] contains modifications of code from crate [fruity], licensed under the MIT License or the Apache License, Version 2.0. See those files for more details. Copies of third-party licenses can be found in [LICENSE-THIRD-PARTY]. [#45067]: https://github.com/rust-lang/rust/issues/45067 [#48249]: https://github.com/rust-lang/rust/issues/48249 [#52440]: https://github.com/rust-lang/rust/issues/52440 [#55812]: https://github.com/rust-lang/rust/issues/55812 [#58613]: https://github.com/rust-lang/rust/issues/58613 [#59107]: https://github.com/rust-lang/rust/issues/59107 [#74327]: https://github.com/rust-lang/rust/issues/74327 [COPYRIGHT]: https://github.com/dylni/normpath/blob/master/COPYRIGHT [documentation]: https://docs.rs/normpath [fruity]: https://crates.io/crates/fruity [`fs::canonicalize`]: https://doc.rust-lang.org/std/fs/fn.canonicalize.html [LICENSE-APACHE]: https://github.com/dylni/normpath/blob/master/LICENSE-APACHE [LICENSE-THIRD-PARTY]: https://github.com/dylni/normpath/blob/master/LICENSE-THIRD-PARTY [src/cmp.rs]: https://github.com/dylni/normpath/blob/master/src/cmp.rs [src/common/localize/macos/fruity.rs]: https://github.com/dylni/normpath/blob/master/src/common/localize/macos/fruity.rs [tests/rust.rs]: https://github.com/dylni/normpath/blob/master/tests/rust.rs normpath-1.5.0/src/base.rs000064400000000000000000000505271046102023000135370ustar 00000000000000use std::borrow::Borrow; use std::borrow::Cow; use std::cmp::Ordering; use std::ffi::OsStr; use std::ffi::OsString; use std::fs::Metadata; use std::fs::ReadDir; use std::hash::Hash; use std::hash::Hasher; use std::io; use std::mem; use std::ops::Deref; use std::path::Component; use std::path::Components; use std::path::Path; use std::path::PathBuf; use super::error::MissingPrefixBufError; use super::error::MissingPrefixError; use super::error::ParentError; use super::imp; use super::PathExt; fn cow_path_into_base_path(path: Cow<'_, Path>) -> Cow<'_, BasePath> { debug_assert!(imp::is_base(&path)); match path { Cow::Borrowed(path) => { Cow::Borrowed(BasePath::from_inner(path.as_os_str())) } Cow::Owned(path) => Cow::Owned(BasePathBuf(path)), } } /// A borrowed path that has a [prefix] on Windows. /// /// Note that comparison traits such as [`PartialEq`] will compare paths /// literally instead of comparing components. The former is more efficient and /// easier to use correctly. /// /// # Safety /// /// This type should not be used for memory safety, but implementations can /// panic if this path is missing a prefix on Windows. A safe `new_unchecked` /// method might be added later that can safely create invalid base paths. /// /// [prefix]: ::std::path::Prefix #[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[repr(transparent)] pub struct BasePath(pub(super) OsStr); impl BasePath { pub(super) fn from_inner(path: &OsStr) -> &Self { // SAFETY: This struct has a layout that makes this operation safe. unsafe { mem::transmute(path) } } /// Creates a new base path. /// /// On Windows, if `path` is missing a [prefix], it will be joined to the /// current directory. /// /// # Errors /// /// Returns an error if reading the current directory fails. /// /// # Examples /// /// ``` /// # use std::io; /// use std::path::Path; /// /// use normpath::BasePath; /// /// if cfg!(windows) { /// let path = Path::new(r"X:\foo\bar"); /// assert_eq!(path, *BasePath::new(path)?); /// /// assert!(BasePath::new(Path::new(r"foo\bar")).is_ok()); /// } /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [prefix]: ::std::path::Prefix #[inline] pub fn new<'a, P>(path: P) -> io::Result> where P: Into>, { let path = path.into(); match path { Cow::Borrowed(path) => Self::try_new(path) .map(Cow::Borrowed) .or_else(|_| imp::to_base(path).map(Cow::Owned)), Cow::Owned(path) => BasePathBuf::new(path).map(Cow::Owned), } } /// Creates a new base path. /// /// # Errors /// /// On Windows, returns an error if `path` is missing a [prefix]. /// /// # Examples /// /// ``` /// use std::path::Path; /// /// # use normpath::error::MissingPrefixError; /// use normpath::BasePath; /// /// if cfg!(windows) { /// let path = r"X:\foo\bar"; /// assert_eq!(Path::new(path), BasePath::try_new(path)?); /// /// assert!(BasePath::try_new(r"foo\bar").is_err()); /// } /// # /// # Ok::<_, MissingPrefixError>(()) /// ``` /// /// [prefix]: ::std::path::Prefix #[inline] pub fn try_new

(path: &P) -> Result<&Self, MissingPrefixError> where P: AsRef + ?Sized, { let path = path.as_ref(); if imp::is_base(path) { Ok(Self::from_inner(path.as_os_str())) } else { Err(MissingPrefixError(())) } } /// Returns a reference to the wrapped path as a platform string. #[inline] #[must_use] pub fn as_os_str(&self) -> &OsStr { &self.0 } /// Returns a reference to the wrapped path. #[inline] #[must_use] pub fn as_path(&self) -> &Path { Path::new(&self.0) } /// Equivalent to [`Path::canonicalize`]. #[inline] pub fn canonicalize(&self) -> io::Result { self.as_path().canonicalize().map(|base| { debug_assert!(imp::is_base(&base)); BasePathBuf(base) }) } /// Equivalent to [`Path::components`]. #[inline] pub fn components(&self) -> Components<'_> { self.as_path().components() } /// Equivalent to [`Path::ends_with`]. #[inline] #[must_use] pub fn ends_with

(&self, child: P) -> bool where P: AsRef, { self.as_path().ends_with(child) } /// Equivalent to [`Path::exists`]. #[inline] #[must_use] pub fn exists(&self) -> bool { self.as_path().exists() } /// Equivalent to [`PathExt::expand`]. #[inline] pub fn expand(&self) -> io::Result> { self.as_path().expand().map(cow_path_into_base_path) } /// Equivalent to [`Path::extension`]. #[inline] #[must_use] pub fn extension(&self) -> Option<&OsStr> { self.as_path().extension() } /// Equivalent to [`Path::file_name`]. #[inline] #[must_use] pub fn file_name(&self) -> Option<&OsStr> { self.as_path().file_name() } /// Equivalent to [`Path::file_stem`]. #[inline] #[must_use] pub fn file_stem(&self) -> Option<&OsStr> { self.as_path().file_stem() } /// Equivalent to [`Path::has_root`]. #[inline] #[must_use] pub fn has_root(&self) -> bool { self.as_path().has_root() } /// Equivalent to [`Path::is_absolute`]. #[inline] #[must_use] pub fn is_absolute(&self) -> bool { self.as_path().is_absolute() } /// Equivalent to [`Path::is_dir`]. #[inline] #[must_use] pub fn is_dir(&self) -> bool { self.as_path().is_dir() } /// Equivalent to [`Path::is_file`]. #[inline] #[must_use] pub fn is_file(&self) -> bool { self.as_path().is_file() } /// Equivalent to [`Path::is_relative`]. #[inline] #[must_use] pub fn is_relative(&self) -> bool { self.as_path().is_relative() } /// Equivalent to [`Path::is_symlink`]. #[inline] #[must_use] pub fn is_symlink(&self) -> bool { self.as_path().is_symlink() } /// An improved version of [`Path::join`] that handles more edge cases. /// /// For example, on Windows, leading `.` and `..` components of `path` will /// be normalized if possible. If `self` is a [verbatim] path, it would be /// invalid to normalize them later. /// /// You should still call [`normalize`] before [`parent`] to normalize some /// additional components. /// /// # Examples /// /// ``` /// use std::path::Path; /// /// use normpath::BasePath; /// /// if cfg!(windows) { /// assert_eq!( /// Path::new(r"\\?\foo\baz\test.rs"), /// BasePath::try_new(r"\\?\foo\bar") /// .unwrap() /// .join("../baz/test.rs"), /// ); /// } /// ``` /// /// [`normalize`]: Self::normalize /// [`parent`]: Self::parent /// [verbatim]: ::std::path::Prefix::is_verbatim #[inline] pub fn join

(&self, path: P) -> BasePathBuf where P: AsRef, { let mut base = self.to_owned(); base.push(path); base } /// Equivalent to [`PathExt::localize_name`]. #[cfg(feature = "localization")] #[cfg_attr(normpath_docs_rs, doc(cfg(feature = "localization")))] #[inline] #[must_use] pub fn localize_name(&self) -> Cow<'_, OsStr> { self.as_path().localize_name() } /// Equivalent to [`Path::metadata`]. #[inline] pub fn metadata(&self) -> io::Result { self.as_path().metadata() } /// Equivalent to [`PathExt::normalize`]. #[inline] pub fn normalize(&self) -> io::Result { self.as_path().normalize() } /// Equivalent to [`PathExt::normalize_virtually`]. #[cfg(any(doc, windows))] #[cfg_attr(normpath_docs_rs, doc(cfg(windows)))] #[inline] pub fn normalize_virtually(&self) -> io::Result { self.as_path().normalize_virtually() } fn check_parent(&self) -> Result<(), ParentError> { self.components() .next_back() .filter(|x| matches!(x, Component::Normal(_) | Component::RootDir)) .map(|_| ()) .ok_or(ParentError(())) } /// Returns this path without its last component. /// /// Returns `Ok(None)` if the last component is [`Component::RootDir`]. /// /// You should usually only call this method on [normalized] paths. They /// will prevent an unexpected path from being returned due to symlinks, /// and some `.` and `..` components will be normalized. /// /// # Errors /// /// Returns an error if the last component is not [`Component::Normal`] or /// [`Component::RootDir`]. To ignore this error, use [`parent_unchecked`]. /// /// # Examples /// /// ``` /// use std::path::Path; /// /// # use normpath::error::ParentError; /// use normpath::BasePath; /// /// if cfg!(windows) { /// assert_eq!( /// Path::new(r"X:\foo"), /// BasePath::try_new(r"X:\foo\bar").unwrap().parent()?.unwrap(), /// ); /// } /// # /// # Ok::<_, ParentError>(()) /// ``` /// /// [normalized]: Self::normalize /// [`parent_unchecked`]: Self::parent_unchecked #[inline] pub fn parent(&self) -> Result, ParentError> { self.check_parent().map(|()| self.parent_unchecked()) } /// Equivalent to [`Path::parent`]. /// /// It is usually better to use [`parent`]. /// /// # Examples /// /// ``` /// use std::path::Path; /// /// use normpath::BasePath; /// /// if cfg!(windows) { /// assert_eq!( /// Path::new(r"X:\foo"), /// BasePath::try_new(r"X:\foo\..") /// .unwrap() /// .parent_unchecked() /// .unwrap(), /// ); /// } /// ``` /// /// [`parent`]: Self::parent #[inline] #[must_use] pub fn parent_unchecked(&self) -> Option<&Self> { self.as_path() .parent() .map(|x| Self::from_inner(x.as_os_str())) } /// Equivalent to [`Path::read_dir`]. #[inline] pub fn read_dir(&self) -> io::Result { self.as_path().read_dir() } /// Equivalent to [`Path::read_link`]. #[inline] pub fn read_link(&self) -> io::Result { self.as_path().read_link() } /// Equivalent to [`PathExt::shorten`]. #[inline] pub fn shorten(&self) -> io::Result> { self.as_path().shorten().map(cow_path_into_base_path) } /// Equivalent to [`Path::starts_with`]. #[inline] #[must_use] pub fn starts_with

(&self, base: P) -> bool where P: AsRef, { self.as_path().starts_with(base) } /// Equivalent to [`Path::symlink_metadata`]. #[inline] pub fn symlink_metadata(&self) -> io::Result { self.as_path().symlink_metadata() } /// Equivalent to [`Path::try_exists`]. #[inline] pub fn try_exists(&self) -> io::Result { self.as_path().try_exists() } } impl AsRef for BasePath { #[inline] fn as_ref(&self) -> &OsStr { &self.0 } } impl AsRef for BasePath { #[inline] fn as_ref(&self) -> &Path { self.as_path() } } impl AsRef for BasePath { #[inline] fn as_ref(&self) -> &Self { self } } impl<'a> From<&'a BasePath> for Cow<'a, BasePath> { #[inline] fn from(value: &'a BasePath) -> Self { Cow::Borrowed(value) } } impl PartialEq for BasePath { #[inline] fn eq(&self, other: &Path) -> bool { &self.0 == other.as_os_str() } } impl PartialEq for Path { #[inline] fn eq(&self, other: &BasePath) -> bool { other == self } } impl PartialOrd for BasePath { #[inline] fn partial_cmp(&self, other: &Path) -> Option { self.0.partial_cmp(other.as_os_str()) } } impl PartialOrd for Path { #[inline] fn partial_cmp(&self, other: &BasePath) -> Option { other.partial_cmp(self) } } impl ToOwned for BasePath { type Owned = BasePathBuf; #[inline] fn to_owned(&self) -> Self::Owned { BasePathBuf(self.0.to_owned().into()) } } /// An owned path that has a [prefix] on Windows. /// /// For more information, see [`BasePath`]. /// /// [prefix]: ::std::path::Prefix #[derive(Clone, Debug)] pub struct BasePathBuf(pub(super) PathBuf); impl BasePathBuf { /// Equivalent to [`BasePath::new`] but returns an owned path. /// /// # Examples /// /// ``` /// # use std::io; /// use std::path::Path; /// /// use normpath::BasePathBuf; /// /// if cfg!(windows) { /// let path = r"X:\foo\bar"; /// assert_eq!(Path::new(path), BasePathBuf::new(path)?); /// /// assert!(BasePathBuf::new(r"foo\bar").is_ok()); /// } /// # /// # Ok::<_, io::Error>(()) /// ``` #[inline] pub fn new

(path: P) -> io::Result where P: Into, { Self::try_new(path).or_else(|x| imp::to_base(&x.0)) } /// Equivalent to [`BasePath::try_new`] but returns an owned path. /// /// # Examples /// /// ``` /// use std::path::Path; /// /// # use normpath::error::MissingPrefixBufError; /// use normpath::BasePathBuf; /// /// if cfg!(windows) { /// let path = r"X:\foo\bar"; /// assert_eq!(Path::new(path), BasePathBuf::try_new(path)?); /// /// assert!(BasePathBuf::try_new(r"foo\bar").is_err()); /// } /// # /// # Ok::<_, MissingPrefixBufError>(()) /// ``` #[inline] pub fn try_new

(path: P) -> Result where P: Into, { let path = path.into(); if imp::is_base(&path) { Ok(Self(path)) } else { Err(MissingPrefixBufError(path)) } } /// Returns the wrapped path as a platform string. #[inline] #[must_use] pub fn into_os_string(self) -> OsString { self.0.into_os_string() } /// Returns the wrapped path. #[inline] #[must_use] pub fn into_path_buf(self) -> PathBuf { self.0 } /// Equivalent to [`BasePath::parent`] but modifies `self` in place. /// /// Returns `Ok(false)` when [`BasePath::parent`] returns `Ok(None)`. /// /// # Examples /// /// ``` /// use std::path::Path; /// /// # use normpath::error::ParentError; /// use normpath::BasePathBuf; /// /// if cfg!(windows) { /// let mut path = BasePathBuf::try_new(r"X:\foo\bar").unwrap(); /// assert!(path.pop()?); /// assert_eq!(Path::new(r"X:\foo"), path); /// } /// # /// # Ok::<_, ParentError>(()) /// ``` #[inline] pub fn pop(&mut self) -> Result { self.check_parent().map(|()| self.pop_unchecked()) } /// Equivalent to [`PathBuf::pop`]. /// /// It is usually better to use [`pop`]. /// /// # Examples /// /// ``` /// use std::path::Path; /// /// use normpath::BasePathBuf; /// /// if cfg!(windows) { /// let mut path = BasePathBuf::try_new(r"X:\foo\..").unwrap(); /// assert!(path.pop_unchecked()); /// assert_eq!(Path::new(r"X:\foo"), path); /// } /// ``` /// /// [`pop`]: Self::pop #[inline] pub fn pop_unchecked(&mut self) -> bool { self.0.pop() } /// Equivalent to [`BasePath::join`] but modifies `self` in place. /// /// # Examples /// /// ``` /// use std::path::Path; /// /// use normpath::BasePathBuf; /// /// if cfg!(windows) { /// let mut path = BasePathBuf::try_new(r"\\?\foo\bar").unwrap(); /// path.push("../baz/test.rs"); /// assert_eq!(Path::new(r"\\?\foo\baz\test.rs"), path); /// } /// ``` #[inline] pub fn push

(&mut self, path: P) where P: AsRef, { imp::push(self, path.as_ref()); } } impl AsRef for BasePathBuf { #[inline] fn as_ref(&self) -> &OsStr { self.as_os_str() } } impl AsRef for BasePathBuf { #[inline] fn as_ref(&self) -> &Path { &self.0 } } impl AsRef for BasePathBuf { #[inline] fn as_ref(&self) -> &BasePath { self } } impl Borrow for BasePathBuf { #[inline] fn borrow(&self) -> &BasePath { self } } impl Deref for BasePathBuf { type Target = BasePath; #[inline] fn deref(&self) -> &BasePath { BasePath::from_inner(self.0.as_os_str()) } } impl Eq for BasePathBuf {} impl From for Cow<'_, BasePath> { #[inline] fn from(value: BasePathBuf) -> Self { Cow::Owned(value) } } impl From for OsString { #[inline] fn from(value: BasePathBuf) -> Self { value.into_os_string() } } impl From for PathBuf { #[inline] fn from(value: BasePathBuf) -> Self { value.0 } } impl Hash for BasePathBuf { #[inline] fn hash(&self, state: &mut H) where H: Hasher, { (**self).hash(state); } } impl Ord for BasePathBuf { #[inline] fn cmp(&self, other: &Self) -> Ordering { (**self).cmp(&**other) } } impl PartialEq for BasePathBuf { #[inline] fn eq(&self, other: &Self) -> bool { **self == **other } } impl PartialOrd for BasePathBuf { #[expect(clippy::non_canonical_partial_ord_impl)] #[inline] fn partial_cmp(&self, other: &Self) -> Option { (**self).partial_cmp(&**other) } } #[cfg(feature = "print_bytes")] #[cfg_attr(normpath_docs_rs, doc(cfg(feature = "print_bytes")))] mod print_bytes { use print_bytes::ByteStr; use print_bytes::ToBytes; #[cfg(windows)] use print_bytes::WideStr; use super::BasePath; use super::BasePathBuf; impl ToBytes for BasePath { #[inline] fn to_bytes(&self) -> ByteStr<'_> { self.0.to_bytes() } #[cfg(windows)] #[inline] fn to_wide(&self) -> Option { self.0.to_wide() } } impl ToBytes for BasePathBuf { #[inline] fn to_bytes(&self) -> ByteStr<'_> { (**self).to_bytes() } #[cfg(windows)] #[inline] fn to_wide(&self) -> Option { (**self).to_wide() } } } #[cfg(feature = "serde")] #[cfg_attr(normpath_docs_rs, doc(cfg(feature = "serde")))] mod serde { use std::ffi::OsString; use serde::Deserialize; use serde::Deserializer; use serde::Serialize; use serde::Serializer; use super::BasePath; use super::BasePathBuf; impl<'de> Deserialize<'de> for BasePathBuf { #[inline] fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { OsString::deserialize(deserializer).map(|x| Self(x.into())) } } impl Serialize for BasePath { #[inline] fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_newtype_struct("BasePath", &self.0) } } impl Serialize for BasePathBuf { #[inline] fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer .serialize_newtype_struct("BasePathBuf", self.as_os_str()) } } } #[cfg(feature = "uniquote")] #[cfg_attr(normpath_docs_rs, doc(cfg(feature = "uniquote")))] mod uniquote { use uniquote::Formatter; use uniquote::Quote; use uniquote::Result; use super::BasePath; use super::BasePathBuf; impl Quote for BasePath { #[inline] fn escape(&self, f: &mut Formatter<'_>) -> Result { self.0.escape(f) } } impl Quote for BasePathBuf { #[inline] fn escape(&self, f: &mut Formatter<'_>) -> Result { (**self).escape(f) } } } normpath-1.5.0/src/cmp.rs000064400000000000000000000045731046102023000134040ustar 00000000000000//! Implementations of comparison traits copied and modified from The Rust //! Programming Language. //! //! Sources: //! - //! //! Copyrights: //! - Copyrights in the Rust project are retained by their contributors. No //! copyright assignment is required to contribute to the Rust project. //! //! Some files include explicit copyright notices and/or license notices. //! For full authorship information, see the version control history or //! //! //! //! - Modifications copyright (c) 2020 dylni ()
//! use std::borrow::Cow; use std::cmp::Ordering; use std::path::Path; use std::path::PathBuf; use super::BasePath; use super::BasePathBuf; macro_rules! r#impl { ( $left:ty , $right:ty ) => { impl PartialEq<$right> for $left { #[inline] fn eq(&self, other: &$right) -> bool { >::eq(self, other.as_ref()) } } impl PartialEq<$left> for $right { #[inline] fn eq(&self, other: &$left) -> bool { other == self } } impl PartialOrd<$right> for $left { #[inline] fn partial_cmp(&self, other: &$right) -> Option { >::partial_cmp( self, other.as_ref(), ) } } impl PartialOrd<$left> for $right { #[inline] fn partial_cmp(&self, other: &$left) -> Option { other.partial_cmp(self) } } }; } r#impl!(BasePathBuf, BasePath); r#impl!(BasePathBuf, &BasePath); r#impl!(Cow<'_, BasePath>, BasePath); r#impl!(Cow<'_, BasePath>, &BasePath); r#impl!(Cow<'_, BasePath>, BasePathBuf); r#impl!(BasePathBuf, Path); r#impl!(BasePathBuf, &Path); r#impl!(BasePathBuf, Cow<'_, Path>); r#impl!(BasePathBuf, PathBuf); r#impl!(BasePath, &Path); r#impl!(BasePath, Cow<'_, Path>); r#impl!(BasePath, PathBuf); r#impl!(&BasePath, Path); r#impl!(&BasePath, Cow<'_, Path>); r#impl!(&BasePath, PathBuf); normpath-1.5.0/src/common/localize/macos/fruity.rs000064400000000000000000000104641046102023000203370ustar 00000000000000//! Implementations copied and modified from Fruity. //! //! Sources: //! - //! //! Copyrights: //! - Copyright (c) 2020 Nikolai Vazquez
//! //! - Modifications copyright (c) 2020 dylni ()
//! use std::os::raw::c_char; macro_rules! __stringify_sel { ( $name:ident ) => { ::std::stringify!($name) }; ( $($name:ident :)+ ) => { ::std::concat!($(::std::stringify!($name), ":"),+) }; } macro_rules! selector { ( $($token:tt)* ) => {{ let sel: *const _ = ::std::concat!(__stringify_sel!($($token)*), "\0"); unsafe { $crate::localize::macos::fruity::sel_registerName(sel.cast()) } }}; } #[link(name = "Foundation", kind = "framework")] extern "C" {} extern "C" { pub(super) fn sel_registerName(name: *const c_char) -> objc::SEL; } pub(super) mod objc { use std::cell::UnsafeCell; use std::ops::Deref; use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr::NonNull; #[expect(clippy::upper_case_acronyms)] pub(super) type BOOL = c_char; #[expect(clippy::upper_case_acronyms)] pub(super) const NO: BOOL = 0; pub(in super::super) type NSUInteger = usize; #[expect(clippy::upper_case_acronyms)] #[repr(transparent)] pub(in super::super) struct SEL(NonNull); #[repr(C)] pub(in super::super) struct Object(UnsafeCell<[u8; 0]>); #[repr(C)] pub(in super::super) struct Class(Object); impl Class { pub(super) fn alloc(&self) -> NSObject { extern "C" { fn objc_msgSend(obj: &Class, sel: SEL) -> NSObject; } let sel = selector!(alloc); unsafe { objc_msgSend(self, sel) } } } #[expect(non_camel_case_types)] #[repr(transparent)] pub(in super::super) struct id(NonNull); impl Deref for id { type Target = Object; fn deref(&self) -> &Self::Target { unsafe { self.0.as_ref() } } } impl Drop for id { fn drop(&mut self) { extern "C" { fn objc_release(obj: &Object); } unsafe { objc_release(self) } } } #[repr(transparent)] pub(in super::super) struct NSObject(id); impl Deref for NSObject { type Target = id; fn deref(&self) -> &Self::Target { &self.0 } } } pub(super) mod foundation { use std::ops::Deref; use super::objc::Class; use super::objc::NSObject; use super::objc::NSUInteger; use super::objc::BOOL; use super::objc::NO; use super::objc::SEL; #[repr(transparent)] pub(in super::super) struct NSStringEncoding(NSUInteger); impl NSStringEncoding { pub(in super::super) const UTF8: Self = Self(4); } #[repr(transparent)] pub(in super::super) struct NSString(NSObject); impl NSString { fn class() -> &'static Class { extern "C" { #[link_name = "OBJC_CLASS_$_NSString"] static CLASS: Class; } unsafe { &CLASS } } pub(in super::super) unsafe fn from_str_no_copy(string: &str) -> Self { extern "C" { fn objc_msgSend( obj: NSString, sel: SEL, bytes: *const u8, length: NSUInteger, encoding: NSStringEncoding, free_when_done: BOOL, ) -> NSString; } let obj = Self(Self::class().alloc()); let sel = selector!(initWithBytesNoCopy:length:encoding:freeWhenDone:); let bytes = string.as_ptr(); let length = string.len(); let encoding = NSStringEncoding::UTF8; let free_when_done = NO; unsafe { objc_msgSend(obj, sel, bytes, length, encoding, free_when_done) } } } impl Deref for NSString { type Target = NSObject; fn deref(&self) -> &Self::Target { &self.0 } } } normpath-1.5.0/src/common/localize/macos/mod.rs000064400000000000000000000056701046102023000175770ustar 00000000000000#![expect(clashing_extern_declarations)] use std::ops::Deref; use std::os::raw::c_char; use std::slice; use std::str; #[macro_use] mod fruity; use fruity::foundation::NSString; use fruity::foundation::NSStringEncoding; use fruity::objc::Class; use fruity::objc::NSObject; use fruity::objc::NSUInteger; use fruity::objc::Object; use fruity::objc::SEL; impl NSString { fn is_empty(&self) -> bool { extern "C" { fn objc_msgSend(obj: &Object, sel: SEL) -> NSUInteger; } let sel = selector!(length); let length = unsafe { objc_msgSend(self, sel) }; length == 0 } fn utf8_length(&self) -> usize { extern "C" { fn objc_msgSend( obj: &Object, sel: SEL, enc: NSStringEncoding, ) -> NSUInteger; } let sel = selector!(lengthOfBytesUsingEncoding:); let length = unsafe { objc_msgSend(self, sel, NSStringEncoding::UTF8) }; if length == 0 { assert!(self.is_empty()); } length } fn to_utf8_ptr(&self) -> *const u8 { extern "C" { fn objc_msgSend(obj: &Object, sel: SEL) -> *const c_char; } let sel = selector!(UTF8String); unsafe { objc_msgSend(self, sel) }.cast() } unsafe fn to_str(&self) -> &str { let length = self.utf8_length(); // SAFETY: These bytes are encoded using UTF-8. unsafe { str::from_utf8_unchecked(slice::from_raw_parts( self.to_utf8_ptr(), length, )) } } } impl ToString for NSString { fn to_string(&self) -> String { // SAFETY: The string has a short lifetime. unsafe { self.to_str() }.to_owned() } } #[repr(transparent)] struct NSFileManager(NSObject); impl NSFileManager { fn class() -> &'static Class { extern "C" { #[link_name = "OBJC_CLASS_$_NSFileManager"] static CLASS: Class; } unsafe { &CLASS } } fn default() -> Self { extern "C" { fn objc_msgSend(obj: &Class, sel: SEL) -> &Object; fn objc_retain(obj: &Object) -> NSFileManager; } let obj = Self::class(); let sel = selector!(defaultManager); unsafe { objc_retain(objc_msgSend(obj, sel)) } } } impl Deref for NSFileManager { type Target = NSObject; fn deref(&self) -> &Self::Target { &self.0 } } pub(super) fn name(path: &str) -> String { extern "C" { fn objc_msgSend(obj: &Object, sel: SEL, path: NSString) -> &Object; fn objc_retain(obj: &Object) -> NSString; } let obj = NSFileManager::default(); let sel = selector!(displayNameAtPath:); // SAFETY: This struct is dropped by the end of this method. let path = unsafe { NSString::from_str_no_copy(path) }; unsafe { objc_retain(objc_msgSend(&obj, sel, path)) }.to_string() } normpath-1.5.0/src/common/localize/mod.rs000064400000000000000000000007311046102023000164660ustar 00000000000000use std::ffi::OsString; use std::path::Path; #[cfg(any(target_os = "ios", target_os = "macos"))] mod macos; #[cfg_attr( not(any(target_os = "ios", target_os = "macos")), expect(unused_variables) )] pub(crate) fn name(path: &Path) -> Option { // Only UTF-8 paths can be localized on MacOS. #[cfg(any(target_os = "ios", target_os = "macos"))] if let Some(path) = path.to_str() { return Some(macos::name(path).into()); } None } normpath-1.5.0/src/common/mod.rs000064400000000000000000000015671046102023000146740ustar 00000000000000use std::borrow::Cow; use std::io; use std::path::Path; use crate::BasePathBuf; #[cfg(feature = "localization")] pub(super) mod localize; #[inline(always)] pub(crate) fn is_base(_: &Path) -> bool { true } #[inline(always)] pub(crate) fn to_base(_: &Path) -> io::Result { unreachable!(); } pub(crate) fn normalize(path: &Path) -> io::Result { // This method rejects null bytes and empty paths, which is consistent with // [GetFullPathNameW] on Windows. path.canonicalize().and_then(BasePathBuf::new) } pub(crate) fn expand(path: &Path) -> io::Result> { path.metadata().map(|_| Cow::Borrowed(path)) } pub(crate) fn shorten(path: &Path) -> io::Result> { expand(path) } pub(crate) fn push(base: &mut BasePathBuf, path: &Path) { if !path.as_os_str().is_empty() { base.0.push(path); } } normpath-1.5.0/src/error.rs000064400000000000000000000034461046102023000137540ustar 00000000000000//! The error types defined by this crate. use std::error::Error; use std::fmt; use std::fmt::Display; use std::fmt::Formatter; use std::path::Path; use std::path::PathBuf; /// The error returned when [`BasePath::try_new`] is given a path without a /// prefix. /// /// [`BasePath::try_new`]: super::BasePath::try_new #[derive(Clone, Debug, PartialEq)] pub struct MissingPrefixError(pub(super) ()); impl Display for MissingPrefixError { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { "path is missing a prefix".fmt(f) } } impl Error for MissingPrefixError {} /// The error returned when [`BasePathBuf::try_new`] is given a path without a /// prefix. /// /// [`BasePathBuf::try_new`]: super::BasePathBuf::try_new #[derive(Clone, Debug, PartialEq)] pub struct MissingPrefixBufError(pub(super) PathBuf); impl MissingPrefixBufError { /// Returns a reference to the path that caused this error. #[inline] #[must_use] pub fn as_path(&self) -> &Path { &self.0 } /// Returns the path that caused this error. #[inline] #[must_use] pub fn into_path_buf(self) -> PathBuf { self.0 } } impl Display for MissingPrefixBufError { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "path is missing a prefix: \"{}\"", self.0.display()) } } impl Error for MissingPrefixBufError {} /// The error returned when [`BasePath::parent`] cannot remove the path's last /// component. /// /// [`BasePath::parent`]: super::BasePath::parent #[derive(Clone, Debug, PartialEq)] pub struct ParentError(pub(super) ()); impl Display for ParentError { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { "cannot remove the path's last component".fmt(f) } } impl Error for ParentError {} normpath-1.5.0/src/lib.rs000064400000000000000000000334731046102023000133740ustar 00000000000000//! This crate provides methods to normalize paths in the recommended way for //! the operating system. //! //! It was made to fix a recurring bug caused by using [`fs::canonicalize`] on //! Windows: [#45067], [#48249], [#52440], [#55812], [#58613], [#59107], //! [#74327]. Normalization is usually a better choice unless you specifically //! need a canonical path. //! //! Using these replacement methods will usually fix those issues, but see //! their documentation for more information: //! - [`PathExt::normalize`] (*usually* replaces [`Path::canonicalize`]) //! - [`BasePath::join`] (replaces [`Path::join`]) //! - [`BasePath::parent`] (replaces [`Path::parent`]) //! - [`BasePathBuf::pop`] (replaces [`PathBuf::pop`]) //! - [`BasePathBuf::push`] (replaces [`PathBuf::push`]) //! //! Additionally, these methods can be used for other enhancements: //! - [`PathExt::localize_name`] //! //! # Features //! //! These features are optional and can be enabled or disabled in a //! "Cargo.toml" file. //! //! ### Optional Features //! //! - **localization** - //! Provides [`PathExt::localize_name`] and [`BasePath::localize_name`]. //! //! - **print\_bytes** - //! Provides implementations of [`print_bytes::ToBytes`] for [`BasePath`] and //! [`BasePathBuf`]. //! //! - **serde** - //! Provides implementations of [`serde::Deserialize`] and/or //! [`serde::Serialize`] for [`BasePath`] and [`BasePathBuf`]. //! //! - **uniquote** - //! Provides implementations of [`uniquote::Quote`] for [`BasePath`] and //! [`BasePathBuf`]. //! //! # Implementation //! //! Some methods return [`Cow`] to account for platform differences. However, //! no guarantee is made that the same variant of that enum will always be //! returned for the same platform. Whichever can be constructed most //! efficiently will be returned. //! //! All traits are [sealed], meaning that they can only be implemented by this //! crate. Otherwise, backward compatibility would be more difficult to //! maintain for new features. //! //! # Sponsorship //! //! If this crate has been useful for your project, let me know with a //! [sponsorship](https://github.com/sponsors/dylni)! Sponsorships help me //! create and maintain my open source libraries, and they are always very //! appreciated. //! //! # Examples //! //! ``` //! use std::io; //! use std::path::Path; //! //! use normpath::BasePathBuf; //! use normpath::PathExt; //! //! fn find_target_dir(path: &Path) -> io::Result> { //! let mut path = path.normalize()?; //! while !path.ends_with("target") { //! match path.pop() { //! Ok(true) => continue, //! Ok(false) => {} //! Err(_) => { //! eprintln!("Some components could not be normalized."); //! } //! } //! return Ok(None); //! } //! Ok(Some(path)) //! } //! ``` //! //! [#45067]: https://github.com/rust-lang/rust/issues/45067 //! [#48249]: https://github.com/rust-lang/rust/issues/48249 //! [#52440]: https://github.com/rust-lang/rust/issues/52440 //! [#55812]: https://github.com/rust-lang/rust/issues/55812 //! [#58613]: https://github.com/rust-lang/rust/issues/58613 //! [#59107]: https://github.com/rust-lang/rust/issues/59107 //! [#74327]: https://github.com/rust-lang/rust/issues/74327 //! [`fs::canonicalize`]: ::std::fs::canonicalize //! [`PathBuf::pop`]: ::std::path::PathBuf::pop //! [`PathBuf::push`]: ::std::path::PathBuf::push //! [sealed]: https://rust-lang.github.io/api-guidelines/future-proofing.html#c-sealed // Only require a nightly compiler when building documentation for docs.rs. // This is a private option that should not be used. // https://github.com/rust-lang/docs.rs/issues/147#issuecomment-389544407 #![cfg_attr(normpath_docs_rs, feature(doc_cfg))] #![warn(unused_results)] use std::borrow::Cow; #[cfg(feature = "localization")] use std::ffi::OsStr; use std::io; #[cfg(feature = "localization")] use std::path::Component; use std::path::Path; mod base; pub use base::BasePath; pub use base::BasePathBuf; mod cmp; pub mod error; #[cfg_attr(windows, path = "windows/mod.rs")] #[cfg_attr(not(windows), path = "common/mod.rs")] mod imp; #[cfg(feature = "localization")] use imp::localize; /// Additional methods added to [`Path`]. pub trait PathExt: private::Sealed { /// Expands `self` from its short form, if the convention exists for the /// platform. /// /// This method reverses [`shorten`] but may not return the original path. /// Additional components may be expanded that were not before calling /// [`shorten`]. /// /// # Implementation /// /// Currently, this method calls: /// - [`GetLongPathNameW`] on Windows. /// /// However, the implementation is subject to change. This section is only /// informative. /// /// # Errors /// /// Returns an error if `self` does not exist, even on Unix. /// /// # Examples /// /// ``` /// # use std::io; /// use std::path::Path; /// /// use normpath::PathExt; /// /// if cfg!(windows) { /// assert_eq!( /// Path::new(r"C:\Documents and Settings"), /// Path::new(r"C:\DOCUME~1").expand()?, /// ); /// } /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [`GetLongPathNameW`]: https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getlongpathnamew /// [`shorten`]: Self::shorten fn expand(&self) -> io::Result> where Self: ToOwned; /// Returns the localized simple name for this path. /// /// If the path does not exist or localization is not possible, the last /// component will be returned. /// /// The returned string should only be used for display to users. It will /// be as similar as possible to the name displayed by the system file /// manager for the path. However, nothing should be assumed about the /// result. /// /// # Implementation /// /// Currently, this method calls: /// ///
  • /// /// [`[NSFileManager displayNameAtPath:]`][displayNameAtPath] on MacOS /// ([rust-lang/rfcs#845]). /// ///
  • /// /// [`SHGetFileInfoW`] on Windows. /// ///
    /// /// This function has a usage note in its documentation: /// ///
    /// /// You should call this function from a background thread. Failure to do /// so could cause the UI to stop responding. /// ///
/// /// However, the implementation is subject to change. This section is only /// informative. /// /// # Panics /// /// Panics if the path ends with a `..` component. In the future, this /// method might also panic for paths ending with `.` components, so they /// should not be given either. They currently cause a platform-dependent /// value to be returned. /// /// You should usually only call this method on [normalized] paths to avoid /// these panics. /// /// # Examples /// /// ``` /// use std::path::Path; /// /// use normpath::PathExt; /// /// assert_eq!("test.rs", &*Path::new("/foo/bar/test.rs").localize_name()); /// ``` /// /// [displayNameAtPath]: https://developer.apple.com/documentation/foundation/nsfilemanager/1409751-displaynameatpath /// [normalized]: Self::normalize /// [rust-lang/rfcs#845]: https://github.com/rust-lang/rfcs/issues/845 /// [`SHGetFileInfoW`]: https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shgetfileinfow #[cfg(feature = "localization")] #[cfg_attr(normpath_docs_rs, doc(cfg(feature = "localization")))] #[must_use] fn localize_name(&self) -> Cow<'_, OsStr>; /// Normalizes `self` relative to the current directory. /// /// The purpose of normalization is to remove `.` and `..` components of a /// path if possible and make it absolute. This may be necessary for /// operations on the path string to be more reliable. /// /// This method will access the file system to normalize the path. If the /// path might not exist, [`normalize_virtually`] can be used instead, but /// it is only available on Windows. Other platforms require file system /// access to perform normalization. /// /// # Unix Behavior /// /// On Unix, normalization is equivalent to canonicalization. /// /// # Windows Behavior /// /// On Windows, normalization is similar to canonicalization, but: /// - the [prefix] of the path is rarely changed. Canonicalization would /// always return a [verbatim] path, which can be difficult to use. /// ([rust-lang/rust#42869]) /// - the result is more consistent. ([rust-lang/rust#49342]) /// - shared partition paths do not cause an error. /// ([rust-lang/rust#52440]) /// /// [Verbatim] paths will not be modified, so they might still contain `.` /// or `..` components. [`BasePath::join`] and [`BasePathBuf::push`] can /// normalize them before they become part of the path. Junction points /// will additionally not be resolved with the current implementation. /// /// # Implementation /// /// Currently, this method calls: /// - [`fs::canonicalize`] on Unix. /// - [`GetFullPathNameW`] on Windows. /// /// However, the implementation is subject to change. This section is only /// informative. /// /// # Errors /// /// Returns an error if `self` cannot be normalized or does not exist, even /// on Windows. /// /// This method is designed to give mostly consistent errors on different /// platforms, even when the functions it calls have different behavior. To /// normalize paths that might not exist, use [`normalize_virtually`]. /// /// # Examples /// /// ```no_run /// # use std::io; /// use std::path::Path; /// /// use normpath::PathExt; /// /// if cfg!(windows) { /// assert_eq!( /// Path::new(r"X:\foo\baz\test.rs"), /// Path::new("X:/foo/bar/../baz/test.rs").normalize()?, /// ); /// } /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [`fs::canonicalize`]: ::std::fs::canonicalize /// [`GetFullPathNameW`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew /// [`normalize_virtually`]: Self::normalize_virtually /// [rust-lang/rust#42869]: https://github.com/rust-lang/rust/issues/42869 /// [rust-lang/rust#49342]: https://github.com/rust-lang/rust/issues/49342 /// [rust-lang/rust#52440]: https://github.com/rust-lang/rust/issues/52440 /// [prefix]: ::std::path::Prefix /// [verbatim]: ::std::path::Prefix::is_verbatim fn normalize(&self) -> io::Result; /// Equivalent to [`normalize`] but does not access the file system. /// /// # Errors /// /// Returns an error if `self` cannot be normalized or contains a null /// byte. Nonexistent paths will not cause an error. /// /// # Examples /// /// ``` /// # use std::io; /// use std::path::Path; /// /// use normpath::PathExt; /// /// #[cfg(windows)] /// assert_eq!( /// Path::new(r"X:\foo\baz\test.rs"), /// Path::new("X:/foo/bar/../baz/test.rs").normalize_virtually()?, /// ); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [`normalize`]: Self::normalize #[cfg(any(doc, windows))] #[cfg_attr(normpath_docs_rs, doc(cfg(windows)))] fn normalize_virtually(&self) -> io::Result; /// Shortens `self` from its expanded form, if the convention exists for /// the platform. /// /// This method reverses [`expand`] but may not return the original path. /// Additional components may be shortened that were not before calling /// [`expand`]. /// /// # Implementation /// /// Currently, this method calls: /// - [`GetShortPathNameW`] on Windows. /// /// However, the implementation is subject to change. This section is only /// informative. /// /// # Errors /// /// Returns an error if `self` does not exist, even on Unix. /// /// # Examples /// /// ``` /// # use std::io; /// use std::path::Path; /// /// use normpath::PathExt; /// /// if cfg!(windows) { /// assert_eq!( /// Path::new(r"C:\DOCUME~1"), /// Path::new(r"C:\Documents and Settings").shorten()?, /// ); /// } /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [`expand`]: Self::expand /// [`GetShortPathNameW`]: https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getshortpathnamew fn shorten(&self) -> io::Result> where Self: ToOwned; } impl PathExt for Path { #[inline] fn expand(&self) -> io::Result> { imp::expand(self) } #[cfg(feature = "localization")] #[inline] fn localize_name(&self) -> Cow<'_, OsStr> { let Some(name) = self.components().next_back() else { return Cow::Borrowed(OsStr::new("")); }; assert_ne!( Component::ParentDir, name, "path ends with a `..` component: \"{}\"", self.display(), ); localize::name(self) .map(Cow::Owned) .unwrap_or_else(|| Cow::Borrowed(name.as_os_str())) } #[inline] fn normalize(&self) -> io::Result { imp::normalize(self) } #[cfg(any(doc, windows))] #[inline] fn normalize_virtually(&self) -> io::Result { imp::normalize_virtually(self) } #[inline] fn shorten(&self) -> io::Result> { imp::shorten(self) } } mod private { use std::path::Path; pub trait Sealed {} impl Sealed for Path {} } normpath-1.5.0/src/windows/localize.rs000064400000000000000000000024511046102023000161120ustar 00000000000000use std::ffi::OsString; use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStringExt; use std::path::Path; use std::ptr; use windows_sys::Win32::UI::Shell::SHGetFileInfoW; use windows_sys::Win32::UI::Shell::SHFILEINFOW; use windows_sys::Win32::UI::Shell::SHGFI_DISPLAYNAME; pub(crate) fn name(path: &Path) -> Option { let mut path: Vec<_> = path.as_os_str().encode_wide().collect(); if path.contains(&0) { return None; } path.push(0); let mut path_info = SHFILEINFOW { hIcon: ptr::null_mut(), iIcon: 0, dwAttributes: 0, szDisplayName: [0; 260], szTypeName: [0; 80], }; let result = unsafe { SHGetFileInfoW( path.as_ptr(), 0, &mut path_info, size_of_val(&path_info) .try_into() .expect("path information too large for WinAPI"), SHGFI_DISPLAYNAME, ) }; if result == 0 { return None; } // The display name buffer has a fixed length, so it must be truncated at // the first null character. Some(OsString::from_wide( path_info .szDisplayName .split(|&x| x == 0) .next() .expect("missing null byte in display name"), )) } normpath-1.5.0/src/windows/mod.rs000064400000000000000000000171361046102023000150750ustar 00000000000000use std::borrow::Cow; use std::env; use std::ffi::OsStr; use std::ffi::OsString; use std::io; use std::ops::Not; use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStringExt; use std::path::Component; use std::path::Path; use std::path::Prefix; use std::path::PrefixComponent; use std::ptr; use windows_sys::Win32::Storage::FileSystem::GetFullPathNameW; use windows_sys::Win32::Storage::FileSystem::GetLongPathNameW; use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW; use crate::BasePath; use crate::BasePathBuf; #[cfg(feature = "localization")] pub(super) mod localize; macro_rules! static_assert { ( $condition:expr ) => { const _: () = assert!($condition, "static assertion failed"); }; } fn is_separator(byte: &u8) -> bool { [b'/', b'\\'].contains(byte) } pub(crate) fn is_base(path: &Path) -> bool { matches!(path.components().next(), Some(Component::Prefix(_))) } pub(crate) fn to_base(path: &Path) -> io::Result { let base = env::current_dir()?; debug_assert!(is_base(&base)); let mut base = BasePathBuf(base); base.push(path); Ok(base) } #[inline(always)] const fn u32_to_usize(n: u32) -> usize { // This assertion should never fail. static_assert!(size_of::() <= size_of::()); n as usize } fn winapi_buffered(mut call_fn: F) -> io::Result> where F: FnMut(*mut u16, u32) -> u32, { let mut buffer = Vec::new(); let mut capacity = 0; loop { capacity = call_fn(buffer.as_mut_ptr(), capacity); if capacity == 0 { break Err(io::Error::last_os_error()); } let length = u32_to_usize(capacity); let Some(mut additional_capacity) = length.checked_sub(buffer.capacity()) else { // SAFETY: These characters were initialized by the syscall. unsafe { buffer.set_len(length); } return Ok(buffer); }; assert_ne!(0, additional_capacity); // WinAPI can recommend an insufficient capacity that causes it to // return incorrect results, so extra space is reserved as a // workaround. let extra_capacity = 2.min(capacity.not()); capacity += extra_capacity; additional_capacity += u32_to_usize(extra_capacity); buffer.reserve(additional_capacity); } } fn winapi_path( path: &Path, call_fn: fn(*const u16, *mut u16, u32) -> u32, ) -> io::Result> { if path.as_os_str().as_encoded_bytes().contains(&0) { return Err(io::Error::new( io::ErrorKind::InvalidInput, "strings passed to WinAPI cannot contains NULs", )); } match path.components().next() { // Verbatim paths should not be modified. Some(Component::Prefix(prefix)) if prefix.kind().is_verbatim() => { return Ok(Cow::Borrowed(path)); } Some(Component::RootDir) if path .as_os_str() .as_encoded_bytes() .get(1) .is_some_and(is_separator) => { return Err(io::Error::new( io::ErrorKind::NotFound, "partial UNC prefixes are invalid", )); } _ => {} } let mut path: Vec<_> = path.as_os_str().encode_wide().collect(); debug_assert!(!path.contains(&0)); path.push(0); path = winapi_buffered(|buffer, capacity| { call_fn(path.as_ptr(), buffer, capacity) })?; Ok(Cow::Owned(OsString::from_wide(&path).into())) } pub(crate) fn normalize_virtually(path: &Path) -> io::Result { winapi_path(path, |path, buffer, capacity| unsafe { GetFullPathNameW(path, capacity, buffer, ptr::null_mut()) }) .map(|x| BasePathBuf(x.into_owned())) } pub(crate) fn normalize(path: &Path) -> io::Result { // Trigger an error for nonexistent paths for consistency with other // platforms. let _ = path.metadata()?; normalize_virtually(path) } pub(crate) fn expand(path: &Path) -> io::Result> { winapi_path(path, |path, buffer, capacity| unsafe { GetLongPathNameW(path, buffer, capacity) }) } pub(crate) fn shorten(path: &Path) -> io::Result> { winapi_path(path, |path, buffer, capacity| unsafe { GetShortPathNameW(path, buffer, capacity) }) } fn get_prefix(base: &BasePath) -> PrefixComponent<'_> { if let Some(Component::Prefix(prefix)) = base.components().next() { prefix } else { // Base paths should always have a prefix. panic!( "base path is missing a prefix: \"{}\"", base.as_path().display(), ); } } fn convert_separators(path: &Path) -> Cow<'_, OsStr> { let path_bytes = path.as_os_str().as_encoded_bytes(); let mut parts = path_bytes.split(|&x| x == b'/'); let part = parts.next().expect("split iterator is empty"); if part.len() == path_bytes.len() { debug_assert_eq!(path_bytes, part); debug_assert_eq!(None, parts.next()); return Cow::Borrowed(path.as_os_str()); } let mut path_bytes = Vec::with_capacity(path_bytes.len()); path_bytes.extend(part); for part in parts { path_bytes.push(b'\\'); path_bytes.extend(part); } // SAFETY: Only UTF-8 substrings were replaced. Cow::Owned(unsafe { OsString::from_encoded_bytes_unchecked(path_bytes) }) } fn push_separator(base: &mut BasePathBuf) { // Add a separator if necessary. base.0.push(""); } pub(crate) fn push(base: &mut BasePathBuf, path: &Path) { let mut components = path.components(); let mut next_component = components.next(); match next_component { Some(Component::Prefix(prefix)) => { // Verbatim paths should not be modified. let mut absolute = prefix.kind().is_verbatim(); if !absolute { next_component = components.next(); // Other prefixes are absolute, except drive-relative prefixes. absolute = !matches!(prefix.kind(), Prefix::Disk(_)) || prefix.kind() != get_prefix(base).kind() // Equivalent to [path.has_root()] but more efficient. || next_component == Some(Component::RootDir); } if absolute { *base = BasePathBuf(path.to_owned()); return; } } Some(Component::RootDir) => { let mut buffer = get_prefix(base).as_os_str().to_owned(); buffer.push(convert_separators(path)); *base = BasePathBuf(buffer.into()); return; } _ => { while let Some(component) = next_component { match component { Component::CurDir => {} Component::ParentDir if base.pop().is_ok() => {} _ => break, } next_component = components.next(); } } } if let Some(component) = next_component { push_separator(base); base.0.as_mut_os_string().push(component); let components = components.as_path(); if !components.as_os_str().is_empty() { push_separator(base); base.0 .as_mut_os_string() .push(convert_separators(components)); } } let path_bytes = path.as_os_str().as_encoded_bytes(); // At least one separator should be kept. if path_bytes.last().is_some_and(is_separator) || matches!(path_bytes, [x, b'.'] if is_separator(x)) { push_separator(base); } }