normpath-1.1.1/.cargo_vcs_info.json0000644000000001360000000000100126640ustar { "git": { "sha1": "04f4be4a5e96b87e4bd9a667ad8dff03e1db85b5" }, "path_in_vcs": "" }normpath-1.1.1/COPYRIGHT000064400000000000000000000005031046102023000127450ustar 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.1.1/Cargo.toml0000644000000034060000000000100106650ustar # 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.57.0" name = "normpath" version = "1.1.1" authors = ["dylni"] exclude = [ ".*", "tests.rs", "/rustfmt.toml", "/src/bin", "/tests", ] 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", ] [dependencies.print_bytes] version = "1.0" optional = true [dependencies.serde] version = "1.0" optional = true [dependencies.uniquote] version = "3.2" optional = true [dev-dependencies.bincode] version = "1.3" [dev-dependencies.tempfile] version = "3.2" [features] localization = [ "windows-sys/Win32_UI_Shell", "windows-sys/Win32_UI_WindowsAndMessaging", ] [target."cfg(not(windows))".dev-dependencies.libc] version = "0.2" [target."cfg(windows)".dependencies.windows-sys] version = "0.48" features = ["Win32_Storage_FileSystem"] [target."cfg(windows)".dev-dependencies.windows-sys] version = "0.48" features = ["Win32_Foundation"] normpath-1.1.1/Cargo.toml.orig000064400000000000000000000022541046102023000143460ustar 00000000000000[package] name = "normpath" version = "1.1.1" authors = ["dylni"] edition = "2021" rust-version = "1.57.0" description = """ More reliable path manipulation """ readme = "README.md" repository = "https://github.com/dylni/normpath" license = "MIT OR Apache-2.0" 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 = "1.0", optional = true } serde = { version = "1.0", optional = true } uniquote = { version = "3.2", optional = true } [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.48", features = ["Win32_Storage_FileSystem"] } [dev-dependencies] bincode = "1.3" tempfile = "3.2" [target.'cfg(windows)'.dev-dependencies] windows-sys = { version = "0.48", features = ["Win32_Foundation"] } [target.'cfg(not(windows))'.dev-dependencies] libc = "0.2" [features] localization = ["windows-sys/Win32_UI_Shell", "windows-sys/Win32_UI_WindowsAndMessaging"] normpath-1.1.1/LICENSE-APACHE000064400000000000000000000236751046102023000134150ustar 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.1.1/LICENSE-MIT000064400000000000000000000021011046102023000131020ustar 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.1.1/LICENSE-THIRD-PARTY000064400000000000000000000566161046102023000142440ustar 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.1.1/README.md000064400000000000000000000056431046102023000127430ustar 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/workflows/build/badge.svg?branch=master)](https://github.com/dylni/normpath/actions?query=branch%3Amaster) ## Usage Add the following lines to your "Cargo.toml" file: ```toml [dependencies] normpath = "1.1" ``` See the [documentation] for available functionality and examples. ## Rust version support The minimum supported Rust toolchain version is currently Rust 1.57.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.1" ``` ## 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.1.1/src/base.rs000064400000000000000000000464471046102023000135420ustar 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::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::normalize; use super::PathExt; /// 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. /// /// Although this type is annotated with `#[repr(transparent)]`, the inner /// representation is not stable. Transmuting between this type and any other /// causes immediate undefined behavior. /// /// [prefix]: ::std::path::Prefix #[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[repr(transparent)] pub struct BasePath(pub(super) OsStr); impl BasePath { 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(|_| normalize::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 normalize::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!(normalize::is_base(&base)); BasePathBuf(base.into_os_string()) }) } /// 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 [`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() } /// 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 [`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() } } 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()) } } /// An owned path that has a [prefix] on Windows. /// /// For more information, see [`BasePath`]. /// /// [prefix]: ::std::path::Prefix #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct BasePathBuf(pub(super) OsString); 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| normalize::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 normalize::is_base(&path) { Ok(Self(path.into_os_string())) } else { Err(MissingPrefixBufError(path)) } } /// Returns the wrapped path as a platform string. #[inline] #[must_use] pub fn into_os_string(self) -> OsString { self.0 } /// Returns the wrapped path. #[inline] #[must_use] pub fn into_path_buf(self) -> PathBuf { self.0.into() } /// 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()) } pub(super) fn replace_with(&mut self, replace_fn: F) where F: FnOnce(PathBuf) -> PathBuf, { self.0 = replace_fn(mem::take(&mut self.0).into()).into_os_string(); } /// 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 { // This value is never used. let mut result = false; self.replace_with(|mut base| { result = base.pop(); base }); result } /// 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, { normalize::push(self, path.as_ref()); } } impl AsRef for BasePathBuf { #[inline] fn as_ref(&self) -> &OsStr { &self.0 } } impl AsRef for BasePathBuf { #[inline] fn as_ref(&self) -> &Path { self.as_path() } } 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) } } 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.0 } } impl From for PathBuf { #[inline] fn from(value: BasePathBuf) -> Self { value.into_path_buf() } } #[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(Self) } } 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.0) } } } #[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.1.1/src/cmp.rs000064400000000000000000000045731046102023000134010ustar 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.1.1/src/common/localize/macos/fruity.rs000064400000000000000000000104601046102023000203300ustar 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; #[allow(clippy::upper_case_acronyms)] pub(super) type BOOL = c_char; #[allow(clippy::upper_case_acronyms)] pub(super) const NO: BOOL = 0; pub(in super::super) type NSUInteger = usize; #[allow(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) } } } #[allow(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.1.1/src/common/localize/macos/mod.rs000064400000000000000000000056671046102023000176020ustar 00000000000000#![allow(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.1.1/src/common/localize/mod.rs000064400000000000000000000007301046102023000164620ustar 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")), allow(unused_variables) )] pub(super) 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.1.1/src/common/normalize.rs000064400000000000000000000012411046102023000160770ustar 00000000000000use std::io; use std::path::Path; use super::BasePathBuf; #[inline(always)] pub(super) fn is_base(_: &Path) -> bool { true } #[inline(always)] pub(super) fn to_base(_: &Path) -> io::Result { unreachable!(); } pub(super) 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(super) fn push(base: &mut BasePathBuf, path: &Path) { if !path.as_os_str().is_empty() { base.replace_with(|mut base| { base.push(path); base }); } } normpath-1.1.1/src/error.rs000064400000000000000000000035271046102023000137510ustar 00000000000000//! The error types defined by this crate. #![allow(clippy::derive_partial_eq_without_eq)] 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.1.1/src/lib.rs000064400000000000000000000255451046102023000133720ustar 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 //! //! 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)] #[cfg(feature = "localization")] 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(feature = "localization")] #[cfg_attr(windows, path = "windows/localize.rs")] #[cfg_attr(not(windows), path = "common/localize/mod.rs")] mod localize; #[cfg_attr(windows, path = "windows/normalize.rs")] #[cfg_attr(not(windows), path = "common/normalize.rs")] mod normalize; /// Additional methods added to [`Path`]. pub trait PathExt: private::Sealed { /// 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. /// /// However, the implementation is subject to change. This section is only /// informative. /// ///
/// Warning: Documentation for SHGetFileInfoW /// has this note: ///
/// You should call this function from a background thread. Failure to do /// so could cause the UI to stop responding. ///
///
/// /// # 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. /// /// 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]) /// /// However, [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. /// /// # 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; } impl PathExt for Path { #[cfg(feature = "localization")] #[inline] fn localize_name(&self) -> Cow<'_, OsStr> { let name = if let Some(name) = self.components().next_back() { name } 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 { normalize::normalize(self) } #[cfg(any(doc, windows))] #[inline] fn normalize_virtually(&self) -> io::Result { normalize::normalize_virtually(self) } } mod private { use std::path::Path; pub trait Sealed {} impl Sealed for Path {} } normpath-1.1.1/src/windows/localize.rs000064400000000000000000000024401046102023000161050ustar 00000000000000use std::ffi::OsString; use std::mem; use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStringExt; use std::path::Path; use windows_sys::Win32::UI::Shell::SHGetFileInfoW; use windows_sys::Win32::UI::Shell::SHFILEINFOW; use windows_sys::Win32::UI::Shell::SHGFI_DISPLAYNAME; pub(super) 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: 0, iIcon: 0, dwAttributes: 0, szDisplayName: [0; 260], szTypeName: [0; 80], }; let result = unsafe { SHGetFileInfoW( path.as_ptr(), 0, &mut path_info, mem::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.1.1/src/windows/normalize.rs000064400000000000000000000154011046102023000163040ustar 00000000000000use std::env; use std::ffi::OsString; use std::io; use std::mem; use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStringExt; use std::path::Component; use std::path::Path; use std::path::PathBuf; use std::path::Prefix; use std::path::PrefixComponent; use std::ptr; use windows_sys::Win32::Storage::FileSystem::GetFullPathNameW; use super::BasePath; use super::BasePathBuf; macro_rules! static_assert { ( $condition:expr ) => { const _: () = assert!($condition, "static assertion failed"); }; } const SEPARATOR: u16 = b'\\' as _; pub(super) fn is_base(path: &Path) -> bool { matches!(path.components().next(), Some(Component::Prefix(_))) } pub(super) fn to_base(path: &Path) -> io::Result { let base = env::current_dir()?; debug_assert!(is_base(&base)); let mut base = BasePathBuf(base.into_os_string()); base.push(path); Ok(base) } fn convert_separators(path: &Path) -> (Vec, PathBuf) { let mut wide_path: Vec<_> = path.as_os_str().encode_wide().collect(); for ch in &mut wide_path { if ch == &b'/'.into() { *ch = SEPARATOR; } } let path = OsString::from_wide(&wide_path).into(); (wide_path, path) } fn normalize_verbatim(path: &Path) -> BasePathBuf { let mut path: Vec<_> = path.as_os_str().encode_wide().collect(); // Normalizing more of a verbatim path can change its meaning. The part // changed here is required for the path to be verbatim. for ch in &mut path[..4] { if ch == &b'/'.into() { *ch = SEPARATOR; } } BasePathBuf(OsString::from_wide(&path)) } pub(super) fn normalize_virtually( initial_path: &Path, ) -> io::Result { // [GetFullPathNameW] always converts separators. let (mut wide_path, path) = convert_separators(initial_path); if wide_path.contains(&0) { return Err(io::Error::new( io::ErrorKind::InvalidInput, "strings passed to WinAPI cannot contains NULs", )); } wide_path.push(0); match path.components().next() { // Verbatim paths should not be modified. Some(Component::Prefix(prefix)) if prefix.kind().is_verbatim() => { return Ok(normalize_verbatim(initial_path)); } Some(Component::RootDir) if wide_path[1] == SEPARATOR => { return Err(io::Error::new( io::ErrorKind::NotFound, "partial UNC prefixes are invalid", )); } _ => {} } let mut buffer = Vec::new(); let mut capacity = 0; loop { capacity = unsafe { GetFullPathNameW( wide_path.as_ptr(), capacity, buffer.as_mut_ptr(), ptr::null_mut(), ) }; if capacity == 0 { break Err(io::Error::last_os_error()); } let _: u32 = capacity; // This assertion should never fail. static_assert!(mem::size_of::() <= mem::size_of::()); let length = capacity as usize; if let Some(mut additional_capacity) = length.checked_sub(buffer.capacity()) { 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. macro_rules! extra_capacity { () => { 2 }; } capacity = capacity.checked_add(extra_capacity!()).ok_or_else(|| { io::Error::new( io::ErrorKind::Other, "required path length is too large for WinAPI", ) })?; additional_capacity += extra_capacity!(); buffer.reserve(additional_capacity); continue; } // SAFETY: These characters were initialized by the syscall. unsafe { buffer.set_len(length); } break Ok(BasePathBuf(OsString::from_wide(&buffer))); } } pub(super) fn normalize(path: &Path) -> io::Result { path.metadata().and_then(|_| normalize_virtually(path)) } 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 push_separator(base: &mut BasePathBuf) { base.replace_with(|mut base| { // Add a separator if necessary. base.push(""); base }); } pub(super) fn push(base: &mut BasePathBuf, initial_path: &Path) { // [GetFullPathNameW] always converts separators. let (wide_path, path) = convert_separators(initial_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. if prefix.kind().is_verbatim() { *base = normalize_verbatim(initial_path); return; } next_component = components.next(); // Other prefixes are absolute, except drive-relative prefixes. if !matches!(prefix.kind(), Prefix::Disk(_)) || prefix.kind() != get_prefix(base).kind() // Equivalent to [path.has_root()] but more efficient. || next_component == Some(Component::RootDir) { *base = BasePathBuf(path.into_os_string()); return; } } Some(Component::RootDir) => { let mut buffer = get_prefix(base).as_os_str().to_owned(); buffer.push(path); *base = BasePathBuf(buffer); 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.push(component); let components = components.as_path(); if !components.as_os_str().is_empty() { push_separator(base); base.0.push(components); } } // At least one separator should be kept. if wide_path.last() == Some(&SEPARATOR) || wide_path.ends_with(&[SEPARATOR, b'.'.into()]) { push_separator(base); } }