find-crate-0.6.3/.cargo_vcs_info.json0000644000000001121377510724300131170ustar { "git": { "sha1": "16f57b46d92b7458a4cab2f83e4e2284435673a2" } } find-crate-0.6.3/.clippy.toml010064400017510000164000000000161377510717500142010ustar 00000000000000msrv = "1.31" find-crate-0.6.3/.editorconfig010064400017510000164000000004711377510717500144100ustar 00000000000000# EditorConfig configuration # https://editorconfig.org root = true [*] charset = utf-8 end_of_line = lf indent_size = 4 indent_style = space insert_final_newline = true trim_trailing_whitespace = true [*.{json,yml,md}] indent_size = 2 [*.sh] indent_size = 2 binary_next_line = true switch_case_indent = true find-crate-0.6.3/.gitattributes010064400017510000164000000000231377510717500146170ustar 00000000000000* text=auto eol=lf find-crate-0.6.3/.gitignore010064400017510000164000000004201377510717500137150ustar 00000000000000target Cargo.lock # For platform and editor specific settings, it is recommended to add to # a global .gitignore file. # Refs: https://docs.github.com/en/free-pro-team@latest/github/using-git/ignoring-files#configuring-ignored-files-for-all-repositories-on-your-computer find-crate-0.6.3/.rustfmt.toml010064400017510000164000000025761377510717500144220ustar 00000000000000# Rustfmt configuration # https://github.com/rust-lang/rustfmt/blob/HEAD/Configurations.md # This is required for bug-fixes, which technically can't be made to the stable # first version. # This is unstable (tracking issue: https://github.com/rust-lang/rustfmt/issues/3383). version = "Two" # Rustfmt cannot format long lines inside macros, but this option detects this. # This is unstable (tracking issue: https://github.com/rust-lang/rustfmt/issues/3391) error_on_line_overflow = true # Override the default formatting style. # See https://internals.rust-lang.org/t/running-rustfmt-on-rust-lang-rust-and-other-rust-lang-repositories/8732/81. use_small_heuristics = "Max" # See https://github.com/rust-dev-tools/fmt-rfcs/issues/149. # This is unstable (tracking issue: https://github.com/rust-lang/rustfmt/issues/3370) overflow_delimited_expr = true # Apply rustfmt to more places. # This is unstable (tracking issue: https://github.com/rust-lang/rustfmt/issues/3362). merge_imports = true # This is unstable (tracking issue: https://github.com/rust-lang/rustfmt/issues/3348). format_code_in_doc_comments = true # Automatically fix deprecated style. use_field_init_shorthand = true use_try_shorthand = true # Set the default settings again to always apply the proper formatting without # being affected by the editor settings. edition = "2018" hard_tabs = false newline_style = "Unix" tab_spaces = 4 find-crate-0.6.3/CHANGELOG.md010064400017510000164000000044411377510717500135450ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org). ## [Unreleased] ## [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 - Made `Manifest::dependencies` and `Package::{name, varsion}` fields public. - Added support for `target.cfg.dependencies`. - Added `Dependencies` enum to manage the kind of dependencies to be searched. - Removed `Manifest::lock()` and `ManifestLock`. - Removed some variant and field form `Error`. - Removed `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. - Updated minimum `toml` version to 0.5.0. ## [0.3.0] - 2019-02-21 - Removed version dependent behavior. - Documentation improvements. ## [0.2.0] - 2019-02-13 - Supported Rust 1.15. ## [0.1.2] - 2019-02-13 - Implemented `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.6.3...HEAD [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.6.3/Cargo.toml0000644000000022741377510724300111300ustar # 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "find-crate" version = "0.6.3" authors = ["Taiki Endo "] exclude = ["/.github", "/scripts"] description = "Find the crate name from the current Cargo.toml.\n" documentation = "https://docs.rs/find-crate" 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"] [dependencies.toml] version = "0.5.2" [dev-dependencies.proc-macro2] version = "1" [dev-dependencies.quote] version = "1" [dev-dependencies.semver] version = "0.11" find-crate-0.6.3/Cargo.toml.orig010064400017510000164000000012661377510717500146250ustar 00000000000000[package] name = "find-crate" version = "0.6.3" authors = ["Taiki Endo "] edition = "2018" license = "Apache-2.0 OR MIT" repository = "https://github.com/taiki-e/find-crate" documentation = "https://docs.rs/find-crate" keywords = ["macros", "crate"] categories = ["development-tools::procedural-macro-helpers"] readme = "README.md" exclude = ["/.github", "/scripts"] description = """ Find the crate name from the current Cargo.toml. """ [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [workspace] members = ["tests/doc"] # NB: toml is public dependencies. [dependencies] toml = "0.5.2" [dev-dependencies] proc-macro2 = "1" quote = "1" semver = "0.11" find-crate-0.6.3/LICENSE-APACHE010064400017510000164000000236761377510717500136730ustar 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.6.3/LICENSE-MIT010064400017510000164000000017771377510717500134010ustar 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.6.3/README.md010064400017510000164000000105041377510717500132100ustar 00000000000000# find-crate [![crates.io](https://img.shields.io/crates/v/find-crate.svg?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)](https://docs.rs/find-crate) [![license](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg?style=flat-square)](#license) [![rustc](https://img.shields.io/badge/rustc-1.31+-blue.svg?style=flat-square)](https://www.rust-lang.org) [![build status](https://img.shields.io/github/workflow/status/taiki-e/find-crate/CI/master?style=flat-square)](https://github.com/taiki-e/find-crate/actions?query=workflow%3ACI+branch%3Amaster) 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.5" ``` *Compiler support: requires rustc 1.31+* ## Examples [`find_crate`] 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(|s| s == "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(|s| s == "foo" || s == "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`] 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 tts = TokenStream::new(); let manifest = Manifest::new().unwrap(); for names in CRATE_NAMES { let name = manifest.find(|s| names.iter().any(|x| s == *x)).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. tts.extend(quote!(extern crate #name as #import_name;)); } tts } ``` By default it will be searched from `dependencies` and `dev-dependencies`. Also, [`find_crate`] and [`Manifest::new`] 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. [`Manifest::new`]: https://docs.rs/find-crate/0.6/find_crate/struct.Manifest.html#method.new [`Manifest`]: https://docs.rs/find-crate/0.6/find_crate/struct.Manifest.html [`find_crate`]: https://docs.rs/find-crate/0.6/find_crate/fn.find_crate.html [`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 ## 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.6.3/src/error.rs010064400017510000164000000040521377510717500142200ustar 00000000000000use std::{fmt, io}; use crate::MANIFEST_DIR; /// An error that occurred when getting manifest. #[derive(Debug)] 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 to open or to read the manifest file. Io(io::Error), /// An error occurred while to parse the manifest file. Toml(toml::de::Error), #[doc(hidden)] __Nonexhaustive, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::NotFoundManifestDir => { write!(f, "`{}` environment variable not found", MANIFEST_DIR) } Error::InvalidManifest(reason) => { write!(f, "The manifest is invalid because: {}", reason) } Error::NotFound => { write!(f, "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), Error::__Nonexhaustive => unreachable!(), } } } 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) } } impl From for Error { fn from(e: toml::de::Error) -> Self { Error::Toml(e) } } find-crate-0.6.3/src/lib.rs010064400017510000164000000342051377510717500136400ustar 00000000000000//! 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. //! //! # Examples //! //! [`find_crate`] 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(|s| s == "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(|s| s == "foo" || s == "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`] 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 tts = TokenStream::new(); //! let manifest = Manifest::new().unwrap(); //! //! for names in CRATE_NAMES { //! let name = manifest.find(|s| names.iter().any(|x| s == *x)).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. //! tts.extend(quote!(extern crate #name as #import_name;)); //! } //! tts //! } //! ``` //! //! By default it will be searched from `dependencies` and `dev-dependencies`. //! Also, [`find_crate`] and [`Manifest::new`] 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 #![doc(test( no_crate_inject, attr( deny(warnings, rust_2018_idioms, single_use_lifetimes), allow(dead_code, unused_variables) ) ))] #![forbid(unsafe_code)] #![warn(future_incompatible, rust_2018_idioms, single_use_lifetimes, unreachable_pub)] #![warn(missing_debug_implementations, missing_docs)] #![warn(clippy::all, clippy::default_trait_access)] mod error; use std::{ env, fs::File, io::Read, path::{Path, PathBuf}, }; use toml::value::{Table, Value}; pub use crate::error::Error; type Result = std::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 /// /// ```rust /// use find_crate::find_crate; /// use proc_macro2::{Ident, Span, TokenStream}; /// use quote::quote; /// /// fn import() -> TokenStream { /// let name = find_crate(|s| s == "foo" || s == "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, PartialEq, Eq)] pub enum Dependencies { /// Search from `dependencies` and `dev-dependencies`. 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"], } } } impl Default for Dependencies { fn default() -> Self { Dependencies::Default } } /// The package data. 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. 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. 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 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()?) } // TODO: Should we support custom manifest paths? // And what should we do if the file is not found? // (should we use `CARGO_MANIFEST_DIR`? Or should we return an error?) /// Creates a new `Manifest` from the specified toml file. fn from_path(manifest_path: &Path) -> Result { let mut bytes = Vec::new(); File::open(manifest_path)?.read_to_end(&mut bytes)?; toml::from_slice(&bytes).map_err(Into::into).map(Self::from_toml) } /// Creates a new `Manifest` from a toml table. pub fn from_toml(manifest: Table) -> Self { Self { manifest, dependencies: Dependencies::default() } } /// Find the crate. /// /// The argument of the closure is the original name of the package. /// /// # Examples /// /// ```rust /// 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(|s| s == "foo" || s == "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;) /// } /// ``` #[inline] pub fn find

(&self, mut predicate: P) -> Option where P: FnMut(&str) -> bool, { self.find2(|s, _| predicate(s)) } /// Find the crate. /// /// The first argument of the closure is the original name of the package /// and the second argument is the version of the package. /// /// # Examples /// /// ```rust /// 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" && 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;) /// } /// ``` #[inline] 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 /// /// ```rust /// 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_string()))?; let package_key_value = package_section.get("name").ok_or_else(|| { Error::InvalidManifest("[package] section is missing `name`".to_string()) })?; let package_key = package_key_value.as_str().ok_or_else(|| { Error::InvalidManifest("`name` in [package] section is not a string".to_string()) })?; let package_version_value = package_section.get("version").ok_or_else(|| { Error::InvalidManifest("[package] section is missing `version`".to_string()) })?; let package_version = package_version_value.as_str().ok_or_else(|| { Error::InvalidManifest("`version` in [package] section is not a string".to_string()) })?; let package = Package { key: package_key.to_string(), package: None, name: package_key.replace("-", "_"), version: package_version.to_string(), }; Ok(package) } } fn manifest_path() -> Result { env::var_os(MANIFEST_DIR).ok_or(Error::NotFoundManifestDir).map(PathBuf::from).map( |mut path| { path.push("Cargo.toml"); 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: P) -> Option where P: FnMut(&str, &str) -> bool, { find_from_dependencies(table.get(dependencies)?.as_table()?, predicate) } dependencies .as_slice() .iter() .find_map(|dependencies| find_inner(manifest, dependencies, &mut predicate)) .or_else(|| { dependencies.as_slice().iter().find_map(|dependencies| { manifest .get("target")? .as_table()? .values() .find_map(|table| find_inner(table.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(|s| if predicate(s, version) { Some(s.to_string()) } 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_string(), package, }) } else { None } }) } find-crate-0.6.3/tests/test.rs010064400017510000164000000104311377510717500144170ustar 00000000000000#![warn(rust_2018_idioms, single_use_lifetimes)] 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] bar = "0.2" "#; const NAME1: &str = "foo"; const NAME2: &str = "bar"; const NAME3: &str = "baz"; let mut manifest = Manifest::from_toml(toml::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!(NAME2, 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!(NAME2, 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_toml(toml::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" "#; const NAME1: &str = "foo"; const NAME2: &str = "bar"; const NAME3: &str = "baz"; let manifest = Manifest::from_toml(toml::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); } #[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_toml(toml::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_toml(toml::from_str(MANIFEST).unwrap()); let package = manifest.crate_package().unwrap(); assert_eq!("crate_name", package.name); assert_eq!("0.1.0", package.version); }