Path.swift icon indicating copy to clipboard operation
Path.swift copied to clipboard

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

Open roydbt opened this issue 10 months ago • 0 comments

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?

roydbt avatar Apr 05 '24 12:04 roydbt