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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Find the crate name from the current `Cargo.toml` (`$crate` for proc-macro).
//!
//! When writing declarative macros, `$crate` representing the current crate is
//! very useful, but procedural macros do not have this. To do the same thing as
//! `$crate` with procedural macros, you need to know the current name of the
//! crate you want to use as `$crate`. This crate provides the features to make
//! it easy.
//!
//! ## Examples
//!
//! [`find_crate()`] gets the crate name from `Cargo.toml`.
//!
//! ```rust
//! # extern crate find_crate;
//! # extern crate proc_macro2;
//! # extern crate quote;
//! 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();
//!     let name = Ident::new(&name, Span::call_site());
//!     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
//! # extern crate find_crate;
//! # extern crate proc_macro2;
//! # extern crate quote;
//! 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();
//!     let name = Ident::new(&name, Span::call_site());
//!     quote!(extern crate #name as _foo;)
//! }
//! ```
//!
//! Search for multiple crates. It is much more efficient than using
//! [`find_crate()`] for each crate.
//!
//! ```rust
//! # extern crate find_crate;
//! # extern crate proc_macro2;
//! # extern crate quote;
//! use find_crate::Manifest;
//! use proc_macro2::{Ident, Span, TokenStream};
//! use quote::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();
//!     let manifest = manifest.lock();
//!
//!     for names in CRATE_NAMES {
//!         let name = manifest.find_name(|s| names.iter().any(|x| s == *x)).unwrap();
//!         let name = Ident::new(&name, Span::call_site());
//!         let import_name = Ident::new(&format!("_{}", names[0]), Span::call_site());
//!         tts.extend(quote!(extern crate #name as #import_name;));
//!     }
//!     tts
//! }
//! ```
//!
//! By default it will be searched from `dependencies`, `dev-dependencies` and `build-dependencies`.
//! Also, `find_crate()` and `Manifest::new()` read `Cargo.toml` in `CARGO_MANIFEST_DIR` as manifest.
//!
//! [`find_crate()`]: fn.find_crate.html

#![doc(html_root_url = "https://docs.rs/find-crate/0.2.0")]
#![deny(missing_docs, missing_debug_implementations, unsafe_code)]
#![cfg_attr(
    feature = "cargo-clippy",
    allow(
        renamed_and_removed_lints,
        redundant_field_names, // Rust 1.17+ => remove
        const_static_lifetime, // Rust 1.17+ => remove
        deprecated_cfg_attr, // Rust 1.30+ => remove
        map_clone
    )
)]

extern crate toml;

use std::borrow::Cow;
use std::env;
use std::error;
use std::fmt;
use std::fs::File;
use std::io::{self, Read as _Read}; // Rust 1.33+ => Read as _
use std::path::{Path, PathBuf};
use std::result;

use toml::value::{Table, Value};

use self::Error::*;

type Result<T> = result::Result<T, Error>;

/// The kinds of dependencies searched by default.
pub const DEFAULT_DEPENDENCIES: &'static [&'static str] = &_DEFAULT_DEPENDENCIES;

// for const_err
const _DEFAULT_DEPENDENCIES: [&'static str; 3] =
    ["dependencies", "dev-dependencies", "build-dependencies"];

/// An error that occurred when getting manifest.
#[derive(Debug)]
pub enum Error {
    /// `CARGO_MANIFEST_DIR` environment variable not found.
    NotFoundManifestDir,
    /// `Cargo.toml` or specified manifest file not found.
    NotFoundManifestFile(PathBuf),
    /// An error occurred while to open the manifest file.
    Open(PathBuf, io::Error),
    /// An error occurred while reading the manifest file.
    Read(PathBuf, io::Error),
    /// An error occurred while parsing the manifest file.
    Toml(toml::de::Error),
    /// The crate with the specified name not found. This error occurs only from [`find_crate()`].
    ///
    /// [`find_crate()`]: fn.find_crate.html
    NotFound(PathBuf),
}

impl fmt::Display for Error {
    #[cfg_attr(rustfmt, rustfmt_skip)] // Rust 1.30+ => #[rustfmt::skip]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::_DEFAULT_DEPENDENCIES as D;
        match *self {
            NotFoundManifestDir => write!(f, "`CARGO_MANIFEST_DIR` environment variable not found"),
            NotFoundManifestFile(ref path) => write!(f, "the manifest file not found: {}", path.display()),
            Open(ref path, ref err) => write!(f, "an error occurred while to open {}: {}", path.display(), err),
            Read(ref path, ref err) => write!(f, "an error occurred while reading {}: {}", path.display(), err),
            Toml(ref err) => write!(f, "an error occurred while parsing the manifest file: {}", err),
            NotFound(ref path) => write!(f, "the crate with the specified name not found in {}, {} or {} in {}", D[0], D[1], D[2], path.display()),
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            NotFoundManifestDir => "`CARGO_MANIFEST_DIR` environment variable not found",
            NotFoundManifestFile(_) => "`Cargo.toml` or specified manifest file not found",
            Open(_, _) => "An error occurred while to open the manifest file",
            Read(_, _) => "An error occurred while reading the manifest file",
            Toml(_) => "An error occurred while parsing the manifest file",
            NotFound(_) => "The crate with the specified name not found",
        }
    }
    #[cfg(stable_1_30)]
    fn source(&self) -> Option<&(error::Error + 'static)> {
        match self {
            Open(_, err) | Read(_, err) => Some(err),
            Toml(err) => Some(err),
            _ => None,
        }
    }
    #[cfg(stable_1_30)] // https://github.com/rust-lang/rust/blob/1.30.0/src/libstd/error.rs#L143
    #[allow(deprecated)]
    fn cause(&self) -> Option<&error::Error> {
        self.source()
    }
    #[cfg(not(stable_1_30))]
    fn cause(&self) -> Option<&error::Error> {
        match *self {
            Open(_, ref err) | Read(_, ref err) => Some(err),
            Toml(ref err) => Some(err),
            _ => None,
        }
    }
}

