|
| 1 | +use crate::utils::{match_type, paths, span_lint_and_sugg, walk_ptrs_ty}; |
| 2 | +use if_chain::if_chain; |
| 3 | +use rustc::hir::*; |
| 4 | +use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass}; |
| 5 | +use rustc::{declare_lint_pass, declare_tool_lint}; |
| 6 | +use rustc_errors::Applicability; |
| 7 | +use std::path::{Component, Path}; |
| 8 | +use syntax::ast::LitKind; |
| 9 | + |
| 10 | +declare_clippy_lint! { |
| 11 | + /// **What it does:*** Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push) |
| 12 | + /// calls on `PathBuf` that can cause overwrites. |
| 13 | + /// |
| 14 | + /// **Why is this bad?** Calling `push` with a root path at the start can overwrite the |
| 15 | + /// previous defined path. |
| 16 | + /// |
| 17 | + /// **Known problems:** None. |
| 18 | + /// |
| 19 | + /// **Example:** |
| 20 | + /// ```rust |
| 21 | + /// use std::path::PathBuf; |
| 22 | + /// |
| 23 | + /// let mut x = PathBuf::from("/foo"); |
| 24 | + /// x.push("/bar"); |
| 25 | + /// assert_eq!(x, PathBuf::from("/bar")); |
| 26 | + /// ``` |
| 27 | + /// Could be written: |
| 28 | + /// |
| 29 | + /// ```rust |
| 30 | + /// use std::path::PathBuf; |
| 31 | + /// |
| 32 | + /// let mut x = PathBuf::from("/foo"); |
| 33 | + /// x.push("bar"); |
| 34 | + /// assert_eq!(x, PathBuf::from("/foo/bar")); |
| 35 | + /// ``` |
| 36 | + pub PATH_BUF_PUSH_OVERWRITE, |
| 37 | + correctness, |
| 38 | + "calling `push` with file system root on `PathBuf` can overwrite it" |
| 39 | +} |
| 40 | + |
| 41 | +declare_lint_pass!(PathBufPushOverwrite => [PATH_BUF_PUSH_OVERWRITE]); |
| 42 | + |
| 43 | +impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathBufPushOverwrite { |
| 44 | + fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { |
| 45 | + if_chain! { |
| 46 | + if let ExprKind::MethodCall(ref path, _, ref args) = expr.node; |
| 47 | + if path.ident.name == "push"; |
| 48 | + if args.len() == 2; |
| 49 | + if match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(&args[0])), &paths::PATH_BUF); |
| 50 | + if let Some(get_index_arg) = args.get(1); |
| 51 | + if let ExprKind::Lit(ref lit) = get_index_arg.node; |
| 52 | + if let LitKind::Str(ref path_lit, _) = lit.node; |
| 53 | + if let pushed_path = Path::new(&path_lit.as_str()); |
| 54 | + if let Some(pushed_path_lit) = pushed_path.to_str(); |
| 55 | + if pushed_path.has_root(); |
| 56 | + if let Some(root) = pushed_path.components().next(); |
| 57 | + if root == Component::RootDir; |
| 58 | + then { |
| 59 | + span_lint_and_sugg( |
| 60 | + cx, |
| 61 | + PATH_BUF_PUSH_OVERWRITE, |
| 62 | + lit.span, |
| 63 | + "Calling `push` with '/' or '\\' (file system root) will overwrite the previous path definition", |
| 64 | + "try", |
| 65 | + format!("\"{}\"", pushed_path_lit.trim_start_matches(|c| c == '/' || c == '\\')), |
| 66 | + Applicability::MachineApplicable, |
| 67 | + ); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments