diff options
author | Nicolas Chauvat <nicolas.chauvat@logilab.fr> | 2009-07-19 02:07:55 +0200 |
---|---|---|
committer | Nicolas Chauvat <nicolas.chauvat@logilab.fr> | 2009-07-19 02:07:55 +0200 |
commit | a1cdde3320add8bbe4557639488bb4d2ef2861fd (patch) | |
tree | f579949c7a7fb9b4efb8a6ccdfcd35484854662b | |
parent | 6bb5a230a8df5ed2fe417c7b85491073da50dfd3 (diff) | |
download | logilab-common-a1cdde3320add8bbe4557639488bb4d2ef2861fd.tar.gz |
[cleanup] delete-trailing-whitespace
-rw-r--r-- | astutils.py | 4 | ||||
-rw-r--r-- | bind.py | 14 | ||||
-rw-r--r-- | cache.py | 14 | ||||
-rw-r--r-- | changelog.py | 28 | ||||
-rw-r--r-- | clcommands.py | 12 | ||||
-rw-r--r-- | cli.py | 24 | ||||
-rw-r--r-- | contexts.py | 4 | ||||
-rw-r--r-- | corbautils.py | 6 | ||||
-rw-r--r-- | daemon.py | 4 | ||||
-rw-r--r-- | debugger.py | 16 | ||||
-rw-r--r-- | fileutils.py | 36 | ||||
-rw-r--r-- | graph.py | 12 | ||||
-rw-r--r-- | html.py | 2 | ||||
-rw-r--r-- | logger.py | 12 | ||||
-rw-r--r-- | monclient.py | 8 | ||||
-rw-r--r-- | monserver.py | 4 | ||||
-rw-r--r-- | optik_ext.py | 46 | ||||
-rw-r--r-- | optparser.py | 8 | ||||
-rw-r--r-- | patricia.py | 20 | ||||
-rw-r--r-- | pdf_ext.py | 12 | ||||
-rw-r--r-- | proc.py | 16 | ||||
-rw-r--r-- | pytest.py | 40 | ||||
-rw-r--r-- | setup.py | 10 | ||||
-rw-r--r-- | shellutils.py | 8 | ||||
-rw-r--r-- | sqlgen.py | 10 | ||||
-rw-r--r-- | table.py | 140 | ||||
-rw-r--r-- | tasksqueue.py | 6 | ||||
-rw-r--r-- | testlib.py | 136 | ||||
-rw-r--r-- | textutils.py | 26 | ||||
-rw-r--r-- | tree.py | 36 | ||||
-rw-r--r-- | twisted_distutils.py | 14 | ||||
-rw-r--r-- | vcgutils.py | 10 | ||||
-rw-r--r-- | visitor.py | 12 | ||||
-rw-r--r-- | xmlrpcutils.py | 22 |
34 files changed, 386 insertions, 386 deletions
diff --git a/astutils.py b/astutils.py index 4c2b4b6..88a0ea1 100644 --- a/astutils.py +++ b/astutils.py @@ -22,7 +22,7 @@ def debuild(ast_tuple): """ if type(ast_tuple[1]) is TupleType: result = '' - for child in ast_tuple[1:]: + for child in ast_tuple[1:]: result = '%s%s' % (result, debuild(child)) return result else: @@ -55,7 +55,7 @@ def _clean(ast_tuple): return v else: return [list(ast_tuple[:2])] - + def cvrtr(tuple): """debug method returning an ast string in a readable fashion""" if type(tuple) is TupleType: @@ -32,7 +32,7 @@ def bind_code(co, globals): """ consts = list(co.co_consts) assigned = {} - + code = co.co_code new_code = "" n = len(code) @@ -60,7 +60,7 @@ def bind_code(co, globals): if oparg is not None: new_code += chr(oparg & 255) new_code += chr( (oparg>>8) & 255 ) - + return make_code(co.co_argcount, co.co_nlocals, co.co_stacksize, @@ -86,7 +86,7 @@ if type(__builtins__) == dict: builtins = __builtins__ else: builtins = __builtins__.__dict__ - + bind_code_opt = bind(bind_code, builtins ) bind_code_opt = bind(bind_code_opt, globals() ) @@ -105,7 +105,7 @@ def optimize_module(m, global_consts): if d: f = bind(f, d) m.__dict__[name] = f - + @@ -187,7 +187,7 @@ def rewrite_code(co, consts_dict, consts_tuple): if oparg is not None: new_code += chr(oparg & 255) new_code += chr( (oparg>>8) & 255 ) - + return make_code(co.co_argcount, co.co_nlocals, co.co_stacksize, @@ -228,7 +228,7 @@ def optimize_module_2(m, globals_consts, bind_builtins=1): defaults = f.func_defaults or () m.__dict__[name] = make_function(newcode, f.func_globals, f.func_name, defaults) - + def run_bench(n): from time import time @@ -245,7 +245,7 @@ def run_bench(n): print "1 regular version", t1 print "2 optimized version", t2 print "ratio (1-2)/1 : %f %%" % (100.*(t1-t2)/t1) - + def test_pystone(): from test import pystone @@ -20,7 +20,7 @@ class Cache(dict): len(self._usage) <= self.size len(self.data) <= self.size """ - + def __init__(self, size=100): """ Warning : Cache.__init__() != dict.__init__(). Constructor does not take any arguments beside size. @@ -30,7 +30,7 @@ class Cache(dict): self._usage = [] self._lock = Lock() super(Cache, self).__init__() - + def _acquire(self): self._lock.acquire() @@ -39,7 +39,7 @@ class Cache(dict): def _update_usage(self, key): if not self._usage: - self._usage.append(key) + self._usage.append(key) elif self._usage[-1] != key: try: self._usage.remove(key) @@ -53,25 +53,25 @@ class Cache(dict): self._usage.append(key) else: pass # key is already the most recently used key - + def __getitem__(self, key): value = super(Cache, self).__getitem__(key) self._update_usage(key) return value __getitem__ = locked(_acquire, _release)(__getitem__) - + def __setitem__(self, key, item): # Just make sure that size > 0 before inserting a new item in the cache if self.size > 0: super(Cache, self).__setitem__(key, item) self._update_usage(key) __setitem__ = locked(_acquire, _release)(__setitem__) - + def __delitem__(self, key): super(Cache, self).__delitem__(key) self._usage.remove(key) __delitem__ = locked(_acquire, _release)(__delitem__) - + def clear(self): super(Cache, self).clear() self._usage = [] diff --git a/changelog.py b/changelog.py index 45c4090..7994a58 100644 --- a/changelog.py +++ b/changelog.py @@ -7,17 +7,17 @@ Sample ChangeLog format:: Change log for project Yoo ========================== - + -- * add a new functionnality 2002-02-01 -- 0.1.1 * fix bug #435454 * fix bug #434356 - + 2002-01-01 -- 0.1 * initial release - + There is 3 entries in this change log, one for each released version and one for the next version (i.e. the current entry). @@ -59,7 +59,7 @@ class Version(tuple): else: parsed = versionstr return tuple.__new__(klass, parsed) - + def __str__(self): return '.'.join([str(i) for i in self]) @@ -70,7 +70,7 @@ class ChangeLogEntry(object): its release date """ version_class = Version - + def __init__(self, date=None, version=None, **kwargs): self.__dict__.update(kwargs) if version: @@ -79,7 +79,7 @@ class ChangeLogEntry(object): self.version = None self.date = date self.messages = [] - + def add_message(self, msg): """add a new message""" self.messages.append(([msg],[])) @@ -119,9 +119,9 @@ class ChangeLogEntry(object): class ChangeLog(object): """object representation of a whole ChangeLog file""" - + entry_class = ChangeLogEntry - + def __init__(self, changelog_file, title=''): self.file = changelog_file self.title = title @@ -132,14 +132,14 @@ class ChangeLog(object): def __repr__(self): return '<ChangeLog %s at %s (%s entries)>' % (self.file, id(self), len(self.entries)) - + def add_entry(self, entry): """add a new entry to the change log""" self.entries.append(entry) def get_entry(self, version='', create=None): """ return a given changelog entry - if version is omited, return the current entry + if version is omited, return the current entry """ if not self.entries: if version or not create: @@ -159,7 +159,7 @@ class ChangeLog(object): """add a new message to the latest opened entry""" entry = self.get_entry(create=create) entry.add_message(msg) - + def load(self): """ read a logilab's ChangeLog from file """ try: @@ -198,17 +198,17 @@ class ChangeLog(object): expect_sub = True self.additional_content += line stream.close() - + def format_title(self): return '%s\n\n' % self.title.strip() - + def save(self): """write back change log""" # filetutils isn't importable in appengine, so import locally from logilab.common.fileutils import ensure_fs_mode ensure_fs_mode(self.file, S_IWRITE) self.write(open(self.file, 'w')) - + def write(self, stream=sys.stdout): """write changelog to stream""" stream.write(self.format_title()) diff --git a/clcommands.py b/clcommands.py index 8e30c0b..9f722b0 100644 --- a/clcommands.py +++ b/clcommands.py @@ -10,7 +10,7 @@ command'specific """ __docformat__ = "restructuredtext en" -# XXX : merge with optparser ? +# XXX : merge with optparser ? import sys from os.path import basename @@ -55,7 +55,7 @@ class Command(Configuration): raise BadCommandUsage('missing argument') if self.max_args is not None and len(args) > self.max_args: raise BadCommandUsage('too many arguments') - + def run(self, args): """run the command with its specific arguments""" raise NotImplementedError() @@ -123,7 +123,7 @@ def cmd_run(cmdname, *args): print 'ERROR: ', err print command.help() - + def main_run(args, doc=DEFAULT_DOC): """command line tool""" try: @@ -142,9 +142,9 @@ def main_run(args, doc=DEFAULT_DOC): class ListCommandsCommand(Command): """list available commands, useful for bash completion.""" name = 'listcommands' - arguments = '[command]' + arguments = '[command]' hidden = True - + def run(self, args): """run the command with its specific arguments""" if args: @@ -160,5 +160,5 @@ class ListCommandsCommand(Command): cmd = _COMMANDS[command] if not cmd.hidden: print command - + register_commands([ListCommandsCommand]) @@ -1,5 +1,5 @@ """Command line interface helper classes. - + It provides some default commands, a help system, a default readline configuration with completion and persistent history. @@ -33,7 +33,7 @@ __docformat__ = "restructuredtext en" import __builtin__ if not hasattr(__builtin__, '_'): __builtin__._ = str - + def init_readline(complete_method, histfile=None): """Init the readline library if available.""" @@ -56,10 +56,10 @@ def init_readline(complete_method, histfile=None): class Completer : """Readline completer.""" - + def __init__(self, commands): self.list = commands - + def complete(self, text, state): """Hook called by readline when <tab> is pressed.""" n = len(text) @@ -77,12 +77,12 @@ class CLIHelper: """An abstract command line interface client which recognize commands and provide an help system. """ - + CMD_MAP = {'help' : _("Others"), 'quit' : _("Others"), } CMD_PREFIX = '' - + def __init__(self, histfile=None) : self._topics = {} self.commands = None @@ -95,7 +95,7 @@ class CLIHelper: try: line = raw_input('>>> ') except EOFError: - print + print break s_line = line.strip() if not s_line: @@ -125,7 +125,7 @@ class CLIHelper: # private methods ######################################################### - + def _register_commands(self): """ register available commands method and return the list of commands name @@ -149,7 +149,7 @@ class CLIHelper: # predefined commands ##################################################### - + def do_help(self, command=None) : """base input of the help system""" if command in self._command_help: @@ -167,7 +167,7 @@ class CLIHelper: commands.sort() for command in commands: print '\t', command[len(self.CMD_PREFIX):] - + else: print _('Available commands about %s:') % command print @@ -182,7 +182,7 @@ class CLIHelper: traceback.print_exc() print 'ERROR in help method %s'% ( command_help_method.func_name) - + help_do_help = ("help", "help [topic|command]", _("print help message for the given topic/command or \ available topics when no argument")) @@ -190,6 +190,6 @@ available topics when no argument")) def do_quit(self): """quit the CLI""" raise EOFError() - + def help_do_quit(self): return ("quit", "quit", _("quit the application")) diff --git a/contexts.py b/contexts.py index d88abfb..d44b339 100644 --- a/contexts.py +++ b/contexts.py @@ -1,4 +1,4 @@ -"""A few useful context managers +"""A few useful context managers :copyright: 2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved. :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr @@ -30,7 +30,7 @@ class tempdir(object): class pushd(object): def __init__(self, directory): self.directory = directory - + def __enter__(self): self.cwd = os.getcwd() os.chdir(self.directory) diff --git a/corbautils.py b/corbautils.py index 53963f3..02ba570 100644 --- a/corbautils.py +++ b/corbautils.py @@ -17,7 +17,7 @@ def get_orb(): The first call to the method initialized the ORB This method is mainly used internally in the module. """ - + global orb if orb is None: import sys @@ -29,7 +29,7 @@ def get_root_context(): returns a reference to the NameService object. This method is mainly used internally in the module. """ - + orb = get_orb() nss = orb.resolve_initial_references("NameService") rootContext = nss._narrow(CosNaming.NamingContext) @@ -47,7 +47,7 @@ def register_object_name(object, namepath): [('logilab','rootmodule'),('chatbot','application'),('chatter','server')] is mapped to 'corbaname::hostname#logilab.rootmodule/chatbot.application/chatter.server' - + The get_object_reference() function can be used to resolve such a URL. """ context = get_root_context() @@ -103,7 +103,7 @@ If it i not the case, remove the file %s''' % (self.name, self._pid_file)) def _run(self): """should be overidden in the mixed class""" raise NotImplementedError() - + ## command line utilities ###################################################### L_OPTIONS = ["help", "log=", "delay=", 'no-detach'] @@ -120,7 +120,7 @@ def print_help(modconfig): Defaults to %s""" % (modconfig.LOG_TRESHOLD, modconfig.DELAY) def handle_option(modconfig, opt_name, opt_value, help_meth): - if opt_name in ('-h','--help'): + if opt_name in ('-h','--help'): help_meth() sys.exit(0) elif opt_name in ('-l','--log'): diff --git a/debugger.py b/debugger.py index e401a0f..567c738 100644 --- a/debugger.py +++ b/debugger.py @@ -44,7 +44,7 @@ else: if lineno == curlineno: annotated.append('%4s\t->\t%s' % (lineno, line)) else: - annotated.append('%4s\t\t%s' % (lineno, line)) + annotated.append('%4s\t\t%s' % (lineno, line)) return '\n'.join(annotated) def colorize_source(source): @@ -53,7 +53,7 @@ else: output = StringIO() parser.format(source, output) return output.getvalue() - + def getsource(obj): """Return the text of the source code for an object. @@ -68,7 +68,7 @@ def getsource(obj): ################################################################ class Debugger(Pdb): """custom debugger - + - sets up a history file - uses ipython if available to colorize lines of code - overrides list command to search for current block instead @@ -81,7 +81,7 @@ class Debugger(Pdb): tcbk = tcbk.tb_next self._tcbk = tcbk self._histfile = osp.join(os.environ["HOME"], ".pdbhist") - + def setup_history_file(self): """if readline is available, read pdb history file """ @@ -144,7 +144,7 @@ class Debugger(Pdb): if word[:n] == attr and word != "__builtins__": matches.append("%s.%s" % (expr, word)) return matches - + def get_class_members(self, klass): """implementation coming from rlcompleter.get_class_members""" ret = dir(klass) @@ -152,8 +152,8 @@ class Debugger(Pdb): for base in klass.__bases__: ret = ret + self.get_class_members(base) return ret - - ## specific / overidden commands + + ## specific / overidden commands def do_list(self, arg): """overrides default list command to display the surrounding block instead of 5 lines of context @@ -178,7 +178,7 @@ class Debugger(Pdb): lineno = self.curframe.f_lineno cmd = 'emacsclient --no-wait +%s %s' % (lineno, filename) os.system(cmd) - + do_o = do_open diff --git a/fileutils.py b/fileutils.py index 6f441ec..a2afbc5 100644 --- a/fileutils.py +++ b/fileutils.py @@ -26,7 +26,7 @@ from logilab.common.shellutils import find def first_level_directory(path): """Return the first level directory of a path. - + >>> first_level_directory('home/syt/work') 'home' >>> first_level_directory('/home/syt/work') @@ -53,14 +53,14 @@ def abspath_listdir(path): """Lists path's content using absolute paths. >>> os.listdir('/home') - ['adim', 'alf', 'arthur', 'auc'] + ['adim', 'alf', 'arthur', 'auc'] >>> abspath_listdir('/home') ['/home/adim', '/home/alf', '/home/arthur', '/home/auc'] """ path = abspath(path) return [join(path, filename) for filename in listdir(path)] - + def is_binary(filename): """Return true if filename may be a binary file, according to it's extension. @@ -86,7 +86,7 @@ def write_open_mode(filename): :param filename: the name of the file :rtype: str - :return: the mode that should be use to open the file ('w' or 'wb') + :return: the mode that should be use to open the file ('w' or 'wb') """ if is_binary(filename): return 'wb' @@ -108,7 +108,7 @@ def ensure_fs_mode(filepath, desired_mode=S_IWRITE): mode = stat(filepath)[ST_MODE] if not mode & desired_mode: chmod(filepath, mode | desired_mode) - + class ProtectedFile(file): """A special file-object class that automatically that automatically @@ -118,15 +118,15 @@ class ProtectedFile(file): created during the ProtectedFile object lifetime. One way to circumvent this would be to chmod / unchmod on each write operation. - + One other way would be to : - + - catch the IOError in the __init__ - + - if IOError, then create a StringIO object - + - each write operation writes in this StringIO obejct - + - on close()/del(), write/append the StringIO content to the file and do the chmod only once """ @@ -145,7 +145,7 @@ class ProtectedFile(file): chmod(self.name, self.original_mode) # Don't re-chmod in case of several restore self.mode_changed = False - + def close(self): """restore mode before closing""" self._restore_mode() @@ -166,10 +166,10 @@ def relative_path(from_file, to_file): (path will be absolute if to_file is an absolute file). This function is useful to create link in `from_file` to `to_file`. This typical use case is used in this function description. - + If both files are relative, they're expected to be relative to the same directory. - + >>> relative_path( from_file='toto/index.html', to_file='index.html') '../index.html' >>> relative_path( from_file='index.html', to_file='toto/index.html') @@ -195,12 +195,12 @@ def relative_path(from_file, to_file): :type from_file: str :param from_file: source file (where links will be inserted) - + :type to_file: str :param to_file: target file (on which links point) :raise UnresolvableError: if it has been unable to guess a correct path - + :rtype: str :return: the relative path of `to_file` from `from_file` """ @@ -260,7 +260,7 @@ def norm_open(path): return open(path, 'U') return StringIO(_LINE_RGX.sub('\n', open(path).read())) - + def lines(path, comments=None): """Return a list of non empty lines in the file located at `path`. @@ -324,7 +324,7 @@ def export(from_dir, to_dir, :type from_dir: str :param from_dir: directory to export - + :type to_dir: str :param to_dir: destination directory @@ -412,7 +412,7 @@ def files_by_ext(directory, include_exts=None, exclude_exts=None, :type include_exts: list or tuple or None :param include_exts: list of file extensions to consider - + :type exclude_exts: list or tuple or None :param exclude_exts: list of file extensions to ignore @@ -59,13 +59,13 @@ class DotBackend: return self._source source = property(get_source) - + def generate(self, outputfile=None, dotfile=None): """Generates a graph file. - + :param outputfile: filename and path [defaults to graphname.png] :param dotfile: filename and path [defaults to graphname.dot] - + :rtype: str :return: a path to the generated file """ @@ -93,7 +93,7 @@ class DotBackend: pdot.write(self.source) pdot.close() if target != 'dot': - os.system('%s -T%s %s -o%s' % (self.renderer, target, + os.system('%s -T%s %s -o%s' % (self.renderer, target, dot_sourcepath, outputfile)) os.unlink(dot_sourcepath) return outputfile @@ -127,7 +127,7 @@ class GraphGenerator: self.backend = backend def generate(self, visitor, propshdlr, outputfile=None): - # the visitor + # the visitor # the property handler is used to get node and edge properties # according to the graph and to the backend self.propshdlr = propshdlr @@ -182,7 +182,7 @@ def _get_cycles(graph_dict, vertice=None, path=None, result=None): def has_path(graph_dict, fromnode, tonode, path=None): """generic function taking a simple graph definition as a dictionary, with node has key associated to a list of nodes directly reachable from it. - + Return None if no path exists to go from `fromnode` to `tonode`, else the first path found """ @@ -11,7 +11,7 @@ warn('html module is deprecated and will disappear in a near release', DeprecationWarning, stacklevel=2) import traceback -from xml.sax.saxutils import escape +from xml.sax.saxutils import escape # mk html traceback error ##################################################### @@ -34,7 +34,7 @@ INDICATORS = ['emergency', 'alert', 'critical', 'error', def make_logger(method='print', threshold=LOG_DEBUG, sid=None, output=None): """return a logger for the given method - + known methods are 'print', 'eprint' and syslog' """ if method == 'print': @@ -63,7 +63,7 @@ class AbstractLogger: def __init__(self, threshold=LOG_DEBUG, priority_indicator=1): self.threshold = threshold self.priority_indicator = priority_indicator - + def log(self, priority=LOG_DEBUG, message='', substs=None): """log a message with priority <priority> substs are optional substrings @@ -98,7 +98,7 @@ class AbstractLogger: l.append(str(e_type) + ': ' + value.__str__()) except UnicodeError: l.append(str(e_type) + ' (message can\'t be displayed)') - + self.log(priority, '\n'.join(l)) @@ -107,14 +107,14 @@ class PrintLogger(AbstractLogger): log everything to a file, using the standard output by default """ - + def __init__(self, threshold, output=sys.stdout, sid=None, encoding='UTF-8'): AbstractLogger.__init__(self, threshold) self.output = output self.sid = sid self.encoding = encoding - + def _writelog(self, priority, message): """overridden from AbstractLogger""" if isinstance(message, unicode): @@ -140,7 +140,7 @@ class SysLogger(AbstractLogger): sid = 'syslog' self.encoding = encoding syslog.openlog(sid, syslog.LOG_PID) - + def _writelog(self, priority, message): """overridden from AbstractLogger""" import syslog diff --git a/monclient.py b/monclient.py index 6de0d28..6124db4 100644 --- a/monclient.py +++ b/monclient.py @@ -23,7 +23,7 @@ class SocketPrinter(threading.Thread): threading.Thread.__init__(self) self.socket = sock self.stop = False - + def run(self): """prints socket input indefinitely""" fd = self.socket.fileno() @@ -35,7 +35,7 @@ class SocketPrinter(threading.Thread): if data: sys.stdout.write(data) sys.stdout.flush() - + def client( host, port ): @@ -64,5 +64,5 @@ if __name__ == "__main__": server_port = int(sys.argv[2]) client(server_host, server_port) - - + + diff --git a/monserver.py b/monserver.py index 26fe959..6fcdebf 100644 --- a/monserver.py +++ b/monserver.py @@ -56,7 +56,7 @@ class MonitorInterpreter(code.InteractiveConsole): elif line.endswith("\n"): line = line[:-1] return line - + class MonitorRequestHandler(SocketServer.BaseRequestHandler): """Request handler for remote interpreter""" @@ -67,7 +67,7 @@ class MonitorRequestHandler(SocketServer.BaseRequestHandler): self.rfile = request.makefile("r") SocketServer.BaseRequestHandler.__init__(self, request, clientaddress, server ) - + def handle(self): """handle on request, through MonitorInterpreter""" saved_stdout = sys.stdout diff --git a/optik_ext.py b/optik_ext.py index 01537ee..70fe6d9 100644 --- a/optik_ext.py +++ b/optik_ext.py @@ -45,7 +45,7 @@ try: # python >= 2.3 from optparse import OptionParser as BaseParser, Option as BaseOption, \ OptionGroup, OptionValueError, OptionError, Values, HelpFormatter, \ - NO_DEFAULT, SUPPRESS_HELP + NO_DEFAULT, SUPPRESS_HELP except ImportError: # python < 2.3 from optik import OptionParser as BaseParser, Option as BaseOption, \ @@ -82,7 +82,7 @@ def check_regexp(option, opt, value): except ValueError: raise OptionValueError( "option %s: invalid regexp value: %r" % (opt, value)) - + def check_csv(option, opt, value): """check a csv value by trying to split it return the list of separated values @@ -174,7 +174,7 @@ def check_time(option, opt, value): def check_bytes(option, opt, value): from logilab.common.textutils import BYTE_UNITS, apply_units apply_units(value, BYTE_UNITS) - + import types class Option(BaseOption): @@ -202,7 +202,7 @@ class Option(BaseOption): def __init__(self, *opts, **attrs): BaseOption.__init__(self, *opts, **attrs) if hasattr(self, "hide") and self.hide: - self.help = SUPPRESS_HELP + self.help = SUPPRESS_HELP def _check_choice(self): """FIXME: need to override this due to optik misdesign""" @@ -237,7 +237,7 @@ class Option(BaseOption): # subclasses to add new actions. return self.take_action( self.action, self.dest, opt, value, values, parser) - + class OptionParser(BaseParser): """override optik.OptionParser to use our Option class """ @@ -268,7 +268,7 @@ class ManHelpFormatter(HelpFormatter): except AttributeError: optstring = self.format_option_strings(option) if option.help: - help_text = self.expand_default(option) + help_text = self.expand_default(option) help = ' '.join([l.strip() for l in help_text.splitlines()]) else: help = '' @@ -293,10 +293,10 @@ class ManHelpFormatter(HelpFormatter): def format_short_description(self, pgm, short_desc): return '''.SH NAME -.B %s +.B %s \- %s ''' % (pgm, short_desc.strip()) - + def format_synopsis(self, pgm): return '''.SH SYNOPSIS .B %s @@ -306,7 +306,7 @@ class ManHelpFormatter(HelpFormatter): .I <arguments> ] ''' % pgm - + def format_long_description(self, pgm, long_desc): long_desc = '\n'.join([line.lstrip() for line in long_desc.splitlines()]) @@ -314,32 +314,32 @@ class ManHelpFormatter(HelpFormatter): if long_desc.lower().startswith(pgm): long_desc = long_desc[len(pgm):] return '''.SH DESCRIPTION -.B %s +.B %s %s ''' % (pgm, long_desc.strip()) - + def format_tail(self, pkginfo): return '''.SH SEE ALSO /usr/share/doc/pythonX.Y-%s/ -.SH COPYRIGHT +.SH COPYRIGHT %s -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, +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 +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, +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. -.SH BUGS +.SH BUGS Please report bugs on the project\'s mailing list: %s @@ -357,6 +357,6 @@ def generate_manpage(optparser, pkginfo, section=1, stream=sys.stdout): print >> stream, optparser.format_option_help(formatter) print >> stream, formatter.format_tail(pkginfo) - + __all__ = ('OptionParser', 'Option', 'OptionGroup', 'OptionValueError', 'Values') diff --git a/optparser.py b/optparser.py index 0b10124..2602a3c 100644 --- a/optparser.py +++ b/optparser.py @@ -18,7 +18,7 @@ With mymod.build that defines two functions run and add_options """ __docformat__ = "restructuredtext en" -# XXX merge with optik_ext ? merge with clcommands ? +# XXX merge with optik_ext ? merge with clcommands ? import sys import optparse @@ -29,7 +29,7 @@ class OptionParser(optparse.OptionParser): optparse.OptionParser.__init__(self, *args, **kwargs) self._commands = {} self.min_args, self.max_args = 0, 1 - + def add_command(self, name, mod_or_funcs, help=''): """name of the command name of module or tuple of functions (run, add_options) @@ -43,7 +43,7 @@ class OptionParser(optparse.OptionParser): print '\ncommands:' for cmdname, (_, help) in self._commands.items(): print '% 10s - %s' % (cmdname, help) - + def parse_command(self, args): if len(args) == 0: self.print_main_help() @@ -67,7 +67,7 @@ class OptionParser(optparse.OptionParser): else: run, add_options = mod_or_f add_options(self) - (options, args) = self.parse_args(args) + (options, args) = self.parse_args(args) if not (self.min_args <= len(args) <= self.max_args): self.error('incorrect number of arguments') return run, options, args diff --git a/patricia.py b/patricia.py index cf34a8e..65805f9 100644 --- a/patricia.py +++ b/patricia.py @@ -40,7 +40,7 @@ def split(index, string): class PatriciaNode: """a PATRICIA trie node """ - + def __init__(self, value='', leaf=0, data=None): self.value = value self.edges = {} @@ -48,7 +48,7 @@ class PatriciaNode: self.datas = [data] else: self.datas = [] - + def insert(self, string, data): """ insert the string in the trie and associate data to it if the string exists is the trie, data is added to the existing datas @@ -86,12 +86,12 @@ class PatriciaNode: datas = self.datas self.datas = [] return datas - else: + else: pfx, e, sfx = split(len(self.value), string) if self.value == pfx: return self.edges[e].remove(sfx) raise KeyError(string) - + def lookup(self, string): """ return datas associated with string raise KeyError if the key isn't found @@ -100,12 +100,12 @@ class PatriciaNode: if self.datas: return self.datas raise KeyError(string) - else: # len(self.value) < len(string): + else: # len(self.value) < len(string): pfx, e, sfx = split(len(self.value), string) if self.value == pfx: return self.edges[e].lookup(sfx) raise KeyError(string) - + def pfx_search(self, pfx, depth=-1): """ return all string with prefix pfx """ sfxs = [] @@ -124,7 +124,7 @@ class PatriciaNode: if self.datas: sfxs.append(self.value) return sfxs - + def __str__(self, indent=''): node_str = ''.join([' %s%s:\n%s' % (indent, key, a.__str__(' %s' % indent)) @@ -140,7 +140,7 @@ class PatriciaTrie: """ wrapper class for a patricia tree delegates to the root of the tree (PatriciaNode) """ - + def __init__(self): self._trie = None self.words = 0 @@ -152,7 +152,7 @@ class PatriciaTrie: self._trie = PatriciaNode(string, 1, data) else: self._trie = self._trie.insert(string, data) - + def remove(self, string): """ remove a string from the tree """ if self._trie is not None: @@ -173,6 +173,6 @@ class PatriciaTrie: def __str__(self): return self._trie.__str__() - + def __repr__(self): return '<PatriciaTrie id=%s words=%s>' % (id(self), self.words) @@ -1,6 +1,6 @@ """Manipulate pdf and fdf files (pdftk recommended). -Notes regarding pdftk, pdf forms and fdf files (form definition file) +Notes regarding pdftk, pdf forms and fdf files (form definition file) fields names can be extracted with: pdftk orig.pdf generate_fdf output truc.fdf @@ -8,7 +8,7 @@ fields names can be extracted with: to merge fdf and pdf: pdftk orig.pdf fill_form test.fdf output result.pdf [flatten] - + without flatten, one could further edit the resulting form. with flatten, everything is turned into text. @@ -18,16 +18,16 @@ with flatten, everything is turned into text. """ __docformat__ = "restructuredtext en" # XXX seems very unix specific -# TODO: check availability of pdftk at import +# TODO: check availability of pdftk at import import os HEAD="""%FDF-1.2 %\xE2\xE3\xCF\xD3 -1 0 obj +1 0 obj << -/FDF +/FDF << /Fields [ """ @@ -35,7 +35,7 @@ HEAD="""%FDF-1.2 TAIL="""] >> >> -endobj +endobj trailer << @@ -52,7 +52,7 @@ class ProcInfo(Node): return int(self.status()[VSIZE]) except IOError: return 0 - + def lineage_memory_usage(self): return self.memory_usage() + sum(child.lineage_memory_usage() for child in self.children) @@ -81,7 +81,7 @@ class ProcInfo(Node): class ProcInfoLoader: """manage process information""" - + def __init__(self): self._loaded = {} @@ -101,8 +101,8 @@ class ProcInfoLoader: procinfo.manager = self self._loaded[pid] = procinfo return procinfo - - + + def load_all(self): """load all processes information""" for pid in self.list_pids(): @@ -153,11 +153,11 @@ class MemorySentinel(Thread): self.interval = interval self.setDaemon(True) self.gpid = gpid - + def stop(self): """stop ap""" self._stop.set() - + def _run(self): pil = ProcInfoLoader() while not self._stop.isSet(): @@ -190,7 +190,7 @@ class ResourceController: def _hangle_sig_timeout(self, sig, frame): raise TimeoutError() - + def _hangle_sig_memory(self, sig, frame): if self._abort_try < self._reprieve: self._abort_try += 1 @@ -214,7 +214,7 @@ class ResourceController: self._timer.start() else: os.killpg(os.getpid(), SIGKILL) - + def setup_limit(self): """set up the process limit""" assert currentThread().getName() == 'MainThread' @@ -22,15 +22,15 @@ could define the following ``pytestconf.py`` file :: import logging from logilab.common.pytest import PyTester - + def update_parser(parser): parser.add_option('-l', '--loglevel', dest='loglevel', action='store', choices=('debug', 'info', 'warning', 'error', 'critical'), default='critical', help="the default log level possible choices are " "('debug', 'info', 'warning', 'error', 'critical')") return parser - - + + class CustomPyTester(PyTester): def __init__(self, cvg, options): super(CustomPyTester, self).__init__(cvg, options) @@ -41,7 +41,7 @@ could define the following ``pytestconf.py`` file :: In your TestCase class you can then get the value of a specific option with the ``optval`` method:: - + class MyTestCase(TestCase): def test_foo(self): loglevel = self.optval('loglevel') @@ -81,7 +81,7 @@ you can filter the function with a simpe python expression - + :copyright: 2000-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved. :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr @@ -152,7 +152,7 @@ class TraceController(object): cls.tracefunc(cls.oldtracer) delattr(sys, '__notrace__') resume_tracing = classmethod(resume_tracing) - + pause_tracing = TraceController.pause_tracing resume_tracing = TraceController.resume_tracing @@ -193,7 +193,7 @@ TESTFILE_RE = re.compile("^((unit)?test.*|smoketest)\.py$") def this_is_a_testfile(filename): """returns True if `filename` seems to be a test file""" return TESTFILE_RE.match(osp.basename(filename)) - + TESTDIR_RE = re.compile("^(unit)?tests?$") def this_is_a_testdir(dirpath): """returns True if `filename` seems to be a test directory""" @@ -266,12 +266,12 @@ class GlobalTestReport(object): self.modulescount += 1 self.ran += 1 self.errmodules.append((filename[:-3], 1, 1)) - + def skip_module(self, filename): self.modulescount += 1 self.ran += 1 self.errmodules.append((filename[:-3], 0, 0)) - + def __str__(self): """this is just presentation stuff""" line1 = ['Ran %s test cases in %.2fs (%.2fs CPU)' @@ -303,7 +303,7 @@ def remove_local_modules_from_sys(testdir): This is used to avoid strange side-effects when using the testall() mode of pytest. For instance, if we run pytest on this tree:: - + A/test/test_utils.py B/test/test_utils.py @@ -326,7 +326,7 @@ def remove_local_modules_from_sys(testdir): class PyTester(object): """encaspulates testrun logic""" - + def __init__(self, cvg, options): self.report = GlobalTestReport() self.cvg = cvg @@ -339,7 +339,7 @@ class PyTester(object): print "*" * 79 print self.report return self.report.failures + self.report.errors - + def testall(self, exitfirst=False): """walks trhough current working directory, finds something @@ -362,7 +362,7 @@ class PyTester(object): # the local directory as a test directory even if # it doesn't have a traditional test directory name self.testonedir(here) - + def testonedir(self, testdir, exitfirst=False): """finds each testfile in the `testdir` and runs it""" for filename in abspath_listdir(testdir): @@ -475,7 +475,7 @@ class DjangoTester(PyTester): setup_test_environment() create_test_db(verbosity=0) self.dbname = self.settings.TEST_DATABASE_NAME - + def after_testfile(self): # Those imports must be done **after** setup_environ was called @@ -484,7 +484,7 @@ class DjangoTester(PyTester): teardown_test_environment() print 'destroying', self.dbname destroy_test_db(self.dbname, verbosity=0) - + def testall(self, exitfirst=False): """walks trhough current working directory, finds something @@ -555,7 +555,7 @@ class DjangoTester(PyTester): self.report.failed_to_test_module(filename) print 'unhandled exception occured while testing', modname print 'error: %s' % exc - return None + return None finally: self.after_testfile() if dirname: @@ -572,7 +572,7 @@ def make_parser(): def rebuild_cmdline(option, opt, value, parser): """carry the option to unittest_main""" parser.newargs.append(opt) - + def rebuild_and_store(option, opt, value, parser): """carry the option to unittest_main and store @@ -602,11 +602,11 @@ def make_parser(): help="Restart tests from where it failed (implies exitfirst) " "(only make sense if tests previously ran with exitfirst only)") parser.add_option('-c', '--capture', callback=rebuild_cmdline, - action="callback", + action="callback", help="Captures and prints standard out/err only on errors " "(only make sense when pytest run one test file)") parser.add_option('--color', callback=rebuild_cmdline, - action="callback", + action="callback", help="colorize tracebacks") parser.add_option('-p', '--printonly', # XXX: I wish I could use the callback action but it @@ -686,7 +686,7 @@ def run(): covermode = getattr(options, 'coverage', None) cvg = None if not '' in sys.path: - sys.path.insert(0, '') + sys.path.insert(0, '') if covermode: # control_import_coverage(rootdir) from logilab.devtools.lib.coverage import Coverage @@ -19,11 +19,11 @@ try: from setuptools import setup from setuptools.command import install_lib USE_SETUPTOOLS = 1 -except ImportError: +except ImportError: from distutils.core import setup from distutils.command import install_lib USE_SETUPTOOLS = 0 - + sys.modules.pop('__pkginfo__', None) # import required features @@ -63,7 +63,7 @@ STD_BLACKLIST = ('CVS', '.svn', '.hg', 'debian', 'dist', 'build') IGNORED_EXTENSIONS = ('.pyc', '.pyo', '.elc', '~') - + def ensure_scripts(linux_scripts): """ @@ -166,7 +166,7 @@ class MyInstallLib(install_lib.install_lib): for directory in include_dirs: dest = join(self.install_dir, base, directory) export(directory, dest, verbose=False) - + def install(**kwargs): """setup entry point""" try: @@ -200,6 +200,6 @@ def install(**kwargs): cmdclass = {'install_lib': MyInstallLib}, **kwargs ) - + if __name__ == '__main__' : install() diff --git a/shellutils.py b/shellutils.py index ccc5267..67e9ab6 100644 --- a/shellutils.py +++ b/shellutils.py @@ -34,7 +34,7 @@ def chown(path, login=None, group=None): """Same as `os.chown` function but accepting user login or group name as argument. If login or group is omitted, it's left unchanged. - Note: you must own the file to chown it (or be root). Otherwise OSError is raised. + Note: you must own the file to chown it (or be root). Otherwise OSError is raised. """ if login is None: uid = -1 @@ -154,7 +154,7 @@ def globfind(directory, pattern, blacklist=STD_BLACKLIST): """Recursively finds files matching glob `pattern` under `directory`. This is an alternative to `logilab.common.shellutils.find`. - + :type directory: str :param directory: directory where the search should start @@ -196,7 +196,7 @@ class Execute: """This is a deadlock safe version of popen2 (no stdin), that returns an object with errorlevel, out and err. """ - + def __init__(self, command): outfile = tempfile.mktemp() errfile = tempfile.mktemp() @@ -256,7 +256,7 @@ def release_lock(lock_file): class ProgressBar(object): """A simple text progression bar.""" - + def __init__(self, nbops, size=20, stream=sys.stdout): self._fstr = '\r[%%-%ss]' % int(size) self._stream = stream @@ -17,7 +17,7 @@ class SQLGenerator : def where(self, keys, addon=None) : """ :param keys: list of keys - + >>> s = SQLGenerator() >>> s.where(['nom']) 'nom = %(nom)s' @@ -34,7 +34,7 @@ class SQLGenerator : def set(self, keys) : """ :param keys: list of keys - + >>> s = SQLGenerator() >>> s.set(['nom']) 'nom = %(nom)s' @@ -47,7 +47,7 @@ class SQLGenerator : """ :param table: name of the table :param params: dictionnary that will be used as in cursor.execute(sql,params) - + >>> s = SQLGenerator() >>> s.insert('test',{'nom':'dupont'}) 'INSERT INTO test ( nom ) VALUES ( %(nom)s )' @@ -221,8 +221,8 @@ def sql_repr(type, val): return "'%s'" % (val,) else: return val - - + + if __name__ == "__main__": import doctest from logilab.common import sqlgen @@ -26,13 +26,13 @@ class Table(object): self.create_columns(col_names) if row_names: self.create_rows(row_names) - + def _next_row_name(self): return 'row%s' % (len(self.row_names)+1) def __iter__(self): return iter(self.data) - + def __eq__(self, other): if other is None: return False @@ -44,7 +44,7 @@ class Table(object): def __len__(self): return len(self.row_names) - + ## Rows / Columns creation ################################################# def create_rows(self, row_names): """Appends row_names to the list of existing rows @@ -52,7 +52,7 @@ class Table(object): self.row_names.extend(row_names) for row_name in row_names: self.data.append([self.default_value]*len(self.col_names)) - + def create_columns(self, col_names): """Appends col_names to the list of existing columns """ @@ -66,7 +66,7 @@ class Table(object): self.row_names.append(row_name) self.data.append([self.default_value]*len(self.col_names)) - + def create_column(self, col_name): """Creates a colname to the col_names list """ @@ -83,7 +83,7 @@ class Table(object): self.sort_by_column_index(col_index, method) except ValueError: raise KeyError("Col (%s) not found in table" % (col_id)) - + def sort_by_column_index(self, col_index, method = 'asc'): """Sorts the table 'in-place' according to data stored in col_index @@ -97,7 +97,7 @@ class Table(object): # If we want reverse sort, then reverse list if method.lower() == 'desc': sort_list.reverse() - + # Rebuild data / row names self.data = [] self.row_names = [] @@ -134,14 +134,14 @@ class Table(object): for row in self.data[:]: if row[col_index] == value: self.data.remove(row) - - + + ## The 'setter' part ####################################################### def set_cell(self, row_index, col_index, data): """sets value of cell 'row_indew', 'col_index' to data """ self.data[row_index][col_index] = data - + def set_cell_by_ids(self, row_id, col_id, data): """sets value of cell mapped by row_id and col_id to data @@ -157,8 +157,8 @@ class Table(object): self.data[row_index][col_index] = data except ValueError: raise KeyError("Column (%s) not found in table" % (col_id)) - - + + def set_row(self, row_index, row_data): """sets the 'row_index' row pre: @@ -167,7 +167,7 @@ class Table(object): """ self.data[row_index] = row_data - + def set_row_by_id(self, row_id, row_data): """sets the 'row_id' column pre: @@ -180,7 +180,7 @@ class Table(object): self.set_row(row_index, row_data) except ValueError: raise KeyError('Row (%s) not found in table' % (row_id)) - + def append_row(self, row_data, row_name=None): """Appends a row to the table @@ -204,7 +204,7 @@ class Table(object): row_name = row_name or self._next_row_name() self.row_names.insert(index, row_name) self.data.insert(index, row_data) - + def delete_row(self, index): """Deletes the 'index' row in the table, and returns it. @@ -212,7 +212,7 @@ class Table(object): """ self.row_names.pop(index) return self.data.pop(index) - + def delete_row_by_id(self, row_id): """Deletes the 'row_id' row in the table. @@ -223,7 +223,7 @@ class Table(object): self.delete_row(row_index) except ValueError: raise KeyError('Row (%s) not found in table' % (row_id)) - + def set_column(self, col_index, col_data): """sets the 'col_index' column @@ -231,7 +231,7 @@ class Table(object): type(col_data) == types.ListType len(col_data) == len(self.row_names) """ - + for row_index, cell_data in enumerate(col_data): self.data[row_index][col_index] = cell_data @@ -248,7 +248,7 @@ class Table(object): self.set_column(col_index, col_data) except ValueError: raise KeyError('Column (%s) not found in table' % (col_id)) - + def append_column(self, col_data, col_name): """Appends the 'col_index' column @@ -259,7 +259,7 @@ class Table(object): self.col_names.append(col_name) for row_index, cell_data in enumerate(col_data): self.data[row_index].append(cell_data) - + def insert_column(self, index, col_data, col_name): """Appends col_data before 'index' in the table. To make 'insert' @@ -272,7 +272,7 @@ class Table(object): self.col_names.insert(index, col_name) for row_index, cell_data in enumerate(col_data): self.data[row_index].insert(index, cell_data) - + def delete_column(self, index): """Deletes the 'index' column in the table, and returns it. @@ -292,15 +292,15 @@ class Table(object): except ValueError: raise KeyError('Column (%s) not found in table' % (col_id)) - + ## The 'getter' part ####################################################### def get_shape(self): """Returns a tuple which represents the table's shape - """ + """ return len(self.row_names), len(self.col_names) shape = property(get_shape) - + def __getitem__(self, indices): """provided for convenience""" rows, multirows = None, False @@ -371,7 +371,7 @@ class Table(object): warn('table.get_cell(i,j) is deprecated, use table[i,j] instead', DeprecationWarning, stacklevel=2) return self.data[row_index][col_index] - + def get_cell_by_ids(self, row_id, col_id): """Returns the element at [row_id][col_id] """ @@ -416,7 +416,7 @@ class Table(object): return set(col) else: return col - + def get_column_by_id(self, col_id, distinct=False): """Returns the 'col_id' col """ @@ -427,7 +427,7 @@ class Table(object): except ValueError: raise KeyError("Column (%s) not found in table" % (col_id)) return self.get_column(col_index, distinct) - + def get_rows(self): """Returns all the rows in the table @@ -442,13 +442,13 @@ class Table(object): """ return [self[:,index] for index in range(len(self.col_names))] - + def apply_stylesheet(self, stylesheet): """Applies the stylesheet to this table """ for instruction in stylesheet.instructions: eval(instruction) - + def transpose(self): """Keeps the self object intact, and returns the transposed (rotated) @@ -502,7 +502,7 @@ class Table(object): lines.insert(0, '-'*max_line_length) lines.append('-'*max_line_length) return '\n'.join(lines) - + def __repr__(self): return repr(self.data) @@ -514,9 +514,9 @@ class Table(object): data.append([str(cell) for cell in row]) lines = ['\t'.join(row) for row in data] return '\n'.join(lines) - - + + class TableStyle: """Defines a table's style """ @@ -535,8 +535,8 @@ class TableStyle: # We shouldn't have to create an entry for # the 1st col (the row_column one) self.units = dict([(col_name,'') for col_name in table.col_names]) - self.units['__row_column__'] = '' - + self.units['__row_column__'] = '' + # XXX FIXME : params order should be reversed for all set() methods def set_size(self, value, col_id): """sets the size of the specified col_id to value @@ -580,7 +580,7 @@ class TableStyle: """ self.units[col_id] = value - + def set_unit_by_index(self, value, col_index): """Allows to set the unit according to the column index rather than using the column's id. @@ -594,13 +594,13 @@ class TableStyle: col_id = self._table.col_names[col_index-1] self.units[col_id] = value - + def get_size(self, col_id): """Returns the size of the specified col_id """ return self.size[col_id] - + def get_size_by_index(self, col_index): """Allows to get the size according to the column index rather than @@ -653,7 +653,7 @@ class TableStyle: return self.units[col_id] -import re +import re CELL_PROG = re.compile("([0-9]+)_([0-9]+)") class TableStyleSheet: @@ -665,9 +665,9 @@ class TableStyleSheet: the following rule : 2_5 = 2_3 + 2_4 You can also use all the math.* operations you want. For example: - 2_5 = sqrt(2_3**2 + 2_4**2) + 2_5 = sqrt(2_3**2 + 2_4**2) """ - + def __init__(self, rules = None): rules = rules or [] self.rules = [] @@ -688,7 +688,7 @@ class TableStyleSheet: except SyntaxError: print "Bad Stylesheet Rule : %s [skipped]"%rule - + def add_rowsum_rule(self, dest_cell, row_index, start_col, end_col): """Creates and adds a rule to sum over the row at row_index from start_col to end_col. @@ -702,7 +702,7 @@ class TableStyleSheet: end_col + 1)] rule = '%d_%d=' % dest_cell + '+'.join(cell_list) self.add_rule(rule) - + def add_rowavg_rule(self, dest_cell, row_index, start_col, end_col): """Creates and adds a rule to make the row average (from start_col @@ -718,7 +718,7 @@ class TableStyleSheet: num = (end_col - start_col + 1) rule = '%d_%d=' % dest_cell + '('+'+'.join(cell_list)+')/%f'%num self.add_rule(rule) - + def add_colsum_rule(self, dest_cell, col_index, start_row, end_row): """Creates and adds a rule to sum over the col at col_index from @@ -728,13 +728,13 @@ class TableStyleSheet: pre: start_row >= 0 end_row > start_row - """ + """ cell_list = ['%d_%d'%(index, col_index) for index in range(start_row, end_row + 1)] rule = '%d_%d=' % dest_cell + '+'.join(cell_list) self.add_rule(rule) - - + + def add_colavg_rule(self, dest_cell, col_index, start_row, end_row): """Creates and adds a rule to make the col average (from start_row to end_row) @@ -776,7 +776,7 @@ class TableCellRenderer: table_style, col_index +1) return self._render_cell_content(final_content, table_style, col_index + 1) - + def render_row_cell(self, row_name, table, table_style): """Renders the cell for 'row_id' row @@ -792,7 +792,7 @@ class TableCellRenderer: col_index = table.col_names.index(col_name) return self._render_cell_content(cell_value, table_style, col_index +1) - + def _render_cell_content(self, content, table_style, col_index): """Makes the appropriate rendering for this cell content. @@ -803,7 +803,7 @@ class TableCellRenderer: """ return content - + def _make_cell_content(self, cell_content, table_style, col_index): """Makes the cell content (adds decoration data, like units for example) @@ -815,7 +815,7 @@ class TableCellRenderer: replacement_char = 0 if replacement_char and final_content == 0: return replacement_char - + try: units_on = self.properties['units'] if units_on: @@ -823,17 +823,17 @@ class TableCellRenderer: cell_content, table_style, col_index) except KeyError: pass - + return final_content - - + + def _add_unit(self, cell_content, table_style, col_index): """Adds unit to the cell_content if needed """ unit = table_style.get_unit_by_index(col_index) return str(cell_content) + " " + unit - - + + class DocbookRenderer(TableCellRenderer): """Defines how to render a cell for a docboook table @@ -845,8 +845,8 @@ class DocbookRenderer(TableCellRenderer): size = table_style.get_size_by_index(col_index) return '<colspec colname="c%d" colwidth="%s"/>\n' % \ (col_index, size) - - + + def _render_cell_content(self, cell_content, table_style, col_index): """Makes the appropriate rendering for this cell content. Rendering properties will be searched using the @@ -866,14 +866,14 @@ class DocbookRenderer(TableCellRenderer): class TableWriter: """A class to write tables """ - + def __init__(self, stream, table, style, **properties): self._stream = stream self.style = style or TableStyle(table) self._table = table self.properties = properties self.renderer = None - + def set_style(self, style): """sets the table's associated style @@ -885,8 +885,8 @@ class TableWriter: """sets the way to render cell """ self.renderer = renderer - - + + def update_properties(self, **properties): """Updates writer's properties (for cell rendering) """ @@ -897,7 +897,7 @@ class TableWriter: """Writes the table """ raise NotImplementedError("write_table must be implemented !") - + class DocbookTableWriter(TableWriter): @@ -911,7 +911,7 @@ class DocbookTableWriter(TableWriter): for col_index in range(len(self._table.col_names)+1): self._stream.write(self.renderer.define_col_header(col_index, self.style)) - + self._stream.write("<thead>\n<row>\n") # XXX FIXME : write an empty entry <=> the first (__row_column) column self._stream.write('<entry></entry>\n') @@ -919,7 +919,7 @@ class DocbookTableWriter(TableWriter): self._stream.write(self.renderer.render_col_cell( col_name, self._table, self.style)) - + self._stream.write("</row>\n</thead>\n") @@ -927,7 +927,7 @@ class DocbookTableWriter(TableWriter): """Writes the table body """ self._stream.write('<tbody>\n') - + for row_index, row in enumerate(self._table.data): self._stream.write('<row>\n') row_name = self._table.row_names[row_index] @@ -935,14 +935,14 @@ class DocbookTableWriter(TableWriter): self._stream.write(self.renderer.render_row_cell(row_name, self._table, self.style)) - + for col_index, cell in enumerate(row): self._stream.write(self.renderer.render_cell( (row_index, col_index), self._table, self.style)) - + self._stream.write('</row>\n') - + self._stream.write('</tbody>\n') @@ -955,7 +955,7 @@ class DocbookTableWriter(TableWriter): (len(self._table.col_names)+1)) self._write_headers() self._write_body() - + self._stream.write('</tgroup>\n</table>\n') - + diff --git a/tasksqueue.py b/tasksqueue.py index 75ade01..008a625 100644 --- a/tasksqueue.py +++ b/tasksqueue.py @@ -37,7 +37,7 @@ class PrioritizedTasksQueue(Queue): task.merge(item) return insort_left(self.queue, item) - + def _get(self): """Get an item from the queue""" return self.queue.pop() @@ -63,10 +63,10 @@ class Task(object): def __repr__(self): return '<Task %s @%#x>' % (self.id, id(self)) - + def __cmp__(self, other): return cmp(self.priority, other.priority) - + def __eq__(self, other): return self.id == other.id @@ -64,7 +64,7 @@ from logilab.common.modutils import load_module_from_name from logilab.common.debugger import Debugger, colorize_source from logilab.common.decorators import cached from logilab.common import textutils - + __all__ = ['main', 'unittest_main', 'find_tests', 'run_test', 'spawn'] @@ -83,7 +83,7 @@ def with_tempdir(callable): """A decorator ensuring no temporary file left when the function return Work only for temporary file create with the tempfile module""" def proxy(*args, **kargs): - + old_tmpdir = tempfile.gettempdir() new_tmpdir = tempfile.mkdtemp("-logilab-common-testlib","temp-dir-") tempfile.tempdir = new_tmpdir @@ -176,7 +176,7 @@ def main(testdir=None, exitafter=True): if all_result: print 'Ran %s test cases in %0.2fs (%0.2fs CPU)' % ( all_result.testsRun, end_time - start_time, - end_ctime - start_ctime), + end_ctime - start_ctime), if all_result.errors: print ', %s errors' % len(all_result.errors), if all_result.failures: @@ -219,7 +219,7 @@ def run_tests(tests, quiet, verbose, runner=None, capture=0): all_result = None for test in tests: if not quiet: - print + print print '-'*80 print "Executing", test result = run_test(test, verbose, runner, capture) @@ -242,9 +242,9 @@ def run_tests(tests, quiet, verbose, runner=None, capture=0): len(result.errors), len(result.failures)) else: good.append(test) - + return good, bad, skipped, all_result - + def find_tests(testdir, prefixes=DEFAULT_PREFIXES, suffix=".py", excludes=(), @@ -304,7 +304,7 @@ def _count(n, word): return "%d %ss" % (n, word) - + ## PostMortem Debug facilities ##### def start_interactive_mode(result): @@ -367,7 +367,7 @@ class SkipAwareTestResult(unittest._TextTestResult): def descrs_for(self, flavour): return getattr(self, '%s_descrs' % flavour.lower()) - + def _create_pdb(self, test_descr, flavour): self.descrs_for(flavour).append( (len(self.debuggers), test_descr) ) if self.pdbmode: @@ -417,7 +417,7 @@ class SkipAwareTestResult(unittest._TextTestResult): def addError(self, test, err): """err == (exc_type, exc, tcbk)""" - exc_type, exc, _ = err # + exc_type, exc, _ = err # if exc_type == TestSkipped: self.addSkipped(test, exc) else: @@ -444,7 +444,7 @@ class SkipAwareTestResult(unittest._TextTestResult): def printErrors(self): super(SkipAwareTestResult, self).printErrors() self.printSkippedList() - + def printSkippedList(self): for _, descr, err in self.skipped: # test, descr, err self.stream.writeln(self.separator1) @@ -575,7 +575,7 @@ class SkipAwareTextTestRunner(unittest.TextTestRunner): tags = getattr(test, 'tags', Tags()) return tags.match(tags_pattern) return True # no pattern - + def _makeResult(self): return SkipAwareTestResult(self.stream, self.descriptions, self.verbosity, self.exitfirst, self.capture, @@ -607,7 +607,7 @@ class SkipAwareTextTestRunner(unittest.TextTestRunner): self.stream.write("OK") failed, errored, skipped = map(len, (result.failures, result.errors, result.skipped)) - + det_results = [] for name, value in (("failures", result.failures), ("errors",result.errors), @@ -638,7 +638,7 @@ class NonStrictTestLoader(unittest.TestLoader): specifying tests to run on command line. For example, if the file test_foo.py contains :: - + class FooTC(TestCase): def test_foo1(self): # ... def test_foo2(self): # ... @@ -692,7 +692,7 @@ class NonStrictTestLoader(unittest.TestLoader): # python2.3 does not implement __iter__ on suites, we need to return # _tests explicitly return suite._tests - + def loadTestsFromName(self, name, module=None): parts = name.split('.') if module is None or len(parts) > 2: @@ -741,7 +741,7 @@ class NonStrictTestLoader(unittest.TestLoader): testCaseClass) return [testname for testname in testnames if not is_skipped(testname)] - + class SkipAwareTestProgram(unittest.TestProgram): # XXX: don't try to stay close to unittest.py, use optparse USAGE = """\ @@ -780,7 +780,7 @@ Examples: super(SkipAwareTestProgram, self).__init__( module=module, defaultTest=defaultTest, testLoader=NonStrictTestLoader()) - + def parseArgs(self, argv): self.pdbmode = False self.exitfirst = False @@ -895,7 +895,7 @@ Examples: restartfile = open(FILE_RESTART, 'r') try: try: - succeededtests = list(elem.rstrip('\n\r') for elem in + succeededtests = list(elem.rstrip('\n\r') for elem in restartfile.readlines()) removeSucceededTests(self.test, succeededtests) except Exception, e: @@ -926,7 +926,7 @@ succeeded tests into", osp.join(os.getcwd(),FILE_RESTART) -class FDCapture: +class FDCapture: """adapted from py lib (http://codespeak.net/py) Capture IO to/from a given os-level filedescriptor. """ @@ -951,14 +951,14 @@ class FDCapture: self.tmpfile.write(line) else: os.write(self._savefd, line) - + ## def maketempfile(self): ## tmpf = os.tmpfile() ## fd = os.dup(tmpf.fileno()) ## newf = os.fdopen(fd, tmpf.mode, 0) # No buffering ## tmpf.close() ## return newf - + def restore(self): """restore original fd and returns captured output""" #XXX: hack hack hack @@ -992,7 +992,7 @@ def _capture(which='stdout', printonly=None): else: fd = 2 return FDCapture(fd, which, printonly) - + def capture_stdout(printonly=None): """captures the standard output @@ -1000,7 +1000,7 @@ def capture_stdout(printonly=None): The restore() method returns the captured stdout and restores it """ return _capture('stdout', printonly) - + def capture_stderr(printonly=None): """captures the standard error output @@ -1060,7 +1060,7 @@ class ClassGetProperty(object): """this is a simple property-like class but for class attributes. """ - + def __init__(self, getter): self.getter = getter @@ -1074,7 +1074,7 @@ class TestCase(unittest.TestCase): capture = False pdbclass = Debugger - + def __init__(self, methodName='runTest'): super(TestCase, self).__init__(methodName) # internal API changed in python2.5 @@ -1091,9 +1091,9 @@ class TestCase(unittest.TestCase): self._current_test_descr = None self._options_ = None - def datadir(cls): # pylint: disable-msg=E0213 + def datadir(cls): # pylint: disable-msg=E0213 """helper attribute holding the standard test's data directory - + NOTE: this is a logilab's standard """ mod = __import__(cls.__module__) @@ -1122,7 +1122,7 @@ class TestCase(unittest.TestCase): return self._current_test_descr return super(TestCase, self).shortDescription() - + def captured_output(self): """return a two tuple with standard output and error stripped""" return self._captured_stdout.strip(), self._captured_stderr.strip() @@ -1135,7 +1135,7 @@ class TestCase(unittest.TestCase): def _stop_capture(self): """stop_capture and restore previous output""" self._force_output_restore() - + def start_capture(self, printonly=None): """start_capture""" self._out.append(capture_stdout(printonly or self._printonly)) @@ -1149,7 +1149,7 @@ class TestCase(unittest.TestCase): self._err[-1].printonly = rgx else: self.start_capture(printonly=rgx) - + def stop_capture(self): """stop output and error capture""" if self._out: @@ -1157,13 +1157,13 @@ class TestCase(unittest.TestCase): _err = self._err.pop() return _out.restore(), _err.restore() return '', '' - + def _force_output_restore(self): """remove all capture set""" while self._out: self._captured_stdout += self._out.pop().restore() self._captured_stderr += self._err.pop().restore() - + def quiet_run(self, result, func, *args, **kwargs): self._start_capture() try: @@ -1225,11 +1225,11 @@ class TestCase(unittest.TestCase): restartfile = open(FILE_RESTART, 'a') try: try: - descr = '.'.join((self.__class__.__module__, - self.__class__.__name__, + descr = '.'.join((self.__class__.__module__, + self.__class__.__name__, self._testMethodName)) restartfile.write(descr+os.linesep) - except Exception, e: + except Exception, e: raise e finally: restartfile.close() @@ -1244,7 +1244,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) result.stopTest(self) - + def _proceed_generative(self, result, testfunc, runcondition=None): # cancel startTest()'s increment result.testsRun -= 1 @@ -1305,7 +1305,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) result.addError(self, self.__exc_info()) return 2 return 0 - + def defaultTestResult(self): """return a new instance of the defaultTestResult""" return SkipAwareTestResult() @@ -1315,7 +1315,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) msg = msg or 'test was skipped' raise TestSkipped(msg) skipped_test = deprecated_function(skip) - + def assertIn(self, object, set): """assert <object> are in <set>""" self.assert_(object in set, "%s not in %s" % (object, set)) @@ -1380,7 +1380,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) "use assertUnorderedIterableEquals instead.", DeprecationWarning, 2) return self.assertUnorderedIterableEquals(got,expected, msg) - + items={} items['missing'] = expected - got items['unexpected'] = got - expected @@ -1418,7 +1418,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) msg = 'list_2 is lacking %r' % _l1 self.fail(msg) assertListEqual = assertListEquals - + def assertLinesEquals(self, list_1, list_2, msg=None): """assert list of lines are equal""" self.assertListEquals(list_1.splitlines(), list_2.splitlines(), msg) @@ -1441,7 +1441,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) """asserts the XML string is well-formed (no DTD conformance check)""" stream = StringIO(xml_string) self.assertXMLWellFormed(stream, msg) - + assertXMLStringValid = deprecated_function( assertXMLStringWellFormed, 'assertXMLStringValid renamed to more precise assertXMLStringWellFormed' @@ -1492,7 +1492,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) # lines that don't start with a ' ' are diff ones if not line.startswith(' '): self.fail('\n'.join(['%s\n'%msg_prefix]+read + list(result))) - + def assertTextEquals(self, text1, text2, junk=None, msg_prefix='Text differ'): """compare two multiline strings (using difflib and splitlines())""" @@ -1506,7 +1506,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) self._difftext(text1.strip().splitlines(True), text2.strip().splitlines(True), junk, msg_prefix) assertTextEqual = assertTextEquals - + def assertStreamEquals(self, stream1, stream2, junk=None, msg_prefix='Stream differ'): """compare two streams (using difflib and readlines())""" @@ -1520,28 +1520,28 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) # ocmpare self._difftext(stream1.readlines(), stream2.readlines(), junk, msg_prefix) - + assertStreamEqual = assertStreamEquals def assertFileEquals(self, fname1, fname2, junk=(' ', '\t')): """compares two files using difflib""" self.assertStreamEqual(file(fname1), file(fname2), junk, msg_prefix='Files differs\n-:%s\n+:%s\n'%(fname1, fname2)) assertFileEqual = assertFileEquals - - + + def assertDirEquals(self, path_a, path_b): """compares two files using difflib""" assert osp.exists(path_a), "%s doesn't exists" % path_a assert osp.exists(path_b), "%s doesn't exists" % path_b - all_a = [ (ipath[len(path_a):].lstrip('/'), idirs, ifiles) + all_a = [ (ipath[len(path_a):].lstrip('/'), idirs, ifiles) for ipath, idirs, ifiles in os.walk(path_a)] all_a.sort(key=itemgetter(0)) - - all_b = [ (ipath[len(path_b):].lstrip('/'), idirs, ifiles) + + all_b = [ (ipath[len(path_b):].lstrip('/'), idirs, ifiles) for ipath, idirs, ifiles in os.walk(path_b)] all_b.sort(key=itemgetter(0)) - + iter_a, iter_b = iter(all_a), iter(all_b) partial_iter = True ipath_a, idirs_a, ifiles_a = data_a = None, None, None @@ -1554,7 +1554,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) self.assert_(ipath_a == ipath_b, - "unexpected %s in %s while looking %s from %s" % + "unexpected %s in %s while looking %s from %s" % (ipath_a, path_a, ipath_b, path_b)) @@ -1570,9 +1570,9 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) errors["missing files"] = sfiles_b - sfiles_a - msgs = [ "%s: %s"% (name, items) + msgs = [ "%s: %s"% (name, items) for name, items in errors.iteritems() if items] - + if msgs: msgs.insert(0,"%s and %s differ :" % ( osp.join(path_a, ipath_a), @@ -1593,7 +1593,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) assertDirEqual = assertDirEquals - + def assertIsInstance(self, obj, klass, msg=None, strict=False): """compares two files using difflib""" if msg is None: @@ -1612,8 +1612,8 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) if msg is None: msg = "%r is not %r"%(obj, other) self.assert_(obj is other, msg) - - + + def assertIsNot(self, obj, other, msg=None): """compares identity of two reference""" if msg is None: @@ -1625,7 +1625,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) if msg is None: msg = "reference to %r when None expected"%(obj,) self.assert_( obj is None, msg ) - + def assertNotNone(self, obj, msg=None): """assert obj is not None""" if msg is None: @@ -1637,11 +1637,11 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART) if msg is None: msg = "%r != %r" % (obj, other) self.assert_(math.fabs(obj - other) < prec, msg) - + def failUnlessRaises(self, excClass, callableObj, *args, **kwargs): """override default failUnlessRaise method to return the raised exception instance. - + Fail unless an exception of class excClass is thrown by callableObj when invoked with arguments args and keyword arguments kwargs. If a different type of exception is @@ -1697,7 +1697,7 @@ else: self.skipped = skipped self.original_find_tests = doctest._find_tests doctest._find_tests = self._find_tests - + def _find_tests(self, module, prefix=None): tests = [] for testinfo in self.original_find_tests(module, prefix): @@ -1727,7 +1727,7 @@ class DocTest(TestCase): suite = SkippedSuite() return suite.run(result) run = __call__ - + def test(self): """just there to trigger test execution""" @@ -1735,13 +1735,13 @@ MAILBOX = None class MockSMTP: """fake smtplib.SMTP""" - + def __init__(self, host, port): self.host = host self.port = port global MAILBOX self.reveived = MAILBOX = [] - + def set_debuglevel(self, debuglevel): """ignore debug level""" @@ -1755,7 +1755,7 @@ class MockSMTP: class MockConfigParser(ConfigParser): """fake ConfigParser.ConfigParser""" - + def __init__(self, options): ConfigParser.__init__(self) for section, pairs in options.iteritems(): @@ -1768,12 +1768,12 @@ class MockConfigParser(ConfigParser): class MockConnection: """fake DB-API 2.0 connexion AND cursor (i.e. cursor() return self)""" - + def __init__(self, results): self.received = [] self.states = [] self.results = results - + def cursor(self): """Mock cursor method""" return self @@ -1824,7 +1824,7 @@ def create_files(paths, chroot): >>> isdir('/tmp/a/b/c') True >>> isfile('/tmp/a/b/c/d/e.py') - True + True >>> isfile('/tmp/a/b/foo.py') True """ @@ -1866,7 +1866,7 @@ def enable_dbc(*args): weaver.weave_module(arg, ContractAspect) return True - + class AttrObject: # XXX cf mock_object def __init__(self, **kwargs): self.__dict__.update(kwargs) @@ -1888,7 +1888,7 @@ class Tags(set): return eval(exp, {}, self) def require_version(version): - """ Compare version of python interpretor to the given one. Skip the test + """ Compare version of python interpretor to the given one. Skip the test if older. """ def check_require_version(f): diff --git a/textutils.py b/textutils.py index fec946f..8aabea2 100644 --- a/textutils.py +++ b/textutils.py @@ -19,11 +19,11 @@ unquote, colorize_ansi :type ANSI_PREFIX: str :var ANSI_PREFIX: ANSI terminal code notifing the start of an ANSI escape sequence - + :type ANSI_END: str :var ANSI_END: ANSI terminal code notifing the end of an ANSI escape sequence - + :type ANSI_RESET: str :var ANSI_RESET: ANSI terminal code reseting format defined by a previous ANSI escape sequence @@ -151,7 +151,7 @@ def normalize_paragraph(text, line_len=80, indent=''): aline, text = splittext(text.strip(), line_len) lines.append(indent + aline) return linesep.join(lines) - + def normalize_rest_paragraph(text, line_len=80, indent=''): """normalize a ReST text to display it with a maximum line size and optionaly arbitrary indentation. Line jumps are normalized. The @@ -194,7 +194,7 @@ def normalize_rest_paragraph(text, line_len=80, indent=''): def splittext(text, line_len): """split the given text on space according to the given max line size - + return a 2-uple: * a line <= line_len if possible * the rest of the text which has to be reported on another line @@ -227,7 +227,7 @@ def get_csv(string, sep=','): :param sep: field separator, default to the comma (',') :rtype: str or unicode - :return: the unquoted string (or the input string if it wasn't quoted) + :return: the unquoted string (or the input string if it wasn't quoted) """ return [word.strip() for word in string.split(sep) if word.strip()] @@ -257,7 +257,7 @@ def apply_units( string, units, inter=None, final=float, blank_reg=_BLANK_RE, value_reg=_VALUE_RE): """Parse the string applying the units defined in units (eg: "1.5m",{'m',60} -> 80). - + :type string: str or unicode :param string: the string to parse @@ -266,17 +266,17 @@ def apply_units( string, units, inter=None, final=float, blank_reg=_BLANK_RE, :type inter: type :param inter: used to parse every intermediate value (need __sum__) - + :type blank_reg: regexp :param blank_reg: should match eveyr blank char to ignore. - + :type value_reg: regexp with "value" and optional "unit" group - :param value_reg: match a value and it's unit into the + :param value_reg: match a value and it's unit into the """ if inter is None: inter = final - + string = _BLANK_RE.sub('',string) values = [] for match in value_reg.finditer(string): @@ -301,7 +301,7 @@ def pretty_match(match, string, underline_char='^'): il mange du bacon ^^^^^ >>> - + :type match: _sre.SRE_match :param match: object returned by re.match, re.search or re.finditer @@ -375,7 +375,7 @@ ANSI_COLORS = { def _get_ansi_code(color=None, style=None): """return ansi escape code corresponding to color and style - + :type color: str or None :param color: the color identifier (see `ANSI_COLORS` for available values) @@ -386,7 +386,7 @@ def _get_ansi_code(color=None, style=None): several style effects at the same time, use a coma as separator. :raise KeyError: if an unexistant color or style identifier is given - + :rtype: str :return: the built escape code """ @@ -47,7 +47,7 @@ class Node(object): def is_leaf(self): return not self.children - + def append(self, child): """add a node to children""" self.children.append(child) @@ -62,7 +62,7 @@ class Node(object): """insert a child node""" self.children.insert(index, child) child.parent = self - + def replace(self, old_child, new_child): """replace a child node with another""" i = self.children.index(old_child) @@ -90,7 +90,7 @@ class Node(object): return parent.children[index+1] except IndexError: return None - + def previous_sibling(self): """ return the previous sibling for this node if any @@ -113,7 +113,7 @@ class Node(object): return root.get_child_by_id(nid, 1) except NodeNotFound : raise NodeNotFound(EX_NODE_NOT_FOUND % nid) - + def get_child_by_id(self, nid, recurse=None): """ return child of given id @@ -167,7 +167,7 @@ class Node(object): return the width of the tree from this node """ return len(self.leaves()) - + def root(self): """ return the root node of the tree @@ -190,7 +190,7 @@ class Node(object): def __iter__(self): return iter(self.children) - + def flatten(self, _list=None): """ return a list with all the nodes descendant from this node @@ -210,13 +210,13 @@ class Node(object): if self.parent is not None: lst.extend(self.parent.lineage()) return lst - + class VNode(Node, VisitedMixIn): """a visitable node """ pass - + class BinaryNode(VNode): """a binary node (ie only two children """ @@ -226,19 +226,19 @@ class BinaryNode(VNode): assert lhs and rhs self.append(lhs) self.append(rhs) - + def remove(self, child): """remove the child and replace this node with the other child """ self.children.remove(child) self.parent.replace(self, self.children[0]) - + def get_parts(self): """ return the left hand side and the right hand side of this node """ return self.children[0], self.children[1] - + if sys.version_info[0:2] >= (2, 2): @@ -246,7 +246,7 @@ if sys.version_info[0:2] >= (2, 2): else: from UserList import UserList list_class = UserList - + class ListNode(VNode, list_class): """Used to manipulate Nodes as Lists """ @@ -254,7 +254,7 @@ class ListNode(VNode, list_class): list_class.__init__(self) VNode.__init__(self) self.children = self - + def __str__(self, indent=0): return '%s%s %s' % (indent*' ', self.__class__.__name__, ', '.join([str(v) for v in self])) @@ -263,17 +263,17 @@ class ListNode(VNode, list_class): """add a node to children""" list_class.append(self, child) child.parent = self - + def insert(self, index, child): """add a node to children""" list_class.insert(self, index, child) child.parent = self - + def remove(self, child): """add a node to children""" list_class.remove(self, child) child.parent = None - + def pop(self, index): """add a node to children""" child = list_class.pop(self, index) @@ -285,7 +285,7 @@ class ListNode(VNode, list_class): # construct list from tree #################################################### def post_order_list(node, filter_func=no_filter): - """ + """ create a list with tree nodes for which the <filter> function returned true in a post order fashion """ @@ -352,4 +352,4 @@ class PrefixedDepthFirstIterator(FilteredIterator): """ def __init__(self, node, filter_func=None): FilteredIterator.__init__(self, node, pre_order_list, filter_func) - + diff --git a/twisted_distutils.py b/twisted_distutils.py index a705854..0d8a455 100644 --- a/twisted_distutils.py +++ b/twisted_distutils.py @@ -70,23 +70,23 @@ class twisted_install(install): def initialize_options (self): install.initialize_options(self) self.twisted_plugins = None - + def has_twisted_plugins(self): return self.distribution.has_twisted_plugins() - + sub_commands = [] sub_commands.extend(install.sub_commands) sub_commands.append(('install_twisted_plugins', has_twisted_plugins)) - + class twisted_build(build): def initialize_options (self): build.initialize_options(self) self.twisted_plugins = None - + def has_twisted_plugins(self): return self.distribution.has_twisted_plugins() - + sub_commands = [] sub_commands.extend(build.sub_commands) sub_commands.append(('build_twisted_plugins', has_twisted_plugins)) @@ -189,8 +189,8 @@ class install_twisted_plugins(Command): def get_outputs(self): return self.outfiles or [] - - + + class TwistedDistribution(Distribution): def __init__(self,attrs=None): diff --git a/vcgutils.py b/vcgutils.py index d25cb35..81e8eec 100644 --- a/vcgutils.py +++ b/vcgutils.py @@ -39,7 +39,7 @@ ATTRS_VAL = { # meaning of possible values: # O -> string -# 1 -> int +# 1 -> int # list -> value in list GRAPH_ATTRS = { 'title' : 0, @@ -128,7 +128,7 @@ def latin_to_vcg(st): class VCGPrinter: """A vcg graph writer. """ - + def __init__(self, output_stream): self._stream = output_stream self._indent = '' @@ -166,7 +166,7 @@ class VCGPrinter: # private ################################################################## - + def _write_attributes(self, attributes_dict, **args): """write graph, node or edge attributes """ @@ -187,12 +187,12 @@ possible attributes are %s''' % (key, attributes_dict.keys())) else: raise Exception('''value %s isn\'t correct for attribute %s correct values are %s''' % (value, key, _type)) - + def _inc_indent(self): """increment indentation """ self._indent = ' %s' % self._indent - + def _dec_indent(self): """decrement indentation """ @@ -17,7 +17,7 @@ class FilteredIterator(object): if filter_func is None: filter_func = no_filter self._list = list_func(node, filter_func) - + def next(self): try: return self._list.pop(0) @@ -30,7 +30,7 @@ class Visitor(object): def __init__(self, iterator_class, filter_func=None): self._iter_class = iterator_class self.filter = filter_func - + def visit(self, node, *args, **kargs): """ launch the visit on a given node @@ -52,13 +52,13 @@ class Visitor(object): def _get_iterator(self, node): return self._iter_class(node, self.filter) - + def open_visit(self, *args, **kargs): """ method called at the beginning of the visit """ pass - + def close_visit(self, result): """ method called at the end of the visit @@ -80,11 +80,11 @@ class VisitedMixIn(object): return self.TYPE.replace('-', '_') except: return self.__class__.__name__.lower() - + def accept(self, visitor, *args, **kwargs): func = getattr(visitor, 'visit_%s' % self.get_visit_name()) return func(self, *args, **kwargs) - + def leave(self, visitor, *args, **kwargs): func = getattr(visitor, 'leave_%s' % self.get_visit_name()) return func(self, *args, **kwargs) diff --git a/xmlrpcutils.py b/xmlrpcutils.py index b31d02f..5d69142 100644 --- a/xmlrpcutils.py +++ b/xmlrpcutils.py @@ -18,21 +18,21 @@ ProtocolError = xmlrpclib.ProtocolError ## self.password = password ## self.verbose = None ## self.has_ssl = httplib.__dict__.has_key("HTTPConnection") - + ## def request(self, host, handler, request_body, verbose=None): ## # issue XML-RPC request ## if self.has_ssl: ## if host.startswith("https:"): h = httplib.HTTPSConnection(host) ## else: h = httplib.HTTPConnection(host) ## else: h = httplib.HTTP(host) - + ## h.putrequest("POST", handler) - + ## # required by HTTP/1.1 ## if not self.has_ssl: # HTTPConnection already does 1.1 ## h.putheader("Host", host) ## h.putheader("Connection", "close") - + ## if request_body: h.send(request_body) ## if self.has_ssl: ## response = h.getresponse() @@ -47,22 +47,22 @@ ProtocolError = xmlrpclib.ProtocolError ## if errcode != 200: ## raise xmlrpclib.ProtocolError(host + handler, errcode, ## errmsg, headers) - + ## file = h.getfile() - + ## return self.parse_response(file) - + class AuthMixin: """basic http authentication mixin for xmlrpc transports""" - + def __init__(self, username, password, encoding): self.verbose = 0 self.username = username self.password = password self.encoding = encoding - + def request(self, host, handler, request_body, verbose=0): """issue XML-RPC request""" h = self.make_connection(host) @@ -96,10 +96,10 @@ class AuthMixin: ## result.seek(0) ## return self.parse_response(result) return self.parse_response(file) - + class BasicAuthTransport(AuthMixin, xmlrpclib.Transport): """basic http authentication transport""" - + class BasicAuthSafeTransport(AuthMixin, xmlrpclib.SafeTransport): """basic https authentication transport""" |