Commit 9bed93f2 authored by Nicolas Chauvat's avatar Nicolas Chauvat
Browse files

[cleanup] delete-trailing-whitespace

parent c1c0dbdbf180
......@@ -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 = []
......
......@@ -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())
......
......@@ -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])
"""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"))
"""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)
......
......@@ -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'):
......
......@@ -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
......
......@@ -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