diff --git a/lib/mkdirs/__tests__/clobber.test.js b/lib/mkdirs/__tests__/clobber.test.js index b932b040..be4ab101 100644 --- a/lib/mkdirs/__tests__/clobber.test.js +++ b/lib/mkdirs/__tests__/clobber.test.js @@ -42,11 +42,7 @@ describe('mkdirp / clobber', () => { it('should clobber', done => { fse.mkdirp(file, 0o755, err => { assert.ok(err) - if (os.platform().indexOf('win') === 0) { - assert.strictEqual(err.code, 'EEXIST') - } else { - assert.strictEqual(err.code, 'ENOTDIR') - } + assert.strictEqual(err.code, 'ENOTDIR') done() }) }) diff --git a/lib/mkdirs/__tests__/issue-93.test.js b/lib/mkdirs/__tests__/issue-93.test.js index 771694e6..ec0270b8 100644 --- a/lib/mkdirs/__tests__/issue-93.test.js +++ b/lib/mkdirs/__tests__/issue-93.test.js @@ -4,6 +4,7 @@ const os = require('os') const fse = require(process.cwd()) const path = require('path') const assert = require('assert') +const util = require('util') /* global before, describe, it */ @@ -23,13 +24,19 @@ describe('mkdirp: issue-93, win32, when drive does not exist, it should return a it('should return a cleaner error than inifinite loop, stack crash', done => { const file = 'R:\\afasd\\afaff\\fdfd' // hopefully drive 'r' does not exist on appveyor + // Different error codes on different Node versions (matches native mkdir behavior) + const assertErr = (err) => assert( + ['EPERM', 'ENOENT'].includes(err.code), + `expected 'EPERM' or 'ENOENT', got ${util.inspect(err.code)}` + ) + fse.mkdirp(file, err => { - assert.strictEqual(err.code, 'ENOENT') + assertErr(err) try { fse.mkdirsSync(file) } catch (err) { - assert.strictEqual(err.code, 'ENOENT') + assertErr(err) } done() diff --git a/lib/mkdirs/__tests__/opts-undef.test.js b/lib/mkdirs/__tests__/opts-undef.test.js index e72e79b5..d5bd0744 100644 --- a/lib/mkdirs/__tests__/opts-undef.test.js +++ b/lib/mkdirs/__tests__/opts-undef.test.js @@ -5,7 +5,6 @@ const os = require('os') const fse = require(process.cwd()) const path = require('path') const assert = require('assert') -const mkdirs = require('../mkdirs') /* global beforeEach, describe, it */ @@ -22,7 +21,7 @@ describe('mkdirs / opts-undef', () => { const newDir = path.join(TEST_DIR, 'doest', 'not', 'exist') assert(!fs.existsSync(newDir)) - mkdirs(newDir, undefined, err => { + fse.mkdirs(newDir, undefined, err => { assert.ifError(err) assert(fs.existsSync(newDir)) done() diff --git a/lib/mkdirs/__tests__/return.test.js b/lib/mkdirs/__tests__/return.test.js deleted file mode 100644 index 0076d9f4..00000000 --- a/lib/mkdirs/__tests__/return.test.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict' - -const os = require('os') -const fse = require('../../') -const path = require('path') -const assert = require('assert') - -/* global afterEach, beforeEach, describe, it */ - -describe('mkdirp / return value', () => { - let TEST_DIR - - beforeEach(done => { - TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'mkdirp-return') - fse.emptyDir(TEST_DIR, done) - }) - - afterEach(done => fse.remove(TEST_DIR, done)) - - it('should', done => { - const x = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) - const y = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) - const z = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) - - const dir = TEST_DIR + path.sep - const file = dir + [x, y, z].join(path.sep) - - // should return the first dir created. - // By this point, it would be profoundly surprising if /tmp didn't - // already exist, since every other test makes things in there. - fse.mkdirp(file, (err, made) => { - assert.ifError(err) - assert.strictEqual(made, dir + x) - fse.mkdirp(file, (err, made) => { - assert.ifError(err) - assert.strictEqual(made, null) - done() - }) - }) - }) -}) diff --git a/lib/mkdirs/__tests__/return_sync.test.js b/lib/mkdirs/__tests__/return_sync.test.js deleted file mode 100644 index 9ab11614..00000000 --- a/lib/mkdirs/__tests__/return_sync.test.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict' - -const os = require('os') -const fse = require('../../') -const path = require('path') -const assert = require('assert') - -/* global afterEach, beforeEach, describe, it */ - -describe('mkdirp / return value', () => { - let TEST_DIR - - beforeEach(done => { - TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'mkdirp-return') - fse.emptyDir(TEST_DIR, done) - }) - - afterEach(done => fse.remove(TEST_DIR, done)) - - it('should', () => { - const x = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) - const y = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) - const z = Math.floor(Math.random() * Math.pow(16, 4)).toString(16) - - const dir = TEST_DIR + path.sep - const file = dir + [x, y, z].join(path.sep) - - // should return the first dir created. - // By this point, it would be profoundly surprising if /tmp didn't - // already exist, since every other test makes things in there. - // Note that this will throw on failure, which will fail the test. - let made = fse.mkdirpSync(file) - assert.strictEqual(made, dir + x) - - // making the same file again should have no effect. - made = fse.mkdirpSync(file) - assert.strictEqual(made, null) - }) -}) diff --git a/lib/mkdirs/__tests__/root.test.js b/lib/mkdirs/__tests__/root.test.js index 2d0974de..441405a2 100644 --- a/lib/mkdirs/__tests__/root.test.js +++ b/lib/mkdirs/__tests__/root.test.js @@ -8,17 +8,17 @@ const assert = require('assert') /* global describe, it */ describe('mkdirp / root', () => { - // '/' on unix, 'c:/' on windows. + // '/' on unix const dir = path.normalize(path.resolve(path.sep)).toLowerCase() - // if not 'c:\\' or 'd:\\', it's probably a network mounted drive, this fails then. TODO: investigate - if (process.platform === 'win32' && (dir.indexOf('c:\\') === -1) && (dir.indexOf('d:\\') === -1)) return + // Windows does not have permission to mkdir on root + if (process.platform === 'win32') return it('should', done => { fse.mkdirp(dir, 0o755, err => { - if (err) throw err + if (err) return done(err) fs.stat(dir, (er, stat) => { - if (er) throw er + if (er) return done(er) assert.ok(stat.isDirectory(), 'target is a directory') done() }) diff --git a/lib/mkdirs/index.js b/lib/mkdirs/index.js index d6e7e5bf..9edecee0 100644 --- a/lib/mkdirs/index.js +++ b/lib/mkdirs/index.js @@ -1,14 +1,14 @@ 'use strict' -const u = require('universalify').fromCallback -const mkdirs = u(require('./mkdirs')) -const mkdirsSync = require('./mkdirs-sync') +const u = require('universalify').fromPromise +const { makeDir: _makeDir, makeDirSync } = require('./make-dir') +const makeDir = u(_makeDir) module.exports = { - mkdirs, - mkdirsSync, + mkdirs: makeDir, + mkdirsSync: makeDirSync, // alias - mkdirp: mkdirs, - mkdirpSync: mkdirsSync, - ensureDir: mkdirs, - ensureDirSync: mkdirsSync + mkdirp: makeDir, + mkdirpSync: makeDirSync, + ensureDir: makeDir, + ensureDirSync: makeDirSync } diff --git a/lib/mkdirs/make-dir.js b/lib/mkdirs/make-dir.js new file mode 100644 index 00000000..f17ecffb --- /dev/null +++ b/lib/mkdirs/make-dir.js @@ -0,0 +1,142 @@ +// Adapted from https://github.com/sindresorhus/make-dir +// Copyright (c) Sindre Sorhus (sindresorhus.com) +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +'use strict' +const fs = require('../fs') +const path = require('path') +const atLeastNode = require('at-least-node') + +const useNativeRecursiveOption = atLeastNode('10.12.0') + +// https://github.com/nodejs/node/issues/8987 +// https://github.com/libuv/libuv/pull/1088 +const checkPath = pth => { + if (process.platform === 'win32') { + const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')) + + if (pathHasInvalidWinCharacters) { + const error = new Error(`Path contains invalid characters: ${pth}`) + error.code = 'EINVAL' + throw error + } + } +} + +const processOptions = options => { + // Must be defined here so we get fresh process.umask() + const defaults = { mode: 0o777 & (~process.umask()) } + if (typeof options === 'number') options = { mode: options } + return { ...defaults, ...options } +} + +const permissionError = pth => { + // This replicates the exception of `fs.mkdir` with native the + // `recusive` option when run on an invalid drive under Windows. + const error = new Error(`operation not permitted, mkdir '${pth}'`) + error.code = 'EPERM' + error.errno = -4048 + error.path = pth + error.syscall = 'mkdir' + return error +} + +module.exports.makeDir = async (input, options) => { + checkPath(input) + options = processOptions(options) + + if (useNativeRecursiveOption) { + const pth = path.resolve(input) + + return fs.mkdir(pth, { + mode: options.mode, + recursive: true + }) + } + + const make = async pth => { + try { + await fs.mkdir(pth, options.mode) + } catch (error) { + if (error.code === 'EPERM') { + throw error + } + + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth) + } + + if (error.message.includes('null bytes')) { + throw error + } + + await make(path.dirname(pth)) + return make(pth) + } + + try { + const stats = await fs.stat(pth) + if (!stats.isDirectory()) { + // This error is never exposed to the user + // it is caught below, and the original error is thrown + throw new Error('The path is not a directory') + } + } catch { + throw error + } + } + } + + return make(path.resolve(input)) +} + +module.exports.makeDirSync = (input, options) => { + checkPath(input) + options = processOptions(options) + + if (useNativeRecursiveOption) { + const pth = path.resolve(input) + + return fs.mkdirSync(pth, { + mode: options.mode, + recursive: true + }) + } + + const make = pth => { + try { + fs.mkdirSync(pth, options.mode) + } catch (error) { + if (error.code === 'EPERM') { + throw error + } + + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth) + } + + if (error.message.includes('null bytes')) { + throw error + } + + make(path.dirname(pth)) + return make(pth) + } + + try { + if (!fs.statSync(pth).isDirectory()) { + // This error is never exposed to the user + // it is caught below, and the original error is thrown + throw new Error('The path is not a directory') + } + } catch { + throw error + } + } + } + + return make(path.resolve(input)) +} diff --git a/lib/mkdirs/mkdirs-sync.js b/lib/mkdirs/mkdirs-sync.js deleted file mode 100644 index decba61a..00000000 --- a/lib/mkdirs/mkdirs-sync.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const path = require('path') -const invalidWin32Path = require('./win32').invalidWin32Path - -function mkdirsSync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts } - } - - let mode = opts.mode - const xfs = opts.fs || fs - - if (process.platform === 'win32' && invalidWin32Path(p)) { - const errInval = new Error(p + ' contains invalid WIN32 path characters.') - errInval.code = 'EINVAL' - throw errInval - } - - if (mode === undefined) { - mode = 0o777 & (~process.umask()) - } - if (!made) made = null - - p = path.resolve(p) - - try { - xfs.mkdirSync(p, mode) - made = made || p - } catch (err) { - if (err.code === 'ENOENT') { - if (path.dirname(p) === p) throw err - made = mkdirsSync(path.dirname(p), opts, made) - mkdirsSync(p, opts, made) - } else { - // In the case of any other error, just see if there's a dir there - // already. If so, then hooray! If not, then something is borked. - let stat - try { - stat = xfs.statSync(p) - } catch { - throw err - } - if (!stat.isDirectory()) throw err - } - } - - return made -} - -module.exports = mkdirsSync diff --git a/lib/mkdirs/mkdirs.js b/lib/mkdirs/mkdirs.js deleted file mode 100644 index 9c72dc91..00000000 --- a/lib/mkdirs/mkdirs.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const path = require('path') -const invalidWin32Path = require('./win32').invalidWin32Path - -function mkdirs (p, opts, callback, made) { - if (typeof opts === 'function') { - callback = opts - opts = {} - } else if (!opts || typeof opts !== 'object') { - opts = { mode: opts } - } - - if (process.platform === 'win32' && invalidWin32Path(p)) { - const errInval = new Error(p + ' contains invalid WIN32 path characters.') - errInval.code = 'EINVAL' - return callback(errInval) - } - - let mode = opts.mode - const xfs = opts.fs || fs - - if (mode === undefined) { - mode = 0o777 & (~process.umask()) - } - if (!made) made = null - - callback = callback || function () {} - p = path.resolve(p) - - xfs.mkdir(p, mode, er => { - if (!er) { - made = made || p - return callback(null, made) - } - switch (er.code) { - case 'ENOENT': - if (path.dirname(p) === p) return callback(er) - mkdirs(path.dirname(p), opts, (er, made) => { - if (er) callback(er, made) - else mkdirs(p, opts, callback, made) - }) - break - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, (er2, stat) => { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) callback(er, made) - else callback(null, made) - }) - break - } - }) -} - -module.exports = mkdirs diff --git a/lib/mkdirs/win32.js b/lib/mkdirs/win32.js deleted file mode 100644 index 99b3920f..00000000 --- a/lib/mkdirs/win32.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict' - -const path = require('path') - -// get drive on windows -function getRootPath (p) { - p = path.normalize(path.resolve(p)).split(path.sep) - if (p.length > 0) return p[0] - return null -} - -// http://stackoverflow.com/a/62888/10333 contains more accurate -// TODO: expand to include the rest -const INVALID_PATH_CHARS = /[<>:"|?*]/ - -function invalidWin32Path (p) { - const rp = getRootPath(p) - p = p.replace(rp, '') - return INVALID_PATH_CHARS.test(p) -} - -module.exports = { - getRootPath, - invalidWin32Path -}