]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/multiple_crate_versions.rs
Auto merge of #4809 - iankronquist:patch-1, r=flip1995
[rust.git] / clippy_lints / src / multiple_crate_versions.rs
1 //! lint on multiple versions of a crate being used
2
3 use crate::utils::span_lint;
4 use rustc_lint::{EarlyContext, EarlyLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6 use rustc_span::source_map::DUMMY_SP;
7 use syntax::ast::*;
8
9 use itertools::Itertools;
10
11 declare_clippy_lint! {
12     /// **What it does:** Checks to see if multiple versions of a crate are being
13     /// used.
14     ///
15     /// **Why is this bad?** This bloats the size of targets, and can lead to
16     /// confusing error messages when structs or traits are used interchangeably
17     /// between different versions of a crate.
18     ///
19     /// **Known problems:** Because this can be caused purely by the dependencies
20     /// themselves, it's not always possible to fix this issue.
21     ///
22     /// **Example:**
23     /// ```toml
24     /// # This will pull in both winapi v0.3.x and v0.2.x, triggering a warning.
25     /// [dependencies]
26     /// ctrlc = "=3.1.0"
27     /// ansi_term = "=0.11.0"
28     /// ```
29     pub MULTIPLE_CRATE_VERSIONS,
30     cargo,
31     "multiple versions of the same crate being used"
32 }
33
34 declare_lint_pass!(MultipleCrateVersions => [MULTIPLE_CRATE_VERSIONS]);
35
36 impl EarlyLintPass for MultipleCrateVersions {
37     fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &Crate) {
38         let metadata = if let Ok(metadata) = cargo_metadata::MetadataCommand::new().exec() {
39             metadata
40         } else {
41             span_lint(cx, MULTIPLE_CRATE_VERSIONS, DUMMY_SP, "could not read cargo metadata");
42
43             return;
44         };
45
46         let mut packages = metadata.packages;
47         packages.sort_by(|a, b| a.name.cmp(&b.name));
48
49         for (name, group) in &packages.into_iter().group_by(|p| p.name.clone()) {
50             let group: Vec<cargo_metadata::Package> = group.collect();
51
52             if group.len() > 1 {
53                 let versions = group.into_iter().map(|p| p.version).join(", ");
54
55                 span_lint(
56                     cx,
57                     MULTIPLE_CRATE_VERSIONS,
58                     DUMMY_SP,
59                     &format!("multiple versions for dependency `{}`: {}", name, versions),
60                 );
61             }
62         }
63     }
64 }