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

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

Open
roydbt opened this issue Apr 5, 2024 · 0 comments
Open

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

roydbt opened this issue Apr 5, 2024 · 0 comments

Comments

@roydbt
Copy link

roydbt commented Apr 5, 2024

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant