| 1 |
""" |
| 2 |
""" |
| 3 |
import os, sys, posixpath |
| 4 |
import py |
| 5 |
|
| 6 |
|
| 7 |
iswin32 = sys.platform == "win32" or (getattr(os, '_name', False) == 'nt') |
| 8 |
|
| 9 |
class Checkers: |
| 10 |
_depend_on_existence = 'exists', 'link', 'dir', 'file' |
| 11 |
|
| 12 |
def __init__(self, path): |
| 13 |
self.path = path |
| 14 |
|
| 15 |
def dir(self): |
| 16 |
raise NotImplementedError |
| 17 |
|
| 18 |
def file(self): |
| 19 |
raise NotImplementedError |
| 20 |
|
| 21 |
def dotfile(self): |
| 22 |
return self.path.basename.startswith('.') |
| 23 |
|
| 24 |
def ext(self, arg): |
| 25 |
if not arg.startswith('.'): |
| 26 |
arg = '.' + arg |
| 27 |
return self.path.ext == arg |
| 28 |
|
| 29 |
def exists(self): |
| 30 |
raise NotImplementedError |
| 31 |
|
| 32 |
def basename(self, arg): |
| 33 |
return self.path.basename == arg |
| 34 |
|
| 35 |
def basestarts(self, arg): |
| 36 |
return self.path.basename.startswith(arg) |
| 37 |
|
| 38 |
def relto(self, arg): |
| 39 |
return self.path.relto(arg) |
| 40 |
|
| 41 |
def fnmatch(self, arg): |
| 42 |
return self.path.fnmatch(arg) |
| 43 |
|
| 44 |
def endswith(self, arg): |
| 45 |
return str(self.path).endswith(arg) |
| 46 |
|
| 47 |
def _evaluate(self, kw): |
| 48 |
for name, value in kw.items(): |
| 49 |
invert = False |
| 50 |
meth = None |
| 51 |
try: |
| 52 |
meth = getattr(self, name) |
| 53 |
except AttributeError: |
| 54 |
if name[:3] == 'not': |
| 55 |
invert = True |
| 56 |
try: |
| 57 |
meth = getattr(self, name[3:]) |
| 58 |
except AttributeError: |
| 59 |
pass |
| 60 |
if meth is None: |
| 61 |
raise TypeError( |
| 62 |
"no %r checker available for %r" % (name, self.path)) |
| 63 |
try: |
| 64 |
if py.code.getrawcode(meth).co_argcount > 1: |
| 65 |
if (not meth(value)) ^ invert: |
| 66 |
return False |
| 67 |
else: |
| 68 |
if bool(value) ^ bool(meth()) ^ invert: |
| 69 |
return False |
| 70 |
except (py.error.ENOENT, py.error.ENOTDIR, py.error.EBUSY): |
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
for name in self._depend_on_existence: |
| 75 |
if name in kw: |
| 76 |
if kw.get(name): |
| 77 |
return False |
| 78 |
name = 'not' + name |
| 79 |
if name in kw: |
| 80 |
if not kw.get(name): |
| 81 |
return False |
| 82 |
return True |
| 83 |
|
| 84 |
class NeverRaised(Exception): |
| 85 |
pass |
| 86 |
|
| 87 |
class PathBase(object): |
| 88 |
""" shared implementation for filesystem path objects.""" |
| 89 |
Checkers = Checkers |
| 90 |
|
| 91 |
def __div__(self, other): |
| 92 |
return self.join(str(other)) |
| 93 |
__truediv__ = __div__ |
| 94 |
|
| 95 |
def basename(self): |
| 96 |
""" basename part of path. """ |
| 97 |
return self._getbyspec('basename')[0] |
| 98 |
basename = property(basename, None, None, basename.__doc__) |
| 99 |
|
| 100 |
def dirname(self): |
| 101 |
""" dirname part of path. """ |
| 102 |
return self._getbyspec('dirname')[0] |
| 103 |
dirname = property(dirname, None, None, dirname.__doc__) |
| 104 |
|
| 105 |
def purebasename(self): |
| 106 |
""" pure base name of the path.""" |
| 107 |
return self._getbyspec('purebasename')[0] |
| 108 |
purebasename = property(purebasename, None, None, purebasename.__doc__) |
| 109 |
|
| 110 |
def ext(self): |
| 111 |
""" extension of the path (including the '.').""" |
| 112 |
return self._getbyspec('ext')[0] |
| 113 |
ext = property(ext, None, None, ext.__doc__) |
| 114 |
|
| 115 |
def dirpath(self, *args, **kwargs): |
| 116 |
""" return the directory path joined with any given path arguments. """ |
| 117 |
return self.new(basename='').join(*args, **kwargs) |
| 118 |
|
| 119 |
def read_binary(self): |
| 120 |
""" read and return a bytestring from reading the path. """ |
| 121 |
with self.open('rb') as f: |
| 122 |
return f.read() |
| 123 |
|
| 124 |
def read_text(self, encoding): |
| 125 |
""" read and return a Unicode string from reading the path. """ |
| 126 |
with self.open("r", encoding=encoding) as f: |
| 127 |
return f.read() |
| 128 |
|
| 129 |
|
| 130 |
def read(self, mode='r'): |
| 131 |
""" read and return a bytestring from reading the path. """ |
| 132 |
with self.open(mode) as f: |
| 133 |
return f.read() |
| 134 |
|
| 135 |
def readlines(self, cr=1): |
| 136 |
""" read and return a list of lines from the path. if cr is False, the |
| 137 |
newline will be removed from the end of each line. """ |
| 138 |
if not cr: |
| 139 |
content = self.read('rU') |
| 140 |
return content.split('\n') |
| 141 |
else: |
| 142 |
f = self.open('rU') |
| 143 |
try: |
| 144 |
return f.readlines() |
| 145 |
finally: |
| 146 |
f.close() |
| 147 |
|
| 148 |
def load(self): |
| 149 |
""" (deprecated) return object unpickled from self.read() """ |
| 150 |
f = self.open('rb') |
| 151 |
try: |
| 152 |
return py.error.checked_call(py.std.pickle.load, f) |
| 153 |
finally: |
| 154 |
f.close() |
| 155 |
|
| 156 |
def move(self, target): |
| 157 |
""" move this path to target. """ |
| 158 |
if target.relto(self): |
| 159 |
raise py.error.EINVAL(target, |
| 160 |
"cannot move path into a subdirectory of itself") |
| 161 |
try: |
| 162 |
self.rename(target) |
| 163 |
except py.error.EXDEV: |
| 164 |
self.copy(target) |
| 165 |
self.remove() |
| 166 |
|
| 167 |
def __repr__(self): |
| 168 |
""" return a string representation of this path. """ |
| 169 |
return repr(str(self)) |
| 170 |
|
| 171 |
def check(self, **kw): |
| 172 |
""" check a path for existence and properties. |
| 173 |
|
| 174 |
Without arguments, return True if the path exists, otherwise False. |
| 175 |
|
| 176 |
valid checkers:: |
| 177 |
|
| 178 |
file=1 # is a file |
| 179 |
file=0 # is not a file (may not even exist) |
| 180 |
dir=1 # is a dir |
| 181 |
link=1 # is a link |
| 182 |
exists=1 # exists |
| 183 |
|
| 184 |
You can specify multiple checker definitions, for example:: |
| 185 |
|
| 186 |
path.check(file=1, link=1) # a link pointing to a file |
| 187 |
""" |
| 188 |
if not kw: |
| 189 |
kw = {'exists' : 1} |
| 190 |
return self.Checkers(self)._evaluate(kw) |
| 191 |
|
| 192 |
def fnmatch(self, pattern): |
| 193 |
"""return true if the basename/fullname matches the glob-'pattern'. |
| 194 |
|
| 195 |
valid pattern characters:: |
| 196 |
|
| 197 |
* matches everything |
| 198 |
? matches any single character |
| 199 |
[seq] matches any character in seq |
| 200 |
[!seq] matches any char not in seq |
| 201 |
|
| 202 |
If the pattern contains a path-separator then the full path |
| 203 |
is used for pattern matching and a '*' is prepended to the |
| 204 |
pattern. |
| 205 |
|
| 206 |
if the pattern doesn't contain a path-separator the pattern |
| 207 |
is only matched against the basename. |
| 208 |
""" |
| 209 |
return FNMatcher(pattern)(self) |
| 210 |
|
| 211 |
def relto(self, relpath): |
| 212 |
""" return a string which is the relative part of the path |
| 213 |
to the given 'relpath'. |
| 214 |
""" |
| 215 |
if not isinstance(relpath, (str, PathBase)): |
| 216 |
raise TypeError("%r: not a string or path object" %(relpath,)) |
| 217 |
strrelpath = str(relpath) |
| 218 |
if strrelpath and strrelpath[-1] != self.sep: |
| 219 |
strrelpath += self.sep |
| 220 |
|
| 221 |
|
| 222 |
strself = str(self) |
| 223 |
if sys.platform == "win32" or getattr(os, '_name', None) == 'nt': |
| 224 |
if os.path.normcase(strself).startswith( |
| 225 |
os.path.normcase(strrelpath)): |
| 226 |
return strself[len(strrelpath):] |
| 227 |
elif strself.startswith(strrelpath): |
| 228 |
return strself[len(strrelpath):] |
| 229 |
return "" |
| 230 |
|
| 231 |
def ensure_dir(self, *args): |
| 232 |
""" ensure the path joined with args is a directory. """ |
| 233 |
return self.ensure(*args, **{"dir": True}) |
| 234 |
|
| 235 |
def bestrelpath(self, dest): |
| 236 |
""" return a string which is a relative path from self |
| 237 |
(assumed to be a directory) to dest such that |
| 238 |
self.join(bestrelpath) == dest and if not such |
| 239 |
path can be determined return dest. |
| 240 |
""" |
| 241 |
try: |
| 242 |
if self == dest: |
| 243 |
return os.curdir |
| 244 |
base = self.common(dest) |
| 245 |
if not base: |
| 246 |
return str(dest) |
| 247 |
self2base = self.relto(base) |
| 248 |
reldest = dest.relto(base) |
| 249 |
if self2base: |
| 250 |
n = self2base.count(self.sep) + 1 |
| 251 |
else: |
| 252 |
n = 0 |
| 253 |
l = [os.pardir] * n |
| 254 |
if reldest: |
| 255 |
l.append(reldest) |
| 256 |
target = dest.sep.join(l) |
| 257 |
return target |
| 258 |
except AttributeError: |
| 259 |
return str(dest) |
| 260 |
|
| 261 |
def exists(self): |
| 262 |
return self.check() |
| 263 |
|
| 264 |
def isdir(self): |
| 265 |
return self.check(dir=1) |
| 266 |
|
| 267 |
def isfile(self): |
| 268 |
return self.check(file=1) |
| 269 |
|
| 270 |
def parts(self, reverse=False): |
| 271 |
""" return a root-first list of all ancestor directories |
| 272 |
plus the path itself. |
| 273 |
""" |
| 274 |
current = self |
| 275 |
l = [self] |
| 276 |
while 1: |
| 277 |
last = current |
| 278 |
current = current.dirpath() |
| 279 |
if last == current: |
| 280 |
break |
| 281 |
l.append(current) |
| 282 |
if not reverse: |
| 283 |
l.reverse() |
| 284 |
return l |
| 285 |
|
| 286 |
def common(self, other): |
| 287 |
""" return the common part shared with the other path |
| 288 |
or None if there is no common part. |
| 289 |
""" |
| 290 |
last = None |
| 291 |
for x, y in zip(self.parts(), other.parts()): |
| 292 |
if x != y: |
| 293 |
return last |
| 294 |
last = x |
| 295 |
return last |
| 296 |
|
| 297 |
def __add__(self, other): |
| 298 |
""" return new path object with 'other' added to the basename""" |
| 299 |
return self.new(basename=self.basename+str(other)) |
| 300 |
|
| 301 |
def __cmp__(self, other): |
| 302 |
""" return sort value (-1, 0, +1). """ |
| 303 |
try: |
| 304 |
return cmp(self.strpath, other.strpath) |
| 305 |
except AttributeError: |
| 306 |
return cmp(str(self), str(other)) |
| 307 |
|
| 308 |
def __lt__(self, other): |
| 309 |
try: |
| 310 |
return self.strpath < other.strpath |
| 311 |
except AttributeError: |
| 312 |
return str(self) < str(other) |
| 313 |
|
| 314 |
def visit(self, fil=None, rec=None, ignore=NeverRaised, bf=False, sort=False): |
| 315 |
""" yields all paths below the current one |
| 316 |
|
| 317 |
fil is a filter (glob pattern or callable), if not matching the |
| 318 |
path will not be yielded, defaulting to None (everything is |
| 319 |
returned) |
| 320 |
|
| 321 |
rec is a filter (glob pattern or callable) that controls whether |
| 322 |
a node is descended, defaulting to None |
| 323 |
|
| 324 |
ignore is an Exception class that is ignoredwhen calling dirlist() |
| 325 |
on any of the paths (by default, all exceptions are reported) |
| 326 |
|
| 327 |
bf if True will cause a breadthfirst search instead of the |
| 328 |
default depthfirst. Default: False |
| 329 |
|
| 330 |
sort if True will sort entries within each directory level. |
| 331 |
""" |
| 332 |
for x in Visitor(fil, rec, ignore, bf, sort).gen(self): |
| 333 |
yield x |
| 334 |
|
| 335 |
def _sortlist(self, res, sort): |
| 336 |
if sort: |
| 337 |
if hasattr(sort, '__call__'): |
| 338 |
res.sort(sort) |
| 339 |
else: |
| 340 |
res.sort() |
| 341 |
|
| 342 |
def samefile(self, other): |
| 343 |
""" return True if other refers to the same stat object as self. """ |
| 344 |
return self.strpath == str(other) |
| 345 |
|
| 346 |
class Visitor: |
| 347 |
def __init__(self, fil, rec, ignore, bf, sort): |
| 348 |
if isinstance(fil, str): |
| 349 |
fil = FNMatcher(fil) |
| 350 |
if isinstance(rec, str): |
| 351 |
self.rec = FNMatcher(rec) |
| 352 |
elif not hasattr(rec, '__call__') and rec: |
| 353 |
self.rec = lambda path: True |
| 354 |
else: |
| 355 |
self.rec = rec |
| 356 |
self.fil = fil |
| 357 |
self.ignore = ignore |
| 358 |
self.breadthfirst = bf |
| 359 |
self.optsort = sort and sorted or (lambda x: x) |
| 360 |
|
| 361 |
def gen(self, path): |
| 362 |
try: |
| 363 |
entries = path.listdir() |
| 364 |
except self.ignore: |
| 365 |
return |
| 366 |
rec = self.rec |
| 367 |
dirs = self.optsort([p for p in entries |
| 368 |
if p.check(dir=1) and (rec is None or rec(p))]) |
| 369 |
if not self.breadthfirst: |
| 370 |
for subdir in dirs: |
| 371 |
for p in self.gen(subdir): |
| 372 |
yield p |
| 373 |
for p in self.optsort(entries): |
| 374 |
if self.fil is None or self.fil(p): |
| 375 |
yield p |
| 376 |
if self.breadthfirst: |
| 377 |
for subdir in dirs: |
| 378 |
for p in self.gen(subdir): |
| 379 |
yield p |
| 380 |
|
| 381 |
class FNMatcher: |
| 382 |
def __init__(self, pattern): |
| 383 |
self.pattern = pattern |
| 384 |
|
| 385 |
def __call__(self, path): |
| 386 |
pattern = self.pattern |
| 387 |
|
| 388 |
if (pattern.find(path.sep) == -1 and |
| 389 |
iswin32 and |
| 390 |
pattern.find(posixpath.sep) != -1): |
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
pattern = pattern.replace(posixpath.sep, path.sep) |
| 395 |
|
| 396 |
if pattern.find(path.sep) == -1: |
| 397 |
name = path.basename |
| 398 |
else: |
| 399 |
name = str(path) |
| 400 |
if not os.path.isabs(pattern): |
| 401 |
pattern = '*' + path.sep + pattern |
| 402 |
return py.std.fnmatch.fnmatch(name, pattern) |
| 403 |
|