# HG changeset patch # User Emmanuel Gil Peyrot # Date 1358528135 -3600 # Node ID 1f160467f5de47fa34466e77101f34a4e70d9744 # Parent e629371a28d3a19b2e12d02fb11cd8cc240fbcb4 Fix pep8 support in src/bridge. diff -r e629371a28d3 -r 1f160467f5de frontends/src/bridge/DBus.py --- a/frontends/src/bridge/DBus.py Fri Jan 18 17:55:35 2013 +0100 +++ b/frontends/src/bridge/DBus.py Fri Jan 18 17:55:35 2013 +0100 @@ -26,27 +26,29 @@ from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True) -const_INT_PREFIX = "org.goffi.SAT" #Interface prefix -const_ERROR_PREFIX = const_INT_PREFIX+".error" +const_INT_PREFIX = "org.goffi.SAT" # Interface prefix +const_ERROR_PREFIX = const_INT_PREFIX + ".error" const_OBJ_PATH = '/org/goffi/SAT/bridge' const_CORE_SUFFIX = ".core" const_PLUGIN_SUFFIX = ".plugin" + class BridgeExceptionNoService(Exception): pass + class DBusBridgeFrontend(BridgeFrontend): def __init__(self): try: self.sessions_bus = dbus.SessionBus() self.db_object = self.sessions_bus.get_object(const_INT_PREFIX, - const_OBJ_PATH) + const_OBJ_PATH) self.db_core_iface = dbus.Interface(self.db_object, - dbus_interface=const_INT_PREFIX + const_CORE_SUFFIX) + dbus_interface=const_INT_PREFIX + const_CORE_SUFFIX) self.db_plugin_iface = dbus.Interface(self.db_object, - dbus_interface=const_INT_PREFIX + const_PLUGIN_SUFFIX) - except dbus.exceptions.DBusException,e: - if e._dbus_error_name=='org.freedesktop.DBus.Error.ServiceUnknown': + dbus_interface=const_INT_PREFIX + const_PLUGIN_SUFFIX) + except dbus.exceptions.DBusException, e: + if e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown': raise BridgeExceptionNoService else: raise e @@ -79,7 +81,7 @@ async = True _callback = kwargs.pop('callback') _errback = kwargs.pop('errback') - elif len(args)>=2 and callable(args[-1]) and callable(args[-2]): + elif len(args) >= 2 and callable(args[-1]) and callable(args[-2]): async = True args = list(args) _errback = args.pop() @@ -89,12 +91,11 @@ if async: kwargs['reply_handler'] = _callback - kwargs['error_handler'] = lambda err:_errback(err._dbus_error_name[len(const_ERROR_PREFIX)+1:]) + kwargs['error_handler'] = lambda err: _errback(err._dbus_error_name[len(const_ERROR_PREFIX) + 1:]) return method(*args, **kwargs) return getPluginMethod - def addContact(self, entity_jid, profile_key="@DEFAULT@"): return self.db_core_iface.addContact(entity_jid, profile_key) @@ -216,11 +217,11 @@ #methods from plugins def joinMUC(self, room_jid, nick, options, profile_key): - if options == None: - options = [('', '')] #XXX: we have to do this awful hack because python dbus need to guess the signature + if options is None: + options = [('', '')] # XXX: we have to do this awful hack because python dbus need to guess the signature return self.db_plugin_iface.joinMUC(room_jid, nick, options, profile_key) def gatewayRegister(self, action, target, data, profile_key): - if data == None: - data = [('', '')] #XXX: we have to do this awful hack because python dbus need to guess the signature + if data is None: + data = [('', '')] # XXX: we have to do this awful hack because python dbus need to guess the signature return self.db_plugin_iface.gatewayRegister(action, target, data, profile_key) \ No newline at end of file diff -r e629371a28d3 -r 1f160467f5de src/bridge/DBus.py --- a/src/bridge/DBus.py Fri Jan 18 17:55:35 2013 +0100 +++ b/src/bridge/DBus.py Fri Jan 18 17:55:35 2013 +0100 @@ -19,7 +19,6 @@ along with this program. If not, see . """ - from bridge import Bridge import dbus import dbus.service @@ -28,42 +27,49 @@ from logging import debug, info, error from twisted.internet.defer import Deferred -const_INT_PREFIX = "org.goffi.SAT" #Interface prefix -const_ERROR_PREFIX = const_INT_PREFIX+".error" +const_INT_PREFIX = "org.goffi.SAT" # Interface prefix +const_ERROR_PREFIX = const_INT_PREFIX + ".error" const_OBJ_PATH = '/org/goffi/SAT/bridge' const_CORE_SUFFIX = ".core" const_PLUGIN_SUFFIX = ".plugin" + class ParseError(Exception): pass + class MethodNotRegistered(dbus.DBusException): _dbus_error_name = const_ERROR_PREFIX + ".MethodNotRegistered" + class InternalError(dbus.DBusException): _dbus_error_name = const_ERROR_PREFIX + ".InternalError" + class AsyncNotDeferred(dbus.DBusException): _dbus_error_name = const_ERROR_PREFIX + ".AsyncNotDeferred" + class DeferredNotAsync(dbus.DBusException): _dbus_error_name = const_ERROR_PREFIX + ".DeferredNotAsync" + class GenericException(dbus.DBusException): def __init__(self, twisted_error): - super(GenericException,self).__init__() + super(GenericException, self).__init__() mess = twisted_error.getErrorMessage() - self._dbus_error_name = const_ERROR_PREFIX+"."+ (mess or str(twisted_error.__class__)) + self._dbus_error_name = const_ERROR_PREFIX + "." + (mess or str(twisted_error.__class__)) + class DbusObject(dbus.service.Object): def __init__(self, bus, path): dbus.service.Object.__init__(self, bus, path) debug("Init DbusObject...") - self.cb={} + self.cb = {} def register(self, name, cb): - self.cb[name]=cb + self.cb[name] = cb def _callback(self, name, *args, **kwargs): """call the callback if it exists, raise an exception else @@ -86,17 +92,16 @@ if not isinstance(result, Deferred): error("Asynchronous method [%s] does not return a Deferred." % name) raise AsyncNotDeferred - result.addCallback(lambda result: callback() if result==None else callback(result)) - result.addErrback(lambda err:errback(GenericException(err))) + result.addCallback(lambda result: callback() if result is None else callback(result)) + result.addErrback(lambda err: errback(GenericException(err))) else: if isinstance(result, Deferred): error("Synchronous method [%s] return a Deferred." % name) raise DeferredNotAsync return result - ### signals ### - @dbus.service.signal(const_INT_PREFIX+const_PLUGIN_SUFFIX, + @dbus.service.signal(const_INT_PREFIX + const_PLUGIN_SUFFIX, signature='') def dummySignal(self): #FIXME: workaround for addSignal (doesn't work if one method doensn't @@ -174,7 +179,6 @@ def subscribe(self, sub_type, entity_jid, profile): pass - ### methods ### @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX, @@ -411,41 +415,40 @@ def updateContact(self, entity_jid, name, groups, profile_key="@DEFAULT@"): return self._callback("updateContact", unicode(entity_jid), unicode(name), groups, unicode(profile_key)) - def __attributes(self, in_sign): """Return arguments to user given a in_sign @param in_sign: in_sign in the short form (using s,a,i,b etc) @return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")""" - i=0 - idx=0 - attr=[] - while i=len(in_sign): + while (True): # we have a dict or a list of tuples + i += 1 + if i >= len(in_sign): raise ParseError("missing }") if in_sign[i] == opening_car: - opening_count+=1 + opening_count += 1 if in_sign[i] == closing_car: - opening_count-=1 + opening_count -= 1 if opening_count == 0: break - i+=1 + i += 1 return attr def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False): @@ -460,30 +463,29 @@ del(_arguments[0]) #first arguments are for the _callback method - arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback','errback=errback']) if async else _arguments)) + arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback', 'errback=errback']) if async else _arguments)) if async: - _arguments.extend(['callback','errback']) + _arguments.extend(['callback', 'errback']) _defaults.extend([None, None]) - #now we create a second list with default values - for i in range(1, len(_defaults)+1): + for i in range(1, len(_defaults) + 1): _arguments[-i] = "%s = %s" % (_arguments[-i], repr(_defaults[-i])) - arguments_defaults = ', '.join(_arguments) + arguments_defaults = ', '.join(_arguments) - code = compile ('def %(name)s (self,%(arguments_defaults)s): return self._callback(%(arguments_callback)s)' % - {'name':name, 'arguments_defaults':arguments_defaults, 'arguments_callback':arguments_callback}, '','exec') - exec (code) #FIXME: to the same thing in a cleaner way, without compile/exec + code = compile('def %(name)s (self,%(arguments_defaults)s): return self._callback(%(arguments_callback)s)' % + {'name': name, 'arguments_defaults': arguments_defaults, 'arguments_callback': arguments_callback}, '', 'exec') + exec (code) # FIXME: to the same thing in a cleaner way, without compile/exec method = locals()[name] async_callbacks = ('callback', 'errback') if async else None setattr(DbusObject, name, dbus.service.method( - const_INT_PREFIX+int_suffix, in_signature=in_sign, out_signature=out_sign, + const_INT_PREFIX + int_suffix, in_signature=in_sign, out_signature=out_sign, async_callbacks=async_callbacks)(method)) function = getattr(self, name) func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface] - func_table[function.__name__] = function #Needed for introspection + func_table[function.__name__] = function # Needed for introspection def addSignal(self, name, int_suffix, signature, doc={}): """Dynamically add a signal to Dbus Bridge""" @@ -491,20 +493,21 @@ #TODO: use doc parameter to name attributes #code = compile ('def '+name+' (self,'+attributes+'): debug ("'+name+' signal")', '','exec') #XXX: the debug is too annoying with xmllog - code = compile ('def '+name+' (self,'+attributes+'): pass', '','exec') + code = compile('def ' + name + ' (self,' + attributes + '): pass', '', 'exec') exec (code) signal = locals()[name] setattr(DbusObject, name, dbus.service.signal( - const_INT_PREFIX+int_suffix, signature=signature)(signal)) + const_INT_PREFIX + int_suffix, signature=signature)(signal)) function = getattr(self, name) func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface] - func_table[function.__name__] = function #Needed for introspection + func_table[function.__name__] = function # Needed for introspection + class DBusBridge(Bridge): def __init__(self): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) Bridge.__init__(self) - info ("Init DBus...") + info("Init DBus...") self.session_bus = dbus.SessionBus() self.dbus_name = dbus.service.BusName(const_INT_PREFIX, self.session_bus) self.dbus_bridge = DbusObject(self.session_bus, const_OBJ_PATH) @@ -551,7 +554,6 @@ def subscribe(self, sub_type, entity_jid, profile): self.dbus_bridge.subscribe(sub_type, entity_jid, profile) - def register(self, name, callback): debug("registering DBus bridge method [%s]", name) self.dbus_bridge.register(name, callback) @@ -565,4 +567,4 @@ def addSignal(self, name, int_suffix, signature, doc={}): self.dbus_bridge.addSignal(name, int_suffix, signature, doc) - setattr(DBusBridge, name, getattr(self.dbus_bridge, name)) + setattr(DBusBridge, name, getattr(self.dbus_bridge, name)) \ No newline at end of file diff -r e629371a28d3 -r 1f160467f5de src/bridge/bridge.py --- a/src/bridge/bridge.py Fri Jan 18 17:55:35 2013 +0100 +++ b/src/bridge/bridge.py Fri Jan 18 17:55:35 2013 +0100 @@ -21,9 +21,10 @@ from logging import debug, info, error + class Bridge(object): def __init__(self): - info ("Bridge initialization") + info("Bridge initialization") ##signals def newContact(self, contact): @@ -38,7 +39,6 @@ def paramUpdate(self, name, value): raise NotImplementedError - ##methods def connect(self): raise NotImplementedError diff -r e629371a28d3 -r 1f160467f5de src/bridge/bridge_constructor/bridge_contructor.py --- a/src/bridge/bridge_constructor/bridge_contructor.py Fri Jan 18 17:55:35 2013 +0100 +++ b/src/bridge/bridge_constructor/bridge_contructor.py Fri Jan 18 17:55:35 2013 +0100 @@ -19,15 +19,14 @@ along with this program. If not, see . """ - #consts NAME = u"bridge_constructor" -VERSION="0.1.0" -DEST_DIR="generated" -ABOUT = NAME+u""" v%s (c) Jérôme Poisson (aka Goffi) 2011 +VERSION = "0.1.0" +DEST_DIR = "generated" +ABOUT = NAME + u""" v%s (c) Jérôme Poisson (aka Goffi) 2011 --- -"""+NAME+u""" Copyright (C) 2011 Jérôme Poisson (aka Goffi) +""" + NAME + u""" Copyright (C) 2011 Jérôme Poisson (aka Goffi) This program comes with ABSOLUTELY NO WARRANTY; This is free software, and you are welcome to redistribute it under certain conditions. @@ -35,11 +34,11 @@ This script construct a SàT bridge using the given protocol """ -MANAGED_PROTOCOLES=['dbus','mediawiki', 'dbus-xml'] -DEFAULT_PROTOCOLE='dbus' -FLAGS=['deprecated', 'async'] +MANAGED_PROTOCOLES = ['dbus', 'mediawiki', 'dbus-xml'] +DEFAULT_PROTOCOLE = 'dbus' +FLAGS = ['deprecated', 'async'] -ENV_OVERRIDE = "SAT_BRIDGE_CONST_" #Prefix used to override a constant +ENV_OVERRIDE = "SAT_BRIDGE_CONST_" # Prefix used to override a constant import sys import os @@ -56,6 +55,7 @@ #Used when the signature parsing is going wrong (invalid signature ?) pass + class Constructor(object): def __init__(self, bridge_template, options): @@ -66,8 +66,8 @@ """Return values of a function in a dict @param name: Name of the function to get @return: dict, each key has the config value or None if the value is not set""" - function={} - for option in ['type','category','sig_in','sig_out','doc']: + function = {} + for option in ['type', 'category', 'sig_in', 'sig_out', 'doc']: try: value = self.bridge_template.get(name, option) except NoOptionError: @@ -79,7 +79,7 @@ """Return default values of a function in a dict @param name: Name of the function to get @return: dict, each key is the integer param number (no key if no default value)""" - default_dict={} + default_dict = {} def_re = re.compile(r"param_(\d+)_default") for option in self.bridge_template.options(name): @@ -97,7 +97,7 @@ """Return list of flags set for this function @param name: Name of the function to get @return: List of flags (string)""" - flags=[] + flags = [] for option in self.bridge_template.options(name): if option in FLAGS: flags.append(option) @@ -107,7 +107,7 @@ """Return documentation of arguments @param name: Name of the function to get @return: dict, each key is the integer param number (no key if no argument doc), value is a tuple (name, doc)""" - doc_dict={} + doc_dict = {} option_re = re.compile(r"doc_param_(\d+)") value_re = re.compile(r"^(\w+): (.*)$", re.MULTILINE | re.DOTALL) for option in self.bridge_template.options(name): @@ -123,7 +123,7 @@ value_match = value_re.match(self.bridge_template.get(name, option)) if not value_match: raise ParseError("Invalid value for parameter doc [%i]" % idx) - doc_dict[idx]=(value_match.group(1),value_match.group(2)) + doc_dict[idx] = (value_match.group(1), value_match.group(2)) return doc_dict def getDoc(self, name): @@ -134,40 +134,39 @@ return self.bridge_template.get(name, "doc") return None - def argumentsParser(self, signature): """Generator which return individual arguments signatures from a global signature""" - start=0 - i=0 + start = 0 + i = 0 - while i=len(signature): + while (True): # we have a dict or a list of tuples + i += 1 + if i >= len(signature): raise ParseError("missing }") if signature[i] == opening_car: - opening_count+=1 + opening_count += 1 if signature[i] == closing_car: - opening_count-=1 + opening_count -= 1 if opening_count == 0: break - i+=1 + i += 1 yield signature[start:i] - start=i + start = i def getArguments(self, signature, name=None, default=None, unicode_protect=False): """Return arguments to user given a signature @@ -176,16 +175,16 @@ @param default: dictionary of default values, like given by getDefault @param unicode_protect: activate unicode protection on strings (return strings as unicode(str)) @return: list of arguments that correspond to a signature (e.g.: "sss" return "arg1, arg2, arg3")""" - idx=0 - attr_string=[] + idx = 0 + attr_string = [] for arg in self.argumentsParser(signature): - attr_string.append(("unicode(%(name)s)%(default)s" if (unicode_protect and arg=='s') else "%(name)s%(default)s") % { - 'name':name[idx][0] if (name and name.has_key(idx)) else "arg_%i" % idx, - 'default':"="+default[idx] if (default and default.has_key(idx)) else '' - }) #give arg_1, arg2, etc or name1, name2=default, etc. \ - #give unicode(arg_1), unicode(arg_2), etc. if unicode_protect is set and arg is a string - idx+=1 + attr_string.append(("unicode(%(name)s)%(default)s" if (unicode_protect and arg == 's') else "%(name)s%(default)s") % { + 'name': name[idx][0] if (name and idx in name) else "arg_%i" % idx, + 'default': "=" + default[idx] if (default and idx in default) else ''}) + # give arg_1, arg2, etc or name1, name2=default, etc. + #give unicode(arg_1), unicode(arg_2), etc. if unicode_protect is set and arg is a string + idx += 1 return ", ".join(attr_string) @@ -207,11 +206,11 @@ try: if not os.path.exists(DEST_DIR): os.mkdir(DEST_DIR) - full_path=os.path.join(DEST_DIR,filename) + full_path = os.path.join(DEST_DIR, filename) if os.path.exists(full_path) and not self.options.force: print ("The destination file [%s] already exists ! Use --force to overwrite it" % full_path) try: - with open(full_path,'w') as dest_file: + with open(full_path, 'w') as dest_file: dest_file.write('\n'.join(file_buf)) except IOError: print ("Can't open destination file [%s]" % full_path) @@ -219,12 +218,13 @@ print("It's not possible to generate the file, check your permissions") exit(1) + class MediawikiConstructor(Constructor): def __init__(self, bridge_template, options): Constructor.__init__(self, bridge_template, options) - self.core_template="mediawiki_template.tpl" - self.core_dest="mediawiki.wiki" + self.core_template = "mediawiki_template.tpl" + self.core_dest = "mediawiki.wiki" def _addTextDecorations(self, text): """Add text decorations like coloration or shortcuts""" @@ -247,16 +247,16 @@ arg_doc = self.getArgumentsDoc(name) arg_default = self.getDefault(name) args_str = self.getArguments(sig_in) - args = args_str.split(', ') if args_str else [] #ugly but it works :) - wiki=[] + args = args_str.split(', ') if args_str else [] # ugly but it works :) + wiki = [] for i in range(len(args)): - if arg_doc.has_key(i): - name,doc=arg_doc[i] - doc='\n:'.join(doc.rstrip('\n').split('\n')) + if i in arg_doc: + name, doc = arg_doc[i] + doc = '\n:'.join(doc.rstrip('\n').split('\n')) wiki.append("; %s: %s" % (name, self._addTextDecorations(doc))) else: wiki.append("; arg_%d: " % i) - if arg_default.has_key(i): + if i in arg_default: wiki.append(":''DEFAULT: %s''" % arg_default[i]) return "\n".join(wiki) @@ -265,8 +265,8 @@ @param name: name of the function """ arg_doc = self.getArgumentsDoc(name) - wiki=[] - if arg_doc.has_key('return'): + wiki = [] + if 'return' in arg_doc: wiki.append('\n|-\n! scope=row | return value\n|') wiki.append('
\n'.join(self._addTextDecorations(arg_doc['return']).rstrip('\n').split('\n'))) return "\n".join(wiki) @@ -283,13 +283,13 @@ async_msg = """
'''This method is asynchronous'''""" deprecated_msg = """
'''/!\ WARNING /!\ : This method is deprecated, please don't use it !'''""" signature_signal = \ -"""\ + """\ ! scope=row | signature | %s |-\ """ % function['sig_in'] signature_method = \ -"""\ + """\ ! scope=row | signature in | %s |- @@ -298,16 +298,15 @@ |-\ """ % (function['sig_in'], function['sig_out']) completion = { - 'signature':signature_signal if function['type']=="signal" else signature_method, - 'sig_out':function['sig_out'] or '', - 'category':function['category'], - 'name':section, - 'doc':self.getDoc(section) or "FIXME: No description available", - 'async':async_msg if "async" in self.getFlags(section) else "", - 'deprecated':deprecated_msg if "deprecated" in self.getFlags(section) else "", - 'parameters':self._wikiParameter(section, function['sig_in']), - 'return':self._wikiReturn(section) if function['type'] == 'method' else '' - } + 'signature': signature_signal if function['type'] == "signal" else signature_method, + 'sig_out': function['sig_out'] or '', + 'category': function['category'], + 'name': section, + 'doc': self.getDoc(section) or "FIXME: No description available", + 'async': async_msg if "async" in self.getFlags(section) else "", + 'deprecated': deprecated_msg if "deprecated" in self.getFlags(section) else "", + 'parameters': self._wikiParameter(section, function['sig_in']), + 'return': self._wikiReturn(section) if function['type'] == 'method' else ''} dest = signals_part if function['type'] == "signal" else methods_part dest.append("""\ @@ -339,7 +338,7 @@ elif line.startswith('##TIMESTAMP##'): core_bridge.append('Generated on %s' % datetime.now()) else: - core_bridge.append(line.replace('\n','')) + core_bridge.append(line.replace('\n', '')) except IOError: print ("Can't open template file [%s]" % self.core_template) sys.exit(1) @@ -347,13 +346,14 @@ #now we write to final file self.finalWrite(self.core_dest, core_bridge) + class DbusConstructor(Constructor): def __init__(self, bridge_template, options): Constructor.__init__(self, bridge_template, options) - self.core_template="dbus_core_template.py" - self.frontend_template="dbus_frontend_template.py" - self.frontend_dest = self.core_dest="DBus.py" + self.core_template = "dbus_core_template.py" + self.frontend_template = "dbus_frontend_template.py" + self.frontend_dest = self.core_dest = "DBus.py" def generateCoreSide(self): signals_part = [] @@ -368,12 +368,11 @@ arg_doc = self.getArgumentsDoc(section) async = "async" in self.getFlags(section) completion = { - 'sig_in':function['sig_in'] or '', - 'sig_out':function['sig_out'] or '', - 'category':'PLUGIN' if function['category'] == 'plugin' else 'CORE', - 'name':section, - 'args':self.getArguments(function['sig_in'], name=arg_doc, default=default ) - } + 'sig_in': function['sig_in'] or '', + 'sig_out': function['sig_out'] or '', + 'category': 'PLUGIN' if function['category'] == 'plugin' else 'CORE', + 'name': section, + 'args': self.getArguments(function['sig_in'], name=arg_doc, default=default)} if function["type"] == "signal": completion['body'] = "pass" if not self.options.debug else 'debug ("%s")' % section @@ -389,7 +388,7 @@ """ % completion) elif function["type"] == "method": - completion['debug'] = "" if not self.options.debug else 'debug ("%s")\n%s' % (section,8*' ') + completion['debug'] = "" if not self.options.debug else 'debug ("%s")\n%s' % (section, 8 * ' ') completion['args_result'] = self.getArguments(function['sig_in'], name=arg_doc, unicode_protect=self.options.unicode) completion['async_comma'] = ', ' if async and function['sig_in'] else '' completion['async_args_def'] = 'callback=None, errback=None' if async else '' @@ -422,9 +421,9 @@ const_name = line[len('const_'):line.find(' = ')] if const_name in const_override: print ("const %s overriden" % const_name) - core_bridge.append('const_%s = %s' % (const_name, os.environ[ENV_OVERRIDE+const_name])) + core_bridge.append('const_%s = %s' % (const_name, os.environ[ENV_OVERRIDE + const_name])) continue - core_bridge.append(line.replace('\n','')) + core_bridge.append(line.replace('\n', '')) except IOError: print ("Can't open template file [%s]" % self.core_template) sys.exit(1) @@ -443,15 +442,14 @@ arg_doc = self.getArgumentsDoc(section) async = "async" in self.getFlags(section) completion = { - 'sig_in':function['sig_in'] or '', - 'sig_out':function['sig_out'] or '', - 'category':'plugin' if function['category'] == 'plugin' else 'core', - 'name':section, - 'args':self.getArguments(function['sig_in'], name=arg_doc, default=default) - } + 'sig_in': function['sig_in'] or '', + 'sig_out': function['sig_out'] or '', + 'category': 'plugin' if function['category'] == 'plugin' else 'core', + 'name': section, + 'args': self.getArguments(function['sig_in'], name=arg_doc, default=default)} if function["type"] == "method": - completion['debug'] = "" if not self.options.debug else 'debug ("%s")\n%s' % (section,8*' ') + completion['debug'] = "" if not self.options.debug else 'debug ("%s")\n%s' % (section, 8 * ' ') completion['args_result'] = self.getArguments(function['sig_in'], name=arg_doc) completion['async_args'] = ', callback=None, errback=None' if async else '' completion['async_comma'] = ', ' if async and function['sig_in'] else '' @@ -478,9 +476,9 @@ const_name = line[len('const_'):line.find(' = ')] if const_name in const_override: print ("const %s overriden" % const_name) - frontend_bridge.append('const_%s = %s' % (const_name, os.environ[ENV_OVERRIDE+const_name])) + frontend_bridge.append('const_%s = %s' % (const_name, os.environ[ENV_OVERRIDE + const_name])) continue - frontend_bridge.append(line.replace('\n','')) + frontend_bridge.append(line.replace('\n', '')) except IOError: print ("Can't open template file [%s]" % self.frontend_template) sys.exit(1) @@ -488,21 +486,21 @@ #now we write to final file self.finalWrite(self.frontend_dest, frontend_bridge) + class DbusXmlConstructor(Constructor): """Constructor for DBus XML syntaxt (used by Qt frontend)""" def __init__(self, bridge_template, options): Constructor.__init__(self, bridge_template, options) - self.template="dbus_xml_template.xml" - self.core_dest="org.goffi.sat.xml" - self.default_annotation = { 'a{ss}': 'StringDict', - 'a(sa{ss}as)': 'QList', - 'a{i(ss)}': 'HistoryT', - 'a(sss)': 'QList', - 'a{sa{s(sia{ss})}}': 'PresenceStatusT', - 'a{sa{ss}}': 'ActionResultExtDataT', - } + self.template = "dbus_xml_template.xml" + self.core_dest = "org.goffi.sat.xml" + self.default_annotation = {'a{ss}': 'StringDict', + 'a(sa{ss}as)': 'QList', + 'a{i(ss)}': 'HistoryT', + 'a(sss)': 'QList', + 'a{sa{s(sia{ss})}}': 'PresenceStatusT', + 'a{sa{ss}}': 'ActionResultExtDataT'} def generateCoreSide(self): try: @@ -520,17 +518,17 @@ for section in sections: function = self.getValues(section) print ("Adding %s %s" % (section, function["type"])) - new_elt = doc.createElement('method' if function["type"]=='method' else 'signal') + new_elt = doc.createElement('method' if function["type"] == 'method' else 'signal') new_elt.setAttribute('name', section) args_in_str = self.getArguments(function['sig_in']) - idx=0 + idx = 0 args_doc = self.getArgumentsDoc(section) for arg in self.argumentsParser(function['sig_in'] or ''): arg_elt = doc.createElement('arg') - arg_elt.setAttribute('name', args_doc[idx][0] if args_doc.has_key(idx) else "arg_%i" % idx) + arg_elt.setAttribute('name', args_doc[idx][0] if idx in args_doc else "arg_%i" % idx) arg_elt.setAttribute('type', arg) - _direction = 'in' if function["type"]=='method' else 'out' + _direction = 'in' if function["type"] == 'method' else 'out' arg_elt.setAttribute('direction', _direction) new_elt.appendChild(arg_elt) if "annotation" in self.options.flags: @@ -539,7 +537,7 @@ annot_elt.setAttribute('name', "com.trolltech.QtDBus.QtTypeName.In%d" % idx) annot_elt.setAttribute('value', self.default_annotation[arg]) new_elt.appendChild(annot_elt) - idx+=1 + idx += 1 if function['sig_out']: arg_elt = doc.createElement('arg') @@ -558,19 +556,22 @@ #now we write to final file self.finalWrite(self.core_dest, [doc.toprettyxml()]) + class ConstructorError(Exception): pass + class ConstructorFactory(object): def create(self, bridge_template, options): - if options.protocole=='dbus': - return DbusConstructor(bridge_template, options) - elif options.protocole=='mediawiki': - return MediawikiConstructor(bridge_template, options) - elif options.protocole=='dbus-xml': - return DbusXmlConstructor(bridge_template, options) + if options.protocole == 'dbus': + return DbusConstructor(bridge_template, options) + elif options.protocole == 'mediawiki': + return MediawikiConstructor(bridge_template, options) + elif options.protocole == 'dbus-xml': + return DbusXmlConstructor(bridge_template, options) - raise ConstructorError('Unknown constructor type') + raise ConstructorError('Unknown constructor type') + class BridgeConstructor(object): def __init__(self): @@ -578,28 +579,27 @@ def check_options(self): """Check command line options""" - _usage=""" + _usage = """ %prog [options] %prog --help for options list """ - parser = OptionParser(usage=_usage,version=ABOUT % VERSION) + parser = OptionParser(usage=_usage, version=ABOUT % VERSION) parser.add_option("-p", "--protocole", action="store", type="string", default=DEFAULT_PROTOCOLE, - help="Generate bridge using PROTOCOLE (default: %s, possible values: [%s])" % (DEFAULT_PROTOCOLE, ", ".join(MANAGED_PROTOCOLES))) + help="Generate bridge using PROTOCOLE (default: %s, possible values: [%s])" % (DEFAULT_PROTOCOLE, ", ".join(MANAGED_PROTOCOLES))) parser.add_option("-s", "--side", action="store", type="string", default="core", - help="Which side of the bridge do you want to make ? (default: %default, possible values: [core, frontend])") + help="Which side of the bridge do you want to make ? (default: %default, possible values: [core, frontend])") parser.add_option("-t", "--template", action="store", type="string", default='bridge_template.ini', - help="Use TEMPLATE to generate bridge (default: %default)") + help="Use TEMPLATE to generate bridge (default: %default)") parser.add_option("-f", "--force", action="store_true", default=False, - help=("Force overwritting of existing files")) + help=("Force overwritting of existing files")) parser.add_option("-d", "--debug", action="store_true", default=False, - help=("Add debug information printing")) + help=("Add debug information printing")) parser.add_option("--no_unicode", action="store_false", dest="unicode", default=True, - help=("Remove unicode type protection from string results")) + help=("Remove unicode type protection from string results")) parser.add_option("--flags", action="store", type="string", - help=("Constructors' specific flags, comma separated")) - + help=("Constructors' specific flags, comma separated")) (self.options, args) = parser.parse_args() self.options.flags = self.options.flags.split(',') if self.options.flags else [] diff -r e629371a28d3 -r 1f160467f5de src/bridge/bridge_constructor/dbus_core_template.py --- a/src/bridge/bridge_constructor/dbus_core_template.py Fri Jan 18 17:55:35 2013 +0100 +++ b/src/bridge/bridge_constructor/dbus_core_template.py Fri Jan 18 17:55:35 2013 +0100 @@ -19,7 +19,6 @@ along with this program. If not, see . """ - from bridge import Bridge import dbus import dbus.service @@ -28,42 +27,49 @@ from logging import debug, info, error from twisted.internet.defer import Deferred -const_INT_PREFIX = "org.goffi.SAT" #Interface prefix -const_ERROR_PREFIX = const_INT_PREFIX+".error" +const_INT_PREFIX = "org.goffi.SAT" # Interface prefix +const_ERROR_PREFIX = const_INT_PREFIX + ".error" const_OBJ_PATH = '/org/goffi/SAT/bridge' const_CORE_SUFFIX = ".core" const_PLUGIN_SUFFIX = ".plugin" + class ParseError(Exception): pass + class MethodNotRegistered(dbus.DBusException): _dbus_error_name = const_ERROR_PREFIX + ".MethodNotRegistered" + class InternalError(dbus.DBusException): _dbus_error_name = const_ERROR_PREFIX + ".InternalError" + class AsyncNotDeferred(dbus.DBusException): _dbus_error_name = const_ERROR_PREFIX + ".AsyncNotDeferred" + class DeferredNotAsync(dbus.DBusException): _dbus_error_name = const_ERROR_PREFIX + ".DeferredNotAsync" + class GenericException(dbus.DBusException): def __init__(self, twisted_error): - super(GenericException,self).__init__() + super(GenericException, self).__init__() mess = twisted_error.getErrorMessage() - self._dbus_error_name = const_ERROR_PREFIX+"."+ (mess or str(twisted_error.__class__)) + self._dbus_error_name = const_ERROR_PREFIX + "." + (mess or str(twisted_error.__class__)) + class DbusObject(dbus.service.Object): def __init__(self, bus, path): dbus.service.Object.__init__(self, bus, path) debug("Init DbusObject...") - self.cb={} + self.cb = {} def register(self, name, cb): - self.cb[name]=cb + self.cb[name] = cb def _callback(self, name, *args, **kwargs): """call the callback if it exists, raise an exception else @@ -86,17 +92,16 @@ if not isinstance(result, Deferred): error("Asynchronous method [%s] does not return a Deferred." % name) raise AsyncNotDeferred - result.addCallback(lambda result: callback() if result==None else callback(result)) - result.addErrback(lambda err:errback(GenericException(err))) + result.addCallback(lambda result: callback() if result is None else callback(result)) + result.addErrback(lambda err: errback(GenericException(err))) else: if isinstance(result, Deferred): error("Synchronous method [%s] return a Deferred." % name) raise DeferredNotAsync return result - ### signals ### - @dbus.service.signal(const_INT_PREFIX+const_PLUGIN_SUFFIX, + @dbus.service.signal(const_INT_PREFIX + const_PLUGIN_SUFFIX, signature='') def dummySignal(self): #FIXME: workaround for addSignal (doesn't work if one method doensn't @@ -105,45 +110,43 @@ pass ##SIGNALS_PART## - ### methods ### ##METHODS_PART## - def __attributes(self, in_sign): """Return arguments to user given a in_sign @param in_sign: in_sign in the short form (using s,a,i,b etc) @return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")""" - i=0 - idx=0 - attr=[] - while i=len(in_sign): + while (True): # we have a dict or a list of tuples + i += 1 + if i >= len(in_sign): raise ParseError("missing }") if in_sign[i] == opening_car: - opening_count+=1 + opening_count += 1 if in_sign[i] == closing_car: - opening_count-=1 + opening_count -= 1 if opening_count == 0: break - i+=1 + i += 1 return attr def addMethod(self, name, int_suffix, in_sign, out_sign, method, async=False): @@ -158,30 +161,29 @@ del(_arguments[0]) #first arguments are for the _callback method - arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback','errback=errback']) if async else _arguments)) + arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback', 'errback=errback']) if async else _arguments)) if async: - _arguments.extend(['callback','errback']) + _arguments.extend(['callback', 'errback']) _defaults.extend([None, None]) - #now we create a second list with default values - for i in range(1, len(_defaults)+1): + for i in range(1, len(_defaults) + 1): _arguments[-i] = "%s = %s" % (_arguments[-i], repr(_defaults[-i])) - arguments_defaults = ', '.join(_arguments) + arguments_defaults = ', '.join(_arguments) - code = compile ('def %(name)s (self,%(arguments_defaults)s): return self._callback(%(arguments_callback)s)' % - {'name':name, 'arguments_defaults':arguments_defaults, 'arguments_callback':arguments_callback}, '','exec') - exec (code) #FIXME: to the same thing in a cleaner way, without compile/exec + code = compile('def %(name)s (self,%(arguments_defaults)s): return self._callback(%(arguments_callback)s)' % + {'name': name, 'arguments_defaults': arguments_defaults, 'arguments_callback': arguments_callback}, '', 'exec') + exec (code) # FIXME: to the same thing in a cleaner way, without compile/exec method = locals()[name] async_callbacks = ('callback', 'errback') if async else None setattr(DbusObject, name, dbus.service.method( - const_INT_PREFIX+int_suffix, in_signature=in_sign, out_signature=out_sign, + const_INT_PREFIX + int_suffix, in_signature=in_sign, out_signature=out_sign, async_callbacks=async_callbacks)(method)) function = getattr(self, name) func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface] - func_table[function.__name__] = function #Needed for introspection + func_table[function.__name__] = function # Needed for introspection def addSignal(self, name, int_suffix, signature, doc={}): """Dynamically add a signal to Dbus Bridge""" @@ -189,26 +191,26 @@ #TODO: use doc parameter to name attributes #code = compile ('def '+name+' (self,'+attributes+'): debug ("'+name+' signal")', '','exec') #XXX: the debug is too annoying with xmllog - code = compile ('def '+name+' (self,'+attributes+'): pass', '','exec') + code = compile('def ' + name + ' (self,' + attributes + '): pass', '', 'exec') exec (code) signal = locals()[name] setattr(DbusObject, name, dbus.service.signal( - const_INT_PREFIX+int_suffix, signature=signature)(signal)) + const_INT_PREFIX + int_suffix, signature=signature)(signal)) function = getattr(self, name) func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface] - func_table[function.__name__] = function #Needed for introspection + func_table[function.__name__] = function # Needed for introspection + class DBusBridge(Bridge): def __init__(self): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) Bridge.__init__(self) - info ("Init DBus...") + info("Init DBus...") self.session_bus = dbus.SessionBus() self.dbus_name = dbus.service.BusName(const_INT_PREFIX, self.session_bus) self.dbus_bridge = DbusObject(self.session_bus, const_OBJ_PATH) ##DIRECT_CALLS## - def register(self, name, callback): debug("registering DBus bridge method [%s]", name) self.dbus_bridge.register(name, callback) @@ -223,4 +225,3 @@ def addSignal(self, name, int_suffix, signature, doc={}): self.dbus_bridge.addSignal(name, int_suffix, signature, doc) setattr(DBusBridge, name, getattr(self.dbus_bridge, name)) - diff -r e629371a28d3 -r 1f160467f5de src/bridge/bridge_constructor/dbus_frontend_template.py --- a/src/bridge/bridge_constructor/dbus_frontend_template.py Fri Jan 18 17:55:35 2013 +0100 +++ b/src/bridge/bridge_constructor/dbus_frontend_template.py Fri Jan 18 17:55:35 2013 +0100 @@ -26,27 +26,29 @@ from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True) -const_INT_PREFIX = "org.goffi.SAT" #Interface prefix -const_ERROR_PREFIX = const_INT_PREFIX+".error" +const_INT_PREFIX = "org.goffi.SAT" # Interface prefix +const_ERROR_PREFIX = const_INT_PREFIX + ".error" const_OBJ_PATH = '/org/goffi/SAT/bridge' const_CORE_SUFFIX = ".core" const_PLUGIN_SUFFIX = ".plugin" + class BridgeExceptionNoService(Exception): pass + class DBusBridgeFrontend(BridgeFrontend): def __init__(self): try: self.sessions_bus = dbus.SessionBus() self.db_object = self.sessions_bus.get_object(const_INT_PREFIX, - const_OBJ_PATH) + const_OBJ_PATH) self.db_core_iface = dbus.Interface(self.db_object, - dbus_interface=const_INT_PREFIX + const_CORE_SUFFIX) + dbus_interface=const_INT_PREFIX + const_CORE_SUFFIX) self.db_plugin_iface = dbus.Interface(self.db_object, - dbus_interface=const_INT_PREFIX + const_PLUGIN_SUFFIX) - except dbus.exceptions.DBusException,e: - if e._dbus_error_name=='org.freedesktop.DBus.Error.ServiceUnknown': + dbus_interface=const_INT_PREFIX + const_PLUGIN_SUFFIX) + except dbus.exceptions.DBusException, e: + if e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown': raise BridgeExceptionNoService else: raise e @@ -79,7 +81,7 @@ async = True _callback = kwargs.pop('callback') _errback = kwargs.pop('errback') - elif len(args)>=2 and callable(args[-1]) and callable(args[-2]): + elif len(args) >= 2 and callable(args[-1]) and callable(args[-2]): async = True args = list(args) _errback = args.pop() @@ -89,22 +91,21 @@ if async: kwargs['reply_handler'] = _callback - kwargs['error_handler'] = lambda err:_errback(err._dbus_error_name[len(const_ERROR_PREFIX)+1:]) + kwargs['error_handler'] = lambda err: _errback(err._dbus_error_name[len(const_ERROR_PREFIX) + 1:]) return method(*args, **kwargs) return getPluginMethod - ##METHODS_PART## #methods from plugins def joinMUC(self, room_jid, nick, options, profile_key): - if options == None: - options = [('', '')] #XXX: we have to do this awful hack because python dbus need to guess the signature + if options is None: + options = [('', '')] # XXX: we have to do this awful hack because python dbus need to guess the signature return self.db_plugin_iface.joinMUC(room_jid, nick, options, profile_key) def gatewayRegister(self, action, target, data, profile_key): - if data == None: - data = [('', '')] #XXX: we have to do this awful hack because python dbus need to guess the signature + if data is None: + data = [('', '')] # XXX: we have to do this awful hack because python dbus need to guess the signature return self.db_plugin_iface.gatewayRegister(action, target, data, profile_key)