find-crate-0.7.1/.cargo_vcs_info.json0000644000000001361046102023000130770ustar { "git": { "sha1": "8df2b29ddbc6a558e571a2fdbfa6d0dae5390a54" }, "path_in_vcs": "" }find-crate-0.7.1/CHANGELOG.md000064400000000000000000000071131046102023000134600ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org). Releases may yanked if there is a security bug, a soundness bug, or a regression. ## [Unreleased] ## [0.7.1] - 2026-02-13 - Update `toml` dependency to 1. ## [0.7.0] - 2026-02-07 - Remove `toml` from public dependencies to prevent `toml` updates from becoming breaking changes. ([#27](https://github.com/taiki-e/find-crate/pull/27), thanks @TechnoPorg) - Remove `Manifest::from_toml`. Use `text.parse()`/`Manifest::from_str(text)` or `Manifest::from_path(path)` instead. - Change the type of `Error::Toml` from `toml::de::Error` to `TomlError`. - Make `Dependencies` enum `#[non_exhaustive]`. - Implement `FromStr` for `Manifest`. ([#27](https://github.com/taiki-e/find-crate/pull/27), thanks @TechnoPorg) - Add `Manifest::from_path`. - Support [version-less manifests](https://github.com/rust-lang/cargo/pull/12786) in `crate_package`. - Support target names that contain ".". - Add `#[must_use]` to constructor and getters. - Update `toml` dependency to 0.9. This increases the minimum supported Rust version (MSRV) to Rust 1.76. - Enable [release immutability](https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases). ## [0.6.3] - 2021-01-05 - Exclude unneeded files from crates.io. ## [0.6.2] - 2020-12-29 - Documentation improvements. ## [0.6.1] - 2020-09-07 - Documentation improvements. ## [0.6.0] - 2020-08-27 - [Add `Manifest::crate_package`.](https://github.com/taiki-e/find-crate/pull/12) - Make `Error` non-exhaustive. ## [0.5.0] - 2019-09-29 - Make `Manifest::dependencies` and `Package::{name, version}` fields public. - Add support for `target.cfg.dependencies`. - Add `Dependencies` enum to manage the kind of dependencies to be searched. - Remove `Manifest::lock()` and `ManifestLock`. - Remove some variant and field form `Error`. - Remove `DEFAULT_DEPENDENCIES`. ## [0.4.0] - 2019-06-16 - Transition to Rust 2018. With this change, the minimum required version will go up to Rust 1.31. - Update minimum `toml` version to 0.5.0. ## [0.3.0] - 2019-02-21 - Remove version dependent behavior. - Documentation improvements. ## [0.2.0] - 2019-02-13 - Support Rust 1.15. ## [0.1.2] - 2019-02-13 - Implement `PartialEq` and `Eq` for `Package`. ## [0.1.1] - 2019-02-13 - Documentation improvements. ## [0.1.0] - 2019-02-13 Initial release [Unreleased]: https://github.com/taiki-e/find-crate/compare/v0.7.1...HEAD [0.7.1]: https://github.com/taiki-e/find-crate/compare/v0.7.0...v0.7.1 [0.7.0]: https://github.com/taiki-e/find-crate/compare/v0.6.3...v0.7.0 [0.6.3]: https://github.com/taiki-e/find-crate/compare/v0.6.2...v0.6.3 [0.6.2]: https://github.com/taiki-e/find-crate/compare/v0.6.1...v0.6.2 [0.6.1]: https://github.com/taiki-e/find-crate/compare/v0.6.0...v0.6.1 [0.6.0]: https://github.com/taiki-e/find-crate/compare/v0.5.0...v0.6.0 [0.5.0]: https://github.com/taiki-e/find-crate/compare/v0.4.0...v0.5.0 [0.4.0]: https://github.com/taiki-e/find-crate/compare/v0.3.0...v0.4.0 [0.3.0]: https://github.com/taiki-e/find-crate/compare/v0.2.0...v0.3.0 [0.2.0]: https://github.com/taiki-e/find-crate/compare/v0.1.2...v0.2.0 [0.1.2]: https://github.com/taiki-e/find-crate/compare/v0.1.1...v0.1.2 [0.1.1]: https://github.com/taiki-e/find-crate/compare/v0.1.0...v0.1.1 [0.1.0]: https://github.com/taiki-e/find-crate/releases/tag/v0.1.0 find-crate-0.7.1/Cargo.lock0000644000000103111046102023000110460ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "equivalent" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "find-crate" version = "0.7.1" dependencies = [ "proc-macro2", "quote", "rustversion", "semver", "static_assertions", "toml", ] [[package]] name = "hashbrown" version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" [[package]] name = "indexmap" version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" dependencies = [ "equivalent", "hashbrown", ] [[package]] name = "proc-macro2" version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" dependencies = [ "proc-macro2", ] [[package]] name = "rustversion" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "semver" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" [[package]] name = "serde_core" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_spanned" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8bbf91e5a4d6315eee45e704372590b30e260ee83af6639d64557f51b067776" dependencies = [ "serde_core", ] [[package]] name = "static_assertions" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "syn" version = "2.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e614ed320ac28113fa64972c4262d5dbc89deacdfd00c34a3e4cea073243c12" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "toml" version = "1.0.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbe30f93627849fa362d4a602212d41bb237dc2bd0f8ba0b2ce785012e124220" dependencies = [ "indexmap", "serde_core", "serde_spanned", "toml_datetime", "toml_parser", "toml_writer", "winnow", ] [[package]] name = "toml_datetime" version = "1.0.0+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32c2555c699578a4f59f0cc68e5116c8d7cabbd45e1409b989d4be085b53f13e" dependencies = [ "serde_core", ] [[package]] name = "toml_parser" version = "1.0.8+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0742ff5ff03ea7e67c8ae6c93cac239e0d9784833362da3f9a9c1da8dfefcbdc" dependencies = [ "winnow", ] [[package]] name = "toml_writer" version = "1.0.6+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607" [[package]] name = "unicode-ident" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "537dd038a89878be9b64dd4bd1b260315c1bb94f4d784956b81e27a088d9a09e" [[package]] name = "winnow" version = "0.7.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829" find-crate-0.7.1/Cargo.toml0000644000000073071046102023000111040ustar # 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.76" name = "find-crate" version = "0.7.1" build = false exclude = [ "/.*", "/tools", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = """ Find the crate name from the current Cargo.toml. """ readme = "README.md" keywords = [ "macros", "crate", ] categories = ["development-tools::procedural-macro-helpers"] license = "Apache-2.0 OR MIT" repository = "https://github.com/taiki-e/find-crate" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [package.metadata.cargo_check_external_types] allowed_external_types = [] [lib] name = "find_crate" path = "src/lib.rs" doc-scrape-examples = false [[test]] name = "test" path = "tests/test.rs" [dependencies.toml] version = "1" features = [ "std", "parse", "serde", ] default-features = false [dev-dependencies.proc-macro2] version = "1" default-features = false [dev-dependencies.quote] version = "1" default-features = false [dev-dependencies.rustversion] version = "1" [dev-dependencies.semver] version = "1" [dev-dependencies.static_assertions] version = "1" [lints.clippy] all = "warn" as_ptr_cast_mut = "warn" as_underscore = "warn" default_union_representation = "warn" inline_asm_x86_att_syntax = "warn" pedantic = "warn" trailing_empty_array = "warn" transmute_undefined_repr = "warn" undocumented_unsafe_blocks = "warn" unused_trait_names = "warn" [lints.clippy.bool_assert_comparison] level = "allow" priority = 1 [lints.clippy.borrow_as_ptr] level = "allow" priority = 1 [lints.clippy.cast_lossless] level = "allow" priority = 1 [lints.clippy.declare_interior_mutable_const] level = "allow" priority = 1 [lints.clippy.doc_markdown] level = "allow" priority = 1 [lints.clippy.float_cmp] level = "allow" priority = 1 [lints.clippy.incompatible_msrv] level = "allow" priority = 1 [lints.clippy.lint_groups_priority] level = "allow" priority = 1 [lints.clippy.manual_assert] level = "allow" priority = 1 [lints.clippy.manual_range_contains] level = "allow" priority = 1 [lints.clippy.missing_errors_doc] level = "allow" priority = 1 [lints.clippy.module_name_repetitions] level = "allow" priority = 1 [lints.clippy.naive_bytecount] level = "allow" priority = 1 [lints.clippy.nonminimal_bool] level = "allow" priority = 1 [lints.clippy.range_plus_one] level = "allow" priority = 1 [lints.clippy.similar_names] level = "allow" priority = 1 [lints.clippy.single_match] level = "allow" priority = 1 [lints.clippy.single_match_else] level = "allow" priority = 1 [lints.clippy.struct_excessive_bools] level = "allow" priority = 1 [lints.clippy.struct_field_names] level = "allow" priority = 1 [lints.clippy.too_many_arguments] level = "allow" priority = 1 [lints.clippy.too_many_lines] level = "allow" priority = 1 [lints.clippy.type_complexity] level = "allow" priority = 1 [lints.clippy.unreadable_literal] level = "allow" priority = 1 [lints.rust] deprecated_safe = "warn" improper_ctypes = "warn" improper_ctypes_definitions = "warn" non_ascii_idents = "warn" rust_2018_idioms = "warn" single_use_lifetimes = "warn" unnameable_types = "warn" unreachable_pub = "warn" unsafe_op_in_unsafe_fn = "warn" [lints.rust.unexpected_cfgs] level = "warn" priority = 0 check-cfg = ["cfg(careful)"] find-crate-0.7.1/Cargo.toml.orig000064400000000000000000000100311046102023000145270ustar 00000000000000[package] name = "find-crate" version = "0.7.1" #publish:version edition = "2021" # NB: Sync with msrv badge in README.md rust-version = "1.76" # For toml license = "Apache-2.0 OR MIT" repository = "https://github.com/taiki-e/find-crate" keywords = ["macros", "crate"] categories = ["development-tools::procedural-macro-helpers"] exclude = ["/.*", "/tools"] description = """ Find the crate name from the current Cargo.toml. """ [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [package.metadata.cargo_check_external_types] # The following are external types that are allowed to be exposed in our public API. allowed_external_types = [ ] [lib] doc-scrape-examples = false [dependencies] toml = { version = "1", default-features = false, features = ["std", "parse", "serde"] } [dev-dependencies] proc-macro2 = { version = "1", default-features = false } quote = { version = "1", default-features = false } rustversion = "1" semver = "1" static_assertions = "1" test-helper = { features = ["git"], git = "https://github.com/taiki-e/test-helper.git", rev = "c5eac31" } [lints] workspace = true [workspace] resolver = "2" members = ["tools/codegen"] # This table is shared by projects under github.com/taiki-e. # Expect for unexpected_cfgs.check-cfg, it is not intended for manual editing. [workspace.lints.rust] deprecated_safe = "warn" improper_ctypes = "warn" improper_ctypes_definitions = "warn" non_ascii_idents = "warn" rust_2018_idioms = "warn" single_use_lifetimes = "warn" unexpected_cfgs = { level = "warn", check-cfg = [ 'cfg(careful)', ] } unnameable_types = "warn" unreachable_pub = "warn" unsafe_op_in_unsafe_fn = "warn" [workspace.lints.clippy] all = "warn" # Downgrade deny-by-default lints pedantic = "warn" as_ptr_cast_mut = "warn" as_underscore = "warn" default_union_representation = "warn" inline_asm_x86_att_syntax = "warn" trailing_empty_array = "warn" transmute_undefined_repr = "warn" undocumented_unsafe_blocks = "warn" unused_trait_names = "warn" # Suppress buggy or noisy clippy lints bool_assert_comparison = { level = "allow", priority = 1 } borrow_as_ptr = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/8286 cast_lossless = { level = "allow", priority = 1 } # https://godbolt.org/z/Pv6vbGG6E declare_interior_mutable_const = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/7665 doc_markdown = { level = "allow", priority = 1 } float_cmp = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/7725 incompatible_msrv = { level = "allow", priority = 1 } # buggy: doesn't consider cfg, https://github.com/rust-lang/rust-clippy/issues/12280, https://github.com/rust-lang/rust-clippy/issues/12257#issuecomment-2093667187 lint_groups_priority = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/12920 manual_assert = { level = "allow", priority = 1 } manual_range_contains = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/6455#issuecomment-1225966395 missing_errors_doc = { level = "allow", priority = 1 } module_name_repetitions = { level = "allow", priority = 1 } # buggy: https://github.com/rust-lang/rust-clippy/issues?q=is%3Aissue+is%3Aopen+module_name_repetitions naive_bytecount = { level = "allow", priority = 1 } nonminimal_bool = { level = "allow", priority = 1 } # buggy: https://github.com/rust-lang/rust-clippy/issues?q=is%3Aissue+is%3Aopen+nonminimal_bool range_plus_one = { level = "allow", priority = 1 } # buggy: https://github.com/rust-lang/rust-clippy/issues?q=is%3Aissue+is%3Aopen+range_plus_one similar_names = { level = "allow", priority = 1 } single_match = { level = "allow", priority = 1 } single_match_else = { level = "allow", priority = 1 } struct_excessive_bools = { level = "allow", priority = 1 } struct_field_names = { level = "allow", priority = 1 } too_many_arguments = { level = "allow", priority = 1 } too_many_lines = { level = "allow", priority = 1 } type_complexity = { level = "allow", priority = 1 } unreadable_literal = { level = "allow", priority = 1 } find-crate-0.7.1/LICENSE-APACHE000064400000000000000000000236761046102023000136070ustar 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 find-crate-0.7.1/LICENSE-MIT000064400000000000000000000017771046102023000133150ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. find-crate-0.7.1/README.md000064400000000000000000000110061046102023000131220ustar 00000000000000# find-crate [![crates.io](https://img.shields.io/crates/v/find-crate?style=flat-square&logo=rust)](https://crates.io/crates/find-crate) [![docs.rs](https://img.shields.io/badge/docs.rs-find--crate-blue?style=flat-square&logo=docs.rs)](https://docs.rs/find-crate) [![license](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue?style=flat-square)](#license) [![msrv](https://img.shields.io/badge/msrv-1.76-blue?style=flat-square&logo=rust)](https://www.rust-lang.org) [![github actions](https://img.shields.io/github/actions/workflow/status/taiki-e/find-crate/ci.yml?branch=main&style=flat-square&logo=github)](https://github.com/taiki-e/find-crate/actions) Find the crate name from the current `Cargo.toml`. When writing declarative macros, `$crate` representing the current crate is very useful, but procedural macros do not have this. If you know the current name of the crate you want to use, you can do the same thing as `$crate`. This crate provides the features to make it easy. ## Usage Add this to your `Cargo.toml`: ```toml [dependencies] find-crate = "0.7" ``` ## Examples [`find_crate`] function gets the crate name from the current `Cargo.toml`. ```rust use find_crate::find_crate; use proc_macro2::{Ident, Span, TokenStream}; use quote::quote; fn import() -> TokenStream { let name = find_crate(|name| name == "foo").unwrap().name; let name = Ident::new(&name, Span::call_site()); // If your proc-macro crate is 2018 edition, use `quote!(use #name as _foo;)` instead. quote!(extern crate #name as _foo;) } ``` As in this example, it is easy to handle cases where proc-macro is exported from multiple crates. ```rust use find_crate::find_crate; use proc_macro2::{Ident, Span, TokenStream}; use quote::quote; fn import() -> TokenStream { let name = find_crate(|name| name == "foo" || name == "foo-core").unwrap().name; let name = Ident::new(&name, Span::call_site()); // If your proc-macro crate is 2018 edition, use `quote!(use #name as _foo;)` instead. quote!(extern crate #name as _foo;) } ``` Using [`Manifest`] to search for multiple crates. It is much more efficient than using [`find_crate`] function for each crate. ```rust use find_crate::Manifest; use proc_macro2::{Ident, Span, TokenStream}; use quote::{format_ident, quote}; const CRATE_NAMES: &[&[&str]] = &[ &["foo", "foo-core"], &["bar", "bar-util", "bar-core"], &["baz"], ]; fn imports() -> TokenStream { let mut tokens = TokenStream::new(); let manifest = Manifest::new().unwrap(); for names in CRATE_NAMES { let name = manifest.find(|name| names.contains(&name)).unwrap().name; let name = Ident::new(&name, Span::call_site()); let import_name = format_ident!("_{}", names[0]); // If your proc-macro crate is 2018 edition, use `quote!(use #name as #import_name;)` instead. tokens.extend(quote!(extern crate #name as #import_name;)); } tokens } ``` By default it will be searched from `dependencies` and `dev-dependencies`. This behavior can be adjusted by changing the [`Manifest::dependencies`] field. [`find_crate`] and [`Manifest::new`] functions read `Cargo.toml` in [`CARGO_MANIFEST_DIR`] as manifest. ## Alternatives If you write function-like procedural macros, [you can combine it with declarative macros to support both crate renaming and macro re-exporting.][rust-lang/futures-rs#2124] This crate is intended to provide more powerful features such as support for multiple crate names and versions. For general purposes, [proc-macro-crate], which provides a simpler API, may be easier to use. [`CARGO_MANIFEST_DIR`]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates [rust-lang/futures-rs#2124]: https://github.com/rust-lang/futures-rs/pull/2124 [proc-macro-crate]: https://github.com/bkchr/proc-macro-crate [`Manifest::new`]: https://docs.rs/find-crate/latest/find_crate/struct.Manifest.html#method.new [`Manifest`]: https://docs.rs/find-crate/latest/find_crate/struct.Manifest.html [`find_crate`]: https://docs.rs/find-crate/latest/find_crate/fn.find_crate.html ## License Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or [MIT license](LICENSE-MIT) at your option. Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. find-crate-0.7.1/src/error.rs000064400000000000000000000045411046102023000141370ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT use alloc::string::String; use core::fmt; use std::io; use crate::MANIFEST_DIR; /// An error which occurred while parsing the TOML manifest #[derive(Debug)] pub struct TomlError { pub(super) error: toml::de::Error, } impl fmt::Display for TomlError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.error.fmt(f) } } impl std::error::Error for TomlError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.error) } } /// An error that occurred when getting manifest. #[derive(Debug)] #[non_exhaustive] pub enum Error { /// The [`CARGO_MANIFEST_DIR`] environment variable not found. /// /// [`CARGO_MANIFEST_DIR`]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates NotFoundManifestDir, /// The manifest is invalid for the following reason. InvalidManifest(String), /// The crate with the specified name not found. This error occurs only from [`find_crate`]. /// /// [`find_crate`]: super::find_crate NotFound, /// An error occurred while trying to open or to read the manifest file. Io(io::Error), /// An error occurred while trying to parse the manifest file. Toml(TomlError), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::NotFoundManifestDir => { write!(f, "`{MANIFEST_DIR}` environment variable not found") } Error::InvalidManifest(reason) => { write!(f, "The manifest is invalid because: {reason}") } Error::NotFound => { f.write_str("the crate with the specified name not found in dependencies") } Error::Io(e) => write!(f, "an error occurred while to open or to read: {e}"), Error::Toml(e) => write!(f, "an error occurred while parsing the manifest file: {e}"), } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::Io(e) => Some(e), Error::Toml(e) => Some(e), _ => None, } } } impl From for Error { fn from(e: io::Error) -> Self { Error::Io(e) } } find-crate-0.7.1/src/gen/tests/assert_impl.rs000064400000000000000000000045471046102023000172510ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT // This file is @generated by find-crate-internal-codegen // (gen_assert_impl function at tools/codegen/src/main.rs). // It is not intended for manual editing. #![cfg_attr(rustfmt, rustfmt::skip)] #![allow( dead_code, unused_macros, clippy::std_instead_of_alloc, clippy::std_instead_of_core, )] fn assert_send() {} fn assert_sync() {} fn assert_unpin() {} fn assert_unwind_safe() {} fn assert_ref_unwind_safe() {} macro_rules! assert_not_send { ($ty:ty) => { static_assertions::assert_not_impl_all!($ty : Send); }; } macro_rules! assert_not_sync { ($ty:ty) => { static_assertions::assert_not_impl_all!($ty : Sync); }; } macro_rules! assert_not_unpin { ($ty:ty) => { static_assertions::assert_not_impl_all!($ty : Unpin); }; } macro_rules! assert_not_unwind_safe { ($ty:ty) => { static_assertions::assert_not_impl_all!($ty : std::panic::UnwindSafe); }; } macro_rules! assert_not_ref_unwind_safe { ($ty:ty) => { static_assertions::assert_not_impl_all!($ty : std::panic::RefUnwindSafe); }; } const _: fn() = || { assert_send::(); assert_sync::(); assert_unpin::(); assert_unwind_safe::(); assert_ref_unwind_safe::(); assert_send::(); assert_sync::(); assert_unpin::(); assert_not_unwind_safe!(crate::error::Error); assert_not_ref_unwind_safe!(crate::error::Error); assert_send::(); assert_sync::(); assert_unpin::(); assert_unwind_safe::(); assert_ref_unwind_safe::(); assert_send::(); assert_sync::(); assert_unpin::(); assert_unwind_safe::(); assert_ref_unwind_safe::(); assert_send::(); assert_sync::(); assert_unpin::(); assert_unwind_safe::(); assert_ref_unwind_safe::(); }; find-crate-0.7.1/src/gen/tests/track_size.rs000064400000000000000000000027341046102023000170610ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT // This file is @generated by find-crate-internal-codegen // (gen_track_size function at tools/codegen/src/main.rs). // It is not intended for manual editing. #![cfg_attr(rustfmt, rustfmt::skip)] #![allow(dead_code, clippy::std_instead_of_alloc, clippy::std_instead_of_core)] use std::{fmt::Write as _, path::Path, string::String}; fn write_size(out: &mut String) { let _ = writeln!( out, "{}: {}", std::any::type_name:: (), std::mem::size_of:: () ); } /// Test the size of public types. This is not intended to keep a specific size and is intended to /// be used only as a help in optimization. /// /// Ignore non-64-bit targets due to usize/ptr size, ignore Miri/cargo-careful as we set /// -Z randomize-layout for them, and ignore old rustc as any::type_name output and size /// optimization may differ between compiler versions. #[rustversion::attr( nightly, cfg_attr(any(not(target_pointer_width = "64"), miri, careful), ignore) )] #[rustversion::attr(not(nightly), ignore)] #[test] fn track_size() { let mut out = String::new(); write_size::(&mut out); write_size::(&mut out); write_size::(&mut out); write_size::(&mut out); write_size::(&mut out); test_helper::git::assert_diff( Path::new(env!("CARGO_MANIFEST_DIR")).join("src/gen/tests/track_size.txt"), out, ); } find-crate-0.7.1/src/gen/tests/track_size.txt000064400000000000000000000002131046102023000172420ustar 00000000000000find_crate::error::TomlError: 88 find_crate::error::Error: 88 find_crate::Dependencies: 1 find_crate::Package: 96 find_crate::Manifest: 40 find-crate-0.7.1/src/lib.rs000064400000000000000000000360441046102023000135570ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT /*! Find the crate name from the current `Cargo.toml`. When writing declarative macros, `$crate` representing the current crate is very useful, but procedural macros do not have this. If you know the current name of the crate you want to use, you can do the same thing as `$crate`. This crate provides the features to make it easy. ## Usage Add this to your `Cargo.toml`: ```toml [dependencies] find-crate = "0.7" ``` ## Examples [`find_crate`] function gets the crate name from the current `Cargo.toml`. ``` use find_crate::find_crate; use proc_macro2::{Ident, Span, TokenStream}; use quote::quote; fn import() -> TokenStream { let name = find_crate(|name| name == "foo").unwrap().name; let name = Ident::new(&name, Span::call_site()); // If your proc-macro crate is 2018 edition, use `quote!(use #name as _foo;)` instead. quote!(extern crate #name as _foo;) } ``` As in this example, it is easy to handle cases where proc-macro is exported from multiple crates. ``` use find_crate::find_crate; use proc_macro2::{Ident, Span, TokenStream}; use quote::quote; fn import() -> TokenStream { let name = find_crate(|name| name == "foo" || name == "foo-core").unwrap().name; let name = Ident::new(&name, Span::call_site()); // If your proc-macro crate is 2018 edition, use `quote!(use #name as _foo;)` instead. quote!(extern crate #name as _foo;) } ``` Using [`Manifest`] to search for multiple crates. It is much more efficient than using [`find_crate`] function for each crate. ``` use find_crate::Manifest; use proc_macro2::{Ident, Span, TokenStream}; use quote::{format_ident, quote}; const CRATE_NAMES: &[&[&str]] = &[ &["foo", "foo-core"], &["bar", "bar-util", "bar-core"], &["baz"], ]; fn imports() -> TokenStream { let mut tokens = TokenStream::new(); let manifest = Manifest::new().unwrap(); for names in CRATE_NAMES { let name = manifest.find(|name| names.contains(&name)).unwrap().name; let name = Ident::new(&name, Span::call_site()); let import_name = format_ident!("_{}", names[0]); // If your proc-macro crate is 2018 edition, use `quote!(use #name as #import_name;)` instead. tokens.extend(quote!(extern crate #name as #import_name;)); } tokens } ``` By default it will be searched from `dependencies` and `dev-dependencies`. This behavior can be adjusted by changing the [`Manifest::dependencies`] field. [`find_crate`] and [`Manifest::new`] functions read `Cargo.toml` in [`CARGO_MANIFEST_DIR`] as manifest. ## Alternatives If you write function-like procedural macros, [you can combine it with declarative macros to support both crate renaming and macro re-exporting.][rust-lang/futures-rs#2124] This crate is intended to provide more powerful features such as support for multiple crate names and versions. For general purposes, [proc-macro-crate], which provides a simpler API, may be easier to use. [`CARGO_MANIFEST_DIR`]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates [rust-lang/futures-rs#2124]: https://github.com/rust-lang/futures-rs/pull/2124 [proc-macro-crate]: https://github.com/bkchr/proc-macro-crate */ #![no_std] #![doc(test( no_crate_inject, attr(allow( dead_code, unused_variables, clippy::undocumented_unsafe_blocks, clippy::unused_trait_names, )) ))] #![forbid(unsafe_code)] #![warn( // Lints that may help when writing public library. missing_debug_implementations, missing_docs, clippy::alloc_instead_of_core, clippy::exhaustive_enums, clippy::exhaustive_structs, clippy::impl_trait_in_params, // clippy::missing_inline_in_public_items, clippy::std_instead_of_alloc, clippy::std_instead_of_core, )] extern crate alloc; extern crate std; #[cfg(test)] #[path = "gen/tests/assert_impl.rs"] mod assert_impl; #[cfg(test)] #[path = "gen/tests/track_size.rs"] mod track_size; mod error; use alloc::{borrow::ToOwned as _, string::String}; use core::str::FromStr; use std::{ env, fs, path::{Path, PathBuf}, }; use toml::value::{Table, Value}; pub use self::error::{Error, TomlError}; type Result = core::result::Result; /// The [`CARGO_MANIFEST_DIR`] environment variable. /// /// [`CARGO_MANIFEST_DIR`]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates const MANIFEST_DIR: &str = "CARGO_MANIFEST_DIR"; /// Find the crate name from the current `Cargo.toml`. /// /// This function reads `Cargo.toml` in [`CARGO_MANIFEST_DIR`] as manifest. /// /// Note that this function needs to be used in the context of proc-macro. /// /// # Examples /// /// ``` /// use find_crate::find_crate; /// use proc_macro2::{Ident, Span, TokenStream}; /// use quote::quote; /// /// fn import() -> TokenStream { /// let name = find_crate(|name| name == "foo" || name == "foo-core").unwrap().name; /// let name = Ident::new(&name, Span::call_site()); /// // If your proc-macro crate is 2018 edition, use `quote!(use #name as _foo;)` instead. /// quote!(extern crate #name as _foo;) /// } /// ``` /// /// [`CARGO_MANIFEST_DIR`]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates pub fn find_crate

