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

View file

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