Skip to content

Commit

Permalink
Merge pull request #5356 from terade/refactoring_prompt_file
Browse files Browse the repository at this point in the history
`rm`: refactor `prompt_file`, issue #5345
  • Loading branch information
cakebaker authored Oct 18, 2023
2 parents 895e136 + b6a6a4d commit 7a60819
Showing 1 changed file with 24 additions and 33 deletions.
57 changes: 24 additions & 33 deletions src/uu/rm/src/rm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,6 @@ fn prompt_dir(path: &Path, options: &Options) -> bool {
}
}

#[allow(clippy::cognitive_complexity)]
fn prompt_file(path: &Path, options: &Options) -> bool {
// If interactive is Never we never want to send prompts
if options.interactive == InteractiveMode::Never {
Expand All @@ -509,45 +508,37 @@ fn prompt_file(path: &Path, options: &Options) -> bool {
// File::open(path) doesn't open the file in write mode so we need to use file options to open it in also write mode to check if it can written too
match File::options().read(true).write(true).open(path) {
Ok(file) => {
if let Ok(metadata) = file.metadata() {
if metadata.permissions().readonly() {
if metadata.len() == 0 {
prompt_yes!(
"remove write-protected regular empty file {}?",
path.quote()
)
} else {
prompt_yes!("remove write-protected regular file {}?", path.quote())
}
} else if options.interactive == InteractiveMode::Always {
if metadata.len() == 0 {
prompt_yes!("remove regular empty file {}?", path.quote())
} else {
prompt_yes!("remove file {}?", path.quote())
}
let Ok(metadata) = file.metadata() else {
return true;
};

if options.interactive == InteractiveMode::Always && !metadata.permissions().readonly()
{
return if metadata.len() == 0 {
prompt_yes!("remove regular empty file {}?", path.quote())
} else {
true
}
} else {
true
prompt_yes!("remove file {}?", path.quote())
};
}
}
Err(err) => {
if err.kind() == ErrorKind::PermissionDenied {
match fs::metadata(path) {
Ok(metadata) if metadata.len() == 0 => {
prompt_yes!(
"remove write-protected regular empty file {}?",
path.quote()
)
}
_ => prompt_yes!("remove write-protected regular file {}?", path.quote()),
}
} else {
true
if err.kind() != ErrorKind::PermissionDenied {
return true;
}
}
}
prompt_file_permission_readonly(path)
}

fn prompt_file_permission_readonly(path: &Path) -> bool {
match fs::metadata(path) {
Ok(metadata) if !metadata.permissions().readonly() => true,
Ok(metadata) if metadata.len() == 0 => prompt_yes!(
"remove write-protected regular empty file {}?",
path.quote()
),
_ => prompt_yes!("remove write-protected regular file {}?", path.quote()),
}
}

// For directories finding if they are writable or not is a hassle. In Unix we can use the built-in rust crate to to check mode bits. But other os don't have something similar afaik
Expand Down

0 comments on commit 7a60819

Please sign in to comment.