/// Find the crate name from the current `Cargo.toml`.
///
/// This function reads `Cargo.toml` in `CARGO_MANIFEST_DIR` as manifest.
///
/// Note that this function must be used in the context of proc-macro.
///
/// ## Examples
///
/// ```rust
/// # extern crate find_crate;
/// # extern crate proc_macro2;
/// # extern crate quote;
/// use find_crate::find_crate;
/// use proc_macro2::{Ident, Span, TokenStream};
/// use quote::quote;
///
/// fn import(import_name: Ident) -> TokenStream {
///     let name = find_crate(|s| s == "foo" || s == "foo-core").unwrap();
///     let name = Ident::new(&name, Span::call_site());
///     quote!(extern crate #name as #import_name;)
/// }
/// ```
pub fn find_crate<P>(predicate: P) -> Result<String>
where
    P: FnMut(&str) -> bool,
{
    let manifest_path = manifest_path()?;
    Manifest::from_path(&manifest_path)?
        .find(predicate)
        .map(|package| package.rust_ident.into_owned())
        .ok_or_else(|| NotFound(manifest_path))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct FindOptions<'a> {
    /// The names of the tables to be searched
    dependencies: &'a [&'a str],
    /// Whether or not to convert the name of the retrieved crate to a valid
    /// rust identifier
    rust_ident: bool,
}

impl<'a> Default for FindOptions<'a> {
    fn default() -> Self {
        FindOptions {
            dependencies: DEFAULT_DEPENDENCIES,
            rust_ident: true,
        }
    }
}

/// 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<'a> {
    /// The key of this dependency in the manifest.
    key: &'a str,

    // value or version key's value
    /// The specified version of the package.
    version: Option<&'a str>,
    // key or package key's value
    /// If this is `None`, the value of `key` field is the original name.
    package: Option<&'a str>,

    /// If this is `Cow::Owned`, the value is a valid rust identifier.
    rust_ident: Cow<'a, str>,
}

impl<'a> Package<'a> {
    /// Returns the current package name.
    pub fn name(&self) -> &str {
        &self.rust_ident
    }

    /// Returns the original package name.
    pub fn original_name(&self) -> &str {
        self.package.as_ref().unwrap_or(&self.key)
    }

    /// Returns `true` if the value returned by `Package::name()` is a valid rust
    /// identifier.
    pub fn is_rust_ident(&self) -> bool {
        match self.rust_ident {
            Cow::Borrowed(ref s) => !s.contains('-'),
            Cow::Owned(_) => true,
        }
    }

    /// Returns `true` if the value returned by `Package::name()` is the original
    /// package name.
    pub fn is_original(&self) -> bool {
        self.package.is_none()
    }

    /// Returns the version of the package.
    pub fn version(&self) -> Option<&str> {
        self.version.as_ref().map(|v| *v)
    }
}

/// The manifest of cargo.
///
/// Note that this item must be used in the context of proc-macro.
#[derive(Debug, Clone)]
pub struct Manifest<'a> {
    manifest: Table,
    options: FindOptions<'a>,
}

