mkdir: Fix the behavior for existing files

Currently, mkdir always succeeds for existing files and it
even modifies their mode. With this change, only mkdir -p for
existing directories will be allowed.
This commit is contained in:
Shinichiro Hamaji 2017-04-01 21:38:56 +09:00
parent 626a3b7611
commit fc235e360e
2 changed files with 25 additions and 8 deletions

View file

@ -94,7 +94,9 @@ fn exec(dirs: Vec<String>, recursive: bool, mode: u16, verbose: bool) -> i32 {
let mut pathbuf = PathBuf::new();
for component in path.components() {
pathbuf.push(component.as_os_str());
status |= mkdir(pathbuf.as_path(), mode, verbose);
if !path.is_dir() {
status |= mkdir(pathbuf.as_path(), mode, verbose);
}
}
} else {
match path.parent() {
@ -119,11 +121,9 @@ fn exec(dirs: Vec<String>, recursive: bool, mode: u16, verbose: bool) -> i32 {
* Wrapper to catch errors, return 1 if failed
*/
fn mkdir(path: &Path, mode: u16, verbose: bool) -> i32 {
if !path.exists() {
if let Err(e) = fs::create_dir(path) {
show_info!("{}: {}", path.display(), e.to_string());
return 1;
}
if let Err(e) = fs::create_dir(path) {
show_info!("{}: {}", path.display(), e.to_string());
return 1;
}
if verbose {

View file

@ -1,11 +1,12 @@
use common::util::*;
static TEST_DIR1: &'static str = "mkdir_test1";
static TEST_DIR2: &'static str = "mkdir_test2";
static TEST_DIR3: &'static str = "mkdir_test3";
static TEST_DIR4: &'static str = "mkdir_test4/mkdir_test4_1";
static TEST_DIR5: &'static str = "mkdir_test5/mkdir_test5_1";
static TEST_DIR6: &'static str = "mkdir_test6";
static TEST_FILE7: &'static str = "mkdir_test7";
#[test]
fn test_mkdir_mkdir() {
@ -16,7 +17,7 @@ fn test_mkdir_mkdir() {
fn test_mkdir_dup_dir() {
let scene = TestScenario::new(util_name!());
scene.ucmd().arg(TEST_DIR2).succeeds();
scene.ucmd().arg(TEST_DIR2).succeeds();
scene.ucmd().arg(TEST_DIR2).fails();
}
#[test]
@ -39,3 +40,19 @@ fn test_mkdir_parent() {
fn test_mkdir_no_parent() {
new_ucmd!().arg(TEST_DIR5).fails();
}
#[test]
fn test_mkdir_dup_dir_parent() {
let scene = TestScenario::new(util_name!());
scene.ucmd().arg(TEST_DIR6).succeeds();
scene.ucmd().arg("-p").arg(TEST_DIR6).succeeds();
}
#[test]
fn test_mkdir_dup_file() {
let scene = TestScenario::new(util_name!());
scene.fixtures.touch(TEST_FILE7);
scene.ucmd().arg(TEST_FILE7).fails();
// mkdir should fail for a file even if -p is specified.
scene.ucmd().arg("-p").arg(TEST_FILE7).fails();
}