rm: added write-protected check for files

Signed-off-by: Stefin <stefin@pm.me>
This commit is contained in:
Stefin 2022-08-20 18:38:10 +05:30
parent aef96083d7
commit 9ffb00cd51

View file

@ -14,6 +14,8 @@ use clap::{crate_version, Arg, Command};
use remove_dir_all::remove_dir_all; use remove_dir_all::remove_dir_all;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::fs; use std::fs;
use std::fs::File;
use std::io::ErrorKind;
use std::io::{stderr, stdin, BufRead, Write}; use std::io::{stderr, stdin, BufRead, Write};
use std::ops::BitOr; use std::ops::BitOr;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -384,7 +386,7 @@ fn remove_file(path: &Path, options: &Options) -> bool {
} else { } else {
true true
}; };
if response { if response && prompt_write_protected(path, false) {
match fs::remove_file(path) { match fs::remove_file(path) {
Ok(_) => { Ok(_) => {
if options.verbose { if options.verbose {
@ -406,6 +408,23 @@ fn remove_file(path: &Path, options: &Options) -> bool {
false false
} }
fn prompt_write_protected(path: &Path, is_dir: bool) -> bool {
match File::open(path) {
Ok(_) => true,
Err(err) => {
if err.kind() == ErrorKind::PermissionDenied {
if is_dir {
prompt(&(format!("rm: remove write-protected directory {}? ", path.quote())))
} else {
prompt(&(format!("rm: remove write-protected file {}? ", path.quote())))
}
} else {
true
}
}
}
}
fn prompt_file(path: &Path, is_dir: bool) -> bool { fn prompt_file(path: &Path, is_dir: bool) -> bool {
if is_dir { if is_dir {
prompt(&(format!("rm: remove directory {}? ", path.quote()))) prompt(&(format!("rm: remove directory {}? ", path.quote())))