Debian Codegraph @

cpython27/Lib/shutil.py

raw symbols SCIP
1 """Utility functions for copying and archiving files and directory trees.
2
3 XXX The functions here don't copy the resource fork or other metadata on Mac.
4
5 """
6
7 import os
8 import sys
9 import stat
10 from os.path import abspath
11 import fnmatch
12 import collections
13 import errno
14
15 try:
16 import zlib
17 del zlib
18 _ZLIB_SUPPORTED = True
19 except ImportError:
20 _ZLIB_SUPPORTED = False
21
22 try:
23 import bz2
24 del bz2
25 _BZ2_SUPPORTED = True
26 except ImportError:
27 _BZ2_SUPPORTED = False
28
29 try:
30 from pwd import getpwnam
31 except ImportError:
32 getpwnam = None
33
34 try:
35 from grp import getgrnam
36 except ImportError:
37 getgrnam = None
38
39 __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
40 "copytree", "move", "rmtree", "Error", "SpecialFileError",
41 "ExecError", "make_archive", "get_archive_formats",
42 "register_archive_format", "unregister_archive_format",
43 "ignore_patterns"]
44
45 class Error(EnvironmentError):
46 pass
47
48 class SpecialFileError(EnvironmentError):
49 """Raised when trying to do a kind of operation (e.g. copying) which is
50 not supported on a special file (e.g. a named pipe)"""
51
52 class ExecError(EnvironmentError):
53 """Raised when a command could not be executed"""
54
55 try:
56 WindowsError
57 except NameError:
58 WindowsError = None
59
60 def copyfileobj(fsrc, fdst, length=16*1024):
61 """copy data from file-like object fsrc to file-like object fdst"""
62 while 1:
63 buf = fsrc.read(length)
64 if not buf:
65 break
66 fdst.write(buf)
67
68 def _samefile(src, dst):
69 # Macintosh, Unix.
70 if hasattr(os.path, 'samefile'):
71 try:
72 return os.path.samefile(src, dst)
73 except OSError:
74 return False
75
76 # All other platforms: check for same pathname.
77 return (os.path.normcase(os.path.abspath(src)) ==
78 os.path.normcase(os.path.abspath(dst)))
79
80 def copyfile(src, dst):
81 """Copy data from src to dst"""
82 if _samefile(src, dst):
83 raise Error("`%s` and `%s` are the same file" % (src, dst))
84
85 for fn in [src, dst]:
86 try:
87 st = os.stat(fn)
88 except OSError:
89 # File most likely does not exist
90 pass
91 else:
92 # XXX What about other special files? (sockets, devices...)
93 if stat.S_ISFIFO(st.st_mode):
94 raise SpecialFileError("`%s` is a named pipe" % fn)
95
96 with open(src, 'rb') as fsrc:
97 with open(dst, 'wb') as fdst:
98 copyfileobj(fsrc, fdst)
99
100 def copymode(src, dst):
101 """Copy mode bits from src to dst"""
102 if hasattr(os, 'chmod'):
103 st = os.stat(src)
104 mode = stat.S_IMODE(st.st_mode)
105 os.chmod(dst, mode)
106
107 def copystat(src, dst):
108 """Copy file metadata
109
110 Copy the permission bits, last access time, last modification time, and
111 flags from `src` to `dst`. On Linux, copystat() also copies the "extended
112 attributes" where possible. The file contents, owner, and group are
113 unaffected. `src` and `dst` are path names given as strings.
114 """
115 st = os.stat(src)
116 mode = stat.S_IMODE(st.st_mode)
117 if hasattr(os, 'utime'):
118 os.utime(dst, (st.st_atime, st.st_mtime))
119 if hasattr(os, 'chmod'):
120 os.chmod(dst, mode)
121 if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
122 try:
123 os.chflags(dst, st.st_flags)
124 except OSError, why:
125 for err in 'EOPNOTSUPP', 'ENOTSUP':
126 if hasattr(errno, err) and why.errno == getattr(errno, err):
127 break
128 else:
129 raise
130
131 def copy(src, dst):
132 """Copy data and mode bits ("cp src dst").
133
134 The destination may be a directory.
135
136 """
137 if os.path.isdir(dst):
138 dst = os.path.join(dst, os.path.basename(src))
139 copyfile(src, dst)
140 copymode(src, dst)
141
142 def copy2(src, dst):
143 """Copy data and metadata. Return the file's destination.
144
145 Metadata is copied with copystat(). Please see the copystat function
146 for more information.
147
148 The destination may be a directory.
149
150 """
151 if os.path.isdir(dst):
152 dst = os.path.join(dst, os.path.basename(src))
153 copyfile(src, dst)
154 copystat(src, dst)
155
156 def ignore_patterns(*patterns):
157 """Function that can be used as copytree() ignore parameter.
158
159 Patterns is a sequence of glob-style patterns
160 that are used to exclude files"""
161 def _ignore_patterns(path, names):
162 ignored_names = []
163 for pattern in patterns:
164 ignored_names.extend(fnmatch.filter(names, pattern))
165 return set(ignored_names)
166 return _ignore_patterns
167
168 def copytree(src, dst, symlinks=False, ignore=None):
169 """Recursively copy a directory tree using copy2().
170
171 The destination directory must not already exist.
172 If exception(s) occur, an Error is raised with a list of reasons.
173
174 If the optional symlinks flag is true, symbolic links in the
175 source tree result in symbolic links in the destination tree; if
176 it is false, the contents of the files pointed to by symbolic
177 links are copied.
178
179 The optional ignore argument is a callable. If given, it
180 is called with the `src` parameter, which is the directory
181 being visited by copytree(), and `names` which is the list of
182 `src` contents, as returned by os.listdir():
183
184 callable(src, names) -> ignored_names
185
186 Since copytree() is called recursively, the callable will be
187 called once for each directory that is copied. It returns a
188 list of names relative to the `src` directory that should
189 not be copied.
190
191 XXX Consider this example code rather than the ultimate tool.
192
193 """
194 names = os.listdir(src)
195 if ignore is not None:
196 ignored_names = ignore(src, names)
197 else:
198 ignored_names = set()
199
200 os.makedirs(dst)
201 errors = []
202 for name in names:
203 if name in ignored_names:
204 continue
205 srcname = os.path.join(src, name)
206 dstname = os.path.join(dst, name)
207 try:
208 if symlinks and os.path.islink(srcname):
209 linkto = os.readlink(srcname)
210 os.symlink(linkto, dstname)
211 elif os.path.isdir(srcname):
212 copytree(srcname, dstname, symlinks, ignore)
213 else:
214 # Will raise a SpecialFileError for unsupported file types
215 copy2(srcname, dstname)
216 # catch the Error from the recursive copytree so that we can
217 # continue with other files
218 except Error, err:
219 errors.extend(err.args[0])
220 except EnvironmentError, why:
221 errors.append((srcname, dstname, str(why)))
222 try:
223 copystat(src, dst)
224 except OSError, why:
225 if WindowsError is not None and isinstance(why, WindowsError):
226 # Copying file access times may fail on Windows
227 pass
228 else:
229 errors.append((src, dst, str(why)))
230 if errors:
231 raise Error, errors
232
233 def rmtree(path, ignore_errors=False, onerror=None):
234 """Recursively delete a directory tree.
235
236 If ignore_errors is set, errors are ignored; otherwise, if onerror
237 is set, it is called to handle the error with arguments (func,
238 path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
239 path is the argument to that function that caused it to fail; and
240 exc_info is a tuple returned by sys.exc_info(). If ignore_errors
241 is false and onerror is None, an exception is raised.
242
243 """
244 if ignore_errors:
245 def onerror(*args):
246 pass
247 elif onerror is None:
248 def onerror(*args):
249 raise
250 try:
251 if os.path.islink(path):
252 # symlinks to directories are forbidden, see bug #1669
253 raise OSError("Cannot call rmtree on a symbolic link")
254 except OSError:
255 onerror(os.path.islink, path, sys.exc_info())
256 # can't continue even if onerror hook returns
257 return
258 names = []
259 try:
260 names = os.listdir(path)
261 except os.error, err:
262 onerror(os.listdir, path, sys.exc_info())
263 for name in names:
264 fullname = os.path.join(path, name)
265 try:
266 mode = os.lstat(fullname).st_mode
267 except os.error:
268 mode = 0
269 if stat.S_ISDIR(mode):
270 rmtree(fullname, ignore_errors, onerror)
271 else:
272 try:
273 os.remove(fullname)
274 except os.error, err:
275 onerror(os.remove, fullname, sys.exc_info())
276 try:
277 os.rmdir(path)
278 except os.error:
279 onerror(os.rmdir, path, sys.exc_info())
280
281
282 def _basename(path):
283 # A basename() variant which first strips the trailing slash, if present.
284 # Thus we always get the last component of the path, even for directories.
285 sep = os.path.sep + (os.path.altsep or '')
286 return os.path.basename(path.rstrip(sep))
287
288 def move(src, dst):
289 """Recursively move a file or directory to another location. This is
290 similar to the Unix "mv" command.
291
292 If the destination is a directory or a symlink to a directory, the source
293 is moved inside the directory. The destination path must not already
294 exist.
295
296 If the destination already exists but is not a directory, it may be
297 overwritten depending on os.rename() semantics.
298
299 If the destination is on our current filesystem, then rename() is used.
300 Otherwise, src is copied to the destination and then removed.
301 A lot more could be done here... A look at a mv.c shows a lot of
302 the issues this implementation glosses over.
303
304 """
305 real_dst = dst
306 if os.path.isdir(dst):
307 if _samefile(src, dst):
308 # We might be on a case insensitive filesystem,
309 # perform the rename anyway.
310 os.rename(src, dst)
311 return
312
313 real_dst = os.path.join(dst, _basename(src))
314 if os.path.exists(real_dst):
315 raise Error, "Destination path '%s' already exists" % real_dst
316 try:
317 os.rename(src, real_dst)
318 except OSError:
319 if os.path.isdir(src):
320 if _destinsrc(src, dst):
321 raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
322 copytree(src, real_dst, symlinks=True)
323 rmtree(src)
324 else:
325 copy2(src, real_dst)
326 os.unlink(src)
327
328 def _destinsrc(src, dst):
329 src = abspath(src)
330 dst = abspath(dst)
331 if not src.endswith(os.path.sep):
332 src += os.path.sep
333 if not dst.endswith(os.path.sep):
334 dst += os.path.sep
335 return dst.startswith(src)
336
337 def _get_gid(name):
338 """Returns a gid, given a group name."""
339 if getgrnam is None or name is None:
340 return None
341 try:
342 result = getgrnam(name)
343 except KeyError:
344 result = None
345 if result is not None:
346 return result[2]
347 return None
348
349 def _get_uid(name):
350 """Returns an uid, given a user name."""
351 if getpwnam is None or name is None:
352 return None
353 try:
354 result = getpwnam(name)
355 except KeyError:
356 result = None
357 if result is not None:
358 return result[2]
359 return None
360
361 def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
362 owner=None, group=None, logger=None):
363 """Create a (possibly compressed) tar file from all the files under
364 'base_dir'.
365
366 'compress' must be "gzip" (the default), "bzip2", or None.
367
368 'owner' and 'group' can be used to define an owner and a group for the
369 archive that is being built. If not provided, the current owner and group
370 will be used.
371
372 The output tar file will be named 'base_name' + ".tar", possibly plus
373 the appropriate compression extension (".gz", or ".bz2").
374
375 Returns the output filename.
376 """
377 if compress is None:
378 tar_compression = ''
379 elif _ZLIB_SUPPORTED and compress == 'gzip':
380 tar_compression = 'gz'
381 elif _BZ2_SUPPORTED and compress == 'bzip2':
382 tar_compression = 'bz2'
383 else:
384 raise ValueError("bad value for 'compress', or compression format not "
385 "supported : {0}".format(compress))
386
387 compress_ext = '.' + tar_compression if compress else ''
388 archive_name = base_name + '.tar' + compress_ext
389 archive_dir = os.path.dirname(archive_name)
390
391 if archive_dir and not os.path.exists(archive_dir):
392 if logger is not None:
393 logger.info("creating %s", archive_dir)
394 if not dry_run:
395 os.makedirs(archive_dir)
396
397
398 # creating the tarball
399 import tarfile # late import so Python build itself doesn't break
400
401 if logger is not None:
402 logger.info('Creating tar archive')
403
404 uid = _get_uid(owner)
405 gid = _get_gid(group)
406
407 def _set_uid_gid(tarinfo):
408 if gid is not None:
409 tarinfo.gid = gid
410 tarinfo.gname = group
411 if uid is not None:
412 tarinfo.uid = uid
413 tarinfo.uname = owner
414 return tarinfo
415
416 if not dry_run:
417 tar = tarfile.open(archive_name, 'w|%s' % tar_compression)
418 try:
419 tar.add(base_dir, filter=_set_uid_gid)
420 finally:
421 tar.close()
422
423 return archive_name
424
425 def _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger):
426 # XXX see if we want to keep an external call here
427 if verbose:
428 zipoptions = "-r"
429 else:
430 zipoptions = "-rq"
431 cmd = ["zip", zipoptions, zip_filename, base_dir]
432 if logger is not None:
433 logger.info(' '.join(cmd))
434 if dry_run:
435 return
436 import subprocess
437 try:
438 subprocess.check_call(cmd)
439 except subprocess.CalledProcessError:
440 # XXX really should distinguish between "couldn't find
441 # external 'zip' command" and "zip failed".
442 raise ExecError, \
443 ("unable to create zip file '%s': "
444 "could neither import the 'zipfile' module nor "
445 "find a standalone zip utility") % zip_filename
446
447 def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
448 """Create a zip file from all the files under 'base_dir'.
449
450 The output zip file will be named 'base_name' + ".zip". Uses either the
451 "zipfile" Python module (if available) or the InfoZIP "zip" utility
452 (if installed and found on the default search path). If neither tool is
453 available, raises ExecError. Returns the name of the output zip
454 file.
455 """
456 zip_filename = base_name + ".zip"
457 archive_dir = os.path.dirname(base_name)
458
459 if archive_dir and not os.path.exists(archive_dir):
460 if logger is not None:
461 logger.info("creating %s", archive_dir)
462 if not dry_run:
463 os.makedirs(archive_dir)
464
465 # If zipfile module is not available, try spawning an external 'zip'
466 # command.
467 try:
468 import zlib
469 import zipfile
470 except ImportError:
471 zipfile = None
472
473 if zipfile is None:
474 _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger)
475 else:
476 if logger is not None:
477 logger.info("creating '%s' and adding '%s' to it",
478 zip_filename, base_dir)
479
480 if not dry_run:
481 with zipfile.ZipFile(zip_filename, "w",
482 compression=zipfile.ZIP_DEFLATED) as zf:
483 path = os.path.normpath(base_dir)
484 if path != os.curdir:
485 zf.write(path, path)
486 if logger is not None:
487 logger.info("adding '%s'", path)
488 for dirpath, dirnames, filenames in os.walk(base_dir):
489 for name in sorted(dirnames):
490 path = os.path.normpath(os.path.join(dirpath, name))
491 zf.write(path, path)
492 if logger is not None:
493 logger.info("adding '%s'", path)
494 for name in filenames:
495 path = os.path.normpath(os.path.join(dirpath, name))
496 if os.path.isfile(path):
497 zf.write(path, path)
498 if logger is not None:
499 logger.info("adding '%s'", path)
500
501 return zip_filename
502
503 _ARCHIVE_FORMATS = {
504 'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"),
505 'zip': (_make_zipfile, [], "ZIP file")
506 }
507
508 if _ZLIB_SUPPORTED:
509 _ARCHIVE_FORMATS['gztar'] = (_make_tarball, [('compress', 'gzip')],
510 "gzip'ed tar-file")
511
512 if _BZ2_SUPPORTED:
513 _ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')],
514 "bzip2'ed tar-file")
515
516 def get_archive_formats():
517 """Returns a list of supported formats for archiving and unarchiving.
518
519 Each element of the returned sequence is a tuple (name, description)
520 """
521 formats = [(name, registry[2]) for name, registry in
522 _ARCHIVE_FORMATS.items()]
523 formats.sort()
524 return formats
525
526 def register_archive_format(name, function, extra_args=None, description=''):
527 """Registers an archive format.
528
529 name is the name of the format. function is the callable that will be
530 used to create archives. If provided, extra_args is a sequence of
531 (name, value) tuples that will be passed as arguments to the callable.
532 description can be provided to describe the format, and will be returned
533 by the get_archive_formats() function.
534 """
535 if extra_args is None:
536 extra_args = []
537 if not isinstance(function, collections.Callable):
538 raise TypeError('The %s object is not callable' % function)
539 if not isinstance(extra_args, (tuple, list)):
540 raise TypeError('extra_args needs to be a sequence')
541 for element in extra_args:
542 if not isinstance(element, (tuple, list)) or len(element) !=2 :
543 raise TypeError('extra_args elements are : (arg_name, value)')
544
545 _ARCHIVE_FORMATS[name] = (function, extra_args, description)
546
547 def unregister_archive_format(name):
548 del _ARCHIVE_FORMATS[name]
549
550 def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
551 dry_run=0, owner=None, group=None, logger=None):
552 """Create an archive file (eg. zip or tar).
553
554 'base_name' is the name of the file to create, minus any format-specific
555 extension; 'format' is the archive format: one of "zip", "tar", "gztar",
556 or "bztar". Or any other registered format.
557
558 'root_dir' is a directory that will be the root directory of the
559 archive; ie. we typically chdir into 'root_dir' before creating the
560 archive. 'base_dir' is the directory where we start archiving from;
561 ie. 'base_dir' will be the common prefix of all files and
562 directories in the archive. 'root_dir' and 'base_dir' both default
563 to the current directory. Returns the name of the archive file.
564
565 'owner' and 'group' are used when creating a tar archive. By default,
566 uses the current owner and group.
567 """
568 save_cwd = os.getcwd()
569 if root_dir is not None:
570 if logger is not None:
571 logger.debug("changing into '%s'", root_dir)
572 base_name = os.path.abspath(base_name)
573 if not dry_run:
574 os.chdir(root_dir)
575
576 if base_dir is None:
577 base_dir = os.curdir
578
579 kwargs = {'dry_run': dry_run, 'logger': logger}
580
581 try:
582 format_info = _ARCHIVE_FORMATS[format]
583 except KeyError:
584 raise ValueError, "unknown archive format '%s'" % format
585
586 func = format_info[0]
587 for arg, val in format_info[1]:
588 kwargs[arg] = val
589
590 if format != 'zip':
591 kwargs['owner'] = owner
592 kwargs['group'] = group
593
594 try:
595 filename = func(base_name, base_dir, **kwargs)
596 finally:
597 if root_dir is not None:
598 if logger is not None:
599 logger.debug("changing back to '%s'", save_cwd)
600 os.chdir(save_cwd)
601
602 return filename