# -*- coding: utf-8 -*- """ Trac Plugin for Monotone Copyright 2006-2008 Thomas Moschny (thomas.moschny@gmx.de) {{{ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA }}} """ import re def add_slash(path): """Prepend a slash. Throughout the this plugin, all paths including the root dir, start with a slash.""" return '/' + path def get_parent(path): """Returns the name of the directory containing path, or None if there is none (because path is '/' or None).""" path = path and path.rstrip('/') return path and (path[0:path.rfind('/')] or '/') or None def get_oldpath(path, renames): """Find out the old name of a path taking into account the renames, which is a dictionary: oldname = renames[newname].""" if path in renames: # simple: path itself changes return renames[path] # one of the parents might have changed it's name parent = get_parent(path) while parent: if parent in renames: oldparent = renames[parent] oldpath = path.replace(parent.rstrip('/'), oldparent.rstrip('/'), 1) return oldpath parent = get_parent(parent) return path def try_int(s): """Try to convert the string s into an integer. Return that integer, or return the string if the conversion fails.""" try: return int(s) except ValueError: return s NATSORT_BIT = re.compile(r'(0|[1-9][0-9]*|[^0-9]+)') def natsort_key(s): """Generate the key for sorting strings naturally.""" return [try_int(w) for w in NATSORT_BIT.findall(s)] def to_unicode(s): """Convert s from utf-8 to unicode, thereby replacing unknown characters with the unicode replace char.""" return unicode(s, "utf-8", "replace") class Memoize(object): """Caches return values of the decorated method.""" def __init__(self, method, get_cache, realm = None): self.method = method self.get_cache = get_cache self.realm = realm or method.__name__ self.cache = None def close(self): if self.cache: self.cache.close() self.cache = None def __call__(self, arg): # Currently, we can only handle one single arg. Moreover, # shelve only supports keys of type integer or string if self.cache: try: return self.cache[arg] except KeyError: # not yet in the cache value = self.method(arg) self.cache[arg] = value return value # oops, no cache yet, get one and restart self.cache = self.get_cache(self.realm) return self.__call__(arg)