Skip to content

Commit

Permalink
fix(mkdir): improve error handling around files (#721)
Browse files Browse the repository at this point in the history
* fix(mkdir): improve error handling around files

In particular, this fixes:

 - if we try to overwrite a file with a mkdir
 - if we try to create a subdirectory of a file
 - adds `continue: true` in spots where we missed it

Fixes #720

* Fixing tests on Windows
  • Loading branch information
nfischer committed May 16, 2017
1 parent a2e13b6 commit 15558cf
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/mkdir.js
Expand Up @@ -57,9 +57,11 @@ function _mkdir(options, dirs) {

dirs.forEach(function (dir) {
try {
fs.lstatSync(dir);
var stat = fs.lstatSync(dir);
if (!options.fullpath) {
common.error('path already exists: ' + dir, { continue: true });
} else if (stat.isFile()) {
common.error('cannot create directory ' + dir + ': File exists', { continue: true });
}
return; // skip dir
} catch (e) {
Expand All @@ -80,12 +82,16 @@ function _mkdir(options, dirs) {
fs.mkdirSync(dir, parseInt('0777', 8));
}
} catch (e) {
var reason;
if (e.code === 'EACCES') {
common.error('cannot create directory ' + dir + ': Permission denied');
reason = 'Permission denied';
} else if (e.code === 'ENOTDIR' || e.code === 'ENOENT') {
reason = 'Not a directory';
} else {
/* istanbul ignore next */
throw e;
}
common.error('cannot create directory ' + dir + ': ' + reason, { continue: true });
}
});
return '';
Expand Down
28 changes: 28 additions & 0 deletions test/mkdir.js
Expand Up @@ -55,6 +55,34 @@ test('root path does not exist', t => {
t.falsy(fs.existsSync('/asdfasdf/foobar'));
});

test('try to overwrite file', t => {
t.truthy(fs.statSync('resources/file1').isFile());
const result = shell.mkdir('resources/file1');
t.truthy(shell.error());
t.is(result.code, 1);
t.is(result.stderr, 'mkdir: path already exists: resources/file1');
t.truthy(fs.statSync('resources/file1').isFile());
});

test('try to overwrite file, with -p', t => {
t.truthy(fs.statSync('resources/file1').isFile());
const result = shell.mkdir('-p', 'resources/file1');
t.truthy(shell.error());
t.is(result.code, 1);
t.is(result.stderr, 'mkdir: cannot create directory resources/file1: File exists');
t.truthy(fs.statSync('resources/file1').isFile());
});

test('try to make a subdirectory of a file', t => {
t.truthy(fs.statSync('resources/file1').isFile());
const result = shell.mkdir('resources/file1/subdir');
t.truthy(shell.error());
t.is(result.code, 1);
t.is(result.stderr, 'mkdir: cannot create directory resources/file1/subdir: Not a directory');
t.truthy(fs.statSync('resources/file1').isFile());
t.falsy(fs.existsSync('resources/file1/subdir'));
});

test('Check for invalid permissions', t => {
if (process.platform !== 'win32') {
// This test case only works on unix, but should work on Windows as well
Expand Down

0 comments on commit 15558cf

Please sign in to comment.