]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/create_dir.rs
Rollup merge of #106260 - chenyukang:yukang/fix-106213-doc, r=GuillaumeGomez
[rust.git] / src / tools / clippy / 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
12     /// Checks usage of `std::fs::create_dir` and suggest using `std::fs::create_dir_all` instead.
13     ///
14     /// ### Why is this bad?
15     /// Sometimes `std::fs::create_dir` is mistakenly chosen over `std::fs::create_dir_all`.
16     ///
17     /// ### Example
18     /// ```rust,ignore
19     /// std::fs::create_dir("foo");
20     /// ```
21     ///
22     /// Use instead:
23     /// ```rust,ignore
24     /// std::fs::create_dir_all("foo");
25     /// ```
26     #[clippy::version = "1.48.0"]
27     pub CREATE_DIR,
28     restriction,
29     "calling `std::fs::create_dir` instead of `std::fs::create_dir_all`"
30 }
31
32 declare_lint_pass!(CreateDir => [CREATE_DIR]);
33
34 impl LateLintPass<'_> for CreateDir {
35     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
36         if_chain! {
37             if let ExprKind::Call(func, [arg, ..]) = expr.kind;
38             if let ExprKind::Path(ref path) = func.kind;
39             if let Some(def_id) = cx.qpath_res(path, func.hir_id).opt_def_id();
40             if match_def_path(cx, def_id, &paths::STD_FS_CREATE_DIR);
41             then {
42                 span_lint_and_sugg(
43                     cx,
44                     CREATE_DIR,
45                     expr.span,
46                     "calling `std::fs::create_dir` where there may be a better way",
47                     "consider calling `std::fs::create_dir_all` instead",
48                     format!("create_dir_all({})", snippet(cx, arg.span, "..")),
49                     Applicability::MaybeIncorrect,
50                 )
51             }
52         }
53     }
54 }