Skip to content

Is there a way to create a file and its directory if missing? #93

@roydbt

Description

@roydbt

Currently, path.touch() fails if path.parent, path.parent.parent, and so on doesn't exist.
Currently, my workaround is as such:

/// Get the missing parent directories of a path, shallow to deep.
/// - Parameter path: The path to get the missing parent directories of.
/// - Returns: An array of the missing parent directories.
func getMissingParentDirectories(of path: Path) -> [Path] {
    var missingParentDirectories: [Path] = []
    var currentPath = path.parent
    while !currentPath.exists {
        missingParentDirectories.append(currentPath)
        currentPath = currentPath.parent
    }
    return missingParentDirectories.reversed()
}

/// Create the missing parent directories of a path, shallow to deep.
/// - Parameter path: The path to create the missing parent directories of.
func createMissingParentDirectories(of path: Path) {
    let missingParentDirectories = getMissingParentDirectories(of: path)
    for missingParentDirectory in missingParentDirectories {
        do {
            try missingParentDirectory.mkdir()
        } catch {
            fatalError("Could not create the directory \(missingParentDirectory)")
        }
    }
}

Is there a native way to do this that I am missing?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions