- strike lots of basically unused code around local path implementation.
and tweak things a bit to make py.path.local at least importable on 3k - also strike unused somewhat related code in initpkg.py --HG-- branch : trunk
This commit is contained in:
parent
561fdca3a2
commit
f3fcb5e6d3
|
@ -17,7 +17,7 @@ For questions please check out http://pylib.org/contact.html
|
|||
.. _`py.code`: http://pylib.org/code.html
|
||||
|
||||
"""
|
||||
from initpkg import initpkg
|
||||
from py.initpkg import initpkg
|
||||
trunk = "trunk"
|
||||
|
||||
version = trunk or "1.0.1"
|
||||
|
|
|
@ -107,54 +107,6 @@ class Package(object):
|
|||
assert base.check()
|
||||
return base
|
||||
|
||||
def _iterfiles(self):
|
||||
from py.__.path.common import checker
|
||||
base = self.getpath()
|
||||
for x in base.visit(checker(file=1, notext='.pyc'),
|
||||
rec=checker(dotfile=0)):
|
||||
yield x
|
||||
|
||||
def shahexdigest(self, cache=[]):
|
||||
""" return sha hexdigest for files contained in package. """
|
||||
if cache:
|
||||
return cache[0]
|
||||
from sha import sha
|
||||
sum = sha()
|
||||
# XXX the checksum depends on the order in which visit() enumerates
|
||||
# the files, and it doesn't depend on the file names and paths
|
||||
for x in self._iterfiles():
|
||||
sum.update(x.read())
|
||||
cache.append(sum.hexdigest())
|
||||
return cache[0]
|
||||
|
||||
def getzipdata(self):
|
||||
""" return string representing a zipfile containing the package. """
|
||||
import zipfile
|
||||
import py
|
||||
try:
|
||||
from cStringIO import StringIO
|
||||
except ImportError:
|
||||
from StringIO import StringIO
|
||||
base = py.__pkg__.getpath().dirpath()
|
||||
outf = StringIO()
|
||||
f = zipfile.ZipFile(outf, 'w', compression=zipfile.ZIP_DEFLATED)
|
||||
try:
|
||||
for x in self._iterfiles():
|
||||
f.write(str(x), x.relto(base))
|
||||
finally:
|
||||
f.close()
|
||||
return outf.getvalue()
|
||||
|
||||
def getrev(self):
|
||||
import py
|
||||
p = py.path.svnwc(self.module.__file__).dirpath()
|
||||
try:
|
||||
return p.info().rev
|
||||
except (KeyboardInterrupt, MemoryError, SystemExit):
|
||||
raise
|
||||
except:
|
||||
return 'unknown'
|
||||
|
||||
def setmodule(modpath, module):
|
||||
#print "sys.modules[%r] = %r" % (modpath, module)
|
||||
sys.modules[modpath] = module
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
import os, sys
|
||||
from py.path import local
|
||||
from py.__.path.common import PathStr
|
||||
|
||||
def autopath(globs=None, basefile='__init__.py'):
|
||||
""" return the (local) path of the "current" file pointed to by globals
|
||||
|
@ -20,21 +19,17 @@ def autopath(globs=None, basefile='__init__.py'):
|
|||
raise ValueError, "cannot compute autopath in interactive mode"
|
||||
__file__ = os.path.abspath(sys.argv[0])
|
||||
|
||||
custom__file__ = isinstance(__file__, PathStr)
|
||||
if custom__file__:
|
||||
ret = __file__.__path__
|
||||
else:
|
||||
ret = local(__file__)
|
||||
if ret.ext in ('.pyc', '.pyo'):
|
||||
ret = ret.new(ext='.py')
|
||||
ret = local(__file__)
|
||||
if ret.ext in ('.pyc', '.pyo'):
|
||||
ret = ret.new(ext='.py')
|
||||
current = pkgdir = ret.dirpath()
|
||||
while 1:
|
||||
if basefile in current:
|
||||
if basefile in current.listdir():
|
||||
pkgdir = current
|
||||
current = current.dirpath()
|
||||
if pkgdir != current:
|
||||
continue
|
||||
elif not custom__file__ and str(current) not in sys.path:
|
||||
elif str(current) not in sys.path:
|
||||
sys.path.insert(0, str(current))
|
||||
break
|
||||
ret.pkgdir = pkgdir
|
||||
|
|
|
@ -88,40 +88,6 @@ def check_import(modpath):
|
|||
print "checking import", modpath
|
||||
assert __import__(modpath)
|
||||
|
||||
def test_shahexdigest():
|
||||
hex = py.__pkg__.shahexdigest()
|
||||
assert len(hex) == 40
|
||||
|
||||
def test_getzipdata():
|
||||
s = py.__pkg__.getzipdata()
|
||||
|
||||
def test_getrev():
|
||||
if not py.path.local(py.__file__).dirpath('.svn').check():
|
||||
py.test.skip("py package is not a svn checkout")
|
||||
d = py.__pkg__.getrev()
|
||||
svnversion = py.path.local.sysfind('svnversion')
|
||||
if svnversion is None:
|
||||
py.test.skip("cannot test svnversion, 'svnversion' binary not found")
|
||||
v = svnversion.sysexec(py.path.local(py.__file__).dirpath())
|
||||
assert v.startswith(str(d))
|
||||
|
||||
# the following test should abasically work in the future
|
||||
def XXXtest_virtual_on_the_fly():
|
||||
py.initpkg('my', {
|
||||
'x.abspath' : 'os.path.abspath',
|
||||
'x.local' : 'py.path.local',
|
||||
'y' : 'smtplib',
|
||||
'z.cmdexec' : 'py.process.cmdexec',
|
||||
})
|
||||
from my.x import abspath
|
||||
from my.x import local
|
||||
import smtplib
|
||||
from my import y
|
||||
assert y is smtplib
|
||||
from my.z import cmdexec
|
||||
from py.process import cmdexec as cmdexec2
|
||||
assert cmdexec is cmdexec2
|
||||
|
||||
#
|
||||
# test support for importing modules
|
||||
#
|
||||
|
|
|
@ -1,40 +1,28 @@
|
|||
"""
|
||||
module with base functionality for std.path package
|
||||
|
||||
"""
|
||||
from __future__ import generators
|
||||
import os, sys
|
||||
import py
|
||||
|
||||
def checktype(pathinstance, kw):
|
||||
names = ('local', 'svnwc', 'svnurl', 'py', )
|
||||
for name,value in kw.items():
|
||||
if name in names:
|
||||
cls = getattr(py.path, name)
|
||||
if bool(isinstance(pathinstance, cls)) ^ bool(value):
|
||||
return False
|
||||
del kw[name]
|
||||
return True
|
||||
|
||||
class checker:
|
||||
""" deprecated: return checker callable checking for the given
|
||||
kwargs-specified specification.
|
||||
"""
|
||||
def __init__(self, **kwargs):
|
||||
py.log._apiwarn("0.9.0",
|
||||
"py.path.checker is deprecated, construct "
|
||||
"calls to pathobj.check() instead",
|
||||
)
|
||||
self.kwargs = kwargs
|
||||
def __call__(self, p):
|
||||
return p.check(**self.kwargs)
|
||||
|
||||
class Checkers:
|
||||
_depend_on_existence = 'exists', 'link'
|
||||
_depend_on_existence = 'exists', 'link', 'dir', 'file'
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
|
||||
def dir(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def file(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def dotfile(self):
|
||||
return self.path.basename.startswith('.')
|
||||
|
||||
def ext(self, arg):
|
||||
if not arg.startswith('.'):
|
||||
arg = '.' + arg
|
||||
return self.path.ext == arg
|
||||
|
||||
def exists(self):
|
||||
raise NotImplementedError
|
||||
|
||||
|
@ -48,7 +36,7 @@ class Checkers:
|
|||
return self.path.relto(arg)
|
||||
|
||||
def fnmatch(self, arg):
|
||||
return fnmatch(arg)(self.path)
|
||||
return FNMatcher(arg)(self.path)
|
||||
|
||||
def endswith(self, arg):
|
||||
return str(self.path).endswith(arg)
|
||||
|
@ -67,7 +55,8 @@ class Checkers:
|
|||
except AttributeError:
|
||||
pass
|
||||
if meth is None:
|
||||
raise TypeError, "no %r checker available for %r" % (name, self.path)
|
||||
raise TypeError(
|
||||
"no %r checker available for %r" % (name, self.path))
|
||||
try:
|
||||
if meth.im_func.func_code.co_argcount > 1:
|
||||
if (not meth(value)) ^ invert:
|
||||
|
@ -93,6 +82,78 @@ class PathBase(object):
|
|||
""" shared implementation for filesystem path objects."""
|
||||
Checkers = Checkers
|
||||
|
||||
def __div__(self, other):
|
||||
return self.join(str(other))
|
||||
|
||||
def basename(self):
|
||||
""" basename part of path. """
|
||||
return self._getbyspec('basename')[0]
|
||||
basename = property(basename, None, None, basename.__doc__)
|
||||
|
||||
def purebasename(self):
|
||||
""" pure base name of the path."""
|
||||
return self._getbyspec('purebasename')[0]
|
||||
purebasename = property(purebasename, None, None, purebasename.__doc__)
|
||||
|
||||
def ext(self):
|
||||
""" extension of the path (including the '.')."""
|
||||
return self._getbyspec('ext')[0]
|
||||
ext = property(ext, None, None, ext.__doc__)
|
||||
|
||||
def dirpath(self, *args, **kwargs):
|
||||
""" return the directory Path of the current Path joined
|
||||
with any given path arguments.
|
||||
"""
|
||||
return self.new(basename='').join(*args, **kwargs)
|
||||
|
||||
def read(self, mode='rb'):
|
||||
""" read and return a bytestring from reading the path. """
|
||||
if sys.version_info < (2,3):
|
||||
for x in 'u', 'U':
|
||||
if x in mode:
|
||||
mode = mode.replace(x, '')
|
||||
f = self.open(mode)
|
||||
try:
|
||||
return f.read()
|
||||
finally:
|
||||
f.close()
|
||||
|
||||
def readlines(self, cr=1):
|
||||
""" read and return a list of lines from the path. if cr is False, the
|
||||
newline will be removed from the end of each line. """
|
||||
if not cr:
|
||||
content = self.read('rU')
|
||||
return content.split('\n')
|
||||
else:
|
||||
f = self.open('rU')
|
||||
try:
|
||||
return f.readlines()
|
||||
finally:
|
||||
f.close()
|
||||
|
||||
def load(self):
|
||||
""" return object unpickled from self.read() """
|
||||
f = self.open('rb')
|
||||
try:
|
||||
from cPickle import load
|
||||
return self._callex(load, f)
|
||||
finally:
|
||||
f.close()
|
||||
|
||||
def move(self, target):
|
||||
""" move this path to target. """
|
||||
if target.relto(self):
|
||||
raise py.error.EINVAL(target, "cannot move path into a subdirectory of itself")
|
||||
try:
|
||||
self.rename(target)
|
||||
except py.error.EXDEV: # invalid cross-device link
|
||||
self.copy(target)
|
||||
self.remove()
|
||||
|
||||
def __repr__(self):
|
||||
""" return a string representation of this path. """
|
||||
return repr(str(self))
|
||||
|
||||
def check(self, **kw):
|
||||
""" check a path for existence, or query its properties
|
||||
|
||||
|
@ -106,31 +167,10 @@ class PathBase(object):
|
|||
when for example the keyword argument 'ext' is '.py', this will
|
||||
return True if self.ext == '.py', False otherwise
|
||||
"""
|
||||
if kw:
|
||||
kw = kw.copy()
|
||||
if not checktype(self, kw):
|
||||
return False
|
||||
else:
|
||||
if not kw:
|
||||
kw = {'exists' : 1}
|
||||
return self.Checkers(self)._evaluate(kw)
|
||||
|
||||
def __iter__(self):
|
||||
for i in self.listdir():
|
||||
yield i
|
||||
|
||||
def __contains__(self, other):
|
||||
if isinstance(other, str):
|
||||
return self.join(other).check()
|
||||
else:
|
||||
if other.dirpath() != self:
|
||||
return False
|
||||
p = self.join(other.basename)
|
||||
return p.check()
|
||||
|
||||
def basename(self):
|
||||
return self._getbyspec('basename')[0]
|
||||
basename = property(basename, None, None, 'basename part of path')
|
||||
|
||||
def relto(self, relpath):
|
||||
""" return a string which is the relative part of the path
|
||||
to the given 'relpath'.
|
||||
|
@ -213,10 +253,6 @@ class PathBase(object):
|
|||
except AttributeError:
|
||||
return cmp(str(self), str(other)) # self.path, other.path)
|
||||
|
||||
def __repr__(self):
|
||||
""" return a string representation of this path. """
|
||||
return repr(str(self))
|
||||
|
||||
def visit(self, fil=None, rec=None, ignore=_dummyclass):
|
||||
""" yields all paths below the current one
|
||||
|
||||
|
@ -231,7 +267,7 @@ class PathBase(object):
|
|||
on any of the paths (by default, all exceptions are reported)
|
||||
"""
|
||||
if isinstance(fil, str):
|
||||
fil = fnmatch(fil)
|
||||
fil = FNMatcher(fil)
|
||||
if rec:
|
||||
if isinstance(rec, str):
|
||||
rec = fnmatch(fil)
|
||||
|
@ -257,14 +293,14 @@ class PathBase(object):
|
|||
return func(*args)
|
||||
except py.error.Error:
|
||||
raise
|
||||
except EnvironmentError, e:
|
||||
if not hasattr(e, 'errno'):
|
||||
except EnvironmentError:
|
||||
cls, value, tb = sys.exc_info()
|
||||
if not hasattr(value, 'errno'):
|
||||
raise
|
||||
__tracebackhide__ = False
|
||||
cls, value, tb = sys.exc_info()
|
||||
errno = e.errno
|
||||
errno = value.errno
|
||||
try:
|
||||
if not isinstance(e, WindowsError):
|
||||
if not isinstance(value, WindowsError):
|
||||
raise NameError
|
||||
except NameError:
|
||||
# we are not on Windows, or we got a proper OSError
|
||||
|
@ -273,21 +309,12 @@ class PathBase(object):
|
|||
try:
|
||||
cls = py.error._getwinerrnoclass(errno)
|
||||
except KeyError:
|
||||
raise cls, value, tb
|
||||
raise cls(value) # tb?
|
||||
value = cls("%s%r" % (func.__name__, args))
|
||||
__tracebackhide__ = True
|
||||
raise cls, value
|
||||
raise cls(value)
|
||||
|
||||
def _gethashinstance(self, hashtype):
|
||||
if hashtype == "md5":
|
||||
return py.std.md5.md5()
|
||||
elif hashtype == "sha":
|
||||
return py.std.sha.sha()
|
||||
else:
|
||||
raise ValueError("unknown hash type: %r" %(hashtype,))
|
||||
|
||||
|
||||
class fnmatch:
|
||||
class FNMatcher:
|
||||
def __init__(self, pattern):
|
||||
self.pattern = pattern
|
||||
def __call__(self, path):
|
||||
|
@ -314,181 +341,3 @@ class fnmatch:
|
|||
from fnmatch import fnmatch
|
||||
return fnmatch(name, pattern)
|
||||
|
||||
|
||||
class FSCheckers(Checkers):
|
||||
_depend_on_existence = Checkers._depend_on_existence+('dir', 'file')
|
||||
|
||||
def dir(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def file(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def dotfile(self):
|
||||
return self.path.basename.startswith('.')
|
||||
|
||||
def ext(self, arg):
|
||||
if not arg.startswith('.'):
|
||||
arg = '.' + arg
|
||||
return self.path.ext == arg
|
||||
|
||||
class FSPathBase(PathBase):
|
||||
""" shared implementation for filesystem path objects."""
|
||||
Checkers = FSCheckers
|
||||
|
||||
def __div__(self, other):
|
||||
return self.join(str(other))
|
||||
|
||||
def dirpath(self, *args, **kwargs):
|
||||
""" return the directory Path of the current Path joined
|
||||
with any given path arguments.
|
||||
"""
|
||||
return self.new(basename='').join(*args, **kwargs)
|
||||
|
||||
def ext(self):
|
||||
""" extension of the path (including the '.')."""
|
||||
return self._getbyspec('ext')[0]
|
||||
ext = property(ext, None, None, 'extension part of path')
|
||||
|
||||
def purebasename(self):
|
||||
""" pure base name of the path."""
|
||||
return self._getbyspec('purebasename')[0]
|
||||
purebasename = property(purebasename, None, None, 'basename without extension')
|
||||
|
||||
def read(self, mode='rb'):
|
||||
""" read and return a bytestring from reading the path. """
|
||||
if py.std.sys.version_info < (2,3):
|
||||
for x in 'u', 'U':
|
||||
if x in mode:
|
||||
mode = mode.replace(x, '')
|
||||
f = self.open(mode)
|
||||
try:
|
||||
return f.read()
|
||||
finally:
|
||||
f.close()
|
||||
|
||||
def readlines(self, cr=1):
|
||||
""" read and return a list of lines from the path. if cr is False, the
|
||||
newline will be removed from the end of each line. """
|
||||
if not cr:
|
||||
content = self.read('rU')
|
||||
return content.split('\n')
|
||||
else:
|
||||
f = self.open('rU')
|
||||
try:
|
||||
return f.readlines()
|
||||
finally:
|
||||
f.close()
|
||||
|
||||
def load(self):
|
||||
""" return object unpickled from self.read() """
|
||||
f = self.open('rb')
|
||||
try:
|
||||
from cPickle import load
|
||||
return self._callex(load, f)
|
||||
finally:
|
||||
f.close()
|
||||
|
||||
def move(self, target):
|
||||
""" move this path to target. """
|
||||
if target.relto(self):
|
||||
raise py.error.EINVAL(target, "cannot move path into a subdirectory of itself")
|
||||
try:
|
||||
self.rename(target)
|
||||
except py.error.EXDEV: # invalid cross-device link
|
||||
self.copy(target)
|
||||
self.remove()
|
||||
|
||||
def _getpymodule(self):
|
||||
"""resolve this path to a module python object. """
|
||||
modname = str(self)
|
||||
modname = modname.replace('.', self.sep)
|
||||
try:
|
||||
return sys.modules[modname]
|
||||
except KeyError:
|
||||
co = self._getpycodeobj()
|
||||
mod = py.std.new.module(modname)
|
||||
mod.__file__ = PathStr(self)
|
||||
if self.basename == '__init__.py':
|
||||
mod.__path__ = [str(self.dirpath())]
|
||||
sys.modules[modname] = mod
|
||||
try:
|
||||
exec co in mod.__dict__
|
||||
except:
|
||||
del sys.modules[modname]
|
||||
raise
|
||||
return mod
|
||||
|
||||
def _getpycodeobj(self):
|
||||
""" read the path and compile it to a py.code.Code object. """
|
||||
s = self.read('rU')
|
||||
# XXX str(self) should show up somewhere in the code's filename
|
||||
return py.code.compile(s)
|
||||
|
||||
class PathStr(str):
|
||||
def __init__(self, path):
|
||||
global old_import_hook
|
||||
self.__path__ = path
|
||||
if old_import_hook is None:
|
||||
import __builtin__
|
||||
old_import_hook = __builtin__.__import__
|
||||
__builtin__.__import__ = custom_import_hook
|
||||
|
||||
def relativeimport(p, name, parent=None):
|
||||
names = name.split('.')
|
||||
last_list = [False] * (len(names)-1) + [True]
|
||||
modules = []
|
||||
for name, is_last in zip(names, last_list):
|
||||
if hasattr(parent, name):
|
||||
# shortcut if there is already the correct name
|
||||
# in the parent package
|
||||
submodule = getattr(parent, name)
|
||||
else:
|
||||
if is_last and p.new(basename=name+'.py').check():
|
||||
p = p.new(basename=name+'.py')
|
||||
else:
|
||||
p = p.new(basename=name).join('__init__.py')
|
||||
if not p.check():
|
||||
return None # not found
|
||||
submodule = p._getpymodule()
|
||||
if parent is not None:
|
||||
setattr(parent, name, submodule)
|
||||
modules.append(submodule)
|
||||
parent = submodule
|
||||
return modules # success
|
||||
|
||||
|
||||
old_import_hook = None
|
||||
|
||||
def custom_import_hook(name, glob=None, loc=None, fromlist=None, extra=None, level=None):
|
||||
__tracebackhide__ = False
|
||||
__file__ = glob and glob.get('__file__')
|
||||
if isinstance(__file__, PathStr):
|
||||
# try to perform a relative import
|
||||
# for cooperation with py.magic.autopath, first look in the pkgdir
|
||||
modules = None
|
||||
if hasattr(__file__.__path__, 'pkgdir'):
|
||||
modules = relativeimport(__file__.__path__.pkgdir, name)
|
||||
if not modules:
|
||||
modules = relativeimport(__file__.__path__, name)
|
||||
if modules:
|
||||
if fromlist:
|
||||
submodule = modules[-1] # innermost submodule
|
||||
# try to import submodules named in the 'fromlist' if the
|
||||
# 'submodule' is a package
|
||||
p = submodule.__file__.__path__
|
||||
if p.check(basename='__init__.py'):
|
||||
for name in fromlist:
|
||||
relativeimport(p, name, parent=submodule)
|
||||
# failures are fine
|
||||
return submodule
|
||||
else:
|
||||
return modules[0] # outermost package
|
||||
# fall-back
|
||||
__tracebackhide__ = True
|
||||
try:
|
||||
return old_import_hook(name, glob, loc, fromlist, level)
|
||||
except TypeError:
|
||||
return old_import_hook(name, glob, loc, fromlist)
|
||||
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@ from py.__.path import common
|
|||
|
||||
COUNTER = itertools.count()
|
||||
|
||||
class RemotePath(common.FSPathBase):
|
||||
class RemotePath(common.PathBase):
|
||||
sep = '/'
|
||||
|
||||
def __init__(self, channel, id, basename=None):
|
||||
|
|
|
@ -9,12 +9,8 @@ from py.__.path import common
|
|||
iswin32 = sys.platform == "win32"
|
||||
|
||||
class Stat(object):
|
||||
pformat = "%s = property(lambda x: getattr(x._osstatresult, 'st_%s'))"
|
||||
|
||||
for name in ('atime blksize blocks ctime dev gid '
|
||||
'ino mode mtime nlink rdev size uid'.split()):
|
||||
code = pformat.replace("%s", name)
|
||||
exec code
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._osstatresult, "st_" + name)
|
||||
|
||||
def __init__(self, path, osstatresult):
|
||||
self.path = path
|
||||
|
@ -37,7 +33,7 @@ class Stat(object):
|
|||
return entry[0]
|
||||
group = property(group)
|
||||
|
||||
class PosixPath(common.FSPathBase):
|
||||
class PosixPath(common.PathBase):
|
||||
def chown(self, user, group, rec=0):
|
||||
""" change ownership to the given user and group.
|
||||
user and group may be specified by a number or
|
||||
|
@ -89,14 +85,14 @@ def getgroupid(group):
|
|||
group = grp.getgrnam(group)[2]
|
||||
return group
|
||||
|
||||
FSBase = not iswin32 and PosixPath or common.FSPathBase
|
||||
FSBase = not iswin32 and PosixPath or common.PathBase
|
||||
|
||||
class LocalPath(FSBase):
|
||||
""" object oriented interface to os.path and other local filesystem
|
||||
related information.
|
||||
"""
|
||||
sep = os.sep
|
||||
class Checkers(common.FSCheckers):
|
||||
class Checkers(common.Checkers):
|
||||
def _stat(self):
|
||||
try:
|
||||
return self._statcache
|
||||
|
@ -129,7 +125,7 @@ class LocalPath(FSBase):
|
|||
Note also that passing in a local path object will simply return
|
||||
the exact same path object. Use new() to get a new copy.
|
||||
"""
|
||||
if isinstance(path, common.FSPathBase):
|
||||
if isinstance(path, common.PathBase):
|
||||
if path.__class__ == cls:
|
||||
return path
|
||||
path = path.strpath
|
||||
|
@ -154,18 +150,25 @@ class LocalPath(FSBase):
|
|||
if rec:
|
||||
# force remove of readonly files on windows
|
||||
if iswin32:
|
||||
self.chmod(0700, rec=1)
|
||||
self.chmod(448, rec=1) # octcal 0700
|
||||
self._callex(py.std.shutil.rmtree, self.strpath)
|
||||
else:
|
||||
self._callex(os.rmdir, self.strpath)
|
||||
else:
|
||||
if iswin32:
|
||||
self.chmod(0700)
|
||||
self.chmod(448) # octcal 0700
|
||||
self._callex(os.remove, self.strpath)
|
||||
|
||||
def computehash(self, hashtype="md5", chunksize=524288):
|
||||
""" return hexdigest of hashvalue for this file. """
|
||||
hash = self._gethashinstance(hashtype)
|
||||
try:
|
||||
try:
|
||||
import hashlib as mod
|
||||
except ImportError:
|
||||
mod = __import__(hashtype)
|
||||
hash = getattr(mod, hashtype)()
|
||||
except (AttributeError, ImportError):
|
||||
raise ValueError("Don't know how to compute %r hash" %(hashtype,))
|
||||
f = self.open('rb')
|
||||
try:
|
||||
while 1:
|
||||
|
@ -247,7 +250,7 @@ class LocalPath(FSBase):
|
|||
elif name == 'ext':
|
||||
append(ext)
|
||||
else:
|
||||
raise ValueError, "invalid part specification %r" % name
|
||||
raise ValueError("invalid part specification %r" % name)
|
||||
return res
|
||||
|
||||
def join(self, *args, **kwargs):
|
||||
|
@ -297,7 +300,7 @@ class LocalPath(FSBase):
|
|||
and possibly sorted.
|
||||
"""
|
||||
if isinstance(fil, str):
|
||||
fil = common.fnmatch(fil)
|
||||
fil = common.FNMatcher(fil)
|
||||
res = []
|
||||
for name in self._callex(os.listdir, self.strpath):
|
||||
childurl = self.join(name)
|
||||
|
@ -525,61 +528,6 @@ class LocalPath(FSBase):
|
|||
raise
|
||||
return mod
|
||||
|
||||
def _getpymodule(self):
|
||||
"""resolve this path to a module python object. """
|
||||
if self.ext != '.c':
|
||||
return super(LocalPath, self)._getpymodule()
|
||||
from py.__.misc.buildcmodule import make_module_from_c
|
||||
mod = make_module_from_c(self)
|
||||
return mod
|
||||
|
||||
def _getpycodeobj(self):
|
||||
""" read the path and compile it to a code object. """
|
||||
dotpy = self.ext == ".py"
|
||||
if dotpy:
|
||||
my_magic = py.std.imp.get_magic()
|
||||
my_timestamp = int(self.mtime())
|
||||
if __debug__:
|
||||
pycfile = self + 'c'
|
||||
else:
|
||||
pycfile = self + 'o'
|
||||
try:
|
||||
f = pycfile.open('rb')
|
||||
try:
|
||||
header = f.read(8)
|
||||
if len(header) == 8:
|
||||
magic, timestamp = py.std.struct.unpack('<4si', header)
|
||||
if magic == my_magic and timestamp == my_timestamp:
|
||||
co = py.std.marshal.load(f)
|
||||
path1 = co.co_filename
|
||||
path2 = str(self)
|
||||
if path1 == path2:
|
||||
return co
|
||||
try:
|
||||
if os.path.samefile(path1, path2):
|
||||
return co
|
||||
except (OSError, # probably path1 not found
|
||||
AttributeError): # samefile() not available
|
||||
pass
|
||||
finally:
|
||||
f.close()
|
||||
except py.error.Error:
|
||||
pass
|
||||
s = self.read(mode='rU') + '\n'
|
||||
codeobj = compile(s, str(self), 'exec', generators.compiler_flag)
|
||||
if dotpy:
|
||||
try:
|
||||
f = pycfile.open('wb')
|
||||
f.write(py.std.struct.pack('<4si', 'TEMP', -1)) # fixed below
|
||||
py.std.marshal.dump(codeobj, f)
|
||||
f.flush()
|
||||
f.seek(0)
|
||||
f.write(py.std.struct.pack('<4si', my_magic, my_timestamp))
|
||||
f.close()
|
||||
except py.error.Error:
|
||||
pass
|
||||
return codeobj
|
||||
|
||||
def sysexec(self, *argv):
|
||||
""" return stdout-put from executing a system child process,
|
||||
where the self path points to the binary (XXX or script)
|
||||
|
|
|
@ -48,7 +48,7 @@ def checkbadchars(url):
|
|||
|
||||
#_______________________________________________________________
|
||||
|
||||
class SvnPathBase(common.FSPathBase):
|
||||
class SvnPathBase(common.PathBase):
|
||||
""" Base implementation for SvnPath implementations. """
|
||||
sep = '/'
|
||||
|
||||
|
@ -168,7 +168,7 @@ class SvnPathBase(common.FSPathBase):
|
|||
and possibly sorted.
|
||||
"""
|
||||
if isinstance(fil, str):
|
||||
fil = common.fnmatch(fil)
|
||||
fil = common.FNMatcher(fil)
|
||||
nameinfo_seq = self._listdir_nameinfo()
|
||||
if len(nameinfo_seq) == 1:
|
||||
name, info = nameinfo_seq[0]
|
||||
|
@ -244,7 +244,7 @@ class SvnPathBase(common.FSPathBase):
|
|||
# raise IOError, "could not determine newest repo revision for %s" % self
|
||||
# return rev
|
||||
|
||||
class Checkers(common.FSCheckers):
|
||||
class Checkers(common.Checkers):
|
||||
def dir(self):
|
||||
try:
|
||||
return self.path.info().kind == 'dir'
|
||||
|
|
|
@ -18,7 +18,7 @@ DEBUG = 0
|
|||
|
||||
rex_blame = re.compile(r'\s*(\d+)\s*(\S+) (.*)')
|
||||
|
||||
class SvnWCCommandPath(common.FSPathBase):
|
||||
class SvnWCCommandPath(common.PathBase):
|
||||
""" path implementation offering access/modification to svn working copies.
|
||||
It has methods similar to the functions in os.path and similar to the
|
||||
commands of the svn client.
|
||||
|
@ -416,7 +416,7 @@ recursively. """
|
|||
depending on implementation choices.
|
||||
"""
|
||||
if isinstance(fil, str):
|
||||
fil = common.fnmatch(fil)
|
||||
fil = common.FNMatcher(fil)
|
||||
# XXX unify argument naming with LocalPath.listdir
|
||||
def notsvn(path):
|
||||
return path.basename != '.svn'
|
||||
|
|
|
@ -1,4 +1,3 @@
|
|||
from py.__.path.common import checker
|
||||
import py
|
||||
|
||||
class CommonPathTests(object):
|
||||
|
@ -99,9 +98,6 @@ class CommonPathTests(object):
|
|||
assert self.root.join('samplefile').check(notdir=1)
|
||||
assert not self.root.join("samplefile").check(dir=1)
|
||||
|
||||
def test_filter_dir(self):
|
||||
assert checker(dir=1)(self.root.join("sampledir"))
|
||||
|
||||
def test_fnmatch_file(self):
|
||||
assert self.root.join("samplefile").check(fnmatch='s*e')
|
||||
assert self.root.join("samplefile").check(notfnmatch='s*x')
|
||||
|
@ -151,12 +147,12 @@ class CommonPathTests(object):
|
|||
assert l[0], self.root.join('sampledir')
|
||||
|
||||
def test_listdir_filter(self):
|
||||
l = self.root.listdir(checker(dir=1))
|
||||
l = self.root.listdir(lambda x: x.check(dir=1))
|
||||
assert self.root.join('sampledir') in l
|
||||
assert not self.root.join('samplefile') in l
|
||||
|
||||
def test_listdir_sorted(self):
|
||||
l = self.root.listdir(checker(basestarts="sample"), sort=True)
|
||||
l = self.root.listdir(lambda x: x.check(basestarts="sample"), sort=True)
|
||||
assert self.root.join('sampledir') == l[0]
|
||||
assert self.root.join('samplefile') == l[1]
|
||||
assert self.root.join('samplepickle') == l[2]
|
||||
|
@ -189,7 +185,7 @@ class CommonPathTests(object):
|
|||
|
||||
def test_visit_endswith(self):
|
||||
l = []
|
||||
for i in self.root.visit(checker(endswith="file")):
|
||||
for i in self.root.visit(lambda x: x.check(endswith="file")):
|
||||
l.append(i.relto(self.root))
|
||||
assert self.root.sep.join(["sampledir", "otherfile"]) in l
|
||||
assert "samplefile" in l
|
||||
|
@ -205,23 +201,6 @@ class CommonPathTests(object):
|
|||
assert cmp(path1, path2) == cmp('samplefile', 'samplefile2')
|
||||
assert cmp(path1, path1) == 0
|
||||
|
||||
def test_contains_path(self):
|
||||
path1 = self.root.join('samplefile')
|
||||
assert path1 in self.root
|
||||
assert not self.root.join('not existing') in self.root
|
||||
|
||||
def test_contains_path_with_basename(self):
|
||||
assert 'samplefile' in self.root
|
||||
assert 'not_existing' not in self.root
|
||||
|
||||
def featuretest_check_docstring(self):
|
||||
here = self.root.__class__
|
||||
assert here.check.__doc__
|
||||
doc = here.check.__doc__
|
||||
for name in dir(local.Checkers):
|
||||
if name[0] != '_':
|
||||
assert name in doc
|
||||
|
||||
def test_simple_read(self):
|
||||
x = self.root.join('samplefile').read('ru')
|
||||
assert x == 'samplefile\n'
|
||||
|
|
|
@ -207,8 +207,12 @@ class CommonFSTests(common.CommonPathTests):
|
|||
assert newp.check(file=1)
|
||||
assert not p.check()
|
||||
finally:
|
||||
newp.move(p)
|
||||
assert p.check()
|
||||
dp = newp.dirpath()
|
||||
if hasattr(dp, 'revert'):
|
||||
dp.revert()
|
||||
else:
|
||||
newp.move(p)
|
||||
assert p.check()
|
||||
|
||||
def test_move_directory(self):
|
||||
source = self.root.join('sampledir')
|
||||
|
@ -217,32 +221,3 @@ class CommonFSTests(common.CommonPathTests):
|
|||
assert dest.check(dir=1)
|
||||
assert dest.join('otherfile').check(file=1)
|
||||
assert not source.join('sampledir').check()
|
||||
|
||||
def test__getpymodule(self):
|
||||
obj = self.root.join('execfile')._getpymodule()
|
||||
assert obj.x == 42
|
||||
|
||||
def test_not_has_resolve(self):
|
||||
# because this would mean confusion with respect to
|
||||
# py.path.extpy
|
||||
assert not hasattr(self.root, 'resolve')
|
||||
|
||||
def test__getpymodule_a(self):
|
||||
otherdir = self.root.join('otherdir')
|
||||
mod = otherdir.join('a.py')._getpymodule()
|
||||
assert mod.result == "got it"
|
||||
|
||||
def test__getpymodule_b(self):
|
||||
otherdir = self.root.join('otherdir')
|
||||
mod = otherdir.join('b.py')._getpymodule()
|
||||
assert mod.stuff == "got it"
|
||||
|
||||
def test__getpymodule_c(self):
|
||||
otherdir = self.root.join('otherdir')
|
||||
mod = otherdir.join('c.py')._getpymodule()
|
||||
assert mod.value == "got it"
|
||||
|
||||
def test__getpymodule_d(self):
|
||||
otherdir = self.root.join('otherdir')
|
||||
mod = otherdir.join('d.py')._getpymodule()
|
||||
assert mod.value2 == "got it"
|
||||
|
|
|
@ -1,54 +0,0 @@
|
|||
from py import path, test
|
||||
import py
|
||||
from py.__.path.svn.testing.test_wccommand import getrepowc
|
||||
|
||||
class TestAPI:
|
||||
|
||||
def setup_class(cls):
|
||||
cls.root = py.test.ensuretemp(cls.__name__)
|
||||
|
||||
def repr_eval_test(self, p):
|
||||
r = repr(p)
|
||||
from py.path import local,svnurl, svnwc
|
||||
y = eval(r)
|
||||
assert y == p
|
||||
|
||||
def test_defaultlocal(self):
|
||||
p = path.local()
|
||||
assert hasattr(p, 'atime')
|
||||
#assert hasattr(p, 'group') # XXX win32?
|
||||
assert hasattr(p, 'setmtime')
|
||||
assert p.check()
|
||||
assert p.check(local=1)
|
||||
assert p.check(svnwc=0)
|
||||
assert not p.check(svnwc=1)
|
||||
self.repr_eval_test(p)
|
||||
|
||||
#assert p.std.path()
|
||||
|
||||
def test_local(self):
|
||||
p = path.local()
|
||||
assert hasattr(p, 'atime')
|
||||
assert hasattr(p, 'setmtime')
|
||||
assert p.check()
|
||||
assert p.check(local=1)
|
||||
self.repr_eval_test(p)
|
||||
|
||||
def test_svnurl(self):
|
||||
p = path.svnurl('http://codespeak.net/svn/py')
|
||||
assert p.check(svnurl=1)
|
||||
self.repr_eval_test(p)
|
||||
|
||||
def test_svnwc(self):
|
||||
p = path.svnwc(self.root)
|
||||
assert p.check(svnwc=1)
|
||||
self.repr_eval_test(p)
|
||||
|
||||
#def test_fspy(self):
|
||||
# p = path.py('smtplib.SMTP')
|
||||
# self.repr_eval_test(p)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test.main()
|
||||
|
|
@ -29,7 +29,9 @@ class TestLocalPath(LocalSetup, CommonFSTests):
|
|||
fn = self.tmpdir.join("testhashfile")
|
||||
fn.write("hello")
|
||||
assert fn.computehash("md5") == md5.md5("hello").hexdigest()
|
||||
assert fn.computehash("sha") == sha.sha("hello").hexdigest()
|
||||
#assert fn.computehash("sha") == sha.sha("hello").hexdigest()
|
||||
if sys.version_info >= (2,4):
|
||||
assert fn.computehash("sha1") == sha.sha("hello").hexdigest()
|
||||
py.test.raises(ValueError, fn.computehash, "asdasd")
|
||||
|
||||
def test_remove_removes_readonly_file(self):
|
||||
|
|
|
@ -234,9 +234,7 @@ class TerminalReporter:
|
|||
self.write_line(msg)
|
||||
|
||||
if self.config.option.debug or self.config.option.traceconfig:
|
||||
rev = py.__pkg__.getrev()
|
||||
self.write_line("using py lib: %s <rev %s>" % (
|
||||
py.path.local(py.__file__).dirpath(), rev))
|
||||
self.write_line("using py lib: %s" % (py.path.local(py.__file__).dirpath()))
|
||||
if self.config.option.traceconfig:
|
||||
plugins = []
|
||||
for plugin in self.config.pluginmanager.comregistry:
|
||||
|
|
Loading…
Reference in New Issue