]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/create_dir.rs
Merge commit '5034d47f721ff4c3a3ff2aca9ef2ef3e1d067f9f' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / create_dir.rs
1 use crate::utils::{match_def_path, paths, snippet, span_lint_and_sugg};
2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_hir::{Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7
8 declare_clippy_lint! {
9     /// **What it does:** Checks usage of `std::fs::create_dir` and suggest using `std::fs::create_dir_all` instead.
10     ///
11     /// **Why is this bad?** Sometimes `std::fs::crate_dir` is mistakenly chosen over `std::fs::create_dir_all`.
12     ///
13     /// **Known problems:** None.
14     ///
15     /// **Example:**
16     ///
17     /// ```rust
18     /// std::fs::create_dir("foo");
19     /// ```
20     /// Use instead:
21     /// ```rust
22     /// std::fs::create_dir_all("foo");
23     /// ```
24     pub CREATE_DIR,
25     restriction,
26     "calling `std::fs::create_dir` instead of `std::fs::create_dir_all`"
27 }
28
29 declare_lint_pass!(CreateDir => [CREATE_DIR]);
30
31 impl LateLintPass<'_> for CreateDir {
32     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
33         if_chain! {
34             if let ExprKind::Call(ref func, ref args) = expr.kind;
35             if let ExprKind::Path(ref path) = func.kind;
36             if let Some(def_id) = cx.qpath_res(path, func.hir_id).opt_def_id();
37             if match_def_path(cx, def_id, &paths::STD_FS_CREATE_DIR);
38             then {
39                 span_lint_and_sugg(
40                     cx,
41                     CREATE_DIR,
42                     expr.span,
43                     "calling `std::fs::create_dir` where there may be a better way",
44                     "consider calling `std::fs::create_dir_all` instead",
45                     format!("create_dir_all({})", snippet(cx, args[0].span, "..")),
46                     Applicability::MaybeIncorrect,
47                 )
48             }
49         }
50     }
51 }