find-crate 0.7.1

Find the crate name from the current Cargo.toml.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
// SPDX-License-Identifier: Apache-2.0 OR MIT

/*!
<!-- Note: Document from sync-markdown-to-rustdoc:start through sync-markdown-to-rustdoc:end
     is synchronized from README.md. Any changes to that range are not preserved. -->
<!-- tidy:sync-markdown-to-rustdoc:start -->

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

<!-- tidy:sync-markdown-to-rustdoc:end -->
*/

#![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<T, E = Error> = core::result::Result<T, E>;

/// 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<P>(predicate: P) -> Result<Package>
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<String>,

    /// 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> {
        Self::from_path(&manifest_path()?)
    }

    /// Creates a new `Manifest` from the specified toml file.
    pub fn from_path(manifest_path: &Path) -> Result<Self> {
        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<P>(&self, mut predicate: P) -> Option<Package>
    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<P>(&self, predicate: P) -> Option<Package>
    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(&current_crate_package.name, Span::call_site());
    ///     quote!(#name)
    /// }
    /// ```
    pub fn crate_package(&self) -> Result<Package> {
        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<Self, Self::Err> {
        Ok(Self {
            manifest: toml::from_str(manifest).map_err(|e| Error::Toml(TomlError { error: e }))?,
            dependencies: Dependencies::default(),
        })
    }
}

fn manifest_path() -> Result<PathBuf> {
    let mut path: PathBuf = env::var_os(MANIFEST_DIR).ok_or(Error::NotFoundManifestDir)?.into();
    path.push("Cargo.toml");
    Ok(path)
}

fn find<P>(manifest: &Table, dependencies: Dependencies, mut predicate: P) -> Option<Package>
where
    P: FnMut(&str, &str) -> bool,
{
    fn find_inner<P>(table: &Table, dependencies: &str, predicate: &mut P) -> Option<Package>
    where
        P: FnMut(&str, &str) -> bool,
    {
        find_from_dependencies(table.get(dependencies)?.as_table()?, predicate)
    }
    fn find_target<P>(table: &Table, dependencies: &str, predicate: &mut P) -> Option<Package>
    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<P>(table: &Table, mut predicate: P) -> Option<Package>
where
    P: FnMut(&str, &str) -> bool,
{
    fn package<P>(value: &Value, version: &str, predicate: P) -> Option<String>
    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
        }
    })
}