Make directory path

From Rosetta Code
Revision as of 19:57, 9 August 2014 by rosettacode>Dchapes (→‎{{header|Go}}: reimplementing std functions whose source is readily and trivially available doesn't seem useful .. it could be pasted here but it could become out of sync)
Make directory path is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

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.


Go

The standard packages include os.MkdirAll which does exactly this (and its source is also available via that link). <lang go> os.MkdirAll("/tmp/some/path/to/dir", 0770)</lang>

Perl 6

There is a builtin function with the same name and it creates subdirectories by default.

<lang perl6>mkdir 'path/to/dir'</lang>

Python

<lang Python> from errno import EEXIST from os import mkdir, curdir from os.path import split, exists

def mkdirp(path, mode=0777):

   head, tail = split(path)
   if not tail:
       head, tail = split(head)
   if head and tail and not exists(head):
       try:
           mkdirp(head, mode)
       except OSError as e:
           # be happy if someone already created the path
           if e.errno != EEXIST:
               raise
       if tail == curdir:  # xxx/newdir/. exists if xxx/newdir exists
           return
   try:
       mkdir(path, mode)
   except OSError as e:
       # be happy if someone already created the path
       if e.errno != EEXIST:
           raise

</lang>

Above is a modified version of the standard library's os.makedirs, for pedagogical purposes. In practice, you would be more likely to use the standard library call:

<lang Python> def mkdirp(path):

   try:
       os.makedirs(path)
   except OSError as exc: # Python >2.5
       if exc.errno == errno.EEXIST and os.path.isdir(path):
           pass
       else: raise

</lang>

In Python3 this becomes even simpler:

<lang Python> def mkdirp(path):

   os.makedirs(path, exist_ok=True)

</lang>


JavaScript

Works with: Node.js

Simplified version of the popular mkdirp library:

<lang Javascript>var path = require('path'); var fs = require('fs');

function mkdirp (p, cb) {

   cb = cb || function () {};
   p = path.resolve(p);
   fs.mkdir(p, function (er) {
       if (!er) {
           return cb(null);
       }
       switch (er.code) {
           case 'ENOENT':
               // The directory doesn't exist. Make its parent and try again.
               mkdirp(path.dirname(p), function (er) {
                   if (er) cb(er);
                   else mkdirp(p, cb);
               });
               break;
               // In the case of any other error, something is borked.
           default:
               cb(er);
               break;
       }
   });

}</lang>

UNIX Shell

Works with: Bourne Again SHell

<lang bash>function mkdirp() { mkdir -p $1; }</lang>