Mercurial > libervia-backend
diff sat/bridge/bridge_constructor/base_constructor.py @ 2624:56f94936df1e
code style reformatting using black
author | Goffi <goffi@goffi.org> |
---|---|
date | Wed, 27 Jun 2018 20:14:46 +0200 |
parents | 26edcf3a30eb |
children | 779351da2c13 |
line wrap: on
line diff
--- a/sat/bridge/bridge_constructor/base_constructor.py Wed Jun 27 07:51:29 2018 +0200 +++ b/sat/bridge/bridge_constructor/base_constructor.py Wed Jun 27 20:14:46 2018 +0200 @@ -1,5 +1,5 @@ #!/usr/bin/env python2 -#-*- coding: utf-8 -*- +# -*- coding: utf-8 -*- # SàT: a XMPP client # Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org) @@ -29,7 +29,7 @@ class ParseError(Exception): - #Used when the signature parsing is going wrong (invalid signature ?) + # Used when the signature parsing is going wrong (invalid signature ?) pass @@ -41,7 +41,7 @@ # replace ##SIGNALS_PART## in template), while the value is the format # keys starting with "signal" will be used for signals, while ones starting with # "method" will be used for methods - # check D-Bus constructor for an example + # check D-Bus constructor for an example CORE_FORMATS = None CORE_TEMPLATE = None CORE_DEST = None @@ -66,7 +66,7 @@ @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']: + for option in ["type", "category", "sig_in", "sig_out", "doc"]: try: value = self.bridge_template.get(name, option) except NoOptionError: @@ -87,7 +87,9 @@ try: idx = int(match.group(1)) except ValueError: - raise ParseError("Invalid value [%s] for parameter number" % match.group(1)) + raise ParseError( + "Invalid value [%s] for parameter number" % match.group(1) + ) default_dict[idx] = self.bridge_template.get(name, option) return default_dict @@ -112,15 +114,17 @@ 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): - if option == 'doc_return': - doc_dict['return'] = self.bridge_template.get(name, option) + if option == "doc_return": + doc_dict["return"] = self.bridge_template.get(name, option) continue match = option_re.match(option) if match: try: idx = int(match.group(1)) except ValueError: - raise ParseError("Invalid value [%s] for parameter number" % match.group(1)) + raise ParseError( + "Invalid value [%s] for parameter number" % match.group(1) + ) value_match = value_re.match(self.bridge_template.get(name, option)) if not value_match: raise ParseError("Invalid value for parameter doc [%i]" % idx) @@ -141,21 +145,35 @@ i = 0 while i < len(signature): - if signature[i] not in ['b', 'y', 'n', 'i', 'x', 'q', 'u', 't', 'd', 's', 'a']: + 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': + if signature[i] == "a": i += 1 - if signature[i] != '{' and signature[i] != '(': # FIXME: must manage tuples out of arrays + 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 opening_car = signature[i] - assert(opening_car in ['{', '(']) - closing_car = '}' if opening_car == '{' else ')' + assert opening_car in ["{", "("] + closing_car = "}" if opening_car == "{" else ")" opening_count = 1 - while (True): # we have a dict or a list of tuples + while True: # we have a dict or a list of tuples i += 1 if i >= len(signature): raise ParseError("missing }") @@ -182,11 +200,19 @@ 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 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 + 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) @@ -214,7 +240,6 @@ """override this method to extend completion""" pass - def generate(self, side): """generate bridge @@ -242,7 +267,7 @@ @param side(str): core or frontend """ side_vars = [] - for var in ('FORMATS', 'TEMPLATE', 'DEST'): + for var in ("FORMATS", "TEMPLATE", "DEST"): attr = "{}_{}".format(side.upper(), var) value = getattr(self, attr) if value is None: @@ -252,59 +277,70 @@ FORMATS, TEMPLATE, DEST = side_vars del side_vars - parts = {part.upper():[] for part in FORMATS} + parts = {part.upper(): [] for part in FORMATS} sections = self.bridge_template.sections() sections.sort() for section in sections: function = self.getValues(section) - print ("Adding %s %s" % (section, function["type"])) + print("Adding %s %s" % (section, function["type"])) default = self.getDefault(section) 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, + "sig_in": function["sig_in"] or "", + "sig_out": function["sig_out"] or "", + "category": "plugin" if function["category"] == "plugin" else "core", + "name": section, # arguments with default values - 'args': self.getArguments(function['sig_in'], name=arg_doc, default=default), - } + "args": self.getArguments( + function["sig_in"], name=arg_doc, default=default + ), + } - extend_method = getattr(self, "{}_completion_{}".format(side, function["type"])) + extend_method = getattr( + self, "{}_completion_{}".format(side, function["type"]) + ) extend_method(completion, function, default, arg_doc, async_) for part, fmt in FORMATS.iteritems(): if part.startswith(function["type"]): parts[part.upper()].append(fmt.format(**completion)) - - #at this point, signals_part, methods_part and direct_calls should be filled, - #we just have to place them in the right part of the template + # at this point, signals_part, methods_part and direct_calls should be filled, + # we just have to place them in the right part of the template bridge = [] - const_override = {env[len(C.ENV_OVERRIDE):]:v for env,v in os.environ.iteritems() if env.startswith(C.ENV_OVERRIDE)} + const_override = { + env[len(C.ENV_OVERRIDE) :]: v + for env, v in os.environ.iteritems() + if env.startswith(C.ENV_OVERRIDE) + } template_path = self.getTemplatePath(TEMPLATE) try: with open(template_path) as template: for line in template: for part, extend_list in parts.iteritems(): - if line.startswith('##{}_PART##'.format(part)): + if line.startswith("##{}_PART##".format(part)): bridge.extend(extend_list) break else: # the line is not a magic part replacement - if line.startswith('const_'): - const_name = line[len('const_'):line.find(' = ')].strip() + if line.startswith("const_"): + const_name = line[len("const_") : line.find(" = ")].strip() if const_name in const_override: print("const {} overriden".format(const_name)) - bridge.append('const_{} = {}'.format(const_name, const_override[const_name])) + bridge.append( + "const_{} = {}".format( + const_name, const_override[const_name] + ) + ) continue - bridge.append(line.replace('\n', '')) + bridge.append(line.replace("\n", "")) except IOError: - print ("can't open template file [{}]".format(template_path)) + print("can't open template file [{}]".format(template_path)) sys.exit(1) - #now we write to final file + # now we write to final file self.finalWrite(DEST, bridge) def finalWrite(self, filename, file_buf): @@ -314,19 +350,24 @@ @param file_buf: list of lines (stings) of the file """ if os.path.exists(self.args.dest_dir) and not os.path.isdir(self.args.dest_dir): - print ("The destination dir [%s] can't be created: a file with this name already exists !") + print( + "The destination dir [%s] can't be created: a file with this name already exists !" + ) sys.exit(1) try: if not os.path.exists(self.args.dest_dir): os.mkdir(self.args.dest_dir) full_path = os.path.join(self.args.dest_dir, filename) if os.path.exists(full_path) and not self.args.force: - print ("The destination file [%s] already exists ! Use --force to overwrite it" % full_path) + print( + "The destination file [%s] already exists ! Use --force to overwrite it" + % full_path + ) try: - with open(full_path, 'w') as dest_file: - dest_file.write('\n'.join(file_buf)) + 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) + print("Can't open destination file [%s]" % full_path) except OSError: print("It's not possible to generate the file, check your permissions") exit(1)