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