1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::{snippet_opt, snippet_with_applicability};
3 use clippy_utils::ty::match_type;
4 use clippy_utils::{match_def_path, paths};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::{Expr, ExprKind};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 declare_clippy_lint! {
13 /// Checks for non-octal values used to set Unix file permissions.
15 /// ### Why is this bad?
16 /// They will be converted into octal, creating potentially
17 /// unintended file permissions.
21 /// use std::fs::OpenOptions;
22 /// use std::os::unix::fs::OpenOptionsExt;
24 /// let mut options = OpenOptions::new();
25 /// options.mode(644);
29 /// use std::fs::OpenOptions;
30 /// use std::os::unix::fs::OpenOptionsExt;
32 /// let mut options = OpenOptions::new();
33 /// options.mode(0o644);
35 pub NON_OCTAL_UNIX_PERMISSIONS,
37 "use of non-octal value to set unix file permissions, which will be translated into octal"
40 declare_lint_pass!(NonOctalUnixPermissions => [NON_OCTAL_UNIX_PERMISSIONS]);
42 impl LateLintPass<'_> for NonOctalUnixPermissions {
43 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
45 ExprKind::MethodCall(path, _, [func, param], _) => {
46 let obj_ty = cx.typeck_results().expr_ty(func).peel_refs();
49 if (path.ident.name == sym!(mode)
50 && (match_type(cx, obj_ty, &paths::OPEN_OPTIONS)
51 || match_type(cx, obj_ty, &paths::DIR_BUILDER)))
52 || (path.ident.name == sym!(set_mode) && match_type(cx, obj_ty, &paths::PERMISSIONS));
53 if let ExprKind::Lit(_) = param.kind;
56 let snip = match snippet_opt(cx, param.span) {
61 if !snip.starts_with("0o") {
62 show_error(cx, param);
67 ExprKind::Call(func, [param]) => {
69 if let ExprKind::Path(ref path) = func.kind;
70 if let Some(def_id) = cx.qpath_res(path, func.hir_id).opt_def_id();
71 if match_def_path(cx, def_id, &paths::PERMISSIONS_FROM_MODE);
72 if let ExprKind::Lit(_) = param.kind;
75 let snip = match snippet_opt(cx, param.span) {
80 if !snip.starts_with("0o") {
81 show_error(cx, param);
91 fn show_error(cx: &LateContext<'_>, param: &Expr<'_>) {
92 let mut applicability = Applicability::MachineApplicable;
95 NON_OCTAL_UNIX_PERMISSIONS,
97 "using a non-octal value to set unix file permissions",
98 "consider using an octal literal instead",
101 snippet_with_applicability(cx, param.span, "0o..", &mut applicability,),