Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create an optimistic mkdirp #9

Merged
merged 6 commits into from
May 22, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 5 additions & 18 deletions packages/io/__tests__/io.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {promises as fs} from 'fs'
import * as os from 'os'
import * as path from 'path'
import * as io from '../src/io'
import * as ioUtil from '../src/io-util'

describe('cp', () => {
it('copies file with no flags', async () => {
Expand Down Expand Up @@ -688,18 +689,6 @@ describe('mkdirP', () => {
expect(worked).toBe(false)
})

it('fails if mkdirP with empty path', async () => {
jclem marked this conversation as resolved.
Show resolved Hide resolved
let worked: boolean
try {
await io.mkdirP('')
worked = true
} catch (err) {
worked = false
}

expect(worked).toBe(false)
})

it('fails if mkdirP with conflicting file path', async () => {
const testPath = path.join(getTestTemp(), 'mkdirP_conflicting_file_path')
await io.mkdirP(getTestTemp())
Expand Down Expand Up @@ -807,14 +796,12 @@ describe('mkdirP', () => {
'9',
'10'
)
process.env['TEST_MKDIRP_FAILSAFE'] = '10'

expect.assertions(1)

try {
await io.mkdirP(testPath)
throw new Error('directory should not have been created')
await ioUtil.mkdirP(testPath, 10)
} catch (err) {
delete process.env['TEST_MKDIRP_FAILSAFE']

// ENOENT is expected, all other errors are not
expect(err.code).toBe('ENOENT')
}
})
Expand Down
43 changes: 43 additions & 0 deletions packages/io/src/io-util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,49 @@ export function isRooted(p: string): boolean {
return p.startsWith('/')
}

/**
* Recursively create a directory at `fsPath`.
*
* This implementation is optimistic, meaning it attempts to create the full
* path first, and backs up the path stack from there.
*
* @param fsPath The path to create
* @param maxDepth The maximum recursion depth
* @param depth The current recursion depth
*/
export async function mkdirP(
fsPath: string,
maxDepth: number = 1000,
depth: number = 1
): Promise<void> {
fsPath = path.resolve(fsPath)

if (depth >= maxDepth) return mkdir(fsPath)

try {
await mkdir(fsPath)
} catch (err) {
switch (err.code) {
case 'ENOENT': {
await mkdirP(path.dirname(fsPath), maxDepth, depth + 1)
await mkdirP(fsPath, maxDepth, depth + 1)
jclem marked this conversation as resolved.
Show resolved Hide resolved
break
}
default: {
let stats: fs.Stats

try {
stats = await stat(fsPath)
} catch (err2) {
throw err
}

if (!stats.isDirectory()) throw err
}
}
}
}

/**
* Best effort attempt to determine whether a file exists and is executable.
* @param filePath file path to check
Expand Down
60 changes: 1 addition & 59 deletions packages/io/src/io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,65 +102,7 @@ export async function rmRF(inputPath: string): Promise<void> {
* @returns Promise<void>
*/
export async function mkdirP(fsPath: string): Promise<void> {
if (!fsPath) {
throw new Error('Parameter p is required')
}

// build a stack of directories to create
const stack: string[] = []
let testDir: string = fsPath

// eslint-disable-next-line no-constant-condition
while (true) {
// validate the loop is not out of control
if (stack.length >= (process.env['TEST_MKDIRP_FAILSAFE'] || 1000)) {
// let the framework throw
await ioUtil.mkdir(fsPath)
return
}

let stats: fs.Stats
try {
stats = await ioUtil.stat(testDir)
} catch (err) {
if (err.code === 'ENOENT') {
// validate the directory is not the drive root
const parentDir = path.dirname(testDir)
if (testDir === parentDir) {
throw new Error(
`Unable to create directory '${fsPath}'. Root directory does not exist: '${testDir}'`
)
}

// push the dir and test the parent
stack.push(testDir)
testDir = parentDir
continue
} else if (err.code === 'UNKNOWN') {
throw new Error(
`Unable to create directory '${fsPath}'. Unable to verify the directory exists: '${testDir}'. If directory is a file share, please verify the share name is correct, the share is online, and the current process has permission to access the share.`
)
} else {
throw err
}
}

if (!stats.isDirectory()) {
throw new Error(
`Unable to create directory '${fsPath}'. Conflicting file exists: '${testDir}'`
)
}

// testDir exists
break
}

// create each directory
let dir = stack.pop()
while (dir != null) {
await ioUtil.mkdir(dir)
dir = stack.pop()
}
await ioUtil.mkdirP(fsPath)
}

/**
Expand Down