Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

shutil.py 25KB

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