PageRenderTime 70ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/shutil.py

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