Path: blob/main/test/lib/python3.9/site-packages/setuptools/_distutils/dir_util.py
4799 views
"""distutils.dir_util12Utility functions for manipulating directories and directory trees."""34import os5import errno6from distutils.errors import DistutilsFileError, DistutilsInternalError7from distutils import log89# cache for by mkpath() -- in addition to cheapening redundant calls,10# eliminates redundant "creating /foo/bar/baz" messages in dry-run mode11_path_created = {}1213# I don't use os.makedirs because a) it's new to Python 1.5.2, and14# b) it blows up if the directory already exists (I want to silently15# succeed in that case).16def mkpath(name, mode=0o777, verbose=1, dry_run=0):17"""Create a directory and any missing ancestor directories.1819If the directory already exists (or if 'name' is the empty string, which20means the current directory, which of course exists), then do nothing.21Raise DistutilsFileError if unable to create some directory along the way22(eg. some sub-path exists, but is a file rather than a directory).23If 'verbose' is true, print a one-line summary of each mkdir to stdout.24Return the list of directories actually created.25"""2627global _path_created2829# Detect a common bug -- name is None30if not isinstance(name, str):31raise DistutilsInternalError(32"mkpath: 'name' must be a string (got %r)" % (name,))3334# XXX what's the better way to handle verbosity? print as we create35# each directory in the path (the current behaviour), or only announce36# the creation of the whole path? (quite easy to do the latter since37# we're not using a recursive algorithm)3839name = os.path.normpath(name)40created_dirs = []41if os.path.isdir(name) or name == '':42return created_dirs43if _path_created.get(os.path.abspath(name)):44return created_dirs4546(head, tail) = os.path.split(name)47tails = [tail] # stack of lone dirs to create4849while head and tail and not os.path.isdir(head):50(head, tail) = os.path.split(head)51tails.insert(0, tail) # push next higher dir onto stack5253# now 'head' contains the deepest directory that already exists54# (that is, the child of 'head' in 'name' is the highest directory55# that does *not* exist)56for d in tails:57#print "head = %s, d = %s: " % (head, d),58head = os.path.join(head, d)59abs_head = os.path.abspath(head)6061if _path_created.get(abs_head):62continue6364if verbose >= 1:65log.info("creating %s", head)6667if not dry_run:68try:69os.mkdir(head, mode)70except OSError as exc:71if not (exc.errno == errno.EEXIST and os.path.isdir(head)):72raise DistutilsFileError(73"could not create '%s': %s" % (head, exc.args[-1]))74created_dirs.append(head)7576_path_created[abs_head] = 177return created_dirs7879def create_tree(base_dir, files, mode=0o777, verbose=1, dry_run=0):80"""Create all the empty directories under 'base_dir' needed to put 'files'81there.8283'base_dir' is just the name of a directory which doesn't necessarily84exist yet; 'files' is a list of filenames to be interpreted relative to85'base_dir'. 'base_dir' + the directory portion of every file in 'files'86will be created if it doesn't already exist. 'mode', 'verbose' and87'dry_run' flags are as for 'mkpath()'.88"""89# First get the list of directories to create90need_dir = set()91for file in files:92need_dir.add(os.path.join(base_dir, os.path.dirname(file)))9394# Now create them95for dir in sorted(need_dir):96mkpath(dir, mode, verbose=verbose, dry_run=dry_run)9798def copy_tree(src, dst, preserve_mode=1, preserve_times=1,99preserve_symlinks=0, update=0, verbose=1, dry_run=0):100"""Copy an entire directory tree 'src' to a new location 'dst'.101102Both 'src' and 'dst' must be directory names. If 'src' is not a103directory, raise DistutilsFileError. If 'dst' does not exist, it is104created with 'mkpath()'. The end result of the copy is that every105file in 'src' is copied to 'dst', and directories under 'src' are106recursively copied to 'dst'. Return the list of files that were107copied or might have been copied, using their output name. The108return value is unaffected by 'update' or 'dry_run': it is simply109the list of all files under 'src', with the names changed to be110under 'dst'.111112'preserve_mode' and 'preserve_times' are the same as for113'copy_file'; note that they only apply to regular files, not to114directories. If 'preserve_symlinks' is true, symlinks will be115copied as symlinks (on platforms that support them!); otherwise116(the default), the destination of the symlink will be copied.117'update' and 'verbose' are the same as for 'copy_file'.118"""119from distutils.file_util import copy_file120121if not dry_run and not os.path.isdir(src):122raise DistutilsFileError(123"cannot copy tree '%s': not a directory" % src)124try:125names = os.listdir(src)126except OSError as e:127if dry_run:128names = []129else:130raise DistutilsFileError(131"error listing files in '%s': %s" % (src, e.strerror))132133if not dry_run:134mkpath(dst, verbose=verbose)135136outputs = []137138for n in names:139src_name = os.path.join(src, n)140dst_name = os.path.join(dst, n)141142if n.startswith('.nfs'):143# skip NFS rename files144continue145146if preserve_symlinks and os.path.islink(src_name):147link_dest = os.readlink(src_name)148if verbose >= 1:149log.info("linking %s -> %s", dst_name, link_dest)150if not dry_run:151os.symlink(link_dest, dst_name)152outputs.append(dst_name)153154elif os.path.isdir(src_name):155outputs.extend(156copy_tree(src_name, dst_name, preserve_mode,157preserve_times, preserve_symlinks, update,158verbose=verbose, dry_run=dry_run))159else:160copy_file(src_name, dst_name, preserve_mode,161preserve_times, update, verbose=verbose,162dry_run=dry_run)163outputs.append(dst_name)164165return outputs166167def _build_cmdtuple(path, cmdtuples):168"""Helper for remove_tree()."""169for f in os.listdir(path):170real_f = os.path.join(path,f)171if os.path.isdir(real_f) and not os.path.islink(real_f):172_build_cmdtuple(real_f, cmdtuples)173else:174cmdtuples.append((os.remove, real_f))175cmdtuples.append((os.rmdir, path))176177def remove_tree(directory, verbose=1, dry_run=0):178"""Recursively remove an entire directory tree.179180Any errors are ignored (apart from being reported to stdout if 'verbose'181is true).182"""183global _path_created184185if verbose >= 1:186log.info("removing '%s' (and everything under it)", directory)187if dry_run:188return189cmdtuples = []190_build_cmdtuple(directory, cmdtuples)191for cmd in cmdtuples:192try:193cmd[0](cmd[1])194# remove dir from cache if it's already there195abspath = os.path.abspath(cmd[1])196if abspath in _path_created:197del _path_created[abspath]198except OSError as exc:199log.warn("error removing %s: %s", directory, exc)200201def ensure_relative(path):202"""Take the full path 'path', and make it a relative path.203204This is useful to make 'path' the second argument to os.path.join().205"""206drive, path = os.path.splitdrive(path)207if path[0:1] == os.sep:208path = drive + path[1:]209return path210211212