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 "%s"' % (self.rev, self._escape(self.strpath))))
'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(self)
'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 any valid base!') if (x == target): if (not x.check(dir=dir)): raise ((dir and py.error.ENOTDIR(x)) or py.error.EISDIR(x)) return x tocreate = target.relto(x) basename = tocreate.split(self.sep, 1)[0] tempdir = py.path.local.mkdtemp() try: tempdir.ensure(tocreate, dir=dir) cmd = ('svn import -m "%s" "%s" "%s"' % (('ensure %s' % self._escape(tocreate)), self._escape(tempdir.join(basename)), x.join(basename)._encodedurl())) self._svncmdexecauth(cmd) self._norev_delentry(x) finally: tempdir.remove() return target
'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:') != (-1)): raise py.error.ENOENT(self, e.err) elif (e.err.find('File not found') != (-1)): raise py.error.ENOENT(self, e.err) elif (e.err.find('not part of a repository') != (-1)): raise py.error.ENOENT(self, e.err) elif (e.err.find('Unable to open') != (-1)): raise py.error.ENOENT(self, e.err) elif (e.err.lower().find('method not allowed') != (-1)): raise py.error.EACCES(self, e.err) raise py.error.Error(e.err) lines = res.split('\n') nameinfo_seq = [] for lsline in lines: if lsline: info = InfoSvnCommand(lsline) if (info._name != '.'): nameinfo_seq.append((info._name, info)) nameinfo_seq.sort() return nameinfo_seq auth = ((self.auth and self.auth.makecmdoptions()) or None) if (self.rev is not None): return self._lsrevcache.getorbuild((self.strpath, self.rev, auth), builder) else: return self._lsnorevcache.getorbuild((self.strpath, auth), builder)
'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 (name, info) in nameinfo_seq] if fil: paths = [x for x in paths if fil(x)] self._sortlist(paths, sort) return paths
'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') or '') xmlpipe = self._svnpopenauth(('svn log --xml %s %s "%s"' % (rev_opt, verbose_opt, self.strpath))) from xml.dom import minidom tree = minidom.parse(xmlpipe) result = [] for logentry in filter(None, tree.firstChild.childNodes): if (logentry.nodeType == logentry.ELEMENT_NODE): result.append(svncommon.LogEntry(logentry)) return result
'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:: path.check(file=1, link=1) # a link pointing to a file'
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 and a \'*\' is prepended to the pattern. if the pattern doesn\'t contain a path-separator the pattern is only matched against the basename.'
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') or (getattr(os, '_name', None) == 'nt')): if os.path.normcase(strself).startswith(os.path.normcase(strrelpath)): return strself[len(strrelpath):] elif strself.startswith(strrelpath): return strself[len(strrelpath):] return ''
'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 = 0 l = ([os.pardir] * n) if reldest: l.append(reldest) target = dest.sep.join(l) return target except AttributeError: return str(dest)
'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 ignoredwhen calling dirlist() on any of the paths (by default, all exceptions are reported) bf if True will cause a breadthfirst search instead of the default depthfirst. Default: False sort if True will sort entries within each directory level.'
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 ValueError(('invalid specification %r' % kw)) else: pb = kw.setdefault('purebasename', purebasename) ext = kw.setdefault('ext', ext) if (ext and (not ext.startswith('.'))): ext = ('.' + ext) kw['basename'] = (pb + ext) kw.setdefault('dirname', dirname) kw.setdefault('sep', self.sep) if kw['basename']: obj.strpath = ('%(dirname)s%(sep)s%(basename)s' % kw) else: obj.strpath = ('%(dirname)s' % kw) return obj
'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)] i = basename.rfind('.') if (i == (-1)): (purebasename, ext) = (basename, '') else: (purebasename, ext) = (basename[:i], basename[i:]) if (name == 'purebasename'): res.append(purebasename) elif (name == 'ext'): res.append(ext) else: raise NameError(("Don't know part %r" % name)) return res
'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))) args.append(url) self._authsvn('co', args)
'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 = ('status -v --xml --no-ignore %s %s %s' % (updates, rec, externals)) out = self._authsvn(cmd) except py.process.cmdexec.Error: cmd = ('status -v --no-ignore %s %s %s' % (updates, rec, externals)) out = self._authsvn(cmd) rootstatus = WCStatus(self).fromstring(out, self) else: rootstatus = XMLWCStatus(self).fromstring(out, self) return rootstatus
'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 of svn blame does not match expected format' % (line,))) (rev, name, _) = m.groups() result.append((int(rev), name, line)) return result
'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.ENOENT(self, e.err) elif (e.err.find('is not under version control') != (-1)): raise py.error.ENOENT(self, e.err) raise if ((output.strip() == '') or (output.lower().find('not a versioned resource') != (-1))): raise py.error.ENOENT(self, output) info = InfoSvnWCCommand(output) if (py.std.sys.platform != 'win32'): if (info.path != self.localpath): raise py.error.ENOENT(self, ('not a versioned resource:' + (' %s != %s' % (info.path, self.localpath)))) cache.info[self] = info return info
'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.append(p) self._sortlist(paths, sort) return paths
'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') or '') locale_env = fixlocale() auth_opt = self._makeauthoptions() cmd = (locale_env + ('svn log --xml %s %s %s "%s"' % (rev_opt, verbose_opt, auth_opt, self.strpath))) popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (stdout, stderr) = popen.communicate() stdout = py.builtin._totext(stdout, sys.getdefaultencoding()) (minidom, ExpatError) = importxml() try: tree = minidom.parseString(stdout) except ExpatError: raise ValueError('no such revision') result = [] for logentry in filter(None, tree.firstChild.childNodes): if (logentry.nodeType == logentry.ELEMENT_NODE): result.append(LogEntry(logentry)) return result
'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, 1)[1] if (c0 == '?'): wcpath = rootwcpath.join(fn, abs=1) rootstatus.unknown.append(wcpath) elif (c0 == 'X'): wcpath = rootwcpath.__class__(rootwcpath.localpath.join(fn, abs=1), auth=rootwcpath.auth) rootstatus.external.append(wcpath) elif (c0 == 'I'): wcpath = rootwcpath.join(fn, abs=1) rootstatus.ignored.append(wcpath) continue m = WCStatus._rex_status.match(rest) if (not m): if (c7 == '*'): fn = rest.strip() wcpath = rootwcpath.join(fn, abs=1) rootstatus.update_available.append(wcpath) continue if (line.lower().find('against revision:') != (-1)): update_rev = int(rest.split(':')[1].strip()) continue if (line.lower().find('status on external') > (-1)): continue raise ValueError(('could not parse line %r' % line)) else: (rev, modrev, author, fn) = m.groups() wcpath = rootwcpath.join(fn, abs=1) if (c0 == 'M'): assert wcpath.check(file=1), "didn't expect a directory with changed content here" rootstatus.modified.append(wcpath) elif ((c0 == 'A') or (c3 == '+')): rootstatus.added.append(wcpath) elif (c0 == 'D'): rootstatus.deleted.append(wcpath) elif (c0 == 'C'): rootstatus.conflict.append(wcpath) elif (c0 == '~'): rootstatus.kindmismatch.append(wcpath) elif (c0 == '!'): rootstatus.incomplete.append(wcpath) elif (c0 == 'R'): rootstatus.replaced.append(wcpath) elif (not c0.strip()): rootstatus.unchanged.append(wcpath) else: raise NotImplementedError(('received flag %r' % c0)) if (c1 == 'M'): rootstatus.prop_modified.append(wcpath) if ((c2 == 'L') or (c5 == 'K')): rootstatus.locked.append(wcpath) if (c7 == '*'): rootstatus.update_available.append(wcpath) if (wcpath == rootwcpath): rootstatus.rev = rev rootstatus.modrev = modrev rootstatus.author = author if update_rev: rootstatus.update_rev = update_rev continue return rootstatus
'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: rootstatus.update_rev = urevels[(-1)].getAttribute('revision') for entryel in doc.getElementsByTagName('entry'): path = entryel.getAttribute('path') statusel = entryel.getElementsByTagName('wc-status')[0] itemstatus = statusel.getAttribute('item') if (itemstatus == 'unversioned'): wcpath = rootwcpath.join(path, abs=1) rootstatus.unknown.append(wcpath) continue elif (itemstatus == 'external'): wcpath = rootwcpath.__class__(rootwcpath.localpath.join(path, abs=1), auth=rootwcpath.auth) rootstatus.external.append(wcpath) continue elif (itemstatus == 'ignored'): wcpath = rootwcpath.join(path, abs=1) rootstatus.ignored.append(wcpath) continue elif (itemstatus == 'incomplete'): wcpath = rootwcpath.join(path, abs=1) rootstatus.incomplete.append(wcpath) continue rev = statusel.getAttribute('revision') if ((itemstatus == 'added') or (itemstatus == 'none')): rev = '0' modrev = '?' author = '?' date = '' elif (itemstatus == 'replaced'): pass else: commitel = entryel.getElementsByTagName('commit')[0] if commitel: modrev = commitel.getAttribute('revision') author = '' author_els = commitel.getElementsByTagName('author') if author_els: for c in author_els[0].childNodes: author += c.nodeValue date = '' for c in commitel.getElementsByTagName('date')[0].childNodes: date += c.nodeValue wcpath = rootwcpath.join(path, abs=1) assert ((itemstatus != 'modified') or wcpath.check(file=1)), "did't expect a directory with changed content here" itemattrname = {'normal': 'unchanged', 'unversioned': 'unknown', 'conflicted': 'conflict', 'none': 'added'}.get(itemstatus, itemstatus) attr = getattr(rootstatus, itemattrname) attr.append(wcpath) propsstatus = statusel.getAttribute('props') if (propsstatus not in ('none', 'normal')): rootstatus.prop_modified.append(wcpath) if (wcpath == rootwcpath): rootstatus.rev = rev rootstatus.modrev = modrev rootstatus.author = author rootstatus.date = date rstatusels = entryel.getElementsByTagName('repos-status') if rstatusels: rstatusel = rstatusels[0] ritemstatus = rstatusel.getAttribute('item') if (ritemstatus in ('added', 'modified')): rootstatus.update_available.append(wcpath) lockels = entryel.getElementsByTagName('lock') if len(lockels): rootstatus.locked.append(wcpath) return rootstatus
'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 self.cache[cls] = visitmethod visitmethod(node)
'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[0] = root key = link[2] del self.__map[key] value = dict.pop(self, key) return (key, value)
'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, v in F.items(): od[k] = v'
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): other = args[1] if isinstance(other, dict): for key in other: self[key] = other[key] elif hasattr(other, 'keys'): for key in other.keys(): self[key] = other[key] else: for (key, value) in other: self[key] = value for (key, value) in kwds.items(): self[key] = value
'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