Mercurial > libervia-backend
diff src/bridge/bridge_constructor/bridge_contructor.py @ 595:1f160467f5de
Fix pep8 support in src/bridge.
author | Emmanuel Gil Peyrot <linkmauve@linkmauve.fr> |
---|---|
date | Fri, 18 Jan 2013 17:55:35 +0100 |
parents | beaf6bec2fcd |
children | 84a6e83157c2 |
line wrap: on
line diff
--- 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 <http://www.gnu.org/licenses/>. """ - #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): - if signature[i] not in ['b','y','n','i','x','q','u','t','d','s','a']: + while i < len(signature): + if signature[i] not in ['b', 'y', 'n', 'i', 'x', 'q', 'u', 't', 'd', 's', 'a']: raise ParseError("Unmanaged attribute type [%c]" % signature[i]) if signature[i] == 'a': - i+=1 - if signature[i]!='{' and signature[i]!='(': #FIXME: must manage tuples out of arrays - i+=1 + i += 1 + if signature[i] != '{' and signature[i] != '(': # FIXME: must manage tuples out of arrays + i += 1 yield signature[start:i] - start=i - continue #we have a simple type for the array + start = i + continue # we have a simple type for the array opening_car = signature[i] - assert(opening_car in ['{','(']) + assert(opening_car in ['{', '(']) closing_car = '}' if opening_car == '{' else ')' opening_count = 1 - while (True): #we have a dict or a list of tuples - i+=1 - if 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('<br />\n'.join(self._addTextDecorations(arg_doc['return']).rstrip('\n').split('\n'))) return "\n".join(wiki) @@ -283,13 +283,13 @@ async_msg = """<br />'''This method is asynchronous'''""" deprecated_msg = """<br />'''<font color="#FF0000">/!\ WARNING /!\ : This method is deprecated, please don't use it !</font>'''""" 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<Contact>', - 'a{i(ss)}': 'HistoryT', - 'a(sss)': 'QList<MenuT>', - '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<Contact>', + 'a{i(ss)}': 'HistoryT', + 'a(sss)': 'QList<MenuT>', + '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 []