| 1 |
""" |
| 2 |
local path implementation. |
| 3 |
""" |
| 4 |
from __future__ import with_statement |
| 5 |
|
| 6 |
from contextlib import contextmanager |
| 7 |
import sys, os, re, atexit, io |
| 8 |
import py |
| 9 |
from py._path import common |
| 10 |
from py._path.common import iswin32 |
| 11 |
from stat import S_ISLNK, S_ISDIR, S_ISREG |
| 12 |
|
| 13 |
from os.path import abspath, normpath, isabs, exists, isdir, isfile, islink, dirname |
| 14 |
|
| 15 |
if sys.version_info > (3,0): |
| 16 |
def map_as_list(func, iter): |
| 17 |
return list(map(func, iter)) |
| 18 |
else: |
| 19 |
map_as_list = map |
| 20 |
|
| 21 |
class Stat(object): |
| 22 |
def __getattr__(self, name): |
| 23 |
return getattr(self._osstatresult, "st_" + name) |
| 24 |
|
| 25 |
def __init__(self, path, osstatresult): |
| 26 |
self.path = path |
| 27 |
self._osstatresult = osstatresult |
| 28 |
|
| 29 |
@property |
| 30 |
def owner(self): |
| 31 |
if iswin32: |
| 32 |
raise NotImplementedError("XXX win32") |
| 33 |
import pwd |
| 34 |
entry = py.error.checked_call(pwd.getpwuid, self.uid) |
| 35 |
return entry[0] |
| 36 |
|
| 37 |
@property |
| 38 |
def group(self): |
| 39 |
""" return group name of file. """ |
| 40 |
if iswin32: |
| 41 |
raise NotImplementedError("XXX win32") |
| 42 |
import grp |
| 43 |
entry = py.error.checked_call(grp.getgrgid, self.gid) |
| 44 |
return entry[0] |
| 45 |
|
| 46 |
def isdir(self): |
| 47 |
return S_ISDIR(self._osstatresult.st_mode) |
| 48 |
|
| 49 |
def isfile(self): |
| 50 |
return S_ISREG(self._osstatresult.st_mode) |
| 51 |
|
| 52 |
def islink(self): |
| 53 |
st = self.path.lstat() |
| 54 |
return S_ISLNK(self._osstatresult.st_mode) |
| 55 |
|
| 56 |
class PosixPath(common.PathBase): |
| 57 |
def chown(self, user, group, rec=0): |
| 58 |
""" change ownership to the given user and group. |
| 59 |
user and group may be specified by a number or |
| 60 |
by a name. if rec is True change ownership |
| 61 |
recursively. |
| 62 |
""" |
| 63 |
uid = getuserid(user) |
| 64 |
gid = getgroupid(group) |
| 65 |
if rec: |
| 66 |
for x in self.visit(rec=lambda x: x.check(link=0)): |
| 67 |
if x.check(link=0): |
| 68 |
py.error.checked_call(os.chown, str(x), uid, gid) |
| 69 |
py.error.checked_call(os.chown, str(self), uid, gid) |
| 70 |
|
| 71 |
def readlink(self): |
| 72 |
""" return value of a symbolic link. """ |
| 73 |
return py.error.checked_call(os.readlink, self.strpath) |
| 74 |
|
| 75 |
def mklinkto(self, oldname): |
| 76 |
""" posix style hard link to another name. """ |
| 77 |
py.error.checked_call(os.link, str(oldname), str(self)) |
| 78 |
|
| 79 |
def mksymlinkto(self, value, absolute=1): |
| 80 |
""" create a symbolic link with the given value (pointing to another name). """ |
| 81 |
if absolute: |
| 82 |
py.error.checked_call(os.symlink, str(value), self.strpath) |
| 83 |
else: |
| 84 |
base = self.common(value) |
| 85 |
|
| 86 |
relsource = self.__class__(value).relto(base) |
| 87 |
reldest = self.relto(base) |
| 88 |
n = reldest.count(self.sep) |
| 89 |
target = self.sep.join(('..', )*n + (relsource, )) |
| 90 |
py.error.checked_call(os.symlink, target, self.strpath) |
| 91 |
|
| 92 |
def getuserid(user): |
| 93 |
import pwd |
| 94 |
if not isinstance(user, int): |
| 95 |
user = pwd.getpwnam(user)[2] |
| 96 |
return user |
| 97 |
|
| 98 |
def getgroupid(group): |
| 99 |
import grp |
| 100 |
if not isinstance(group, int): |
| 101 |
group = grp.getgrnam(group)[2] |
| 102 |
return group |
| 103 |
|
| 104 |
FSBase = not iswin32 and PosixPath or common.PathBase |
| 105 |
|
| 106 |
class LocalPath(FSBase): |
| 107 |
""" object oriented interface to os.path and other local filesystem |
| 108 |
related information. |
| 109 |
""" |
| 110 |
class ImportMismatchError(ImportError): |
| 111 |
""" raised on pyimport() if there is a mismatch of __file__'s""" |
| 112 |
|
| 113 |
sep = os.sep |
| 114 |
class Checkers(common.Checkers): |
| 115 |
def _stat(self): |
| 116 |
try: |
| 117 |
return self._statcache |
| 118 |
except AttributeError: |
| 119 |
try: |
| 120 |
self._statcache = self.path.stat() |
| 121 |
except py.error.ELOOP: |
| 122 |
self._statcache = self.path.lstat() |
| 123 |
return self._statcache |
| 124 |
|
| 125 |
def dir(self): |
| 126 |
return S_ISDIR(self._stat().mode) |
| 127 |
|
| 128 |
def file(self): |
| 129 |
return S_ISREG(self._stat().mode) |
| 130 |
|
| 131 |
def exists(self): |
| 132 |
return self._stat() |
| 133 |
|
| 134 |
def link(self): |
| 135 |
st = self.path.lstat() |
| 136 |
return S_ISLNK(st.mode) |
| 137 |
|
| 138 |
def __init__(self, path=None, expanduser=False): |
| 139 |
""" Initialize and return a local Path instance. |
| 140 |
|
| 141 |
Path can be relative to the current directory. |
| 142 |
If path is None it defaults to the current working directory. |
| 143 |
If expanduser is True, tilde-expansion is performed. |
| 144 |
Note that Path instances always carry an absolute path. |
| 145 |
Note also that passing in a local path object will simply return |
| 146 |
the exact same path object. Use new() to get a new copy. |
| 147 |
""" |
| 148 |
if path is None: |
| 149 |
self.strpath = py.error.checked_call(os.getcwd) |
| 150 |
elif isinstance(path, common.PathBase): |
| 151 |
self.strpath = path.strpath |
| 152 |
elif isinstance(path, py.builtin._basestring): |
| 153 |
if expanduser: |
| 154 |
path = os.path.expanduser(path) |
| 155 |
self.strpath = abspath(path) |
| 156 |
else: |
| 157 |
raise ValueError("can only pass None, Path instances " |
| 158 |
"or non-empty strings to LocalPath") |
| 159 |
|
| 160 |
def __hash__(self): |
| 161 |
return hash(self.strpath) |
| 162 |
|
| 163 |
def __eq__(self, other): |
| 164 |
s1 = self.strpath |
| 165 |
s2 = getattr(other, "strpath", other) |
| 166 |
if iswin32: |
| 167 |
s1 = s1.lower() |
| 168 |
try: |
| 169 |
s2 = s2.lower() |
| 170 |
except AttributeError: |
| 171 |
return False |
| 172 |
return s1 == s2 |
| 173 |
|
| 174 |
def __ne__(self, other): |
| 175 |
return not (self == other) |
| 176 |
|
| 177 |
def __lt__(self, other): |
| 178 |
return self.strpath < getattr(other, "strpath", other) |
| 179 |
|
| 180 |
def __gt__(self, other): |
| 181 |
return self.strpath > getattr(other, "strpath", other) |
| 182 |
|
| 183 |
def samefile(self, other): |
| 184 |
""" return True if 'other' references the same file as 'self'. |
| 185 |
""" |
| 186 |
other = getattr(other, "strpath", other) |
| 187 |
if not isabs(other): |
| 188 |
other = abspath(other) |
| 189 |
if self == other: |
| 190 |
return True |
| 191 |
if iswin32: |
| 192 |
return False |
| 193 |
return py.error.checked_call( |
| 194 |
os.path.samefile, self.strpath, other) |
| 195 |
|
| 196 |
def remove(self, rec=1, ignore_errors=False): |
| 197 |
""" remove a file or directory (or a directory tree if rec=1). |
| 198 |
if ignore_errors is True, errors while removing directories will |
| 199 |
be ignored. |
| 200 |
""" |
| 201 |
if self.check(dir=1, link=0): |
| 202 |
if rec: |
| 203 |
|
| 204 |
if iswin32: |
| 205 |
self.chmod(448, rec=1) |
| 206 |
py.error.checked_call(py.std.shutil.rmtree, self.strpath, |
| 207 |
ignore_errors=ignore_errors) |
| 208 |
else: |
| 209 |
py.error.checked_call(os.rmdir, self.strpath) |
| 210 |
else: |
| 211 |
if iswin32: |
| 212 |
self.chmod(448) |
| 213 |
py.error.checked_call(os.remove, self.strpath) |
| 214 |
|
| 215 |
def computehash(self, hashtype="md5", chunksize=524288): |
| 216 |
""" return hexdigest of hashvalue for this file. """ |
| 217 |
try: |
| 218 |
try: |
| 219 |
import hashlib as mod |
| 220 |
except ImportError: |
| 221 |
if hashtype == "sha1": |
| 222 |
hashtype = "sha" |
| 223 |
mod = __import__(hashtype) |
| 224 |
hash = getattr(mod, hashtype)() |
| 225 |
except (AttributeError, ImportError): |
| 226 |
raise ValueError("Don't know how to compute %r hash" %(hashtype,)) |
| 227 |
f = self.open('rb') |
| 228 |
try: |
| 229 |
while 1: |
| 230 |
buf = f.read(chunksize) |
| 231 |
if not buf: |
| 232 |
return hash.hexdigest() |
| 233 |
hash.update(buf) |
| 234 |
finally: |
| 235 |
f.close() |
| 236 |
|
| 237 |
def new(self, **kw): |
| 238 |
""" create a modified version of this path. |
| 239 |
the following keyword arguments modify various path parts:: |
| 240 |
|
| 241 |
a:/some/path/to/a/file.ext |
| 242 |
xx drive |
| 243 |
xxxxxxxxxxxxxxxxx dirname |
| 244 |
xxxxxxxx basename |
| 245 |
xxxx purebasename |
| 246 |
xxx ext |
| 247 |
""" |
| 248 |
obj = object.__new__(self.__class__) |
| 249 |
if not kw: |
| 250 |
obj.strpath = self.strpath |
| 251 |
return obj |
| 252 |
drive, dirname, basename, purebasename,ext = self._getbyspec( |
| 253 |
"drive,dirname,basename,purebasename,ext") |
| 254 |
if 'basename' in kw: |
| 255 |
if 'purebasename' in kw or 'ext' in kw: |
| 256 |
raise ValueError("invalid specification %r" % kw) |
| 257 |
else: |
| 258 |
pb = kw.setdefault('purebasename', purebasename) |
| 259 |
try: |
| 260 |
ext = kw['ext'] |
| 261 |
except KeyError: |
| 262 |
pass |
| 263 |
else: |
| 264 |
if ext and not ext.startswith('.'): |
| 265 |
ext = '.' + ext |
| 266 |
kw['basename'] = pb + ext |
| 267 |
|
| 268 |
if ('dirname' in kw and not kw['dirname']): |
| 269 |
kw['dirname'] = drive |
| 270 |
else: |
| 271 |
kw.setdefault('dirname', dirname) |
| 272 |
kw.setdefault('sep', self.sep) |
| 273 |
obj.strpath = normpath( |
| 274 |
"%(dirname)s%(sep)s%(basename)s" % kw) |
| 275 |
return obj |
| 276 |
|
| 277 |
def _getbyspec(self, spec): |
| 278 |
""" see new for what 'spec' can be. """ |
| 279 |
res = [] |
| 280 |
parts = self.strpath.split(self.sep) |
| 281 |
|
| 282 |
args = filter(None, spec.split(',') ) |
| 283 |
append = res.append |
| 284 |
for name in args: |
| 285 |
if name == 'drive': |
| 286 |
append(parts[0]) |
| 287 |
elif name == 'dirname': |
| 288 |
append(self.sep.join(parts[:-1])) |
| 289 |
else: |
| 290 |
basename = parts[-1] |
| 291 |
if name == 'basename': |
| 292 |
append(basename) |
| 293 |
else: |
| 294 |
i = basename.rfind('.') |
| 295 |
if i == -1: |
| 296 |
purebasename, ext = basename, '' |
| 297 |
else: |
| 298 |
purebasename, ext = basename[:i], basename[i:] |
| 299 |
if name == 'purebasename': |
| 300 |
append(purebasename) |
| 301 |
elif name == 'ext': |
| 302 |
append(ext) |
| 303 |
else: |
| 304 |
raise ValueError("invalid part specification %r" % name) |
| 305 |
return res |
| 306 |
|
| 307 |
def dirpath(self, *args, **kwargs): |
| 308 |
""" return the directory path joined with any given path arguments. """ |
| 309 |
if not kwargs: |
| 310 |
path = object.__new__(self.__class__) |
| 311 |
path.strpath = dirname(self.strpath) |
| 312 |
if args: |
| 313 |
path = path.join(*args) |
| 314 |
return path |
| 315 |
return super(LocalPath, self).dirpath(*args, **kwargs) |
| 316 |
|
| 317 |
def join(self, *args, **kwargs): |
| 318 |
""" return a new path by appending all 'args' as path |
| 319 |
components. if abs=1 is used restart from root if any |
| 320 |
of the args is an absolute path. |
| 321 |
""" |
| 322 |
sep = self.sep |
| 323 |
strargs = [getattr(arg, "strpath", arg) for arg in args] |
| 324 |
strpath = self.strpath |
| 325 |
if kwargs.get('abs'): |
| 326 |
newargs = [] |
| 327 |
for arg in reversed(strargs): |
| 328 |
if isabs(arg): |
| 329 |
strpath = arg |
| 330 |
strargs = newargs |
| 331 |
break |
| 332 |
newargs.insert(0, arg) |
| 333 |
for arg in strargs: |
| 334 |
arg = arg.strip(sep) |
| 335 |
if iswin32: |
| 336 |
|
| 337 |
arg = arg.strip('/') |
| 338 |
arg = arg.replace('/', sep) |
| 339 |
strpath = strpath + sep + arg |
| 340 |
obj = object.__new__(self.__class__) |
| 341 |
obj.strpath = normpath(strpath) |
| 342 |
return obj |
| 343 |
|
| 344 |
def open(self, mode='r', ensure=False, encoding=None): |
| 345 |
""" return an opened file with the given mode. |
| 346 |
|
| 347 |
If ensure is True, create parent directories if needed. |
| 348 |
""" |
| 349 |
if ensure: |
| 350 |
self.dirpath().ensure(dir=1) |
| 351 |
if encoding: |
| 352 |
return py.error.checked_call(io.open, self.strpath, mode, encoding=encoding) |
| 353 |
return py.error.checked_call(open, self.strpath, mode) |
| 354 |
|
| 355 |
def _fastjoin(self, name): |
| 356 |
child = object.__new__(self.__class__) |
| 357 |
child.strpath = self.strpath + self.sep + name |
| 358 |
return child |
| 359 |
|
| 360 |
def islink(self): |
| 361 |
return islink(self.strpath) |
| 362 |
|
| 363 |
def check(self, **kw): |
| 364 |
if not kw: |
| 365 |
return exists(self.strpath) |
| 366 |
if len(kw) == 1: |
| 367 |
if "dir" in kw: |
| 368 |
return not kw["dir"] ^ isdir(self.strpath) |
| 369 |
if "file" in kw: |
| 370 |
return not kw["file"] ^ isfile(self.strpath) |
| 371 |
return super(LocalPath, self).check(**kw) |
| 372 |
|
| 373 |
_patternchars = set("*?[" + os.path.sep) |
| 374 |
def listdir(self, fil=None, sort=None): |
| 375 |
""" list directory contents, possibly filter by the given fil func |
| 376 |
and possibly sorted. |
| 377 |
""" |
| 378 |
if fil is None and sort is None: |
| 379 |
names = py.error.checked_call(os.listdir, self.strpath) |
| 380 |
return map_as_list(self._fastjoin, names) |
| 381 |
if isinstance(fil, py.builtin._basestring): |
| 382 |
if not self._patternchars.intersection(fil): |
| 383 |
child = self._fastjoin(fil) |
| 384 |
if exists(child.strpath): |
| 385 |
return [child] |
| 386 |
return [] |
| 387 |
fil = common.FNMatcher(fil) |
| 388 |
names = py.error.checked_call(os.listdir, self.strpath) |
| 389 |
res = [] |
| 390 |
for name in names: |
| 391 |
child = self._fastjoin(name) |
| 392 |
if fil is None or fil(child): |
| 393 |
res.append(child) |
| 394 |
self._sortlist(res, sort) |
| 395 |
return res |
| 396 |
|
| 397 |
def size(self): |
| 398 |
""" return size of the underlying file object """ |
| 399 |
return self.stat().size |
| 400 |
|
| 401 |
def mtime(self): |
| 402 |
""" return last modification time of the path. """ |
| 403 |
return self.stat().mtime |
| 404 |
|
| 405 |
def copy(self, target, mode=False): |
| 406 |
""" copy path to target.""" |
| 407 |
if self.check(file=1): |
| 408 |
if target.check(dir=1): |
| 409 |
target = target.join(self.basename) |
| 410 |
assert self!=target |
| 411 |
copychunked(self, target) |
| 412 |
if mode: |
| 413 |
copymode(self, target) |
| 414 |
else: |
| 415 |
def rec(p): |
| 416 |
return p.check(link=0) |
| 417 |
for x in self.visit(rec=rec): |
| 418 |
relpath = x.relto(self) |
| 419 |
newx = target.join(relpath) |
| 420 |
newx.dirpath().ensure(dir=1) |
| 421 |
if x.check(link=1): |
| 422 |
newx.mksymlinkto(x.readlink()) |
| 423 |
continue |
| 424 |
elif x.check(file=1): |
| 425 |
copychunked(x, newx) |
| 426 |
elif x.check(dir=1): |
| 427 |
newx.ensure(dir=1) |
| 428 |
if mode: |
| 429 |
copymode(x, newx) |
| 430 |
|
| 431 |
def rename(self, target): |
| 432 |
""" rename this path to target. """ |
| 433 |
target = getattr(target, "strpath", target) |
| 434 |
return py.error.checked_call(os.rename, self.strpath, target) |
| 435 |
|
| 436 |
def dump(self, obj, bin=1): |
| 437 |
""" pickle object into path location""" |
| 438 |
f = self.open('wb') |
| 439 |
try: |
| 440 |
py.error.checked_call(py.std.pickle.dump, obj, f, bin) |
| 441 |
finally: |
| 442 |
f.close() |
| 443 |
|
| 444 |
def mkdir(self, *args): |
| 445 |
""" create & return the directory joined with args. """ |
| 446 |
p = self.join(*args) |
| 447 |
py.error.checked_call(os.mkdir, getattr(p, "strpath", p)) |
| 448 |
return p |
| 449 |
|
| 450 |
def write_binary(self, data, ensure=False): |
| 451 |
""" write binary data into path. If ensure is True create |
| 452 |
missing parent directories. |
| 453 |
""" |
| 454 |
if ensure: |
| 455 |
self.dirpath().ensure(dir=1) |
| 456 |
with self.open('wb') as f: |
| 457 |
f.write(data) |
| 458 |
|
| 459 |
def write_text(self, data, encoding, ensure=False): |
| 460 |
""" write text data into path using the specified encoding. |
| 461 |
If ensure is True create missing parent directories. |
| 462 |
""" |
| 463 |
if ensure: |
| 464 |
self.dirpath().ensure(dir=1) |
| 465 |
with self.open('w', encoding=encoding) as f: |
| 466 |
f.write(data) |
| 467 |
|
| 468 |
def write(self, data, mode='w', ensure=False): |
| 469 |
""" write data into path. If ensure is True create |
| 470 |
missing parent directories. |
| 471 |
""" |
| 472 |
if ensure: |
| 473 |
self.dirpath().ensure(dir=1) |
| 474 |
if 'b' in mode: |
| 475 |
if not py.builtin._isbytes(data): |
| 476 |
raise ValueError("can only process bytes") |
| 477 |
else: |
| 478 |
if not py.builtin._istext(data): |
| 479 |
if not py.builtin._isbytes(data): |
| 480 |
data = str(data) |
| 481 |
else: |
| 482 |
data = py.builtin._totext(data, sys.getdefaultencoding()) |
| 483 |
f = self.open(mode) |
| 484 |
try: |
| 485 |
f.write(data) |
| 486 |
finally: |
| 487 |
f.close() |
| 488 |
|
| 489 |
def _ensuredirs(self): |
| 490 |
parent = self.dirpath() |
| 491 |
if parent == self: |
| 492 |
return self |
| 493 |
if parent.check(dir=0): |
| 494 |
parent._ensuredirs() |
| 495 |
if self.check(dir=0): |
| 496 |
try: |
| 497 |
self.mkdir() |
| 498 |
except py.error.EEXIST: |
| 499 |
|
| 500 |
|
| 501 |
if self.check(dir=0): |
| 502 |
raise |
| 503 |
return self |
| 504 |
|
| 505 |
def ensure(self, *args, **kwargs): |
| 506 |
""" ensure that an args-joined path exists (by default as |
| 507 |
a file). if you specify a keyword argument 'dir=True' |
| 508 |
then the path is forced to be a directory path. |
| 509 |
""" |
| 510 |
p = self.join(*args) |
| 511 |
if kwargs.get('dir', 0): |
| 512 |
return p._ensuredirs() |
| 513 |
else: |
| 514 |
p.dirpath()._ensuredirs() |
| 515 |
if not p.check(file=1): |
| 516 |
p.open('w').close() |
| 517 |
return p |
| 518 |
|
| 519 |
def stat(self, raising=True): |
| 520 |
""" Return an os.stat() tuple. """ |
| 521 |
if raising == True: |
| 522 |
return Stat(self, py.error.checked_call(os.stat, self.strpath)) |
| 523 |
try: |
| 524 |
return Stat(self, os.stat(self.strpath)) |
| 525 |
except KeyboardInterrupt: |
| 526 |
raise |
| 527 |
except Exception: |
| 528 |
return None |
| 529 |
|
| 530 |
def lstat(self): |
| 531 |
""" Return an os.lstat() tuple. """ |
| 532 |
return Stat(self, py.error.checked_call(os.lstat, self.strpath)) |
| 533 |
|
| 534 |
def setmtime(self, mtime=None): |
| 535 |
""" set modification time for the given path. if 'mtime' is None |
| 536 |
(the default) then the file's mtime is set to current time. |
| 537 |
|
| 538 |
Note that the resolution for 'mtime' is platform dependent. |
| 539 |
""" |
| 540 |
if mtime is None: |
| 541 |
return py.error.checked_call(os.utime, self.strpath, mtime) |
| 542 |
try: |
| 543 |
return py.error.checked_call(os.utime, self.strpath, (-1, mtime)) |
| 544 |
except py.error.EINVAL: |
| 545 |
return py.error.checked_call(os.utime, self.strpath, (self.atime(), mtime)) |
| 546 |
|
| 547 |
def chdir(self): |
| 548 |
""" change directory to self and return old current directory """ |
| 549 |
try: |
| 550 |
old = self.__class__() |
| 551 |
except py.error.ENOENT: |
| 552 |
old = None |
| 553 |
py.error.checked_call(os.chdir, self.strpath) |
| 554 |
return old |
| 555 |
|
| 556 |
|
| 557 |
@contextmanager |
| 558 |
def as_cwd(self): |
| 559 |
""" return context manager which changes to current dir during the |
| 560 |
managed "with" context. On __enter__ it returns the old dir. |
| 561 |
""" |
| 562 |
old = self.chdir() |
| 563 |
try: |
| 564 |
yield old |
| 565 |
finally: |
| 566 |
old.chdir() |
| 567 |
|
| 568 |
def realpath(self): |
| 569 |
""" return a new path which contains no symbolic links.""" |
| 570 |
return self.__class__(os.path.realpath(self.strpath)) |
| 571 |
|
| 572 |
def atime(self): |
| 573 |
""" return last access time of the path. """ |
| 574 |
return self.stat().atime |
| 575 |
|
| 576 |
def __repr__(self): |
| 577 |
return 'local(%r)' % self.strpath |
| 578 |
|
| 579 |
def __str__(self): |
| 580 |
""" return string representation of the Path. """ |
| 581 |
return self.strpath |
| 582 |
|
| 583 |
def chmod(self, mode, rec=0): |
| 584 |
""" change permissions to the given mode. If mode is an |
| 585 |
integer it directly encodes the os-specific modes. |
| 586 |
if rec is True perform recursively. |
| 587 |
""" |
| 588 |
if not isinstance(mode, int): |
| 589 |
raise TypeError("mode %r must be an integer" % (mode,)) |
| 590 |
if rec: |
| 591 |
for x in self.visit(rec=rec): |
| 592 |
py.error.checked_call(os.chmod, str(x), mode) |
| 593 |
py.error.checked_call(os.chmod, str(self), mode) |
| 594 |
|
| 595 |
def pypkgpath(self): |
| 596 |
""" return the Python package path by looking for the last |
| 597 |
directory upwards which still contains an __init__.py. |
| 598 |
Return None if a pkgpath can not be determined. |
| 599 |
""" |
| 600 |
pkgpath = None |
| 601 |
for parent in self.parts(reverse=True): |
| 602 |
if parent.isdir(): |
| 603 |
if not parent.join('__init__.py').exists(): |
| 604 |
break |
| 605 |
if not isimportable(parent.basename): |
| 606 |
break |
| 607 |
pkgpath = parent |
| 608 |
return pkgpath |
| 609 |
|
| 610 |
def _ensuresyspath(self, ensuremode, path): |
| 611 |
if ensuremode: |
| 612 |
s = str(path) |
| 613 |
if ensuremode == "append": |
| 614 |
if s not in sys.path: |
| 615 |
sys.path.append(s) |
| 616 |
else: |
| 617 |
if s != sys.path[0]: |
| 618 |
sys.path.insert(0, s) |
| 619 |
|
| 620 |
def pyimport(self, modname=None, ensuresyspath=True): |
| 621 |
""" return path as an imported python module. |
| 622 |
|
| 623 |
If modname is None, look for the containing package |
| 624 |
and construct an according module name. |
| 625 |
The module will be put/looked up in sys.modules. |
| 626 |
if ensuresyspath is True then the root dir for importing |
| 627 |
the file (taking __init__.py files into account) will |
| 628 |
be prepended to sys.path if it isn't there already. |
| 629 |
If ensuresyspath=="append" the root dir will be appended |
| 630 |
if it isn't already contained in sys.path. |
| 631 |
if ensuresyspath is False no modification of syspath happens. |
| 632 |
""" |
| 633 |
if not self.check(): |
| 634 |
raise py.error.ENOENT(self) |
| 635 |
|
| 636 |
pkgpath = None |
| 637 |
if modname is None: |
| 638 |
pkgpath = self.pypkgpath() |
| 639 |
if pkgpath is not None: |
| 640 |
pkgroot = pkgpath.dirpath() |
| 641 |
names = self.new(ext="").relto(pkgroot).split(self.sep) |
| 642 |
if names[-1] == "__init__": |
| 643 |
names.pop() |
| 644 |
modname = ".".join(names) |
| 645 |
else: |
| 646 |
pkgroot = self.dirpath() |
| 647 |
modname = self.purebasename |
| 648 |
|
| 649 |
self._ensuresyspath(ensuresyspath, pkgroot) |
| 650 |
__import__(modname) |
| 651 |
mod = sys.modules[modname] |
| 652 |
if self.basename == "__init__.py": |
| 653 |
return mod |
| 654 |
|
| 655 |
modfile = mod.__file__ |
| 656 |
if modfile[-4:] in ('.pyc', '.pyo'): |
| 657 |
modfile = modfile[:-1] |
| 658 |
elif modfile.endswith('$py.class'): |
| 659 |
modfile = modfile[:-9] + '.py' |
| 660 |
if modfile.endswith(os.path.sep + "__init__.py"): |
| 661 |
if self.basename != "__init__.py": |
| 662 |
modfile = modfile[:-12] |
| 663 |
try: |
| 664 |
issame = self.samefile(modfile) |
| 665 |
except py.error.ENOENT: |
| 666 |
issame = False |
| 667 |
if not issame: |
| 668 |
raise self.ImportMismatchError(modname, modfile, self) |
| 669 |
return mod |
| 670 |
else: |
| 671 |
try: |
| 672 |
return sys.modules[modname] |
| 673 |
except KeyError: |
| 674 |
|
| 675 |
import types |
| 676 |
mod = types.ModuleType(modname) |
| 677 |
mod.__file__ = str(self) |
| 678 |
sys.modules[modname] = mod |
| 679 |
try: |
| 680 |
py.builtin.execfile(str(self), mod.__dict__) |
| 681 |
except: |
| 682 |
del sys.modules[modname] |
| 683 |
raise |
| 684 |
return mod |
| 685 |
|
| 686 |
def sysexec(self, *argv, **popen_opts): |
| 687 |
""" return stdout text from executing a system child process, |
| 688 |
where the 'self' path points to executable. |
| 689 |
The process is directly invoked and not through a system shell. |
| 690 |
""" |
| 691 |
from subprocess import Popen, PIPE |
| 692 |
argv = map_as_list(str, argv) |
| 693 |
popen_opts['stdout'] = popen_opts['stderr'] = PIPE |
| 694 |
proc = Popen([str(self)] + argv, **popen_opts) |
| 695 |
stdout, stderr = proc.communicate() |
| 696 |
ret = proc.wait() |
| 697 |
if py.builtin._isbytes(stdout): |
| 698 |
stdout = py.builtin._totext(stdout, sys.getdefaultencoding()) |
| 699 |
if ret != 0: |
| 700 |
if py.builtin._isbytes(stderr): |
| 701 |
stderr = py.builtin._totext(stderr, sys.getdefaultencoding()) |
| 702 |
raise py.process.cmdexec.Error(ret, ret, str(self), |
| 703 |
stdout, stderr,) |
| 704 |
return stdout |
| 705 |
|
| 706 |
def sysfind(cls, name, checker=None, paths=None): |
| 707 |
""" return a path object found by looking at the systems |
| 708 |
underlying PATH specification. If the checker is not None |
| 709 |
it will be invoked to filter matching paths. If a binary |
| 710 |
cannot be found, None is returned |
| 711 |
Note: This is probably not working on plain win32 systems |
| 712 |
but may work on cygwin. |
| 713 |
""" |
| 714 |
if isabs(name): |
| 715 |
p = py.path.local(name) |
| 716 |
if p.check(file=1): |
| 717 |
return p |
| 718 |
else: |
| 719 |
if paths is None: |
| 720 |
if iswin32: |
| 721 |
paths = os.environ['Path'].split(';') |
| 722 |
if '' not in paths and '.' not in paths: |
| 723 |
paths.append('.') |
| 724 |
try: |
| 725 |
systemroot = os.environ['SYSTEMROOT'] |
| 726 |
except KeyError: |
| 727 |
pass |
| 728 |
else: |
| 729 |
paths = [path.replace('%SystemRoot%', systemroot) |
| 730 |
for path in paths] |
| 731 |
else: |
| 732 |
paths = os.environ['PATH'].split(':') |
| 733 |
tryadd = [] |
| 734 |
if iswin32: |
| 735 |
tryadd += os.environ['PATHEXT'].split(os.pathsep) |
| 736 |
tryadd.append("") |
| 737 |
|
| 738 |
for x in paths: |
| 739 |
for addext in tryadd: |
| 740 |
p = py.path.local(x).join(name, abs=True) + addext |
| 741 |
try: |
| 742 |
if p.check(file=1): |
| 743 |
if checker: |
| 744 |
if not checker(p): |
| 745 |
continue |
| 746 |
return p |
| 747 |
except py.error.EACCES: |
| 748 |
pass |
| 749 |
return None |
| 750 |
sysfind = classmethod(sysfind) |
| 751 |
|
| 752 |
def _gethomedir(cls): |
| 753 |
try: |
| 754 |
x = os.environ['HOME'] |
| 755 |
except KeyError: |
| 756 |
try: |
| 757 |
x = os.environ["HOMEDRIVE"] + os.environ['HOMEPATH'] |
| 758 |
except KeyError: |
| 759 |
return None |
| 760 |
return cls(x) |
| 761 |
_gethomedir = classmethod(_gethomedir) |
| 762 |
|
| 763 |
|
| 764 |
|
| 765 |
|
| 766 |
@classmethod |
| 767 |
def get_temproot(cls): |
| 768 |
""" return the system's temporary directory |
| 769 |
(where tempfiles are usually created in) |
| 770 |
""" |
| 771 |
import tempfile |
| 772 |
return py.path.local(tempfile.gettempdir()) |
| 773 |
|
| 774 |
@classmethod |
| 775 |
def mkdtemp(cls, rootdir=None): |
| 776 |
""" return a Path object pointing to a fresh new temporary directory |
| 777 |
(which we created ourself). |
| 778 |
""" |
| 779 |
import tempfile |
| 780 |
if rootdir is None: |
| 781 |
rootdir = cls.get_temproot() |
| 782 |
return cls(py.error.checked_call(tempfile.mkdtemp, dir=str(rootdir))) |
| 783 |
|
| 784 |
def make_numbered_dir(cls, prefix='session-', rootdir=None, keep=3, |
| 785 |
lock_timeout = 172800, |
| 786 |
min_timeout = 300): |
| 787 |
""" return unique directory with a number greater than the current |
| 788 |
maximum one. The number is assumed to start directly after prefix. |
| 789 |
if keep is true directories with a number less than (maxnum-keep) |
| 790 |
will be removed. |
| 791 |
""" |
| 792 |
if rootdir is None: |
| 793 |
rootdir = cls.get_temproot() |
| 794 |
|
| 795 |
nprefix = prefix.lower() |
| 796 |
|
| 797 |
def parse_num(path): |
| 798 |
""" Parse the number out of a path (if it matches the prefix) """ |
| 799 |
nbasename = path.basename.lower() |
| 800 |
if nbasename.startswith(nprefix): |
| 801 |
try: |
| 802 |
return int(nbasename[len(prefix):]) |
| 803 |
except ValueError: |
| 804 |
pass |
| 805 |
|
| 806 |
def create_lockfile(path): |
| 807 |
"""Exclusively create lockfile. Throws when failed""" |
| 808 |
mypid = os.getpid() |
| 809 |
lockfile = path.join(".lock") |
| 810 |
if hasattr(lockfile, "mksymlinkto"): |
| 811 |
lockfile.mksymlinkto(str(mypid)) |
| 812 |
else: |
| 813 |
fd = py.error.checked_call( |
| 814 |
os.open, str(lockfile), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644 |
| 815 |
) |
| 816 |
with os.fdopen(fd, "w") as f: |
| 817 |
f.write(str(mypid)) |
| 818 |
return lockfile |
| 819 |
|
| 820 |
def atexit_remove_lockfile(lockfile): |
| 821 |
"""Ensure lockfile is removed at process exit""" |
| 822 |
mypid = os.getpid() |
| 823 |
|
| 824 |
def try_remove_lockfile(): |
| 825 |
|
| 826 |
|
| 827 |
|
| 828 |
|
| 829 |
|
| 830 |
if os.getpid() != mypid: |
| 831 |
return |
| 832 |
try: |
| 833 |
lockfile.remove() |
| 834 |
except py.error.Error: |
| 835 |
pass |
| 836 |
|
| 837 |
atexit.register(try_remove_lockfile) |
| 838 |
|
| 839 |
|
| 840 |
lastmax = None |
| 841 |
while True: |
| 842 |
maxnum = -1 |
| 843 |
for path in rootdir.listdir(): |
| 844 |
num = parse_num(path) |
| 845 |
if num is not None: |
| 846 |
maxnum = max(maxnum, num) |
| 847 |
|
| 848 |
|
| 849 |
try: |
| 850 |
udir = rootdir.mkdir(prefix + str(maxnum + 1)) |
| 851 |
if lock_timeout: |
| 852 |
lockfile = create_lockfile(udir) |
| 853 |
atexit_remove_lockfile(lockfile) |
| 854 |
except (py.error.EEXIST, py.error.ENOENT, py.error.EBUSY): |
| 855 |
|
| 856 |
|
| 857 |
|
| 858 |
|
| 859 |
|
| 860 |
|
| 861 |
|
| 862 |
|
| 863 |
if lastmax == maxnum: |
| 864 |
raise |
| 865 |
lastmax = maxnum |
| 866 |
continue |
| 867 |
break |
| 868 |
|
| 869 |
|
| 870 |
if keep: |
| 871 |
for path in rootdir.listdir(): |
| 872 |
num = parse_num(path) |
| 873 |
if num is not None and num <= (maxnum - keep): |
| 874 |
if min_timeout: |
| 875 |
|
| 876 |
|
| 877 |
|
| 878 |
|
| 879 |
|
| 880 |
|
| 881 |
try: |
| 882 |
t1 = path.lstat().mtime |
| 883 |
t2 = lockfile.lstat().mtime |
| 884 |
if abs(t2-t1) < min_timeout: |
| 885 |
continue |
| 886 |
except py.error.Error: |
| 887 |
continue |
| 888 |
lf = path.join('.lock') |
| 889 |
try: |
| 890 |
t1 = lf.lstat().mtime |
| 891 |
t2 = lockfile.lstat().mtime |
| 892 |
if not lock_timeout or abs(t2-t1) < lock_timeout: |
| 893 |
continue |
| 894 |
except py.error.Error: |
| 895 |
pass |
| 896 |
try: |
| 897 |
path.remove(rec=1) |
| 898 |
except KeyboardInterrupt: |
| 899 |
raise |
| 900 |
except: |
| 901 |
pass |
| 902 |
|
| 903 |
|
| 904 |
try: |
| 905 |
username = os.environ['USER'] |
| 906 |
except KeyError: |
| 907 |
try: |
| 908 |
username = os.environ['USERNAME'] |
| 909 |
except KeyError: |
| 910 |
username = 'current' |
| 911 |
|
| 912 |
src = str(udir) |
| 913 |
dest = src[:src.rfind('-')] + '-' + username |
| 914 |
try: |
| 915 |
os.unlink(dest) |
| 916 |
except OSError: |
| 917 |
pass |
| 918 |
try: |
| 919 |
os.symlink(src, dest) |
| 920 |
except (OSError, AttributeError, NotImplementedError): |
| 921 |
pass |
| 922 |
|
| 923 |
return udir |
| 924 |
make_numbered_dir = classmethod(make_numbered_dir) |
| 925 |
|
| 926 |
def copymode(src, dest): |
| 927 |
py.std.shutil.copymode(str(src), str(dest)) |
| 928 |
|
| 929 |
def copychunked(src, dest): |
| 930 |
chunksize = 524288 |
| 931 |
fsrc = src.open('rb') |
| 932 |
try: |
| 933 |
fdest = dest.open('wb') |
| 934 |
try: |
| 935 |
while 1: |
| 936 |
buf = fsrc.read(chunksize) |
| 937 |
if not buf: |
| 938 |
break |
| 939 |
fdest.write(buf) |
| 940 |
finally: |
| 941 |
fdest.close() |
| 942 |
finally: |
| 943 |
fsrc.close() |
| 944 |
|
| 945 |
def isimportable(name): |
| 946 |
if name and (name[0].isalpha() or name[0] == '_'): |
| 947 |
name = name.replace("_", '') |
| 948 |
return not name or name.isalnum() |