blob: c41046a380bd826756910bda92a1f0d14cc729b2 [file] [log] [blame]
Tarek Ziadéc3399782010-02-23 05:39:18 +00001"""Utility functions for copying and archiving files and directory trees.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +00002
Guido van Rossum959fa011999-08-18 20:03:17 +00003XXX The functions here don't copy the resource fork or other metadata on Mac.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +00004
5"""
Guido van Rossumc6360141990-10-13 19:23:40 +00006
Guido van Rossumc96207a1992-03-31 18:55:40 +00007import os
Guido van Rossum83c03e21999-02-23 23:07:51 +00008import sys
Guido van Rossum9d0a3df1997-04-29 14:45:19 +00009import stat
Brett Cannon1c3fa182004-06-19 21:11:35 +000010from os.path import abspath
Georg Brandl2ee470f2008-07-16 12:55:28 +000011import fnmatch
Tarek Ziadé396fad72010-02-23 05:30:31 +000012import collections
Antoine Pitrou910bd512010-03-22 20:11:09 +000013import errno
Tarek Ziadé6ac91722010-04-28 17:51:36 +000014import tarfile
Tarek Ziadé396fad72010-02-23 05:30:31 +000015
16try:
Tarek Ziadéffa155a2010-04-29 13:34:35 +000017 import bz2
Florent Xicluna54540ec2011-11-04 08:29:17 +010018 del bz2
Tarek Ziadéffa155a2010-04-29 13:34:35 +000019 _BZ2_SUPPORTED = True
20except ImportError:
21 _BZ2_SUPPORTED = False
22
23try:
Tarek Ziadé396fad72010-02-23 05:30:31 +000024 from pwd import getpwnam
25except ImportError:
26 getpwnam = None
27
28try:
29 from grp import getgrnam
30except ImportError:
31 getgrnam = None
Guido van Rossumc6360141990-10-13 19:23:40 +000032
Tarek Ziadéc3399782010-02-23 05:39:18 +000033__all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
34 "copytree", "move", "rmtree", "Error", "SpecialFileError",
35 "ExecError", "make_archive", "get_archive_formats",
Tarek Ziadé6ac91722010-04-28 17:51:36 +000036 "register_archive_format", "unregister_archive_format",
37 "get_unpack_formats", "register_unpack_format",
Éric Araujoc5efe652011-08-21 14:30:00 +020038 "unregister_unpack_format", "unpack_archive",
Brian Curtinc57a3452012-06-22 16:00:30 -050039 "ignore_patterns", "chown", "which"]
Éric Araujoe4d5b8e2011-08-08 16:51:11 +020040 # disk_usage is added later, if available on the platform
Martin v. Löwise9ce0b02002-10-07 13:23:24 +000041
Neal Norwitz4ce69a52005-09-01 00:45:28 +000042class Error(EnvironmentError):
Martin v. Löwise9ce0b02002-10-07 13:23:24 +000043 pass
Guido van Rossumc6360141990-10-13 19:23:40 +000044
Antoine Pitrou7fff0962009-05-01 21:09:44 +000045class SpecialFileError(EnvironmentError):
46 """Raised when trying to do a kind of operation (e.g. copying) which is
47 not supported on a special file (e.g. a named pipe)"""
48
Tarek Ziadé396fad72010-02-23 05:30:31 +000049class ExecError(EnvironmentError):
50 """Raised when a command could not be executed"""
51
Tarek Ziadé6ac91722010-04-28 17:51:36 +000052class ReadError(EnvironmentError):
53 """Raised when an archive cannot be read"""
54
55class RegistryError(Exception):
56 """Raised when a registery operation with the archiving
57 and unpacking registeries fails"""
58
59
Georg Brandl6aa2d1f2008-08-12 08:35:52 +000060try:
61 WindowsError
62except NameError:
63 WindowsError = None
64
Greg Stein42bb8b32000-07-12 09:55:30 +000065def copyfileobj(fsrc, fdst, length=16*1024):
66 """copy data from file-like object fsrc to file-like object fdst"""
67 while 1:
68 buf = fsrc.read(length)
69 if not buf:
70 break
71 fdst.write(buf)
72
Johannes Gijsbers46f14592004-08-14 13:30:02 +000073def _samefile(src, dst):
74 # Macintosh, Unix.
Tarek Ziadé1eab9cc2010-04-19 21:19:57 +000075 if hasattr(os.path, 'samefile'):
Johannes Gijsbersf9a098e2004-08-14 14:51:01 +000076 try:
77 return os.path.samefile(src, dst)
78 except OSError:
79 return False
Johannes Gijsbers46f14592004-08-14 13:30:02 +000080
81 # All other platforms: check for same pathname.
82 return (os.path.normcase(os.path.abspath(src)) ==
83 os.path.normcase(os.path.abspath(dst)))
Tim Peters495ad3c2001-01-15 01:36:40 +000084
Antoine Pitrou78091e62011-12-29 18:54:15 +010085def copyfile(src, dst, symlinks=False):
86 """Copy data from src to dst.
87
88 If optional flag `symlinks` is set and `src` is a symbolic link, a new
89 symlink will be created instead of copying the file it points to.
90
91 """
Johannes Gijsbers46f14592004-08-14 13:30:02 +000092 if _samefile(src, dst):
Collin Winterce36ad82007-08-30 01:19:48 +000093 raise Error("`%s` and `%s` are the same file" % (src, dst))
Johannes Gijsbers46f14592004-08-14 13:30:02 +000094
Antoine Pitrou7fff0962009-05-01 21:09:44 +000095 for fn in [src, dst]:
96 try:
97 st = os.stat(fn)
98 except OSError:
99 # File most likely does not exist
100 pass
Benjamin Petersonc0d98aa2009-06-05 19:13:27 +0000101 else:
102 # XXX What about other special files? (sockets, devices...)
103 if stat.S_ISFIFO(st.st_mode):
104 raise SpecialFileError("`%s` is a named pipe" % fn)
Tarek Ziadéb01142b2010-05-05 22:43:04 +0000105
Antoine Pitrou78091e62011-12-29 18:54:15 +0100106 if symlinks and os.path.islink(src):
107 os.symlink(os.readlink(src), dst)
108 else:
109 with open(src, 'rb') as fsrc:
110 with open(dst, 'wb') as fdst:
111 copyfileobj(fsrc, fdst)
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500112 return dst
Guido van Rossumc6360141990-10-13 19:23:40 +0000113
Antoine Pitrou78091e62011-12-29 18:54:15 +0100114def copymode(src, dst, symlinks=False):
115 """Copy mode bits from src to dst.
Guido van Rossumc6360141990-10-13 19:23:40 +0000116
Antoine Pitrou78091e62011-12-29 18:54:15 +0100117 If the optional flag `symlinks` is set, symlinks aren't followed if and
118 only if both `src` and `dst` are symlinks. If `lchmod` isn't available (eg.
119 Linux), in these cases, this method does nothing.
120
121 """
122 if symlinks and os.path.islink(src) and os.path.islink(dst):
123 if hasattr(os, 'lchmod'):
124 stat_func, chmod_func = os.lstat, os.lchmod
125 else:
126 return
127 elif hasattr(os, 'chmod'):
128 stat_func, chmod_func = os.stat, os.chmod
129 else:
130 return
131
132 st = stat_func(src)
133 chmod_func(dst, stat.S_IMODE(st.st_mode))
134
135def copystat(src, dst, symlinks=False):
136 """Copy all stat info (mode bits, atime, mtime, flags) from src to dst.
137
138 If the optional flag `symlinks` is set, symlinks aren't followed if and
139 only if both `src` and `dst` are symlinks.
140
141 """
Larry Hastings9cf065c2012-06-22 16:30:09 -0700142 def _nop(*args, ns=None, follow_symlinks=None):
Antoine Pitrou78091e62011-12-29 18:54:15 +0100143 pass
144
Larry Hastings9cf065c2012-06-22 16:30:09 -0700145 # follow symlinks (aka don't not follow symlinks)
146 follow = not (symlinks and os.path.islink(src) and os.path.islink(dst))
147 if follow:
148 # use the real function if it exists
149 def lookup(name):
150 return getattr(os, name, _nop)
Antoine Pitrou78091e62011-12-29 18:54:15 +0100151 else:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700152 # use the real function only if it exists
153 # *and* it supports follow_symlinks
154 def lookup(name):
155 fn = getattr(os, name, _nop)
156 if fn in os.supports_follow_symlinks:
157 return fn
158 return _nop
Antoine Pitrou78091e62011-12-29 18:54:15 +0100159
Larry Hastings9cf065c2012-06-22 16:30:09 -0700160 st = lookup("stat")(src, follow_symlinks=follow)
Walter Dörwald294bbf32002-06-06 09:48:13 +0000161 mode = stat.S_IMODE(st.st_mode)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700162 lookup("utime")(dst, ns=(st.st_atime_ns, st.st_mtime_ns),
163 follow_symlinks=follow)
164 try:
165 lookup("chmod")(dst, mode, follow_symlinks=follow)
166 except NotImplementedError:
167 # if we got a NotImplementedError, it's because
168 # * follow_symlinks=False,
169 # * lchown() is unavailable, and
170 # * either
171 # * fchownat() is unvailable or
172 # * fchownat() doesn't implement AT_SYMLINK_NOFOLLOW.
173 # (it returned ENOSUP.)
174 # therefore we're out of options--we simply cannot chown the
175 # symlink. give up, suppress the error.
176 # (which is what shutil always did in this circumstance.)
177 pass
Antoine Pitrou78091e62011-12-29 18:54:15 +0100178 if hasattr(st, 'st_flags'):
Antoine Pitrou910bd512010-03-22 20:11:09 +0000179 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700180 lookup("chflags")(dst, st.st_flags, follow_symlinks=follow)
Antoine Pitrou910bd512010-03-22 20:11:09 +0000181 except OSError as why:
Ned Deilybaf75712012-05-10 17:05:19 -0700182 for err in 'EOPNOTSUPP', 'ENOTSUP':
183 if hasattr(errno, err) and why.errno == getattr(errno, err):
184 break
185 else:
Antoine Pitrou910bd512010-03-22 20:11:09 +0000186 raise
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000187
Antoine Pitrou424246f2012-05-12 19:02:01 +0200188if hasattr(os, 'listxattr'):
189 def _copyxattr(src, dst, symlinks=False):
190 """Copy extended filesystem attributes from `src` to `dst`.
191
192 Overwrite existing attributes.
193
194 If the optional flag `symlinks` is set, symlinks won't be followed.
195
196 """
Antoine Pitrou424246f2012-05-12 19:02:01 +0200197
Larry Hastings9cf065c2012-06-22 16:30:09 -0700198 for name in os.listxattr(src, follow_symlinks=symlinks):
Antoine Pitrou424246f2012-05-12 19:02:01 +0200199 try:
Larry Hastings9cf065c2012-06-22 16:30:09 -0700200 value = os.getxattr(src, name, follow_symlinks=symlinks)
201 os.setxattr(dst, name, value, follow_symlinks=symlinks)
Antoine Pitrou424246f2012-05-12 19:02:01 +0200202 except OSError as e:
203 if e.errno not in (errno.EPERM, errno.ENOTSUP, errno.ENODATA):
204 raise
205else:
206 def _copyxattr(*args, **kwargs):
207 pass
208
Antoine Pitrou78091e62011-12-29 18:54:15 +0100209def copy(src, dst, symlinks=False):
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500210 """Copy data and mode bits ("cp src dst"). Return the file's destination.
Tim Peters495ad3c2001-01-15 01:36:40 +0000211
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000212 The destination may be a directory.
213
Antoine Pitrou78091e62011-12-29 18:54:15 +0100214 If the optional flag `symlinks` is set, symlinks won't be followed. This
215 resembles GNU's "cp -P src dst".
216
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000217 """
Guido van Rossuma2baf461997-04-29 14:06:46 +0000218 if os.path.isdir(dst):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000219 dst = os.path.join(dst, os.path.basename(src))
Antoine Pitrou78091e62011-12-29 18:54:15 +0100220 copyfile(src, dst, symlinks=symlinks)
221 copymode(src, dst, symlinks=symlinks)
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500222 return dst
Guido van Rossumc6360141990-10-13 19:23:40 +0000223
Antoine Pitrou78091e62011-12-29 18:54:15 +0100224def copy2(src, dst, symlinks=False):
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500225 """Copy data and all stat info ("cp -p src dst"). Return the file's
226 destination."
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000227
228 The destination may be a directory.
229
Antoine Pitrou78091e62011-12-29 18:54:15 +0100230 If the optional flag `symlinks` is set, symlinks won't be followed. This
231 resembles GNU's "cp -P src dst".
232
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000233 """
Guido van Rossuma2baf461997-04-29 14:06:46 +0000234 if os.path.isdir(dst):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000235 dst = os.path.join(dst, os.path.basename(src))
Antoine Pitrou78091e62011-12-29 18:54:15 +0100236 copyfile(src, dst, symlinks=symlinks)
237 copystat(src, dst, symlinks=symlinks)
Antoine Pitrou424246f2012-05-12 19:02:01 +0200238 _copyxattr(src, dst, symlinks=symlinks)
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500239 return dst
Guido van Rossumc6360141990-10-13 19:23:40 +0000240
Georg Brandl2ee470f2008-07-16 12:55:28 +0000241def ignore_patterns(*patterns):
242 """Function that can be used as copytree() ignore parameter.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000243
Georg Brandl2ee470f2008-07-16 12:55:28 +0000244 Patterns is a sequence of glob-style patterns
245 that are used to exclude files"""
246 def _ignore_patterns(path, names):
247 ignored_names = []
248 for pattern in patterns:
249 ignored_names.extend(fnmatch.filter(names, pattern))
250 return set(ignored_names)
251 return _ignore_patterns
252
Tarek Ziadéfb437512010-04-20 08:57:33 +0000253def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,
254 ignore_dangling_symlinks=False):
Tarek Ziadé5340db32010-04-19 22:30:51 +0000255 """Recursively copy a directory tree.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000256
257 The destination directory must not already exist.
Neal Norwitza4c93b62003-02-23 21:36:32 +0000258 If exception(s) occur, an Error is raised with a list of reasons.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000259
260 If the optional symlinks flag is true, symbolic links in the
261 source tree result in symbolic links in the destination tree; if
262 it is false, the contents of the files pointed to by symbolic
Tarek Ziadéfb437512010-04-20 08:57:33 +0000263 links are copied. If the file pointed by the symlink doesn't
264 exist, an exception will be added in the list of errors raised in
265 an Error exception at the end of the copy process.
266
267 You can set the optional ignore_dangling_symlinks flag to true if you
Tarek Ziadé8c26c7d2010-04-23 13:03:50 +0000268 want to silence this exception. Notice that this has no effect on
269 platforms that don't support os.symlink.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000270
Georg Brandl2ee470f2008-07-16 12:55:28 +0000271 The optional ignore argument is a callable. If given, it
272 is called with the `src` parameter, which is the directory
273 being visited by copytree(), and `names` which is the list of
274 `src` contents, as returned by os.listdir():
275
276 callable(src, names) -> ignored_names
277
278 Since copytree() is called recursively, the callable will be
279 called once for each directory that is copied. It returns a
280 list of names relative to the `src` directory that should
281 not be copied.
282
Tarek Ziadé5340db32010-04-19 22:30:51 +0000283 The optional copy_function argument is a callable that will be used
284 to copy each file. It will be called with the source path and the
285 destination path as arguments. By default, copy2() is used, but any
286 function that supports the same signature (like copy()) can be used.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000287
288 """
Guido van Rossuma2baf461997-04-29 14:06:46 +0000289 names = os.listdir(src)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000290 if ignore is not None:
291 ignored_names = ignore(src, names)
292 else:
293 ignored_names = set()
294
Johannes Gijsberse4172ea2005-01-08 12:31:29 +0000295 os.makedirs(dst)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000296 errors = []
Guido van Rossuma2baf461997-04-29 14:06:46 +0000297 for name in names:
Georg Brandl2ee470f2008-07-16 12:55:28 +0000298 if name in ignored_names:
299 continue
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000300 srcname = os.path.join(src, name)
301 dstname = os.path.join(dst, name)
302 try:
Tarek Ziadéfb437512010-04-20 08:57:33 +0000303 if os.path.islink(srcname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000304 linkto = os.readlink(srcname)
Tarek Ziadéfb437512010-04-20 08:57:33 +0000305 if symlinks:
Antoine Pitrou78091e62011-12-29 18:54:15 +0100306 # We can't just leave it to `copy_function` because legacy
307 # code with a custom `copy_function` may rely on copytree
308 # doing the right thing.
Tarek Ziadéfb437512010-04-20 08:57:33 +0000309 os.symlink(linkto, dstname)
Antoine Pitrou78091e62011-12-29 18:54:15 +0100310 copystat(srcname, dstname, symlinks=symlinks)
Tarek Ziadéfb437512010-04-20 08:57:33 +0000311 else:
312 # ignore dangling symlink if the flag is on
313 if not os.path.exists(linkto) and ignore_dangling_symlinks:
314 continue
315 # otherwise let the copy occurs. copy2 will raise an error
316 copy_function(srcname, dstname)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000317 elif os.path.isdir(srcname):
Tarek Ziadé5340db32010-04-19 22:30:51 +0000318 copytree(srcname, dstname, symlinks, ignore, copy_function)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000319 else:
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000320 # Will raise a SpecialFileError for unsupported file types
Tarek Ziadé5340db32010-04-19 22:30:51 +0000321 copy_function(srcname, dstname)
Georg Brandla1be88e2005-08-31 22:48:45 +0000322 # catch the Error from the recursive copytree so that we can
323 # continue with other files
Guido van Rossumb940e112007-01-10 16:19:56 +0000324 except Error as err:
Georg Brandla1be88e2005-08-31 22:48:45 +0000325 errors.extend(err.args[0])
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000326 except EnvironmentError as why:
327 errors.append((srcname, dstname, str(why)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000328 try:
329 copystat(src, dst)
Guido van Rossumb940e112007-01-10 16:19:56 +0000330 except OSError as why:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000331 if WindowsError is not None and isinstance(why, WindowsError):
332 # Copying file access times may fail on Windows
333 pass
334 else:
335 errors.extend((src, dst, str(why)))
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000336 if errors:
Collin Winterce36ad82007-08-30 01:19:48 +0000337 raise Error(errors)
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500338 return dst
Guido van Rossumd7673291998-02-06 21:38:09 +0000339
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200340# version vulnerable to race conditions
341def _rmtree_unsafe(path, onerror):
Christian Heimes9bd667a2008-01-20 15:14:11 +0000342 try:
343 if os.path.islink(path):
344 # symlinks to directories are forbidden, see bug #1669
345 raise OSError("Cannot call rmtree on a symbolic link")
346 except OSError:
347 onerror(os.path.islink, path, sys.exc_info())
348 # can't continue even if onerror hook returns
349 return
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000350 names = []
351 try:
352 names = os.listdir(path)
Éric Araujocfcc9772011-08-10 20:54:33 +0200353 except os.error:
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000354 onerror(os.listdir, path, sys.exc_info())
355 for name in names:
356 fullname = os.path.join(path, name)
357 try:
358 mode = os.lstat(fullname).st_mode
359 except os.error:
360 mode = 0
361 if stat.S_ISDIR(mode):
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200362 _rmtree_unsafe(fullname, onerror)
Barry Warsaw234d9a92003-01-24 17:36:15 +0000363 else:
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000364 try:
Hynek Schlawack2100b422012-06-23 20:28:32 +0200365 os.unlink(fullname)
Éric Araujocfcc9772011-08-10 20:54:33 +0200366 except os.error:
Hynek Schlawack2100b422012-06-23 20:28:32 +0200367 onerror(os.unlink, fullname, sys.exc_info())
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000368 try:
369 os.rmdir(path)
370 except os.error:
371 onerror(os.rmdir, path, sys.exc_info())
Guido van Rossumd7673291998-02-06 21:38:09 +0000372
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200373# Version using fd-based APIs to protect against races
374def _rmtree_safe_fd(topfd, path, onerror):
375 names = []
376 try:
Hynek Schlawack2100b422012-06-23 20:28:32 +0200377 names = os.listdir(topfd)
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200378 except os.error:
Hynek Schlawack2100b422012-06-23 20:28:32 +0200379 onerror(os.listdir, path, sys.exc_info())
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200380 for name in names:
381 fullname = os.path.join(path, name)
382 try:
Hynek Schlawack2100b422012-06-23 20:28:32 +0200383 orig_st = os.stat(name, dir_fd=topfd)
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200384 mode = orig_st.st_mode
385 except os.error:
386 mode = 0
387 if stat.S_ISDIR(mode):
388 try:
Hynek Schlawack2100b422012-06-23 20:28:32 +0200389 dirfd = os.open(name, os.O_RDONLY, dir_fd=topfd)
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200390 except os.error:
Hynek Schlawack2100b422012-06-23 20:28:32 +0200391 onerror(os.open, fullname, sys.exc_info())
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200392 else:
393 try:
394 if os.path.samestat(orig_st, os.fstat(dirfd)):
395 _rmtree_safe_fd(dirfd, fullname, onerror)
396 finally:
397 os.close(dirfd)
398 else:
399 try:
Hynek Schlawack2100b422012-06-23 20:28:32 +0200400 os.unlink(name, dir_fd=topfd)
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200401 except os.error:
Hynek Schlawack2100b422012-06-23 20:28:32 +0200402 onerror(os.unlink, fullname, sys.exc_info())
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200403 try:
404 os.rmdir(path)
405 except os.error:
406 onerror(os.rmdir, path, sys.exc_info())
407
Hynek Schlawack2100b422012-06-23 20:28:32 +0200408rmtree_is_safe = _use_fd_functions = (os.unlink in os.supports_dir_fd and
409 os.open in os.supports_dir_fd)
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200410def rmtree(path, ignore_errors=False, onerror=None):
411 """Recursively delete a directory tree.
412
413 If ignore_errors is set, errors are ignored; otherwise, if onerror
414 is set, it is called to handle the error with arguments (func,
Hynek Schlawack2100b422012-06-23 20:28:32 +0200415 path, exc_info) where func is platform and implementation dependent;
Hynek Schlawack67be92b2012-06-23 17:58:42 +0200416 path is the argument to that function that caused it to fail; and
417 exc_info is a tuple returned by sys.exc_info(). If ignore_errors
418 is false and onerror is None, an exception is raised.
419
420 """
421 if ignore_errors:
422 def onerror(*args):
423 pass
424 elif onerror is None:
425 def onerror(*args):
426 raise
427 if _use_fd_functions:
428 # Note: To guard against symlink races, we use the standard
429 # lstat()/open()/fstat() trick.
430 try:
431 orig_st = os.lstat(path)
432 except Exception:
433 onerror(os.lstat, path, sys.exc_info())
434 return
435 try:
436 fd = os.open(path, os.O_RDONLY)
437 except Exception:
438 onerror(os.lstat, path, sys.exc_info())
439 return
440 try:
441 if (stat.S_ISDIR(orig_st.st_mode) and
442 os.path.samestat(orig_st, os.fstat(fd))):
443 _rmtree_safe_fd(fd, path, onerror)
444 elif (stat.S_ISREG(orig_st.st_mode)):
445 raise NotADirectoryError(20,
446 "Not a directory: '{}'".format(path))
447 finally:
448 os.close(fd)
449 else:
450 return _rmtree_unsafe(path, onerror)
451
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000452
Christian Heimesada8c3b2008-03-18 18:26:33 +0000453def _basename(path):
454 # A basename() variant which first strips the trailing slash, if present.
455 # Thus we always get the last component of the path, even for directories.
456 return os.path.basename(path.rstrip(os.path.sep))
457
458def move(src, dst):
459 """Recursively move a file or directory to another location. This is
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500460 similar to the Unix "mv" command. Return the file or directory's
461 destination.
Christian Heimesada8c3b2008-03-18 18:26:33 +0000462
463 If the destination is a directory or a symlink to a directory, the source
464 is moved inside the directory. The destination path must not already
465 exist.
466
467 If the destination already exists but is not a directory, it may be
468 overwritten depending on os.rename() semantics.
469
470 If the destination is on our current filesystem, then rename() is used.
Antoine Pitrou0a08d7a2012-01-06 20:16:19 +0100471 Otherwise, src is copied to the destination and then removed. Symlinks are
472 recreated under the new name if os.rename() fails because of cross
473 filesystem renames.
474
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000475 A lot more could be done here... A look at a mv.c shows a lot of
476 the issues this implementation glosses over.
477
478 """
Christian Heimesada8c3b2008-03-18 18:26:33 +0000479 real_dst = dst
480 if os.path.isdir(dst):
Ronald Oussorenf51738b2011-05-06 10:23:04 +0200481 if _samefile(src, dst):
482 # We might be on a case insensitive filesystem,
483 # perform the rename anyway.
484 os.rename(src, dst)
485 return
486
Christian Heimesada8c3b2008-03-18 18:26:33 +0000487 real_dst = os.path.join(dst, _basename(src))
488 if os.path.exists(real_dst):
489 raise Error("Destination path '%s' already exists" % real_dst)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000490 try:
Christian Heimesada8c3b2008-03-18 18:26:33 +0000491 os.rename(src, real_dst)
Éric Araujocfcc9772011-08-10 20:54:33 +0200492 except OSError:
Antoine Pitrou0a08d7a2012-01-06 20:16:19 +0100493 if os.path.islink(src):
494 linkto = os.readlink(src)
495 os.symlink(linkto, real_dst)
496 os.unlink(src)
497 elif os.path.isdir(src):
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000498 if _destinsrc(src, dst):
Collin Winterce36ad82007-08-30 01:19:48 +0000499 raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst))
Christian Heimesada8c3b2008-03-18 18:26:33 +0000500 copytree(src, real_dst, symlinks=True)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000501 rmtree(src)
502 else:
Christian Heimesada8c3b2008-03-18 18:26:33 +0000503 copy2(src, real_dst)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000504 os.unlink(src)
Brian Curtin0d0a1de2012-06-18 18:41:07 -0500505 return real_dst
Brett Cannon1c3fa182004-06-19 21:11:35 +0000506
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000507def _destinsrc(src, dst):
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000508 src = abspath(src)
509 dst = abspath(dst)
510 if not src.endswith(os.path.sep):
511 src += os.path.sep
512 if not dst.endswith(os.path.sep):
513 dst += os.path.sep
514 return dst.startswith(src)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000515
516def _get_gid(name):
517 """Returns a gid, given a group name."""
518 if getgrnam is None or name is None:
519 return None
520 try:
521 result = getgrnam(name)
522 except KeyError:
523 result = None
524 if result is not None:
525 return result[2]
526 return None
527
528def _get_uid(name):
529 """Returns an uid, given a user name."""
530 if getpwnam is None or name is None:
531 return None
532 try:
533 result = getpwnam(name)
534 except KeyError:
535 result = None
536 if result is not None:
537 return result[2]
538 return None
539
540def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
541 owner=None, group=None, logger=None):
542 """Create a (possibly compressed) tar file from all the files under
543 'base_dir'.
544
Tarek Ziadé5e2be872010-04-20 21:40:47 +0000545 'compress' must be "gzip" (the default), "bzip2", or None.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000546
547 'owner' and 'group' can be used to define an owner and a group for the
548 archive that is being built. If not provided, the current owner and group
549 will be used.
550
Éric Araujo4433a5f2010-12-15 20:26:30 +0000551 The output tar file will be named 'base_name' + ".tar", possibly plus
Tarek Ziadé5e2be872010-04-20 21:40:47 +0000552 the appropriate compression extension (".gz", or ".bz2").
Tarek Ziadé396fad72010-02-23 05:30:31 +0000553
554 Returns the output filename.
555 """
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000556 tar_compression = {'gzip': 'gz', None: ''}
557 compress_ext = {'gzip': '.gz'}
558
559 if _BZ2_SUPPORTED:
560 tar_compression['bzip2'] = 'bz2'
561 compress_ext['bzip2'] = '.bz2'
Tarek Ziadé396fad72010-02-23 05:30:31 +0000562
563 # flags for compression program, each element of list will be an argument
Éric Araujoc1b7e7f2011-09-18 23:12:30 +0200564 if compress is not None and compress not in compress_ext:
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000565 raise ValueError("bad value for 'compress', or compression format not "
566 "supported : {0}".format(compress))
Tarek Ziadé396fad72010-02-23 05:30:31 +0000567
Tarek Ziadé5e2be872010-04-20 21:40:47 +0000568 archive_name = base_name + '.tar' + compress_ext.get(compress, '')
Tarek Ziadé396fad72010-02-23 05:30:31 +0000569 archive_dir = os.path.dirname(archive_name)
Tarek Ziadé5e2be872010-04-20 21:40:47 +0000570
Tarek Ziadé396fad72010-02-23 05:30:31 +0000571 if not os.path.exists(archive_dir):
Éric Araujoac4e58e2011-01-29 20:32:11 +0000572 if logger is not None:
Éric Araujo43a7ee12011-08-19 02:55:11 +0200573 logger.info("creating %s", archive_dir)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000574 if not dry_run:
575 os.makedirs(archive_dir)
576
Tarek Ziadé396fad72010-02-23 05:30:31 +0000577 # creating the tarball
Tarek Ziadé396fad72010-02-23 05:30:31 +0000578 if logger is not None:
579 logger.info('Creating tar archive')
580
581 uid = _get_uid(owner)
582 gid = _get_gid(group)
583
584 def _set_uid_gid(tarinfo):
585 if gid is not None:
586 tarinfo.gid = gid
587 tarinfo.gname = group
588 if uid is not None:
589 tarinfo.uid = uid
590 tarinfo.uname = owner
591 return tarinfo
592
593 if not dry_run:
594 tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
595 try:
596 tar.add(base_dir, filter=_set_uid_gid)
597 finally:
598 tar.close()
599
Tarek Ziadé396fad72010-02-23 05:30:31 +0000600 return archive_name
601
Tarek Ziadée2124162010-04-21 13:35:21 +0000602def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):
Tarek Ziadé396fad72010-02-23 05:30:31 +0000603 # XXX see if we want to keep an external call here
604 if verbose:
605 zipoptions = "-r"
606 else:
607 zipoptions = "-rq"
608 from distutils.errors import DistutilsExecError
609 from distutils.spawn import spawn
610 try:
611 spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
612 except DistutilsExecError:
613 # XXX really should distinguish between "couldn't find
614 # external 'zip' command" and "zip failed".
615 raise ExecError("unable to create zip file '%s': "
616 "could neither import the 'zipfile' module nor "
617 "find a standalone zip utility") % zip_filename
618
619def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
620 """Create a zip file from all the files under 'base_dir'.
621
Éric Araujo4433a5f2010-12-15 20:26:30 +0000622 The output zip file will be named 'base_name' + ".zip". Uses either the
Tarek Ziadé396fad72010-02-23 05:30:31 +0000623 "zipfile" Python module (if available) or the InfoZIP "zip" utility
624 (if installed and found on the default search path). If neither tool is
625 available, raises ExecError. Returns the name of the output zip
626 file.
627 """
628 zip_filename = base_name + ".zip"
629 archive_dir = os.path.dirname(base_name)
630
631 if not os.path.exists(archive_dir):
632 if logger is not None:
633 logger.info("creating %s", archive_dir)
634 if not dry_run:
635 os.makedirs(archive_dir)
636
637 # If zipfile module is not available, try spawning an external 'zip'
638 # command.
639 try:
640 import zipfile
641 except ImportError:
642 zipfile = None
643
644 if zipfile is None:
Tarek Ziadée2124162010-04-21 13:35:21 +0000645 _call_external_zip(base_dir, zip_filename, verbose, dry_run)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000646 else:
647 if logger is not None:
648 logger.info("creating '%s' and adding '%s' to it",
649 zip_filename, base_dir)
650
651 if not dry_run:
652 zip = zipfile.ZipFile(zip_filename, "w",
653 compression=zipfile.ZIP_DEFLATED)
654
655 for dirpath, dirnames, filenames in os.walk(base_dir):
656 for name in filenames:
657 path = os.path.normpath(os.path.join(dirpath, name))
658 if os.path.isfile(path):
659 zip.write(path, path)
660 if logger is not None:
661 logger.info("adding '%s'", path)
662 zip.close()
663
664 return zip_filename
665
666_ARCHIVE_FORMATS = {
667 'gztar': (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
Tarek Ziadé396fad72010-02-23 05:30:31 +0000668 'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"),
Éric Araujoc1b7e7f2011-09-18 23:12:30 +0200669 'zip': (_make_zipfile, [], "ZIP file")
Tarek Ziadé396fad72010-02-23 05:30:31 +0000670 }
671
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000672if _BZ2_SUPPORTED:
673 _ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')],
674 "bzip2'ed tar-file")
675
Tarek Ziadé396fad72010-02-23 05:30:31 +0000676def get_archive_formats():
677 """Returns a list of supported formats for archiving and unarchiving.
678
679 Each element of the returned sequence is a tuple (name, description)
680 """
681 formats = [(name, registry[2]) for name, registry in
682 _ARCHIVE_FORMATS.items()]
683 formats.sort()
684 return formats
685
686def register_archive_format(name, function, extra_args=None, description=''):
687 """Registers an archive format.
688
689 name is the name of the format. function is the callable that will be
690 used to create archives. If provided, extra_args is a sequence of
691 (name, value) tuples that will be passed as arguments to the callable.
692 description can be provided to describe the format, and will be returned
693 by the get_archive_formats() function.
694 """
695 if extra_args is None:
696 extra_args = []
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200697 if not callable(function):
Tarek Ziadé396fad72010-02-23 05:30:31 +0000698 raise TypeError('The %s object is not callable' % function)
699 if not isinstance(extra_args, (tuple, list)):
700 raise TypeError('extra_args needs to be a sequence')
701 for element in extra_args:
Éric Araujoc1b7e7f2011-09-18 23:12:30 +0200702 if not isinstance(element, (tuple, list)) or len(element) !=2:
Tarek Ziadé396fad72010-02-23 05:30:31 +0000703 raise TypeError('extra_args elements are : (arg_name, value)')
704
705 _ARCHIVE_FORMATS[name] = (function, extra_args, description)
706
707def unregister_archive_format(name):
708 del _ARCHIVE_FORMATS[name]
709
710def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
711 dry_run=0, owner=None, group=None, logger=None):
712 """Create an archive file (eg. zip or tar).
713
714 'base_name' is the name of the file to create, minus any format-specific
Tarek Ziadé5e2be872010-04-20 21:40:47 +0000715 extension; 'format' is the archive format: one of "zip", "tar", "bztar"
716 or "gztar".
Tarek Ziadé396fad72010-02-23 05:30:31 +0000717
718 'root_dir' is a directory that will be the root directory of the
719 archive; ie. we typically chdir into 'root_dir' before creating the
720 archive. 'base_dir' is the directory where we start archiving from;
721 ie. 'base_dir' will be the common prefix of all files and
722 directories in the archive. 'root_dir' and 'base_dir' both default
723 to the current directory. Returns the name of the archive file.
724
725 'owner' and 'group' are used when creating a tar archive. By default,
726 uses the current owner and group.
727 """
728 save_cwd = os.getcwd()
729 if root_dir is not None:
730 if logger is not None:
731 logger.debug("changing into '%s'", root_dir)
732 base_name = os.path.abspath(base_name)
733 if not dry_run:
734 os.chdir(root_dir)
735
736 if base_dir is None:
737 base_dir = os.curdir
738
739 kwargs = {'dry_run': dry_run, 'logger': logger}
740
741 try:
742 format_info = _ARCHIVE_FORMATS[format]
743 except KeyError:
744 raise ValueError("unknown archive format '%s'" % format)
745
746 func = format_info[0]
747 for arg, val in format_info[1]:
748 kwargs[arg] = val
749
750 if format != 'zip':
751 kwargs['owner'] = owner
752 kwargs['group'] = group
753
754 try:
755 filename = func(base_name, base_dir, **kwargs)
756 finally:
757 if root_dir is not None:
758 if logger is not None:
759 logger.debug("changing back to '%s'", save_cwd)
760 os.chdir(save_cwd)
761
762 return filename
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000763
764
765def get_unpack_formats():
766 """Returns a list of supported formats for unpacking.
767
768 Each element of the returned sequence is a tuple
769 (name, extensions, description)
770 """
771 formats = [(name, info[0], info[3]) for name, info in
772 _UNPACK_FORMATS.items()]
773 formats.sort()
774 return formats
775
776def _check_unpack_options(extensions, function, extra_args):
777 """Checks what gets registered as an unpacker."""
778 # first make sure no other unpacker is registered for this extension
779 existing_extensions = {}
780 for name, info in _UNPACK_FORMATS.items():
781 for ext in info[0]:
782 existing_extensions[ext] = name
783
784 for extension in extensions:
785 if extension in existing_extensions:
786 msg = '%s is already registered for "%s"'
787 raise RegistryError(msg % (extension,
788 existing_extensions[extension]))
789
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200790 if not callable(function):
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000791 raise TypeError('The registered function must be a callable')
792
793
794def register_unpack_format(name, extensions, function, extra_args=None,
795 description=''):
796 """Registers an unpack format.
797
798 `name` is the name of the format. `extensions` is a list of extensions
799 corresponding to the format.
800
801 `function` is the callable that will be
802 used to unpack archives. The callable will receive archives to unpack.
803 If it's unable to handle an archive, it needs to raise a ReadError
804 exception.
805
806 If provided, `extra_args` is a sequence of
807 (name, value) tuples that will be passed as arguments to the callable.
808 description can be provided to describe the format, and will be returned
809 by the get_unpack_formats() function.
810 """
811 if extra_args is None:
812 extra_args = []
813 _check_unpack_options(extensions, function, extra_args)
814 _UNPACK_FORMATS[name] = extensions, function, extra_args, description
815
816def unregister_unpack_format(name):
817 """Removes the pack format from the registery."""
818 del _UNPACK_FORMATS[name]
819
820def _ensure_directory(path):
821 """Ensure that the parent directory of `path` exists"""
822 dirname = os.path.dirname(path)
823 if not os.path.isdir(dirname):
824 os.makedirs(dirname)
825
826def _unpack_zipfile(filename, extract_dir):
827 """Unpack zip `filename` to `extract_dir`
828 """
829 try:
830 import zipfile
831 except ImportError:
832 raise ReadError('zlib not supported, cannot unpack this archive.')
833
834 if not zipfile.is_zipfile(filename):
835 raise ReadError("%s is not a zip file" % filename)
836
837 zip = zipfile.ZipFile(filename)
838 try:
839 for info in zip.infolist():
840 name = info.filename
841
842 # don't extract absolute paths or ones with .. in them
843 if name.startswith('/') or '..' in name:
844 continue
845
846 target = os.path.join(extract_dir, *name.split('/'))
847 if not target:
848 continue
849
850 _ensure_directory(target)
851 if not name.endswith('/'):
852 # file
853 data = zip.read(info.filename)
Éric Araujoc1b7e7f2011-09-18 23:12:30 +0200854 f = open(target, 'wb')
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000855 try:
856 f.write(data)
857 finally:
858 f.close()
859 del data
860 finally:
861 zip.close()
862
863def _unpack_tarfile(filename, extract_dir):
864 """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
865 """
866 try:
867 tarobj = tarfile.open(filename)
868 except tarfile.TarError:
869 raise ReadError(
870 "%s is not a compressed or uncompressed tar file" % filename)
871 try:
872 tarobj.extractall(extract_dir)
873 finally:
874 tarobj.close()
875
876_UNPACK_FORMATS = {
877 'gztar': (['.tar.gz', '.tgz'], _unpack_tarfile, [], "gzip'ed tar-file"),
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000878 'tar': (['.tar'], _unpack_tarfile, [], "uncompressed tar file"),
879 'zip': (['.zip'], _unpack_zipfile, [], "ZIP file")
880 }
881
Tarek Ziadéffa155a2010-04-29 13:34:35 +0000882if _BZ2_SUPPORTED:
883 _UNPACK_FORMATS['bztar'] = (['.bz2'], _unpack_tarfile, [],
884 "bzip2'ed tar-file")
885
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000886def _find_unpack_format(filename):
887 for name, info in _UNPACK_FORMATS.items():
888 for extension in info[0]:
889 if filename.endswith(extension):
890 return name
891 return None
892
893def unpack_archive(filename, extract_dir=None, format=None):
894 """Unpack an archive.
895
896 `filename` is the name of the archive.
897
898 `extract_dir` is the name of the target directory, where the archive
899 is unpacked. If not provided, the current working directory is used.
900
901 `format` is the archive format: one of "zip", "tar", or "gztar". Or any
902 other registered format. If not provided, unpack_archive will use the
903 filename extension and see if an unpacker was registered for that
904 extension.
905
906 In case none is found, a ValueError is raised.
907 """
908 if extract_dir is None:
909 extract_dir = os.getcwd()
910
911 if format is not None:
912 try:
913 format_info = _UNPACK_FORMATS[format]
914 except KeyError:
915 raise ValueError("Unknown unpack format '{0}'".format(format))
916
Nick Coghlanabf202d2011-03-16 13:52:20 -0400917 func = format_info[1]
918 func(filename, extract_dir, **dict(format_info[2]))
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000919 else:
920 # we need to look at the registered unpackers supported extensions
921 format = _find_unpack_format(filename)
922 if format is None:
923 raise ReadError("Unknown archive format '{0}'".format(filename))
924
925 func = _UNPACK_FORMATS[format][1]
926 kwargs = dict(_UNPACK_FORMATS[format][2])
927 func(filename, extract_dir, **kwargs)
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200928
Éric Araujoe4d5b8e2011-08-08 16:51:11 +0200929
930if hasattr(os, 'statvfs'):
931
932 __all__.append('disk_usage')
933 _ntuple_diskusage = collections.namedtuple('usage', 'total used free')
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200934
935 def disk_usage(path):
Éric Araujoe4d5b8e2011-08-08 16:51:11 +0200936 """Return disk usage statistics about the given path.
937
Sandro Tosif8ae4fa2012-04-23 20:07:15 +0200938 Returned value is a named tuple with attributes 'total', 'used' and
Éric Araujoe4d5b8e2011-08-08 16:51:11 +0200939 'free', which are the amount of total, used and free space, in bytes.
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200940 """
Éric Araujoe4d5b8e2011-08-08 16:51:11 +0200941 st = os.statvfs(path)
942 free = st.f_bavail * st.f_frsize
943 total = st.f_blocks * st.f_frsize
944 used = (st.f_blocks - st.f_bfree) * st.f_frsize
945 return _ntuple_diskusage(total, used, free)
946
947elif os.name == 'nt':
948
949 import nt
950 __all__.append('disk_usage')
951 _ntuple_diskusage = collections.namedtuple('usage', 'total used free')
952
953 def disk_usage(path):
954 """Return disk usage statistics about the given path.
955
956 Returned valus is a named tuple with attributes 'total', 'used' and
957 'free', which are the amount of total, used and free space, in bytes.
958 """
959 total, free = nt._getdiskusage(path)
960 used = total - free
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +0200961 return _ntuple_diskusage(total, used, free)
Sandro Tosid902a142011-08-22 23:28:27 +0200962
Éric Araujo0ac4a5d2011-09-01 08:31:51 +0200963
Sandro Tosid902a142011-08-22 23:28:27 +0200964def chown(path, user=None, group=None):
965 """Change owner user and group of the given path.
966
967 user and group can be the uid/gid or the user/group names, and in that case,
968 they are converted to their respective uid/gid.
969 """
970
971 if user is None and group is None:
972 raise ValueError("user and/or group must be set")
973
974 _user = user
975 _group = group
976
977 # -1 means don't change it
978 if user is None:
979 _user = -1
980 # user can either be an int (the uid) or a string (the system username)
981 elif isinstance(user, str):
982 _user = _get_uid(user)
983 if _user is None:
984 raise LookupError("no such user: {!r}".format(user))
985
986 if group is None:
987 _group = -1
988 elif not isinstance(group, int):
989 _group = _get_gid(group)
990 if _group is None:
991 raise LookupError("no such group: {!r}".format(group))
992
993 os.chown(path, _user, _group)
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100994
995def get_terminal_size(fallback=(80, 24)):
996 """Get the size of the terminal window.
997
998 For each of the two dimensions, the environment variable, COLUMNS
999 and LINES respectively, is checked. If the variable is defined and
1000 the value is a positive integer, it is used.
1001
1002 When COLUMNS or LINES is not defined, which is the common case,
1003 the terminal connected to sys.__stdout__ is queried
1004 by invoking os.get_terminal_size.
1005
1006 If the terminal size cannot be successfully queried, either because
1007 the system doesn't support querying, or because we are not
1008 connected to a terminal, the value given in fallback parameter
1009 is used. Fallback defaults to (80, 24) which is the default
1010 size used by many terminal emulators.
1011
1012 The value returned is a named tuple of type os.terminal_size.
1013 """
1014 # columns, lines are the working values
1015 try:
1016 columns = int(os.environ['COLUMNS'])
1017 except (KeyError, ValueError):
1018 columns = 0
1019
1020 try:
1021 lines = int(os.environ['LINES'])
1022 except (KeyError, ValueError):
1023 lines = 0
1024
1025 # only query if necessary
1026 if columns <= 0 or lines <= 0:
1027 try:
1028 size = os.get_terminal_size(sys.__stdout__.fileno())
1029 except (NameError, OSError):
1030 size = os.terminal_size(fallback)
1031 if columns <= 0:
1032 columns = size.columns
1033 if lines <= 0:
1034 lines = size.lines
1035
1036 return os.terminal_size((columns, lines))
Brian Curtinc57a3452012-06-22 16:00:30 -05001037
1038def which(cmd, mode=os.F_OK | os.X_OK, path=None):
Brian Curtindc00f1e2012-06-22 22:49:12 -05001039 """Given a command, mode, and a PATH string, return the path which
Brian Curtin21935362012-06-22 22:48:06 -05001040 conforms to the given mode on the PATH, or None if there is no such file.
1041 `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of
1042 os.environ.get("PATH"), or can be overridden with a custom search path."""
Brian Curtinc57a3452012-06-22 16:00:30 -05001043 # Check that a given file can be accessed with the correct mode.
1044 # Additionally check that `file` is not a directory, as on Windows
1045 # directories pass the os.access check.
1046 def _access_check(fn, mode):
1047 if (os.path.exists(fn) and os.access(fn, mode)
1048 and not os.path.isdir(fn)):
1049 return True
1050 return False
1051
1052 # Short circuit. If we're given a full path which matches the mode
1053 # and it exists, we're done here.
1054 if _access_check(cmd, mode):
1055 return cmd
1056
1057 path = (path or os.environ.get("PATH", os.defpath)).split(os.pathsep)
1058
1059 if sys.platform == "win32":
1060 # The current directory takes precedence on Windows.
1061 if not os.curdir in path:
1062 path.insert(0, os.curdir)
1063
1064 # PATHEXT is necessary to check on Windows.
1065 pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
1066 # See if the given file matches any of the expected path extensions.
1067 # This will allow us to short circuit when given "python.exe".
1068 matches = [cmd for ext in pathext if cmd.lower().endswith(ext.lower())]
1069 # If it does match, only test that one, otherwise we have to try others.
1070 files = [cmd + ext.lower() for ext in pathext] if not matches else [cmd]
1071 else:
1072 # On other platforms you don't have things like PATHEXT to tell you
1073 # what file suffixes are executable, so just pass on cmd as-is.
1074 files = [cmd]
1075
1076 seen = set()
1077 for dir in path:
Antoine Pitrou07c24d12012-06-22 23:33:05 +02001078 dir = os.path.normcase(dir)
Brian Curtinc57a3452012-06-22 16:00:30 -05001079 if not dir in seen:
1080 seen.add(dir)
1081 for thefile in files:
1082 name = os.path.join(dir, thefile)
1083 if _access_check(name, mode):
1084 return name
1085 return None