From 1dfee83aea507ad588a7a31bae2529aba2b8371f Mon Sep 17 00:00:00 2001 From: Ryan Zimmerman Date: Mon, 3 Feb 2020 09:34:52 -0500 Subject: [PATCH 1/7] BREAKING: Use internal fork of make-dir for mkdirs implementation Resolves #619 Everything should work similarly to how it did before; except that we no longer return a file path on success (to match fs.mkdir). Also, errors may be different. --- lib/mkdirs/__tests__/opts-undef.test.js | 3 +- lib/mkdirs/__tests__/return.test.js | 41 ------- lib/mkdirs/__tests__/return_sync.test.js | 39 ------- lib/mkdirs/index.js | 18 +-- lib/mkdirs/make-dir.js | 137 +++++++++++++++++++++++ lib/mkdirs/mkdirs-sync.js | 52 --------- lib/mkdirs/mkdirs.js | 61 ---------- lib/mkdirs/win32.js | 25 ----- 8 files changed, 147 insertions(+), 229 deletions(-) delete mode 100644 lib/mkdirs/__tests__/return.test.js delete mode 100644 lib/mkdirs/__tests__/return_sync.test.js create mode 100644 lib/mkdirs/make-dir.js delete mode 100644 lib/mkdirs/mkdirs-sync.js delete mode 100644 lib/mkdirs/mkdirs.js delete mode 100644 lib/mkdirs/win32.js 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/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..3cf435ca --- /dev/null +++ b/lib/mkdirs/make-dir.js @@ -0,0 +1,137 @@ +// 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') + +// Check for Node v10.12.0+ +const nodeVersion = process.version.split('.') +const nodeVersionMajor = Number.parseInt(nodeVersion[0], 10) +const nodeVersionMinor = Number.parseInt(nodeVersion[1], 10) +const useNativeRecursiveOption = nodeVersionMajor >= 10 && nodeVersionMinor >= 12 + +// 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) + } + + const stats = await fs.stat(pth) + if (!stats.isDirectory()) { + 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()) { + 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 -} From d65f9f5d0ed45478b1ed0a05292b6b0146b1cbba Mon Sep 17 00:00:00 2001 From: Ryan Zimmerman Date: Thu, 6 Feb 2020 15:22:18 -0500 Subject: [PATCH 2/7] Hopefully fix Windows tests - Error codes are different - Match fs.mkdir behavior on Windows when creating root --- lib/mkdirs/__tests__/issue-93.test.js | 4 ++-- lib/mkdirs/__tests__/root.test.js | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/mkdirs/__tests__/issue-93.test.js b/lib/mkdirs/__tests__/issue-93.test.js index 771694e6..c8b942e0 100644 --- a/lib/mkdirs/__tests__/issue-93.test.js +++ b/lib/mkdirs/__tests__/issue-93.test.js @@ -24,12 +24,12 @@ 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 fse.mkdirp(file, err => { - assert.strictEqual(err.code, 'ENOENT') + assert.strictEqual(err.code, 'EPERM') try { fse.mkdirsSync(file) } catch (err) { - assert.strictEqual(err.code, 'ENOENT') + assert.strictEqual(err.code, 'EPERM') } done() 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() }) From 51938c27273c4f47c4642e55a71a7b3d982a66ad Mon Sep 17 00:00:00 2001 From: Ryan Zimmerman Date: Fri, 14 Feb 2020 08:29:13 -0500 Subject: [PATCH 3/7] Port https://github.com/sindresorhus/make-dir/pull/24 --- lib/mkdirs/make-dir.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/mkdirs/make-dir.js b/lib/mkdirs/make-dir.js index 3cf435ca..39654b48 100644 --- a/lib/mkdirs/make-dir.js +++ b/lib/mkdirs/make-dir.js @@ -79,8 +79,12 @@ module.exports.makeDir = async (input, options) => { return make(pth) } - const stats = await fs.stat(pth) - if (!stats.isDirectory()) { + try { + const stats = await fs.stat(pth) + if (!stats.isDirectory()) { + throw new Error('The path is not a directory') + } + } catch { throw error } } From 53fbddf1d6876ca7a5f685436f38e1a486d7be0b Mon Sep 17 00:00:00 2001 From: Ryan Zimmerman Date: Fri, 14 Feb 2020 08:30:19 -0500 Subject: [PATCH 4/7] Add comment for clarity --- lib/mkdirs/make-dir.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/mkdirs/make-dir.js b/lib/mkdirs/make-dir.js index 39654b48..ecfcaf60 100644 --- a/lib/mkdirs/make-dir.js +++ b/lib/mkdirs/make-dir.js @@ -82,6 +82,8 @@ module.exports.makeDir = async (input, options) => { 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 { @@ -129,6 +131,8 @@ module.exports.makeDirSync = (input, options) => { 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 { From 29b55cb4c41ae59cbce7ad291559bba75ef47584 Mon Sep 17 00:00:00 2001 From: Ryan Zimmerman Date: Fri, 14 Feb 2020 08:31:57 -0500 Subject: [PATCH 5/7] Use at-least-node for version sniffing --- lib/mkdirs/make-dir.js | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/lib/mkdirs/make-dir.js b/lib/mkdirs/make-dir.js index ecfcaf60..f17ecffb 100644 --- a/lib/mkdirs/make-dir.js +++ b/lib/mkdirs/make-dir.js @@ -6,12 +6,9 @@ 'use strict' const fs = require('../fs') const path = require('path') +const atLeastNode = require('at-least-node') -// Check for Node v10.12.0+ -const nodeVersion = process.version.split('.') -const nodeVersionMajor = Number.parseInt(nodeVersion[0], 10) -const nodeVersionMinor = Number.parseInt(nodeVersion[1], 10) -const useNativeRecursiveOption = nodeVersionMajor >= 10 && nodeVersionMinor >= 12 +const useNativeRecursiveOption = atLeastNode('10.12.0') // https://github.com/nodejs/node/issues/8987 // https://github.com/libuv/libuv/pull/1088 From eac8cd9286784bb4546b1d3bf18220dd65160b0f Mon Sep 17 00:00:00 2001 From: Ryan Zimmerman Date: Fri, 14 Feb 2020 08:39:27 -0500 Subject: [PATCH 6/7] Consistent error codes across OSes --- lib/mkdirs/__tests__/clobber.test.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) 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() }) }) From b0d3a827445e59a41df6a916a3b55aa9fa8200b3 Mon Sep 17 00:00:00 2001 From: Ryan Zimmerman Date: Fri, 14 Feb 2020 09:03:25 -0500 Subject: [PATCH 7/7] Allow different error codes on different Node versions --- lib/mkdirs/__tests__/issue-93.test.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/mkdirs/__tests__/issue-93.test.js b/lib/mkdirs/__tests__/issue-93.test.js index c8b942e0..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, 'EPERM') + assertErr(err) try { fse.mkdirsSync(file) } catch (err) { - assert.strictEqual(err.code, 'EPERM') + assertErr(err) } done()