]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/wildcard_dependencies.rs
Only run cargo lints, when they are warn/deny/forbid
[rust.git] / clippy_lints / src / wildcard_dependencies.rs
1 use crate::utils::{run_lints, span_lint};
2 use rustc_hir::{hir_id::CRATE_HIR_ID, Crate};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_session::{declare_lint_pass, declare_tool_lint};
5 use rustc_span::source_map::DUMMY_SP;
6
7 use if_chain::if_chain;
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for wildcard dependencies in the `Cargo.toml`.
11     ///
12     /// **Why is this bad?** [As the edition guide says](https://rust-lang-nursery.github.io/edition-guide/rust-2018/cargo-and-crates-io/crates-io-disallows-wildcard-dependencies.html),
13     /// it is highly unlikely that you work with any possible version of your dependency,
14     /// and wildcard dependencies would cause unnecessary breakage in the ecosystem.
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     ///
20     /// ```toml
21     /// [dependencies]
22     /// regex = "*"
23     /// ```
24     pub WILDCARD_DEPENDENCIES,
25     cargo,
26     "wildcard dependencies being used"
27 }
28
29 declare_lint_pass!(WildcardDependencies => [WILDCARD_DEPENDENCIES]);
30
31 impl LateLintPass<'_, '_> for WildcardDependencies {
32     fn check_crate(&mut self, cx: &LateContext<'_, '_>, _: &Crate<'_>) {
33         if !run_lints(cx, &[WILDCARD_DEPENDENCIES], CRATE_HIR_ID) {
34             return;
35         }
36
37         let metadata = if let Ok(metadata) = cargo_metadata::MetadataCommand::new().no_deps().exec() {
38             metadata
39         } else {
40             span_lint(cx, WILDCARD_DEPENDENCIES, DUMMY_SP, "could not read cargo metadata");
41             return;
42         };
43
44         for dep in &metadata.packages[0].dependencies {
45             // VersionReq::any() does not work
46             if_chain! {
47                 if let Ok(wildcard_ver) = semver::VersionReq::parse("*");
48                 if let Some(ref source) = dep.source;
49                 if !source.starts_with("git");
50                 if dep.req == wildcard_ver;
51                 then {
52                     span_lint(
53                         cx,
54                         WILDCARD_DEPENDENCIES,
55                         DUMMY_SP,
56                         &format!("wildcard dependency for `{}`", dep.name),
57                     );
58                 }
59             }
60         }
61     }
62 }