1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-29 12:07:46 +00:00

Merge pull request #581 from kwantam/master

fix `rm` and `rmdir`
This commit is contained in:
Heather 2015-05-09 08:11:28 +03:00
commit 39de3f7b71
2 changed files with 160 additions and 110 deletions

View file

@ -1,5 +1,5 @@
#![crate_name = "rm"]
#![feature(collections, core, old_io, old_path, rustc_private)]
#![feature(file_type, dir_entry_ext, path_ext, rustc_private)]
/*
* This file is part of the uutils coreutils package.
@ -13,27 +13,26 @@
extern crate getopts;
extern crate libc;
use std::old_io::{print, stdin, stdio, fs, BufferedReader};
use std::old_io::fs::PathExtensions;
use std::collections::VecDeque;
use std::fs::{self, PathExt};
use std::io::{stdin, stderr, BufRead, Write};
use std::ops::BitOr;
use std::path::{Path, PathBuf};
#[path = "../common/util.rs"]
#[macro_use]
mod util;
#[derive(Eq, PartialEq)]
#[derive(Eq, PartialEq, Clone, Copy)]
enum InteractiveMode {
InteractiveNone,
InteractiveOnce,
InteractiveAlways
}
impl Copy for InteractiveMode {}
static NAME: &'static str = "rm";
pub fn uumain(args: Vec<String>) -> i32 {
let program = args[0].clone();
// TODO: make getopts support -R in addition to -r
let opts = [
getopts::optflag("f", "force", "ignore nonexistent files and arguments, never prompt"),
@ -49,7 +48,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit")
];
let matches = match getopts::getopts(args.tail(), &opts) {
let matches = match getopts::getopts(&args[1..], &opts) {
Ok(m) => m,
Err(f) => {
crash!(1, "{}", f)
@ -59,10 +58,9 @@ pub fn uumain(args: Vec<String>) -> i32 {
println!("rm 1.0.0");
println!("");
println!("Usage:");
println!(" {0} [OPTION]... [FILE]...", program);
println!("");
print(getopts::usage("Remove (unlink) the FILE(s).", &opts).as_slice());
println!(" {0} [OPTION]... [FILE]...", &args[0][..]);
println!("");
println!("{}", &getopts::usage("Remove (unlink) the FILE(s).", &opts)[..]);
println!("By default, rm does not remove directories. Use the --recursive (-r)");
println!("option to remove each listed directory, too, along with all of its contents");
println!("");
@ -79,7 +77,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
println!("rm 1.0.0");
} else if matches.free.is_empty() {
show_error!("missing an argument");
show_error!("for help, try '{0} --help'", program);
show_error!("for help, try '{0} --help'", &args[0][..]);
return 1;
} else {
let force = matches.opt_present("force");
@ -89,7 +87,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
} else if matches.opt_present("I") {
InteractiveMode::InteractiveOnce
} else if matches.opt_present("interactive") {
match matches.opt_str("interactive").unwrap().as_slice() {
match &matches.opt_str("interactive").unwrap()[..] {
"none" => InteractiveMode::InteractiveNone,
"once" => InteractiveMode::InteractiveOnce,
"always" => InteractiveMode::InteractiveAlways,
@ -116,9 +114,9 @@ pub fn uumain(args: Vec<String>) -> i32 {
return 0;
}
}
if let Err(e) = remove(matches.free, force, interactive, one_fs, preserve_root,
recursive, dir, verbose) {
return e;
if remove(matches.free, force, interactive, one_fs, preserve_root, recursive, dir, verbose) {
return 1;
}
}
@ -126,114 +124,165 @@ pub fn uumain(args: Vec<String>) -> i32 {
}
// TODO: implement one-file-system
fn remove(files: Vec<String>, force: bool, interactive: InteractiveMode, one_fs: bool, preserve_root: bool, recursive: bool, dir: bool, verbose: bool) -> Result<(), i32> {
let mut r = Ok(());
#[allow(unused_variables)]
fn remove(files: Vec<String>, force: bool, interactive: InteractiveMode, one_fs: bool, preserve_root: bool, recursive: bool, dir: bool, verbose: bool) -> bool {
let mut had_err = false;
for filename in files.iter() {
let filename = filename.as_slice();
let filename = &filename[..];
let file = Path::new(filename);
if file.exists() {
if file.is_dir() {
if recursive && (filename != "/" || !preserve_root) {
let walk_dir = match fs::walk_dir(&file) {
Ok(m) => m,
Err(f) => {
crash!(1, "{}", f.to_string());
if interactive != InteractiveMode::InteractiveAlways {
match fs::remove_dir_all(file) {
Err(e) => {
had_err = true;
show_error!("could not remove '{}': {}", filename, e);
},
_ => (),
};
} else {
let mut dirs: VecDeque<PathBuf> = VecDeque::new();
let mut files: Vec<PathBuf> = Vec::new();
let mut rmdirstack: Vec<PathBuf> = Vec::new();
dirs.push_back(file.to_path_buf());
while !dirs.is_empty() {
let dir = dirs.pop_front().unwrap();
if !prompt(&(format!("rm: descend into directory '{}'? ", dir.display()))[..]) {
continue;
}
// iterate over items in this directory, adding to either file or
// directory queue
match fs::read_dir(dir.as_path()) {
Ok(rdir) => {
for ent in rdir {
match ent {
Ok(ref f) => match f.file_type() {
Ok(t) => {
if t.is_dir() {
dirs.push_back(f.path());
} else {
files.push(f.path());
}
},
Err(e) => {
had_err = true;
show_error!("reading '{}': {}", f.path().display(), e);
},
},
Err(ref e) => {
had_err = true;
show_error!("recursing into '{}': {}", filename, e);
},
};
}
},
Err(e) => {
had_err = true;
show_error!("could not recurse into '{}': {}", dir.display(), e);
continue;
},
};
for f in files.iter() {
had_err = remove_file(f.as_path(), interactive, verbose).bitor(had_err);
}
files.clear();
rmdirstack.push(dir);
}
};
r = remove(walk_dir.map(|x| x.as_str().unwrap().to_string()).collect(), force, interactive, one_fs, preserve_root, recursive, dir, verbose).and(r);
r = remove_dir(&file, filename, interactive, verbose).and(r);
for d in rmdirstack.iter().rev() {
had_err = remove_dir(d.as_path(), interactive, verbose).bitor(had_err);
}
}
} else if dir && (filename != "/" || !preserve_root) {
r = remove_dir(&file, filename, interactive, verbose).and(r);
had_err = remove_dir(&file, interactive, verbose).bitor(had_err);
} else {
if recursive {
show_error!("could not remove directory '{}'",
filename);
r = Err(1);
show_error!("could not remove directory '{}'", filename);
had_err = true;
} else {
show_error!("could not remove directory '{}' (did you mean to pass '-r'?)",
filename);
r = Err(1);
show_error!("could not remove directory '{}' (did you mean to pass '-r'?)", filename);
had_err = true;
}
}
} else {
r = remove_file(&file, filename.as_slice(), interactive, verbose).and(r);
had_err = remove_file(&file, interactive, verbose).bitor(had_err);
}
} else if !force {
show_error!("no such file or directory '{}'", filename);
r = Err(1);
had_err = true;
}
}
r
had_err
}
fn remove_dir(path: &Path, name: &str, interactive: InteractiveMode, verbose: bool) -> Result<(), i32> {
fn remove_dir(path: &Path, interactive: InteractiveMode, verbose: bool) -> bool {
let response =
if interactive == InteractiveMode::InteractiveAlways {
prompt_file(path, name)
prompt_file(path, true)
} else {
true
};
if response {
match fs::rmdir(path) {
Ok(_) => if verbose { println!("Removed '{}'", name); },
Err(f) => {
show_error!("{}", f.to_string());
return Err(1);
match fs::remove_dir(path) {
Ok(_) => if verbose { println!("removed '{}'", path.display()); },
Err(e) => {
show_error!("removing '{}': {}", path.display(), e);
return true;
}
}
}
Ok(())
false
}
fn remove_file(path: &Path, name: &str, interactive: InteractiveMode, verbose: bool) -> Result<(), i32> {
fn remove_file(path: &Path, interactive: InteractiveMode, verbose: bool) -> bool {
let response =
if interactive == InteractiveMode::InteractiveAlways {
prompt_file(path, name)
prompt_file(path, false)
} else {
true
};
if response {
match fs::unlink(path) {
Ok(_) => if verbose { println!("Removed '{}'", name); },
Err(f) => {
show_error!("{}", f.to_string());
return Err(1);
match fs::remove_file(path) {
Ok(_) => if verbose { println!("removed '{}'", path.display()); },
Err(e) => {
show_error!("removing '{}': {}", path.display(), e);
return true;
}
}
}
Ok(())
false
}
fn prompt_file(path: &Path, name: &str) -> bool {
if path.is_dir() {
prompt(format!("Remove directory '{}'? ", name).as_slice())
fn prompt_file(path: &Path, is_dir: bool) -> bool {
if is_dir {
prompt(&(format!("rm: remove directory '{}'? ", path.display()))[..])
} else {
prompt(format!("Remove file '{}'? ", name).as_slice())
prompt(&(format!("rm: remove file '{}'? ", path.display()))[..])
}
}
fn prompt(msg: &str) -> bool {
print(msg);
read_prompt()
}
fn read_prompt() -> bool {
stdio::flush();
match BufferedReader::new(stdin()).read_line() {
Ok(line) => {
match line.as_slice().char_at(0) {
'y' | 'Y' => true,
'n' | 'N' => false,
_ => {
print!("Please enter either Y or N: ");
read_prompt()
}
stderr().write_all(msg.as_bytes()).unwrap_or(());
stderr().flush().unwrap_or(());
let mut buf = Vec::new();
let stdin = stdin();
let mut stdin = stdin.lock();
match stdin.read_until('\n' as u8, &mut buf) {
Ok(x) if x > 0 => {
match buf[0] {
0x59 | 0x79 => true,
_ => false,
}
}
Err(_) => true
_ => false,
}
}

View file

@ -1,5 +1,5 @@
#![crate_name = "rmdir"]
#![feature(collections, core, old_io, old_path, rustc_private)]
#![feature(rustc_private)]
/*
* This file is part of the uutils coreutils package.
@ -13,8 +13,9 @@
extern crate getopts;
extern crate libc;
use std::old_io::{print, fs};
use std::old_io::fs::PathExtensions;
use std::path::Path;
use std::io::Write;
use std::fs;
#[path = "../common/util.rs"]
#[macro_use]
@ -32,7 +33,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
getopts::optflag("h", "help", "print this help and exit"),
getopts::optflag("V", "version", "output version information and exit")
];
let matches = match getopts::getopts(args.tail(), &opts) {
let matches = match getopts::getopts(&args[1..], &opts) {
Ok(m) => m,
Err(f) => {
show_error!("{}", f);
@ -46,7 +47,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
println!("Usage:");
println!(" {0} [OPTION]... DIRECTORY...", program);
println!("");
print(getopts::usage("Remove the DIRECTORY(ies), if they are empty.", &opts).as_slice());
println!("{}", &getopts::usage("Remove the DIRECTORY(ies), if they are empty.", &opts)[..]);
} else if matches.opt_present("version") {
println!("rmdir 1.0.0");
} else if matches.free.is_empty() {
@ -66,58 +67,58 @@ pub fn uumain(args: Vec<String>) -> i32 {
0
}
fn remove(dirs: Vec<String>, ignore: bool, parents: bool, verbose: bool) -> Result<(), i32>{
fn remove(dirs: Vec<String>, ignore: bool, parents: bool, verbose: bool) -> Result<(), i32> {
let mut r = Ok(());
for dir in dirs.iter() {
let path = Path::new(dir.as_slice());
if path.exists() {
if path.is_dir() {
r = remove_dir(&path, dir.as_slice(), ignore, parents, verbose).and(r);
} else {
show_error!("failed to remove '{}' (file)", *dir);
r = Err(1);
let path = Path::new(&dir[..]);
r = remove_dir(&path, ignore, verbose).and(r);
if parents {
let mut p = path;
loop {
let new_p = match p.parent() {
Some(p) => p,
None => break,
};
p = new_p;
match p.as_os_str().to_str() {
None => break,
Some(s) => match s {
"" | "." | "/" => break,
_ => (),
},
};
r = remove_dir(p, ignore, verbose).and(r);
}
} else {
show_error!("no such file or directory '{}'", *dir);
r = Err(1);
}
}
r
}
fn remove_dir(path: &Path, dir: &str, ignore: bool, parents: bool, verbose: bool) -> Result<(), i32> {
let mut walk_dir = match fs::walk_dir(path) {
fn remove_dir(path: &Path, ignore: bool, verbose: bool) -> Result<(), i32> {
let mut read_dir = match fs::read_dir(path) {
Ok(m) => m,
Err(f) => {
show_error!("{}", f.to_string());
Err(e) => {
show_error!("reading directory '{}': {}", path.display(), e);
return Err(1);
}
};
let mut r = Ok(());
if walk_dir.next() == None {
match fs::rmdir(path) {
Ok(_) => {
if verbose {
println!("Removed directory '{}'", dir);
}
if parents {
let dirname = path.dirname_str().unwrap();
if dirname != "." {
r = remove_dir(&Path::new(dirname), dirname, ignore, parents, verbose).and(r);
}
}
}
Err(f) => {
show_error!("{}", f.to_string());
if read_dir.next().is_none() {
match fs::remove_dir(path) {
Err(e) => {
show_error!("removing directory '{}': {}", path.display(), e);
r = Err(1);
}
},
Ok(_) if verbose => println!("Removed directory '{}'", path.display()),
_ => (),
}
} else if !ignore {
show_error!("Failed to remove directory '{}' (non-empty)", dir);
show_error!("failed to remove '{}' Directory not empty", path.display());
r = Err(1);
}