desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'execute an svn command, return a pipe for reading stdin'
def _svnpopenauth(self, cmd):
cmd = (svncommon.fixlocale() + cmd) if (self.auth is not None): cmd += (' ' + self.auth.makecmdoptions()) return self._popen(cmd)
'return an opened file with the given mode.'
def open(self, mode='r'):
if (mode not in ('r', 'rU')): raise ValueError(('mode %r not supported' % (mode,))) assert self.check(file=1) if (self.rev is None): return self._svnpopenauth(('svn cat "%s"' % (self._escape(self.strpath),))) else: return self._svnpopenauth(('svn cat -r %s...
'return the directory path of the current path joined with any given path arguments.'
def dirpath(self, *args, **kwargs):
l = self.strpath.split(self.sep) if (len(l) < 4): raise py.error.EINVAL(self, 'base is not valid') elif (len(l) == 4): return self.join(*args, **kwargs) else: return self.new(basename='').join(*args, **kwargs)
'create & return the directory joined with args. pass a \'msg\' keyword argument to set the commit message.'
def mkdir(self, *args, **kwargs):
commit_msg = kwargs.get('msg', 'mkdir by py lib invocation') createpath = self.join(*args) createpath._svnwrite('mkdir', '-m', commit_msg) self._norev_delentry(createpath.dirpath()) return createpath
'copy path to target with checkin message msg.'
def copy(self, target, msg='copied by py lib invocation'):
if (getattr(target, 'rev', None) is not None): raise py.error.EINVAL(target, 'revisions are immutable') self._svncmdexecauth(('svn copy -m "%s" "%s" "%s"' % (msg, self._escape(self), self._escape(target)))) self._norev_delentry(target.dirpath())
'rename this path to target with checkin message msg.'
def rename(self, target, msg='renamed by py lib invocation'):
if (getattr(self, 'rev', None) is not None): raise py.error.EINVAL(self, 'revisions are immutable') self._svncmdexecauth(('svn move -m "%s" --force "%s" "%s"' % (msg, self._escape(self), self._escape(target)))) self._norev_delentry(self.dirpath()) self._norev_delentry(sel...
'remove a file or directory (or a directory tree if rec=1) with checkin message msg.'
def remove(self, rec=1, msg='removed by py lib invocation'):
if (self.rev is not None): raise py.error.EINVAL(self, 'revisions are immutable') self._svncmdexecauth(('svn rm -m "%s" "%s"' % (msg, self._escape(self)))) self._norev_delentry(self.dirpath())
'export to a local path topath should not exist prior to calling this, returns a py.path.local instance'
def export(self, topath):
topath = py.path.local(topath) args = [('"%s"' % (self._escape(self),)), ('"%s"' % (self._escape(topath),))] if (self.rev is not None): args = (['-r', str(self.rev)] + args) self._svncmdexecauth(('svn export %s' % (' '.join(args),))) return topath
'ensure that an args-joined path exists (by default as a file). If you specify a keyword argument \'dir=True\' then the path is forced to be a directory path.'
def ensure(self, *args, **kwargs):
if (getattr(self, 'rev', None) is not None): raise py.error.EINVAL(self, 'revisions are immutable') target = self.join(*args) dir = kwargs.get('dir', 0) for x in target.parts(reverse=True): if x.check(): break else: raise py.error.ENOENT(target, 'has not ...
'return an Info structure with svn-provided information.'
def info(self):
parent = self.dirpath() nameinfo_seq = parent._listdir_nameinfo() bn = self.basename for (name, info) in nameinfo_seq: if (name == bn): return info raise py.error.ENOENT(self)
'return sequence of name-info directory entries of self'
def _listdir_nameinfo(self):
def builder(): try: res = self._svnwithrev('ls', '-v') except process.cmdexec.Error: e = sys.exc_info()[1] if (e.err.find('non-existent in that revision') != (-1)): raise py.error.ENOENT(self, e.err) elif (e.err.find('E200009:'...
'list directory contents, possibly filter by the given fil func and possibly sorted.'
def listdir(self, fil=None, sort=None):
if isinstance(fil, str): fil = common.FNMatcher(fil) nameinfo_seq = self._listdir_nameinfo() if (len(nameinfo_seq) == 1): (name, info) = nameinfo_seq[0] if ((name == self.basename) and (info.kind == 'file')): raise py.error.ENOTDIR(self) paths = [self.join(name) for (...
'return a list of LogEntry instances for this path. rev_start is the starting revision (defaulting to the first one). rev_end is the last revision (defaulting to HEAD). if verbose is True, then the LogEntry instances also know which files changed.'
def log(self, rev_start=None, rev_end=1, verbose=False):
assert self.check() rev_start = (((rev_start is None) and 'HEAD') or rev_start) rev_end = (((rev_end is None) and 'HEAD') or rev_end) if ((rev_start == 'HEAD') and (rev_end == 1)): rev_opt = '' else: rev_opt = ('-r %s:%s' % (rev_start, rev_end)) verbose_opt = ((verbose and '-v...
'basename part of path.'
def basename(self):
return self._getbyspec('basename')[0]
'dirname part of path.'
def dirname(self):
return self._getbyspec('dirname')[0]
'pure base name of the path.'
def purebasename(self):
return self._getbyspec('purebasename')[0]
'extension of the path (including the \'.\').'
def ext(self):
return self._getbyspec('ext')[0]
'return the directory path joined with any given path arguments.'
def dirpath(self, *args, **kwargs):
return self.new(basename='').join(*args, **kwargs)
'read and return a bytestring from reading the path.'
def read_binary(self):
with self.open('rb') as f: return f.read()
'read and return a Unicode string from reading the path.'
def read_text(self, encoding):
with self.open('r', encoding=encoding) as f: return f.read()
'read and return a bytestring from reading the path.'
def read(self, mode='r'):
with self.open(mode) as f: return f.read()
'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.'
def readlines(self, cr=1):
if (not cr): content = self.read('rU') return content.split('\n') else: f = self.open('rU') try: return f.readlines() finally: f.close()
'(deprecated) return object unpickled from self.read()'
def load(self):
f = self.open('rb') try: return py.error.checked_call(py.std.pickle.load, f) finally: f.close()
'move this path to target.'
def move(self, 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: self.copy(target) self.remove()
'return a string representation of this path.'
def __repr__(self):
return repr(str(self))
'check a path for existence and properties. Without arguments, return True if the path exists, otherwise False. valid checkers:: file=1 # is a file file=0 # is not a file (may not even exist) dir=1 # is a dir link=1 # is a link exists=1 # exists You can specify multiple checker definitions, for example:: ...
def check(self, **kw):
if (not kw): kw = {'exists': 1} return self.Checkers(self)._evaluate(kw)
'return true if the basename/fullname matches the glob-\'pattern\'. valid pattern characters:: * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any char not in seq If the pattern contains a path-separator then the full path is used for pattern matching...
def fnmatch(self, pattern):
return FNMatcher(pattern)(self)
'return a string which is the relative part of the path to the given \'relpath\'.'
def relto(self, relpath):
if (not isinstance(relpath, (str, PathBase))): raise TypeError(('%r: not a string or path object' % (relpath,))) strrelpath = str(relpath) if (strrelpath and (strrelpath[(-1)] != self.sep)): strrelpath += self.sep strself = self.strpath if ((sys.platform == 'win32')...
'ensure the path joined with args is a directory.'
def ensure_dir(self, *args):
return self.ensure(*args, **{'dir': True})
'return a string which is a relative path from self (assumed to be a directory) to dest such that self.join(bestrelpath) == dest and if not such path can be determined return dest.'
def bestrelpath(self, dest):
try: if (self == dest): return os.curdir base = self.common(dest) if (not base): return str(dest) self2base = self.relto(base) reldest = dest.relto(base) if self2base: n = (self2base.count(self.sep) + 1) else: n ...
'return a root-first list of all ancestor directories plus the path itself.'
def parts(self, reverse=False):
current = self l = [self] while 1: last = current current = current.dirpath() if (last == current): break l.append(current) if (not reverse): l.reverse() return l
'return the common part shared with the other path or None if there is no common part.'
def common(self, other):
last = None for (x, y) in zip(self.parts(), other.parts()): if (x != y): return last last = x return last
'return new path object with \'other\' added to the basename'
def __add__(self, other):
return self.new(basename=(self.basename + str(other)))
'return sort value (-1, 0, +1).'
def __cmp__(self, other):
try: return cmp(self.strpath, other.strpath) except AttributeError: return cmp(str(self), str(other))
'yields all paths below the current one fil is a filter (glob pattern or callable), if not matching the path will not be yielded, defaulting to None (everything is returned) rec is a filter (glob pattern or callable) that controls whether a node is descended, defaulting to None ignore is an Exception class that is igno...
def visit(self, fil=None, rec=None, ignore=NeverRaised, bf=False, sort=False):
for x in Visitor(fil, rec, ignore, bf, sort).gen(self): (yield x)
'return True if other refers to the same stat object as self.'
def samefile(self, other):
return (self.strpath == str(other))
'return a string representation (including rev-number)'
def __str__(self):
return self.strpath
'create a modified version of this path. A \'rev\' argument indicates a new revision. the following keyword arguments modify various path parts:: http://host.com/repo/path/file.ext |-----------------------| dirname |------| basename |--| purebasename |--| ext'
def new(self, **kw):
obj = object.__new__(self.__class__) obj.rev = kw.get('rev', self.rev) obj.auth = kw.get('auth', self.auth) (dirname, basename, purebasename, ext) = self._getbyspec('dirname,basename,purebasename,ext') if ('basename' in kw): if (('purebasename' in kw) or ('ext' in kw)): raise Val...
'get specified parts of the path. \'arg\' is a string with comma separated path parts. The parts are returned in exactly the order of the specification. you may specify the following parts: http://host.com/repo/path/file.ext |-----------------------| dirname |------| basename |--| purebasename |--| ext'
def _getbyspec(self, spec):
res = [] parts = self.strpath.split(self.sep) for name in spec.split(','): name = name.strip() if (name == 'dirname'): res.append(self.sep.join(parts[:(-1)])) elif (name == 'basename'): res.append(parts[(-1)]) else: basename = parts[(-1)] ...
'return true if path and rev attributes each match'
def __eq__(self, other):
return ((str(self) == str(other)) and ((self.rev == other.rev) or (self.rev == other.rev)))
'return a new Path (with the same revision) which is composed of the self Path followed by \'args\' path components.'
def join(self, *args):
if (not args): return self args = tuple([arg.strip(self.sep) for arg in args]) parts = ((self.strpath,) + args) newpath = self.__class__(self.sep.join(parts), self.rev, self.auth) return newpath
'return the content of the given property.'
def propget(self, name):
value = self._propget(name) return value
'list all property names.'
def proplist(self):
content = self._proplist() return content
'Return the size of the file content of the Path.'
def size(self):
return self.info().size
'Return the last modification time of the file.'
def mtime(self):
return self.info().mtime
'pickle object into path location'
def dump(self, obj):
return self.localpath.dump(obj)
'return current SvnPath for this WC-item.'
def svnurl(self):
info = self.info() return py.path.svnurl(info.url)
'switch to given URL.'
def switch(self, url):
self._authsvn('switch', [url])
'checkout from url to local wcpath.'
def checkout(self, url=None, rev=None):
args = [] if (url is None): url = self.url if ((rev is None) or (rev == (-1))): if ((py.std.sys.platform != 'win32') and (_getsvnversion() == '1.3')): url += '@HEAD' elif (_getsvnversion() == '1.3'): url += ('@%d' % rev) else: args.append(('-r' + str(rev))...
'update working copy item to given revision. (None -> HEAD).'
def update(self, rev='HEAD', interactive=True):
opts = ['-r', rev] if (not interactive): opts.append('--non-interactive') self._authsvn('up', opts)
'write content into local filesystem wc.'
def write(self, content, mode='w'):
self.localpath.write(content, mode)
'return the directory Path of the current Path.'
def dirpath(self, *args):
return self.__class__(self.localpath.dirpath(*args), auth=self.auth)
'ensure that an args-joined path exists (by default as a file). if you specify a keyword argument \'directory=True\' then the path is forced to be a directory path.'
def ensure(self, *args, **kwargs):
p = self.join(*args) if p.check(): if p.check(versioned=False): p.add() return p if kwargs.get('dir', 0): return p._ensuredirs() parent = p.dirpath() parent._ensuredirs() p.write('') p.add() return p
'create & return the directory joined with args.'
def mkdir(self, *args):
if args: return self.join(*args).mkdir() else: self._svn('mkdir') return self
'add ourself to svn'
def add(self):
self._svn('add')
'remove a file or a directory tree. \'rec\'ursive is ignored and considered always true (because of underlying svn semantics.'
def remove(self, rec=1, force=1):
assert rec, 'svn cannot remove non-recursively' if (not self.check(versioned=True)): py.path.local(self).remove() return flags = [] if force: flags.append('--force') self._svn('remove', *flags)
'copy path to target.'
def copy(self, target):
py.process.cmdexec(('svn copy %s %s' % (str(self), str(target))))
'rename this path to target.'
def rename(self, target):
py.process.cmdexec(('svn move --force %s %s' % (str(self), str(target))))
'set a lock (exclusive) on the resource'
def lock(self):
out = self._authsvn('lock').strip() if (not out): raise ValueError('unknown error in svn lock command')
'unset a previously set lock'
def unlock(self):
out = self._authsvn('unlock').strip() if out.startswith('svn:'): raise Exception(out[4:])
'remove any locks from the resource'
def cleanup(self):
try: self.unlock() except: pass
'return (collective) Status object for this file.'
def status(self, updates=0, rec=0, externals=0):
if externals: raise ValueError('XXX cannot perform status() on external items yet') else: externals = '' if rec: rec = '' else: rec = '--non-recursive' if updates: updates = '-u' else: updates = '' try: cmd = ('stat...
'return a diff of the current path against revision rev (defaulting to the last one).'
def diff(self, rev=None):
args = [] if (rev is not None): args.append(('-r %d' % rev)) out = self._authsvn('diff', args) return out
'return a list of tuples of three elements: (revision, commiter, line)'
def blame(self):
out = self._svn('blame') result = [] blamelines = out.splitlines() reallines = py.path.svnurl(self.url).readlines() for (i, (blameline, line)) in enumerate(zip(blamelines, reallines)): m = rex_blame.match(blameline) if (not m): raise ValueError(('output line %r o...
'commit with support for non-recursive commits'
def commit(self, msg='', rec=1):
cmd = ('commit -m "%s" --force-log' % (msg.replace('"', '\\"'),)) if (not rec): cmd += ' -N' out = self._authsvn(cmd) try: del cache.info[self] except KeyError: pass if out: m = self._rex_commit.match(out) return int(m.group(1))
'set property name to value on this path.'
def propset(self, name, value, *args):
d = py.path.local.mkdtemp() try: p = d.join('value') p.write(value) self._svn('propset', name, '--file', str(p), *args) finally: d.remove()
'get property name on this path.'
def propget(self, name):
res = self._svn('propget', name) return res[:(-1)]
'delete property name on this path.'
def propdel(self, name):
res = self._svn('propdel', name) return res[:(-1)]
'return a mapping of property names to property values. If rec is True, then return a dictionary mapping sub-paths to such mappings.'
def proplist(self, rec=0):
if rec: res = self._svn('proplist -R') return make_recursive_propdict(self, res) else: res = self._svn('proplist') lines = res.split('\n') lines = [x.strip() for x in lines[1:]] return PropListDict(self, lines)
'revert the local changes of this path. if rec is True, do so recursively.'
def revert(self, rec=0):
if rec: result = self._svn('revert -R') else: result = self._svn('revert') return result
'create a modified version of this path. A \'rev\' argument indicates a new revision. the following keyword arguments modify various path parts: http://host.com/repo/path/file.ext |-----------------------| dirname |------| basename |--| purebasename |--| ext'
def new(self, **kw):
if kw: localpath = self.localpath.new(**kw) else: localpath = self.localpath return self.__class__(localpath, auth=self.auth)
'return a new Path (with the same revision) which is composed of the self Path followed by \'args\' path components.'
def join(self, *args, **kwargs):
if (not args): return self localpath = self.localpath.join(*args, **kwargs) return self.__class__(localpath, auth=self.auth)
'return an Info structure with svn-provided information.'
def info(self, usecache=1):
info = (usecache and cache.info.get(self)) if (not info): try: output = self._svn('info') except py.process.cmdexec.Error: e = sys.exc_info()[1] if (e.err.find('Path is not a working copy directory') != (-1)): raise py.error.E...
'return a sequence of Paths. listdir will return either a tuple or a list of paths depending on implementation choices.'
def listdir(self, fil=None, sort=None):
if isinstance(fil, str): fil = common.FNMatcher(fil) def notsvn(path): return (path.basename != '.svn') paths = [] for localpath in self.localpath.listdir(notsvn): p = self.__class__(localpath, auth=self.auth) if (notsvn(p) and ((not fil) or fil(p))): paths.ap...
'return an opened file with the given mode.'
def open(self, mode='r'):
return open(self.strpath, mode)
'return a list of LogEntry instances for this path. rev_start is the starting revision (defaulting to the first one). rev_end is the last revision (defaulting to HEAD). if verbose is True, then the LogEntry instances also know which files changed.'
def log(self, rev_start=None, rev_end=1, verbose=False):
assert self.check() rev_start = (((rev_start is None) and 'HEAD') or rev_start) rev_end = (((rev_end is None) and 'HEAD') or rev_end) if ((rev_start == 'HEAD') and (rev_end == 1)): rev_opt = '' else: rev_opt = ('-r %s:%s' % (rev_start, rev_end)) verbose_opt = ((verbose and '-v...
'Return the size of the file content of the Path.'
def size(self):
return self.info().size
'Return the last modification time of the file.'
def mtime(self):
return self.info().mtime
'return a new WCStatus object from data \'s\''
def fromstring(data, rootwcpath, rev=None, modrev=None, author=None):
rootstatus = WCStatus(rootwcpath, rev, modrev, author) update_rev = None for line in data.split('\n'): if (not line.strip()): continue (flags, rest) = (line[:8], line[8:]) (c0, c1, c2, c3, c4, c5, x6, c7) = flags if (c0 in '?XI'): fn = line.split(None,...
'parse \'data\' (XML string as outputted by svn st) into a status obj'
def fromstring(data, rootwcpath, rev=None, modrev=None, author=None):
rootstatus = WCStatus(rootwcpath, rev, modrev, author) update_rev = None (minidom, ExpatError) = importxml() try: doc = minidom.parseString(data) except ExpatError: e = sys.exc_info()[1] raise ValueError(str(e)) urevels = doc.getElementsByTagName('against') if urevels...
'dispatcher on node\'s class/bases name.'
def visit(self, node):
cls = node.__class__ try: visitmethod = self.cache[cls] except KeyError: for subclass in cls.__mro__: visitmethod = getattr(self, subclass.__name__, None) if (visitmethod is not None): break else: visitmethod = self.__object ...
'return attribute list suitable for styling.'
def getstyle(self, tag):
try: styledict = tag.style.__dict__ except AttributeError: return [] else: stylelist = [((x + ': ') + y) for (x, y) in styledict.items()] return [(u(' style="%s"') % u('; ').join(stylelist))]
'can (and will) be overridden in subclasses'
def _issingleton(self, tagname):
return self.shortempty
'can (and will) be overridden in subclasses'
def _isinline(self, tagname):
return False
'xml-escape the given unicode string.'
def __call__(self, ustring):
try: ustring = unicode(ustring) except UnicodeDecodeError: ustring = unicode(ustring, 'utf-8', errors='replace') return self.charef_rex.sub(self._replacer, ustring)
'Initialize an ordered dictionary. Signature is the same as for regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary.'
def __init__(self, *args, **kwds):
if (len(args) > 1): raise TypeError(('expected at most 1 arguments, got %d' % len(args))) try: self.__root except AttributeError: self.__root = root = [] root[:] = [root, root, None] self.__map = {} self.__update(*args, **kwds)
'od.__setitem__(i, y) <==> od[i]=y'
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
if (key not in self): root = self.__root last = root[0] last[1] = root[0] = self.__map[key] = [last, root, key] dict_setitem(self, key, value)
'od.__delitem__(y) <==> del od[y]'
def __delitem__(self, key, dict_delitem=dict.__delitem__):
dict_delitem(self, key) (link_prev, link_next, key) = self.__map.pop(key) link_prev[1] = link_next link_next[0] = link_prev
'od.__iter__() <==> iter(od)'
def __iter__(self):
root = self.__root curr = root[1] while (curr is not root): (yield curr[2]) curr = curr[1]
'od.__reversed__() <==> reversed(od)'
def __reversed__(self):
root = self.__root curr = root[0] while (curr is not root): (yield curr[2]) curr = curr[0]
'od.clear() -> None. Remove all items from od.'
def clear(self):
try: for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() except AttributeError: pass dict.clear(self)
'od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false.'
def popitem(self, last=True):
if (not self): raise KeyError('dictionary is empty') root = self.__root if last: link = root[0] link_prev = link[0] link_prev[1] = root root[0] = link_prev else: link = root[1] link_next = link[1] root[1] = link_next link_next...
'od.keys() -> list of keys in od'
def keys(self):
return list(self)
'od.values() -> list of values in od'
def values(self):
return [self[key] for key in self]
'od.items() -> list of (key, value) pairs in od'
def items(self):
return [(key, self[key]) for key in self]
'od.iterkeys() -> an iterator over the keys in od'
def iterkeys(self):
return iter(self)
'od.itervalues -> an iterator over the values in od'
def itervalues(self):
for k in self: (yield self[k])
'od.iteritems -> an iterator over the (key, value) items in od'
def iteritems(self):
for k in self: (yield (k, self[k]))
'od.update(E, **F) -> None. Update od from dict/iterable E and F. If E is a dict instance, does: for k in E: od[k] = E[k] If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] Or if E is an iterable of items, does: for k, v in E: od[k] = v In either case, this is followed by: for k, ...
def update(*args, **kwds):
if (len(args) > 2): raise TypeError(('update() takes at most 2 positional arguments (%d given)' % (len(args),))) elif (not args): raise TypeError('update() takes at least 1 argument (0 given)') self = args[0] other = () if (len(args) == 2)...
'od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.'
def pop(self, key, default=__marker):
if (key in self): result = self[key] del self[key] return result if (default is self.__marker): raise KeyError(key) return default