From 24e22931656478e774f1da6021a5a1c46b41b475 Mon Sep 17 00:00:00 2001 From: Yasser Tahiri Date: Sat, 7 Aug 2021 11:07:05 +0100 Subject: [PATCH 1/7] =?UTF-8?q?=E2=9B=8F=20Refactor=20Code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace yield inside for loop with yield from - Replace if statement with if expression --- mako/ext/babelplugin.py | 3 +-- mako/ext/extract.py | 6 ++---- mako/ext/linguaplugin.py | 3 +-- mako/ext/pygmentplugin.py | 5 +---- 4 files changed, 5 insertions(+), 12 deletions(-) diff --git a/mako/ext/babelplugin.py b/mako/ext/babelplugin.py index 76bbc5b..91b33b4 100644 --- a/mako/ext/babelplugin.py +++ b/mako/ext/babelplugin.py @@ -54,5 +54,4 @@ def extract(fileobj, keywords, comment_tags, options): :rtype: ``iterator`` """ extractor = BabelMakoExtractor(keywords, comment_tags, options) - for message in extractor(fileobj): - yield message + yield from extractor(fileobj) diff --git a/mako/ext/extract.py b/mako/ext/extract.py index ad2348a..7cfcbac 100644 --- a/mako/ext/extract.py +++ b/mako/ext/extract.py @@ -16,8 +16,7 @@ def process_file(self, fileobj): template_node = lexer.Lexer( fileobj.read(), input_encoding=self.config["encoding"] ).parse() - for extracted in self.extract_nodes(template_node.get_children()): - yield extracted + yield from self.extract_nodes(template_node.get_children()) def extract_nodes(self, nodes): translator_comments = [] @@ -112,8 +111,7 @@ def extract_nodes(self, nodes): in_translator_comments = False if child_nodes: - for extracted in self.extract_nodes(child_nodes): - yield extracted + yield from self.extract_nodes(child_nodes) @staticmethod def _split_comment(lineno, comment): diff --git a/mako/ext/linguaplugin.py b/mako/ext/linguaplugin.py index c40fa74..e429ace 100644 --- a/mako/ext/linguaplugin.py +++ b/mako/ext/linguaplugin.py @@ -31,8 +31,7 @@ def __call__(self, filename, options, fileobj=None): else: must_close = False try: - for message in self.process_file(fileobj): - yield message + yield from self.process_file(fileobj) finally: if must_close: fileobj.close() diff --git a/mako/ext/pygmentplugin.py b/mako/ext/pygmentplugin.py index 943a67a..10199d5 100644 --- a/mako/ext/pygmentplugin.py +++ b/mako/ext/pygmentplugin.py @@ -144,10 +144,7 @@ def __init__(self, **options): def syntax_highlight(filename="", language=None): mako_lexer = MakoLexer() - if compat.py3k: - python_lexer = Python3Lexer() - else: - python_lexer = PythonLexer() + python_lexer = Python3Lexer() if compat.py3k else PythonLexer() if filename.startswith("memory:") or language == "mako": return lambda string: highlight( string, mako_lexer, pygments_html_formatter From 3e84c9c482cb8907e014fb5a14fc8a04c09a1e2a Mon Sep 17 00:00:00 2001 From: Yasser Tahiri Date: Sat, 7 Aug 2021 11:07:24 +0100 Subject: [PATCH 2/7] =?UTF-8?q?=F0=9F=9B=A0=20Refactor=20Multipart=20of=20?= =?UTF-8?q?code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mako/ast.py | 2 +- mako/exceptions.py | 24 +++--- mako/lexer.py | 190 ++++++++++++++++++++++----------------------- mako/lookup.py | 22 +++--- mako/parsetree.py | 18 ++--- mako/pygen.py | 40 ++++------ mako/pyparser.py | 24 +++--- mako/runtime.py | 17 ++-- mako/template.py | 35 ++++----- mako/util.py | 34 ++++---- 10 files changed, 183 insertions(+), 223 deletions(-) diff --git a/mako/ast.py b/mako/ast.py index cfae280..f458b4d 100644 --- a/mako/ast.py +++ b/mako/ast.py @@ -97,7 +97,7 @@ def __init__(self, code, **exception_kwargs): code = code + "pass" elif keyword == "try": code = code + "pass\nexcept:pass" - elif keyword == "elif" or keyword == "else": + elif keyword in ["elif", "else"]: code = "if False:pass\n" + code + "pass" elif keyword == "except": code = "try:pass\n" + code + "pass" diff --git a/mako/exceptions.py b/mako/exceptions.py index ea7b20d..6bb1e9f 100644 --- a/mako/exceptions.py +++ b/mako/exceptions.py @@ -172,15 +172,11 @@ def _init(self, trcback): # A normal .py file (not a Template) if not compat.py3k: try: - fp = open(filename, "rb") - encoding = util.parse_encoding(fp) - fp.close() + with open(filename, "rb") as fp: + encoding = util.parse_encoding(fp) except IOError: encoding = None - if encoding: - line = line.decode(encoding) - else: - line = line.decode("ascii", "replace") + line = line.decode(encoding) if encoding else line.decode("ascii", "replace") new_trcback.append( ( filename, @@ -235,14 +231,12 @@ def _init(self, trcback): else: if new_trcback: try: - # A normal .py file (not a Template) - fp = open(new_trcback[-1][0], "rb") - encoding = util.parse_encoding(fp) - if compat.py3k and not encoding: - encoding = "utf-8" - fp.seek(0) - self.source = fp.read() - fp.close() + with open(new_trcback[-1][0], "rb") as fp: + encoding = util.parse_encoding(fp) + if compat.py3k and not encoding: + encoding = "utf-8" + fp.seek(0) + self.source = fp.read() if encoding: self.source = self.source.decode(encoding) except IOError: diff --git a/mako/lexer.py b/mako/lexer.py index 6226e26..16b3cdb 100644 --- a/mako/lexer.py +++ b/mako/lexer.py @@ -66,10 +66,7 @@ def match(self, regexp, flags=None): try: reg = _regexp_cache[(regexp, flags)] except KeyError: - if flags: - reg = re.compile(regexp, flags) - else: - reg = re.compile(regexp) + reg = re.compile(regexp, flags) if flags else re.compile(regexp) _regexp_cache[(regexp, flags)] = reg return self.match_reg(reg) @@ -87,10 +84,7 @@ def match_reg(self, reg): match = reg.match(self.text, self.match_position) if match: (start, end) = match.span() - if end == start: - self.match_position = end + 1 - else: - self.match_position = end + self.match_position = end + 1 if end == start else end self.matched_lineno = self.lineno lines = re.findall(r"\n", self.text[mp : self.match_position]) cp = mp - 1 @@ -98,8 +92,8 @@ def match_reg(self, reg): cp -= 1 self.matched_charpos = mp - cp self.lineno += len(lines) - # print "MATCHED:", match.group(0), "LINE START:", - # self.matched_lineno, "LINE END:", self.lineno + # print "MATCHED:", match.group(0), "LINE START:", + # self.matched_lineno, "LINE END:", self.lineno # print "MATCH:", regexp, "\n", self.text[mp : mp + 15], \ # (match and "TRUE" or "FALSE") return match @@ -161,12 +155,15 @@ def append_node(self, nodecls, *args, **kwargs): if self.control_line: control_frame = self.control_line[-1] control_frame.nodes.append(node) - if not ( - isinstance(node, parsetree.ControlLine) - and control_frame.is_ternary(node.keyword) + if ( + not ( + isinstance(node, parsetree.ControlLine) + and control_frame.is_ternary(node.keyword) + ) + and self.ternary_stack + and self.ternary_stack[-1] ): - if self.ternary_stack and self.ternary_stack[-1]: - self.ternary_stack[-1][-1].nodes.append(node) + self.ternary_stack[-1][-1].nodes.append(node) if isinstance(node, parsetree.Tag): if len(self.tag): node.parent = self.tag[-1] @@ -219,11 +216,7 @@ def decode_raw_stream(self, text, decode_raw, known_encoding, filename): ) else: m = self._coding_re.match(text.decode("utf-8", "ignore")) - if m: - parsed_encoding = m.group(1) - else: - parsed_encoding = known_encoding or "utf-8" - + parsed_encoding = m.group(1) if m else known_encoding or "utf-8" if decode_raw: try: text = text.decode(parsed_encoding) @@ -312,35 +305,34 @@ def match_tag_start(self): re.I | re.S | re.X, ) - if match: - keyword, attr, isend = match.groups() - self.keyword = keyword - attributes = {} - if attr: - for att in re.findall( - r"\s*(\w+)\s*=\s*(?:'([^']*)'|\"([^\"]*)\")", attr - ): - key, val1, val2 = att - text = val1 or val2 - text = text.replace("\r\n", "\n") - attributes[key] = text - self.append_node(parsetree.Tag, keyword, attributes) - if isend: - self.tag.pop() - else: - if keyword == "text": - match = self.match(r"(.*?)(?=\)", re.S) - if not match: - raise exceptions.SyntaxException( - "Unclosed tag: <%%%s>" % self.tag[-1].keyword, - **self.exception_kwargs - ) - self.append_node(parsetree.Text, match.group(1)) - return self.match_tag_end() - return True - else: + if not match: return False + keyword, attr, isend = match.groups() + self.keyword = keyword + attributes = {} + if attr: + for att in re.findall( + r"\s*(\w+)\s*=\s*(?:'([^']*)'|\"([^\"]*)\")", attr + ): + key, val1, val2 = att + text = val1 or val2 + text = text.replace("\r\n", "\n") + attributes[key] = text + self.append_node(parsetree.Tag, keyword, attributes) + if isend: + self.tag.pop() + elif keyword == "text": + match = self.match(r"(.*?)(?=\)", re.S) + if not match: + raise exceptions.SyntaxException( + "Unclosed tag: <%%%s>" % self.tag[-1].keyword, + **self.exception_kwargs + ) + self.append_node(parsetree.Text, match.group(1)) + return self.match_tag_end() + return True + def match_tag_end(self): match = self.match(r"\") if match: @@ -363,15 +355,15 @@ def match_tag_end(self): def match_end(self): match = self.match(r"\Z", re.S) - if match: - string = match.group() - if string: - return string - else: - return True - else: + if not match: return False + string = match.group() + if string: + return string + else: + return True + def match_text(self): match = self.match( r""" @@ -422,63 +414,63 @@ def match_python_block(self): def match_expression(self): match = self.match(r"\${") - if match: - line, pos = self.matched_lineno, self.matched_charpos - text, end = self.parse_until_text(True, r"\|", r"}") - if end == "|": - escapes, end = self.parse_until_text(True, r"}") - else: - escapes = "" - text = text.replace("\r\n", "\n") - self.append_node( - parsetree.Expression, - text, - escapes.strip(), - lineno=line, - pos=pos, - ) - return True - else: + if not match: return False + line, pos = self.matched_lineno, self.matched_charpos + text, end = self.parse_until_text(True, r"\|", r"}") + if end == "|": + escapes, end = self.parse_until_text(True, r"}") + else: + escapes = "" + text = text.replace("\r\n", "\n") + self.append_node( + parsetree.Expression, + text, + escapes.strip(), + lineno=line, + pos=pos, + ) + return True + def match_control_line(self): match = self.match( r"(?<=^)[\t ]*(%(?!%)|##)[\t ]*((?:(?:\\r?\n)|[^\r\n])*)" r"(?:\r?\n|\Z)", re.M, ) - if match: - operator = match.group(1) - text = match.group(2) - if operator == "%": - m2 = re.match(r"(end)?(\w+)\s*(.*)", text) - if not m2: + if not match: + return False + + operator = match.group(1) + text = match.group(2) + if operator == "%": + m2 = re.match(r"(end)?(\w+)\s*(.*)", text) + if not m2: + raise exceptions.SyntaxException( + "Invalid control line: '%s'" % text, + **self.exception_kwargs + ) + isend, keyword = m2.group(1, 2) + isend = isend is not None + + if isend: + if not len(self.control_line): raise exceptions.SyntaxException( - "Invalid control line: '%s'" % text, + "No starting keyword '%s' for '%s'" + % (keyword, text), **self.exception_kwargs ) - isend, keyword = m2.group(1, 2) - isend = isend is not None - - if isend: - if not len(self.control_line): - raise exceptions.SyntaxException( - "No starting keyword '%s' for '%s'" - % (keyword, text), - **self.exception_kwargs - ) - elif self.control_line[-1].keyword != keyword: - raise exceptions.SyntaxException( - "Keyword '%s' doesn't match keyword '%s'" - % (text, self.control_line[-1].keyword), - **self.exception_kwargs - ) - self.append_node(parsetree.ControlLine, keyword, isend, text) - else: - self.append_node(parsetree.Comment, text) - return True + elif self.control_line[-1].keyword != keyword: + raise exceptions.SyntaxException( + "Keyword '%s' doesn't match keyword '%s'" + % (text, self.control_line[-1].keyword), + **self.exception_kwargs + ) + self.append_node(parsetree.ControlLine, keyword, isend, text) else: - return False + self.append_node(parsetree.Comment, text) + return True def match_comment(self): """matches the multiline version of a comment""" diff --git a/mako/lookup.py b/mako/lookup.py index 476326d..65d83b2 100644 --- a/mako/lookup.py +++ b/mako/lookup.py @@ -270,15 +270,14 @@ def adjust_uri(self, uri, relativeto): if key in self._uri_cache: return self._uri_cache[key] - if uri[0] != "/": - if relativeto is not None: - v = self._uri_cache[key] = posixpath.join( - posixpath.dirname(relativeto), uri - ) - else: - v = self._uri_cache[key] = "/" + uri - else: + if uri[0] == "/": v = self._uri_cache[key] = uri + elif relativeto is not None: + v = self._uri_cache[key] = posixpath.join( + posixpath.dirname(relativeto), uri + ) + else: + v = self._uri_cache[key] = "/" + uri return v def filename_to_uri(self, filename): @@ -342,11 +341,10 @@ def _check(self, uri, template): try: template_stat = os.stat(template.filename) - if template.module._modified_time < template_stat[stat.ST_MTIME]: - self._collection.pop(uri, None) - return self._load(template.filename, uri) - else: + if template.module._modified_time >= template_stat[stat.ST_MTIME]: return template + self._collection.pop(uri, None) + return self._load(template.filename, uri) except OSError: self._collection.pop(uri, None) raise exceptions.TemplateLookupException( diff --git a/mako/parsetree.py b/mako/parsetree.py index 801e48a..f019f8f 100644 --- a/mako/parsetree.py +++ b/mako/parsetree.py @@ -304,10 +304,10 @@ def __init__( missing = [r for r in required if r not in self.parsed_attributes] if len(missing): raise exceptions.CompileException( - "Missing attribute(s): %s" - % ",".join([repr(m) for m in missing]), + ("Missing attribute(s): %s" % ",".join(repr(m) for m in missing)), **self.exception_kwargs ) + self.parent = None self.nodes = [] @@ -339,9 +339,8 @@ def _parse_attributes(self, expressions, nonexpressions): code.undeclared_identifiers ) expr.append("(%s)" % m.group(1)) - else: - if x: - expr.append(repr(x)) + elif x: + expr.append(repr(x)) self.parsed_attributes[key] = " + ".join(expr) or repr("") elif key in nonexpressions: if re.search(r"\${.+?}", self.attributes[key]): @@ -610,13 +609,12 @@ def __init__(self, namespace, defname, attributes, **kwargs): namespace, defname, ",".join( - [ - "%s=%s" % (k, v) - for k, v in self.parsed_attributes.items() - if k != "args" - ] + "%s=%s" % (k, v) + for k, v in self.parsed_attributes.items() + if k != "args" ), ) + self.code = ast.PythonCode(self.expression, **self.exception_kwargs) self.body_decl = ast.FunctionArgs( attributes.get("args", ""), **self.exception_kwargs diff --git a/mako/pygen.py b/mako/pygen.py index 947721f..02ee8a8 100644 --- a/mako/pygen.py +++ b/mako/pygen.py @@ -96,18 +96,20 @@ def writeline(self, line): is_comment = line and len(line) and line[0] == "#" # see if this line should decrease the indentation level - if not is_comment and (not hastext or self._is_unindentor(line)): - - if self.indent > 0: - self.indent -= 1 - # if the indent_detail stack is empty, the user - # probably put extra closures - the resulting - # module wont compile. - if len(self.indent_detail) == 0: - raise exceptions.SyntaxException( - "Too many whitespace closures" - ) - self.indent_detail.pop() + if ( + not is_comment + and (not hastext or self._is_unindentor(line)) + and self.indent > 0 + ): + self.indent -= 1 + # if the indent_detail stack is empty, the user + # probably put extra closures - the resulting + # module wont compile. + if len(self.indent_detail) == 0: + raise exceptions.SyntaxException( + "Too many whitespace closures" + ) + self.indent_detail.pop() if line is None: return @@ -167,13 +169,7 @@ def _is_unindentor(self, line): # if the current line doesnt have one of the "unindentor" keywords, # return False match = re.match(r"^\s*(else|elif|except|finally).*\:", line) - if not match: - return False - - # whitespace matches up, we have a compound indentor, - # and this line has an unindentor, this - # is probably good enough - return True + return bool(match) # should we decide that its not good enough, heres # more stuff to check. @@ -218,11 +214,7 @@ def _in_multi_line(self, line): current_state = self.backslashed or self.triplequoted - if re.search(r"\\$", line): - self.backslashed = True - else: - self.backslashed = False - + self.backslashed = bool(re.search(r"\\$", line)) triples = len(re.findall(r"\"\"\"|\'\'\'", line)) if triples == 1 or triples % 2 != 0: self.triplequoted = not self.triplequoted diff --git a/mako/pyparser.py b/mako/pyparser.py index b16672d..8b47921 100644 --- a/mako/pyparser.py +++ b/mako/pyparser.py @@ -108,8 +108,7 @@ def visit_FunctionDef(self, node): def _expand_tuples(self, args): for arg in args: if isinstance(arg, _ast.Tuple): - for n in arg.elts: - yield n + yield from arg.elts else: yield arg @@ -170,15 +169,15 @@ def visit_ImportFrom(self, node): for name in node.names: if name.asname is not None: self._add_declared(name.asname) + elif name.name == "*": + raise exceptions.CompileException( + "'import *' is not supported, since all identifier " + "names must be explicitly declared. Please use the " + "form 'from import , , " + "...' instead.", + **self.exception_kwargs + ) else: - if name.name == "*": - raise exceptions.CompileException( - "'import *' is not supported, since all identifier " - "names must be explicitly declared. Please use the " - "form 'from import , , " - "...' instead.", - **self.exception_kwargs - ) self._add_declared(name.name) @@ -225,10 +224,7 @@ def visit_FunctionDef(self, node): self.listener.argnames = argnames self.listener.defaults = node.args.defaults # ast self.listener.kwargnames = kwargnames - if compat.py2k: - self.listener.kwdefaults = [] - else: - self.listener.kwdefaults = node.args.kw_defaults + self.listener.kwdefaults = [] if compat.py2k else node.args.kw_defaults self.listener.varargs = node.args.vararg self.listener.kwargs = node.args.kwarg diff --git a/mako/runtime.py b/mako/runtime.py index 465908e..6bcdde0 100644 --- a/mako/runtime.py +++ b/mako/runtime.py @@ -482,15 +482,14 @@ def get_namespace(self, uri): key = (self, uri) if key in self.context.namespaces: return self.context.namespaces[key] - else: - ns = TemplateNamespace( - uri, - self.context._copy(), - templateuri=uri, - calling_uri=self._templateuri, - ) - self.context.namespaces[key] = ns - return ns + ns = TemplateNamespace( + uri, + self.context._copy(), + templateuri=uri, + calling_uri=self._templateuri, + ) + self.context.namespaces[key] = ns + return ns def get_template(self, uri): """Return a :class:`.Template` from the given ``uri``. diff --git a/mako/template.py b/mako/template.py index 5ed2320..0888601 100644 --- a/mako/template.py +++ b/mako/template.py @@ -267,7 +267,7 @@ def __init__( preprocessor=None, lexer_cls=None, include_error_handler=None, - ): + ): # sourcery no-metrics if uri: self.module_id = re.sub(r"\W", "_", uri) self.uri = uri @@ -387,11 +387,7 @@ def _setup_cache_args( ): self.cache_impl = cache_impl self.cache_enabled = cache_enabled - if cache_args: - self.cache_args = cache_args - else: - self.cache_args = {} - + self.cache_args = cache_args or {} # transfer deprecated cache_* args if cache_type: self.cache_args["type"] = cache_type @@ -658,9 +654,10 @@ def get_module_source_metadata(cls, module_source, full_line_map=False): r"__M_BEGIN_METADATA(.+?)__M_END_METADATA", module_source, re.S ).group(1) source_map = json.loads(source_map) - source_map["line_map"] = dict( - (int(k), int(v)) for k, v in source_map["line_map"].items() - ) + source_map["line_map"] = { + int(k): int(v) for k, v in source_map["line_map"].items() + } + if full_line_map: f_line_map = source_map["full_line_map"] = [] line_map = source_map["line_map"] @@ -681,22 +678,22 @@ def code(self): @property def source(self): - if self.template_source is not None: - if self.module._source_encoding and not isinstance( - self.template_source, compat.text_type - ): - return self.template_source.decode( - self.module._source_encoding - ) - else: - return self.template_source - else: + if self.template_source is None: data = util.read_file(self.template_filename) if self.module._source_encoding: return data.decode(self.module._source_encoding) else: return data + elif self.module._source_encoding and not isinstance( + self.template_source, compat.text_type + ): + return self.template_source.decode( + self.module._source_encoding + ) + else: + return self.template_source + def _compile(template, text, filename, generate_magic_comment): lexer = template.lexer_cls( diff --git a/mako/util.py b/mako/util.py index 16e3c72..b75fdc4 100644 --- a/mako/util.py +++ b/mako/util.py @@ -30,18 +30,17 @@ def __init__(self, group): def load(self, name): if name in self.impls: return self.impls[name]() - else: - import pkg_resources + import pkg_resources - for impl in pkg_resources.iter_entry_points(self.group, name): - self.impls[name] = impl.load - return impl.load() - else: - from mako import exceptions + for impl in pkg_resources.iter_entry_points(self.group, name): + self.impls[name] = impl.load + return impl.load() + else: + from mako import exceptions - raise exceptions.RuntimeException( - "Can't load plugin %s %s" % (self.group, name) - ) + raise exceptions.RuntimeException( + "Can't load plugin %s %s" % (self.group, name) + ) def register(self, name, modulepath, objname): def load(): @@ -148,10 +147,7 @@ class FastEncodingBuffer(object): def __init__(self, encoding=None, errors="strict", as_unicode=False): self.data = collections.deque() self.encoding = encoding - if as_unicode: - self.delim = compat.u("") - else: - self.delim = "" + self.delim = compat.u("") if as_unicode else "" self.as_unicode = as_unicode self.errors = errors self.write = self.data.append @@ -203,9 +199,8 @@ def values(self): def setdefault(self, key, value): if key in self: return self[key] - else: - self[key] = value - return value + self[key] = value + return value def __setitem__(self, key, value): item = dict.get(self, key) @@ -295,7 +290,7 @@ def sorted_dict_repr(d): """ keys = list(d.keys()) keys.sort() - return "{" + ", ".join(["%r: %r" % (k, d[k]) for k in keys]) + "}" + return "{" + ", ".join("%r: %r" % (k, d[k]) for k in keys) + "}" def restore__ast(_ast): @@ -382,8 +377,7 @@ class Bar(object): pass def read_file(path, mode="rb"): fp = open(path, mode) try: - data = fp.read() - return data + return fp.read() finally: fp.close() From 3c904540bc835627654f03c0c447d9e5d36890d8 Mon Sep 17 00:00:00 2001 From: Yasser Tahiri Date: Sat, 7 Aug 2021 11:07:45 +0100 Subject: [PATCH 3/7] =?UTF-8?q?=E2=9A=99=20Use=20`with`=20when=20opening?= =?UTF-8?q?=20file=20to=20ensure=20closure?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- setup.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/setup.py b/setup.py index cc5127d..b3b42f6 100644 --- a/setup.py +++ b/setup.py @@ -6,14 +6,12 @@ from setuptools import setup from setuptools.command.test import test as TestCommand -v = open(os.path.join(os.path.dirname(__file__), "mako", "__init__.py")) -VERSION = ( - re.compile(r".*__version__ = [\"'](.*?)[\"']", re.S) - .match(v.read()) - .group(1) -) -v.close() - +with open(os.path.join(os.path.dirname(__file__), "mako", "__init__.py")) as v: + VERSION = ( + re.compile(r".*__version__ = [\"'](.*?)[\"']", re.S) + .match(v.read()) + .group(1) + ) readme = os.path.join(os.path.dirname(__file__), "README.rst") install_requires = ["MarkupSafe>=0.9.2"] From 7706cd6cfdd8161bf769483041e17de648066748 Mon Sep 17 00:00:00 2001 From: Yasser Tahiri Date: Sat, 7 Aug 2021 11:10:14 +0100 Subject: [PATCH 4/7] =?UTF-8?q?=F0=9F=9B=A0=20Fix=20Metric=20Tag?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mako/template.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mako/template.py b/mako/template.py index 0888601..3ce2d6e 100644 --- a/mako/template.py +++ b/mako/template.py @@ -267,7 +267,7 @@ def __init__( preprocessor=None, lexer_cls=None, include_error_handler=None, - ): # sourcery no-metrics + ): if uri: self.module_id = re.sub(r"\W", "_", uri) self.uri = uri @@ -686,8 +686,8 @@ def source(self): return data elif self.module._source_encoding and not isinstance( - self.template_source, compat.text_type - ): + self.template_source, compat.text_type + ): return self.template_source.decode( self.module._source_encoding ) From 34088202d70eb0ab06a2eba26d8108a10c94f8bc Mon Sep 17 00:00:00 2001 From: Yasser Tahiri Date: Tue, 14 Sep 2021 04:39:54 +0100 Subject: [PATCH 5/7] Revert: Add the deleted comment --- mako/exceptions.py | 1 + 1 file changed, 1 insertion(+) diff --git a/mako/exceptions.py b/mako/exceptions.py index 6bb1e9f..353a594 100644 --- a/mako/exceptions.py +++ b/mako/exceptions.py @@ -231,6 +231,7 @@ def _init(self, trcback): else: if new_trcback: try: + # A normal .py file (not a Template) with open(new_trcback[-1][0], "rb") as fp: encoding = util.parse_encoding(fp) if compat.py3k and not encoding: From d94a8090586619b8f046b4ca9ac63ac64469b877 Mon Sep 17 00:00:00 2001 From: Yasser Tahiri Date: Tue, 14 Sep 2021 04:41:24 +0100 Subject: [PATCH 6/7] Revert: Add the Deleted Comment --- mako/pygen.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/mako/pygen.py b/mako/pygen.py index 02ee8a8..3aaf626 100644 --- a/mako/pygen.py +++ b/mako/pygen.py @@ -169,6 +169,9 @@ def _is_unindentor(self, line): # if the current line doesnt have one of the "unindentor" keywords, # return False match = re.match(r"^\s*(else|elif|except|finally).*\:", line) + # whitespace matches up, we have a compound indentor, + # and this line has an unindentor, this + # is probably good enough return bool(match) # should we decide that its not good enough, heres From c6243b116441f4b14e1cff00f47ed72aee3d3133 Mon Sep 17 00:00:00 2001 From: Federico Caselli Date: Mon, 25 Oct 2021 20:14:07 +0200 Subject: [PATCH 7/7] update review feedback Change-Id: I5cc5d75ce180c509a466e9e2a6aef19a87a4b9e5 --- mako/lexer.py | 4 ---- mako/util.py | 5 +---- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/mako/lexer.py b/mako/lexer.py index a86f5da..306ae4b 100644 --- a/mako/lexer.py +++ b/mako/lexer.py @@ -80,10 +80,6 @@ def match_reg(self, reg): cp -= 1 self.matched_charpos = mp - cp self.lineno += len(lines) - # print "MATCHED:", match.group(0), "LINE START:", - # self.matched_lineno, "LINE END:", self.lineno - # print "MATCH:", regexp, "\n", self.text[mp : mp + 15], \ - # (match and "TRUE" or "FALSE") return match def parse_until_text(self, watch_nesting, *text): diff --git a/mako/util.py b/mako/util.py index a273e27..952655c 100644 --- a/mako/util.py +++ b/mako/util.py @@ -370,11 +370,8 @@ class Bar: pass def read_file(path, mode="rb"): - fp = open(path, mode) - try: + with open(path, mode) as fp: return fp.read() - finally: - fp.close() def read_python_file(path):