]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/multiple_crate_versions.rs
Merge #3432
[rust.git] / clippy_lints / src / multiple_crate_versions.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 //! lint on multiple versions of a crate being used
11
12 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::syntax::{ast::*, source_map::DUMMY_SP};
15 use crate::utils::span_lint;
16
17 use cargo_metadata;
18 use itertools::Itertools;
19
20 /// **What it does:** Checks to see if multiple versions of a crate are being
21 /// used.
22 ///
23 /// **Why is this bad?** This bloats the size of targets, and can lead to
24 /// confusing error messages when structs or traits are used interchangeably
25 /// between different versions of a crate.
26 ///
27 /// **Known problems:** Because this can be caused purely by the dependencies
28 /// themselves, it's not always possible to fix this issue.
29 ///
30 /// **Example:**
31 /// ```toml
32 /// # This will pull in both winapi v0.3.4 and v0.2.8, triggering a warning.
33 /// [dependencies]
34 /// ctrlc = "3.1.0"
35 /// ansi_term = "0.11.0"
36 /// ```
37 declare_clippy_lint! {
38     pub MULTIPLE_CRATE_VERSIONS,
39     cargo,
40     "multiple versions of the same crate being used"
41 }
42
43 pub struct Pass;
44
45 impl LintPass for Pass {
46     fn get_lints(&self) -> LintArray {
47         lint_array!(MULTIPLE_CRATE_VERSIONS)
48     }
49 }
50
51 impl EarlyLintPass for Pass {
52     fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &Crate) {
53         let metadata = if let Ok(metadata) = cargo_metadata::metadata_deps(None, true) {
54             metadata
55         } else {
56             span_lint(cx, MULTIPLE_CRATE_VERSIONS, DUMMY_SP, "could not read cargo metadata");
57
58             return;
59         };
60
61         let mut packages = metadata.packages;
62         packages.sort_by(|a, b| a.name.cmp(&b.name));
63
64         for (name, group) in &packages.into_iter().group_by(|p| p.name.clone()) {
65             let group: Vec<cargo_metadata::Package> = group.collect();
66
67             if group.len() > 1 {
68                 let versions = group.into_iter().map(|p| p.version).join(", ");
69
70                 span_lint(
71                     cx,
72                     MULTIPLE_CRATE_VERSIONS,
73                     DUMMY_SP,
74                     &format!("multiple versions for dependency `{}`: {}", name, versions),
75                 );
76             }
77         }
78     }
79 }