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 #[clippy::version = "1.53.0"]
36 pub NON_OCTAL_UNIX_PERMISSIONS,
38 "use of non-octal value to set unix file permissions, which will be translated into octal"
41 declare_lint_pass!(NonOctalUnixPermissions => [NON_OCTAL_UNIX_PERMISSIONS]);
43 impl LateLintPass<'_> for NonOctalUnixPermissions {
44 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
46 ExprKind::MethodCall(path, _, [func, param], _) => {
47 let obj_ty = cx.typeck_results().expr_ty(func).peel_refs();
50 if (path.ident.name == sym!(mode)
51 && (match_type(cx, obj_ty, &paths::OPEN_OPTIONS)
52 || match_type(cx, obj_ty, &paths::DIR_BUILDER)))
53 || (path.ident.name == sym!(set_mode) && match_type(cx, obj_ty, &paths::PERMISSIONS));
54 if let ExprKind::Lit(_) = param.kind;
57 let snip = match snippet_opt(cx, param.span) {
62 if !snip.starts_with("0o") {
63 show_error(cx, param);
68 ExprKind::Call(func, [param]) => {
70 if let ExprKind::Path(ref path) = func.kind;
71 if let Some(def_id) = cx.qpath_res(path, func.hir_id).opt_def_id();
72 if match_def_path(cx, def_id, &paths::PERMISSIONS_FROM_MODE);
73 if let ExprKind::Lit(_) = param.kind;
76 let snip = match snippet_opt(cx, param.span) {
81 if !snip.starts_with("0o") {
82 show_error(cx, param);
92 fn show_error(cx: &LateContext<'_>, param: &Expr<'_>) {
93 let mut applicability = Applicability::MachineApplicable;
96 NON_OCTAL_UNIX_PERMISSIONS,
98 "using a non-octal value to set unix file permissions",
99 "consider using an octal literal instead",
102 snippet_with_applicability(cx, param.span, "0o..", &mut applicability,),