(predicate: P) -> Result where P: FnMut(&str) -> bool, { Manifest::new()?.find(predicate).ok_or(Error::NotFound) } /// The kind of dependencies to be searched. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[non_exhaustive] pub enum Dependencies { /// Search from `dependencies` and `dev-dependencies`. #[default] Default, /// Search from `dependencies`. Release, /// Search from `dev-dependencies`. Dev, /// Search from `build-dependencies`. Build, /// Search from `dependencies`, `dev-dependencies` and `build-dependencies`. All, } impl Dependencies { fn as_slice(self) -> &'static [&'static str] { match self { Dependencies::Default => &["dependencies", "dev-dependencies"], Dependencies::Release => &["dependencies"], Dependencies::Dev => &["dev-dependencies"], Dependencies::Build => &["build-dependencies"], Dependencies::All => &["dependencies", "dev-dependencies", "build-dependencies"], } } } /// The package information. This has information on the current package name, /// original package name, and specified version. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Package { /// The key of this dependency in the manifest. key: String, // The key or the value of 'package' key. // If this is `None`, the value of `key` field is the original name. package: Option, /// The current name of the package. This is always a valid rust identifier /// (`-` is replaced with `_`). pub name: String, /// The version requirement of the package. Returns `*` if no version /// requirement is specified. pub version: String, } impl Package { /// Returns the original package name. #[must_use] pub fn original_name(&self) -> &str { self.package.as_ref().unwrap_or(&self.key) } /// Returns `true` if the value of the [`name`] field is the original package /// name. /// /// [`name`]: Package::name #[must_use] pub fn is_original(&self) -> bool { self.package.is_none() } } /// The manifest of cargo. /// /// Note that this function needs to be used in the context of proc-macro. #[derive(Debug, Clone)] pub struct Manifest { manifest: Table, /// The kind of dependencies to be searched. pub dependencies: Dependencies, } impl Manifest { /// Creates a new `Manifest` from the current `Cargo.toml`. /// /// This function reads `Cargo.toml` in [`CARGO_MANIFEST_DIR`] as manifest. /// /// [`CARGO_MANIFEST_DIR`]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates pub fn new() -> Result { Self::from_path(&manifest_path()?) } /// Creates a new `Manifest` from the specified toml file. pub fn from_path(manifest_path: &Path) -> Result { Self::from_str(&fs::read_to_string(manifest_path)?) } /// Finds the crate with crate name, and returns its package information. /// /// The argument of the closure is the original name of the package. /// /// # Examples /// /// ``` /// use find_crate::Manifest; /// use proc_macro2::{Ident, Span, TokenStream}; /// use quote::quote; /// /// fn import() -> TokenStream { /// let manifest = Manifest::new().unwrap(); /// let name = manifest.find(|name| name == "foo" || name == "foo-core").unwrap().name; /// let name = Ident::new(&name, Span::call_site()); /// // If your proc-macro crate is 2018 edition, use `quote!(use #name as _foo;)` instead. /// quote!(extern crate #name as _foo;) /// } /// ``` pub fn find

