From cc06967a37df6e2d86f774ae9ba06f7786506406 Mon Sep 17 00:00:00 2001 From: Ryan Zimmerman Date: Mon, 3 Feb 2020 09:34:52 -0500 Subject: [PATCH] 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..df4b350a --- /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) + + await 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) + + 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 -}