Create a directory and any missing ancestor directories. If the directory already exists (or if 'name' is the empty string, which means the current directory, which of course exists), then do nothing. Raise DistutilsFileError if unable to create some directory along the way (eg
(name, mode=0o777, verbose=1, dry_run=0)
| 15 | # b) it blows up if the directory already exists (I want to silently |
| 16 | # succeed in that case). |
| 17 | def mkpath(name, mode=0o777, verbose=1, dry_run=0): |
| 18 | """Create a directory and any missing ancestor directories. |
| 19 | |
| 20 | If the directory already exists (or if 'name' is the empty string, which |
| 21 | means the current directory, which of course exists), then do nothing. |
| 22 | Raise DistutilsFileError if unable to create some directory along the way |
| 23 | (eg. some sub-path exists, but is a file rather than a directory). |
| 24 | If 'verbose' is true, print a one-line summary of each mkdir to stdout. |
| 25 | Return the list of directories actually created. |
| 26 | """ |
| 27 | |
| 28 | global _path_created |
| 29 | |
| 30 | # Detect a common bug -- name is None |
| 31 | if not isinstance(name, str): |
| 32 | raise DistutilsInternalError( |
| 33 | "mkpath: 'name' must be a string (got %r)" % (name,)) |
| 34 | |
| 35 | # XXX what's the better way to handle verbosity? print as we create |
| 36 | # each directory in the path (the current behaviour), or only announce |
| 37 | # the creation of the whole path? (quite easy to do the latter since |
| 38 | # we're not using a recursive algorithm) |
| 39 | |
| 40 | name = os.path.normpath(name) |
| 41 | created_dirs = [] |
| 42 | if os.path.isdir(name) or name == '': |
| 43 | return created_dirs |
| 44 | if _path_created.get(os.path.abspath(name)): |
| 45 | return created_dirs |
| 46 | |
| 47 | (head, tail) = os.path.split(name) |
| 48 | tails = [tail] # stack of lone dirs to create |
| 49 | |
| 50 | while head and tail and not os.path.isdir(head): |
| 51 | (head, tail) = os.path.split(head) |
| 52 | tails.insert(0, tail) # push next higher dir onto stack |
| 53 | |
| 54 | # now 'head' contains the deepest directory that already exists |
| 55 | # (that is, the child of 'head' in 'name' is the highest directory |
| 56 | # that does *not* exist) |
| 57 | for d in tails: |
| 58 | #print "head = %s, d = %s: " % (head, d), |
| 59 | head = os.path.join(head, d) |
| 60 | abs_head = os.path.abspath(head) |
| 61 | |
| 62 | if _path_created.get(abs_head): |
| 63 | continue |
| 64 | |
| 65 | if verbose >= 1: |
| 66 | log.info("creating %s", head) |
| 67 | |
| 68 | if not dry_run: |
| 69 | try: |
| 70 | os.mkdir(head, mode) |
| 71 | except OSError as exc: |
| 72 | if not (exc.errno == errno.EEXIST and os.path.isdir(head)): |
| 73 | raise DistutilsFileError( |
| 74 | "could not create '%s': %s" % (head, exc.args[-1])) |