(&self, mut predicate: P) -> Option where P: FnMut(&str) -> bool, { self.find2(|s, _| predicate(s)) } /// Finds the crate with crate name and version, and returns its package information. /// /// The first argument of the closure is the original name of the package /// and the second argument is the version of the package. /// /// # Examples /// /// ``` /// use find_crate::Manifest; /// use proc_macro2::{Ident, Span, TokenStream}; /// use quote::quote; /// use semver::{Version, VersionReq}; /// /// fn check_version(req: &str, version: &Version) -> bool { /// VersionReq::parse(req).unwrap().matches(version) /// } /// /// fn import() -> TokenStream { /// let version = Version::parse("0.3.0").unwrap(); /// let manifest = Manifest::new().unwrap(); /// let name = manifest /// .find2(|name, req| name == "foo" && (req == "*" || check_version(req, &version))) /// .unwrap() /// .name; /// let name = Ident::new(&name, Span::call_site()); /// // If your proc-macro crate is 2018 edition, use `quote!(use #name as _foo;)` instead. /// quote!(extern crate #name as _foo;) /// } /// ``` pub fn find2

(&self, predicate: P) -> Option where P: FnMut(&str, &str) -> bool, { find(&self.manifest, self.dependencies, predicate) } /// The package for the crate that this manifest represents. /// /// # Examples /// /// ``` /// use find_crate::Manifest; /// use proc_macro2::{Ident, Span, TokenStream}; /// use quote::quote; /// /// fn current_crate_name() -> TokenStream { /// let manifest = Manifest::new().unwrap(); /// let current_crate_package = manifest.crate_package().unwrap(); /// let name = Ident::new(¤t_crate_package.name, Span::call_site()); /// quote!(#name) /// } /// ``` pub fn crate_package(&self) -> Result { let package_section = self .manifest .get("package") .ok_or_else(|| Error::InvalidManifest("[package] section is missing".to_owned()))?; let package_key_value = package_section.get("name").ok_or_else(|| { Error::InvalidManifest("[package] section is missing `name`".to_owned()) })?; let package_key = package_key_value.as_str().ok_or_else(|| { Error::InvalidManifest("`name` in [package] section is not a string".to_owned()) })?; let package_version = match package_section.get("version") { Some(package_version_value) => package_version_value.as_str().ok_or_else(|| { Error::InvalidManifest("`version` in [package] section is not a string".to_owned()) })?, // Cargo supports version-less manifests: https://github.com/rust-lang/cargo/pull/12786 None => "0.0.0", }; let package = Package { key: package_key.to_owned(), package: None, name: package_key.replace('-', "_"), version: package_version.to_owned(), }; Ok(package) } } impl FromStr for Manifest { type Err = Error; /// Creates a new `Manifest` from a string containing a TOML file. fn from_str(manifest: &str) -> Result { Ok(Self { manifest: toml::from_str(manifest).map_err(|e| Error::Toml(TomlError { error: e }))?, dependencies: Dependencies::default(), }) } } fn manifest_path() -> Result { let mut path: PathBuf = env::var_os(MANIFEST_DIR).ok_or(Error::NotFoundManifestDir)?.into(); path.push("Cargo.toml"); Ok(path) } fn find

(manifest: &Table, dependencies: Dependencies, mut predicate: P) -> Option where P: FnMut(&str, &str) -> bool, { fn find_inner

(table: &Table, dependencies: &str, predicate: &mut P) -> Option where P: FnMut(&str, &str) -> bool, { find_from_dependencies(table.get(dependencies)?.as_table()?, predicate) } fn find_target

(table: &Table, dependencies: &str, predicate: &mut P) -> Option where P: FnMut(&str, &str) -> bool, { table.values().find_map(|table| { let table = table.as_table()?; find_inner(table, dependencies, predicate) .or_else(|| find_target(table, dependencies, predicate)) }) } dependencies .as_slice() .iter() .find_map(|dependencies| find_inner(manifest, dependencies, &mut predicate)) .or_else(|| { dependencies.as_slice().iter().find_map(|dependencies| { find_target(manifest.get("target")?.as_table()?, dependencies, &mut predicate) }) }) } fn find_from_dependencies

(table: &Table, mut predicate: P) -> Option where P: FnMut(&str, &str) -> bool, { fn package

(value: &Value, version: &str, predicate: P) -> Option where P: FnOnce(&str, &str) -> bool, { value .as_table()? .get("package")? .as_str() .and_then(|name| if predicate(name, version) { Some(name.to_owned()) } else { None }) } fn version(value: &Value) -> Option<&str> { value.as_str().or_else(|| value.as_table()?.get("version")?.as_str()) } table.iter().find_map(|(key, value)| { let version = version(value).unwrap_or("*"); let package = package(value, version, &mut predicate); if package.is_some() || predicate(key, version) { Some(Package { key: key.clone(), name: key.replace('-', "_"), version: version.to_owned(), package, }) } else { None } }) } find-crate-0.7.1/tests/test.rs000064400000000000000000000123051046102023000143350ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT #![allow(clippy::needless_raw_string_hashes)] use std::str::FromStr as _; use find_crate::{Dependencies, Manifest}; use semver::{Version, VersionReq}; #[test] fn dependencies() { const MANIFEST: &str = r#" [dependencies] foo = "0.1" [dev-dependencies.foo] version = "0.1.1" [build-dependencies] foo-bar = "0.2" "#; const NAME1: &str = "foo"; const NAME2: &str = "foo-bar"; const NAME3: &str = "baz"; let mut manifest = Manifest::from_str(MANIFEST).unwrap(); assert_eq!(Dependencies::Default, manifest.dependencies); assert_eq!(NAME1, manifest.find(|s| s == NAME1).unwrap().name); assert_eq!("0.1", manifest.find(|s| s == NAME1).unwrap().version); manifest.dependencies = Dependencies::Dev; assert_eq!(NAME1, manifest.find(|s| s == NAME1).unwrap().name); assert_eq!("0.1.1", manifest.find(|s| s == NAME1).unwrap().version); manifest.dependencies = Dependencies::Build; assert_eq!(None, manifest.find(|s| s == NAME1)); assert_eq!("foo_bar", manifest.find(|s| s == NAME2).unwrap().name); assert_eq!("0.2", manifest.find(|s| s == NAME2).unwrap().version); manifest.dependencies = Dependencies::Default; assert_eq!(None, manifest.find(|s| s == NAME2)); manifest.dependencies = Dependencies::All; assert_eq!("foo_bar", manifest.find(|s| s == NAME2).unwrap().name); assert_eq!("0.2", manifest.find(|s| s == NAME2).unwrap().version); assert_eq!(None, manifest.find(|s| s == NAME3)); } #[test] fn renamed() { const MANIFEST: &str = r#" [dependencies] foo-renamed = { package = "foo", version = "0.1" } [dependencies.bar_renamed] package = "bar" version = "0.2" "#; const NAME1: &str = "foo"; const NAME2: &str = "bar"; let manifest = Manifest::from_str(MANIFEST).unwrap(); assert_eq!("foo_renamed", manifest.find(|s| s == NAME1).unwrap().name); assert_eq!("0.1", manifest.find(|s| s == NAME1).unwrap().version); assert_eq!("bar_renamed", manifest.find(|s| s == NAME2).unwrap().name); assert_eq!("0.2", manifest.find(|s| s == NAME2).unwrap().version); } #[test] fn target() { const MANIFEST: &str = r#" [target.'cfg(target_os = "linux")'.dependencies] foo = "0.1" [target.'cfg(target_os = "macos")'.dependencies] bar = { version = "0.2" } [target.x86_64-unknown-linux-gnu.dependencies.baz] version = "0.3" [target.thumbv8m.base-none-eabi.dependencies] foo-bar = "0.1" "#; const NAME1: &str = "foo"; const NAME2: &str = "bar"; const NAME3: &str = "baz"; const NAME4: &str = "foo-bar"; let manifest = Manifest::from_str(MANIFEST).unwrap(); assert_eq!(NAME1, manifest.find(|s| s == NAME1).unwrap().name); assert_eq!("0.1", manifest.find(|s| s == NAME1).unwrap().version); assert_eq!(NAME2, manifest.find(|s| s == NAME2).unwrap().name); assert_eq!("0.2", manifest.find(|s| s == NAME2).unwrap().version); assert_eq!(NAME3, manifest.find(|s| s == NAME3).unwrap().name); assert_eq!("0.3", manifest.find(|s| s == NAME3).unwrap().version); assert_eq!("foo_bar", manifest.find(|s| s == NAME4).unwrap().name); assert_eq!("0.1", manifest.find(|s| s == NAME4).unwrap().version); } #[test] fn workspace() { const MANIFEST: &str = r#" [dependencies] foo.workspace = true "#; const NAME1: &str = "foo"; let manifest = Manifest::from_str(MANIFEST).unwrap(); assert_eq!(Dependencies::Default, manifest.dependencies); assert_eq!(NAME1, manifest.find(|s| s == NAME1).unwrap().name); assert_eq!("*", manifest.find(|s| s == NAME1).unwrap().version); } #[test] fn find2() { fn check(req: &str, version: &Version) -> bool { VersionReq::parse(req).unwrap().matches(version) } const MANIFEST: &str = r#" [dependencies] foo = "0.1" bar = "0.2" baz = { path = ".." } "#; const NAME1: &str = "foo"; const NAME2: &str = "bar"; const NAME3: &str = "baz"; let manifest = Manifest::from_str(MANIFEST).unwrap(); let version = Version::parse("0.2.0").unwrap(); assert_eq!(None, manifest.find2(|s, v| s == NAME1 && check(v, &version))); assert_eq!(NAME2, manifest.find2(|s, v| s == NAME2 && check(v, &version)).unwrap().name); assert_eq!("0.2", manifest.find2(|s, v| s == NAME2 && check(v, &version)).unwrap().version); assert_eq!(NAME3, manifest.find2(|s, v| s == NAME3 && check(v, &version)).unwrap().name); assert_eq!("*", manifest.find2(|s, v| s == NAME3 && check(v, &version)).unwrap().version); } #[test] fn crate_name() { const MANIFEST: &str = r#" [package] name = "crate-name" version = "0.1.0" "#; let manifest = Manifest::from_str(MANIFEST).unwrap(); let package = manifest.crate_package().unwrap(); assert_eq!("crate_name", package.name); assert_eq!("0.1.0", package.version); let manifest = r#" [package] name = "crate-name" "#; let manifest = Manifest::from_str(manifest).unwrap(); let package = manifest.crate_package().unwrap(); assert_eq!("crate_name", package.name); assert_eq!("0.0.0", package.version); }