Task

Create a directory and any missing parents.

This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.

Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return successfully.
Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).

It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.




import std.stdio;
 
void main() {
    makeDir("parent/test");
}
 
/// Manual implementation of what mkdirRecurse in std.file does.
void makeDir(string path) out {
    import std.exception : enforce;
    import std.file : exists;
    enforce(path.exists, "Failed to create the requested directory.");
} body {
    import std.array : array;
    import std.file;
    import std.path : pathSplitter, chainPath;
 
    auto workdir = "";
    foreach (dir; path.pathSplitter) {
        workdir = chainPath(workdir, dir).array;
        if (workdir.exists) {
            if (!workdir.isDir) {
                import std.conv : text;
                throw new FileException(text("The file ", workdir, " in the path ", path, " is not a directory."));
            }
        } else {
            workdir.mkdir();
        }
    }
}