impl<'a> Manifest<'a> {
    /// Constructs a new `Manifest` from the current `Cargo.toml`.
    ///
    /// This function reads `Cargo.toml` in `CARGO_MANIFEST_DIR` as manifest.
    pub fn new() -> Result<Self> {
        Self::from_path(&manifest_path()?)
    }

    /// Constructs a new `Manifest` from the specified toml file.
    pub fn from_path(manifest_path: &Path) -> Result<Self> {
        fn open(path: &Path) -> Result<Vec<u8>> {
            let mut bytes = Vec::new();
            File::open(path)
                .map_err(|e| Open(path.to_owned(), e))?
                .read_to_end(&mut bytes)
                .map_err(|e| Read(path.to_owned(), e))
                .map(|_| bytes)
        }

        if !manifest_path.is_file() {
            Err(NotFoundManifestFile(manifest_path.to_owned()))
        } else {
            Self::from_bytes(&open(&manifest_path)?)
        }
    }

    /// Constructs a new `Manifest` from the bytes.
    fn from_bytes(bytes: &[u8]) -> Result<Self> {
        toml::from_slice(bytes).map_err(Toml).map(Self::from_raw)
    }

    /// Constructs a new `Manifest` from the raw manifest.
    fn from_raw(manifest: Table) -> Self {
        Manifest {
            manifest: manifest,
            options: FindOptions::default(),
        }
    }

    /// Returns the kinds of dependencies to be searched. The default is
    /// `dependencies`, `dev-dependencies` and `build-dependencies`.
    pub fn dependencies(&self) -> &[&str] {
        self.options.dependencies
    }

    /// Sets the kinds of dependencies to be searched. The default is
    /// `dependencies`, `dev-dependencies` and `build-dependencies`.
    pub fn set_dependencies(&mut self, dependencies: &'a [&'a str]) {
        self.options.dependencies = dependencies;
    }

    /// Returns whether or not to convert the name of the retrieved crate to a
    /// valid rust identifier. The default is `true`.
    pub fn rust_ident(&self) -> bool {
        self.options.rust_ident
    }

    /// Sets whether or not to convert the name of the retrieved crate to a
    /// valid rust identifier.
    pub fn set_rust_ident(&mut self, rust_ident: bool) {
        self.options.rust_ident = rust_ident;
    }

    /// Lock the kinds of dependencies to be searched. This is more efficient when you want to
    /// search multiple times without changing the kinds of dependencies to be searched.
    pub fn lock(&self) -> ManifestLock {
        ManifestLock::new(self)
    }

    /// Find the crate name.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// # extern crate find_crate;
    /// # extern crate proc_macro2;
    /// # extern crate quote;
    /// use find_crate::Manifest;
    /// use proc_macro2::{Ident, Span, TokenStream};
    /// use quote::quote;
    ///
    /// fn import(import_name: Ident) -> TokenStream {
    ///     let manifest = Manifest::new().unwrap();
    ///     let name = manifest.find_name(|s| s == "foo" || s == "foo-core").unwrap();
    ///     let name = Ident::new(&name, Span::call_site());
    ///     quote!(extern crate #name as #import_name;)
    /// }
    /// ```
    pub fn find_name<P>(&self, predicate: P) -> Option<Cow<str>>
    where
        P: FnMut(&str) -> bool,
    {
        self.find(predicate).map(|package| package.rust_ident)
    }

    /// Find the crate.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// # extern crate find_crate;
    /// # extern crate proc_macro2;
    /// # extern crate quote;
    /// use find_crate::Manifest;
    /// use proc_macro2::{Ident, Span, TokenStream};
    /// use quote::quote;
    ///
    /// fn import(import_name: Ident) -> TokenStream {
    ///     let manifest = Manifest::new().unwrap();
    ///     let package = manifest.find(|s| s == "foo" || s == "foo-core").unwrap();
    ///     let name = Ident::new(package.name(), Span::call_site());
    ///     quote!(extern crate #name as #import_name;)
    /// }
    /// ```
    pub fn find<P>(&self, mut predicate: P) -> Option<Package>
    where
        P: FnMut(&str) -> bool,
    {
        find_map(self.dependencies().iter(), |dependencies| {
            self._find(dependencies, &mut predicate)
        })
    }

    fn _find<P>(&self, dependencies: &str, predicate: P) -> Option<Package>
    where
        P: FnMut(&str) -> bool,
    {
        self.manifest
            .get(dependencies)
            .and_then(|v| v.as_table())
            .and_then(|t| find_from_dependencies(t, predicate, self.rust_ident()))
    }
}

/// A locked reference to the dependencies tables of `Manifest` to be searched.
#[derive(Debug, Clone)]
pub struct ManifestLock<'a> {
    manifest: &'a Manifest<'a>,
    tables: Vec<&'a Table>,
}

impl<'a> ManifestLock<'a> {
    fn new(manifest: &'a Manifest<'a>) -> Self {
        ManifestLock {
            tables: manifest
                .dependencies()
                .iter()
                .filter_map(|&dependencies| {
                    manifest
                        .manifest
                        .get(dependencies)
                        .and_then(|v| v.as_table())
                })
                .collect(),
            manifest: manifest,
        }
    }

    /// Find the crate name.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// # extern crate find_crate;
    /// # extern crate proc_macro2;
    /// # extern crate quote;
    /// use find_crate::Manifest;
    /// use proc_macro2::{Ident, Span, TokenStream};
    /// use quote::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();
    ///     let manifest = manifest.lock();
    ///
    ///     for names in CRATE_NAMES {
    ///         let name = manifest.find_name(|s| names.iter().any(|x| s == *x)).unwrap();
    ///         let name = Ident::new(&name, Span::call_site());
    ///         let import_name = Ident::new(&format!("_{}", names[0]), Span::call_site());
    ///         tts.extend(quote!(extern crate #name as #import_name;));
    ///     }
    ///     tts
    /// }
    /// ```
    pub fn find_name<P>(&self, predicate: P) -> Option<Cow<str>>
    where
        P: FnMut(&str) -> bool,
    {
        self.find(predicate).map(|package| package.rust_ident)
    }

    /// Find the crate.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// # extern crate find_crate;
    /// # extern crate proc_macro2;
    /// # extern crate quote;
    /// use find_crate::Manifest;
    /// use proc_macro2::{Ident, Span, TokenStream};
    /// use quote::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();
    ///     let manifest = manifest.lock();
    ///
    ///     for names in CRATE_NAMES {
    ///         let package = manifest.find(|s| names.iter().any(|x| s == *x)).unwrap();
    ///         let name = Ident::new(package.name(), Span::call_site());
    ///         let import_name = Ident::new(&format!("_{}", names[0]), Span::call_site());
    ///         tts.extend(quote!(extern crate #name as #import_name;));
    ///     }
    ///     tts
    /// }
    /// ```
    pub fn find<P>(&self, mut predicate: P) -> Option<Package>
    where
        P: FnMut(&str) -> bool,
    {
        find_map(self.tables.iter(), |dependencies| {
            find_from_dependencies(dependencies, &mut predicate, self.manifest.rust_ident())
        })
    }
}

#[cfg(stable_1_30)]
fn find_map<I: Iterator, B, F: FnMut(I::Item) -> Option<B>>(mut iter: I, f: F) -> Option<B> {
    iter.find_map(f)
}
#[cfg(not(stable_1_30))]
fn find_map<I: Iterator, B, F: FnMut(I::Item) -> Option<B>>(iter: I, f: F) -> Option<B> {
    iter.filter_map(f).next()
}

fn manifest_path() -> Result<PathBuf> {
    env::var_os("CARGO_MANIFEST_DIR")
        .ok_or_else(|| NotFoundManifestDir)
        .map(PathBuf::from)
        .map(|mut manifest_path| {
            manifest_path.push("Cargo.toml");
            manifest_path
        })
}

fn find_from_dependencies<P>(table: &Table, mut predicate: P, convert: bool) -> Option<Package>
where
    P: FnMut(&str) -> bool,
{
    fn package<P>(value: &Value, mut predicate: P) -> Option<&str>
    where
        P: FnMut(&str) -> bool,
    {
        value
            .as_table()
            .and_then(|t| t.get("package"))
            .and_then(|v| v.as_str())
            .and_then(|s| if predicate(s) { Some(s) } else { None })
    }

    fn version(value: &Value) -> Option<&str> {
        value.as_str().or_else(|| {
            value
                .as_table()
                .and_then(|t| t.get("version"))
                .and_then(|v| v.as_str())
        })
    }

    fn rust_ident(s: &str, convert: bool) -> Cow<str> {
        if convert {
            Cow::Owned(s.replace("-", "_"))
        } else {
            Cow::Borrowed(s)
        }
    }

    find_map(table.iter(), |(key, value)| {
        if predicate(key) {
            Some(Package {
                key: key,
                version: version(value),
                package: None,
                rust_ident: rust_ident(key, convert),
            })
        } else if let package @ Some(_) = package(value, &mut predicate) {
            Some(Package {
                key: key,
                version: version(value),
                package: package,
                rust_ident: rust_ident(key, convert),
            })
        } else {
            None
        }
    })
}