Skip to content

Commit 4b4e815

Browse files
ssbrcopybara-github
authored andcommitted
Enable pytype for a couple of things in fix.
PiperOrigin-RevId: 396091963
1 parent 52ed46b commit 4b4e815

File tree

6 files changed

+41
-28
lines changed

6 files changed

+41
-28
lines changed

refex/python/matcher.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -182,9 +182,7 @@ def _coerce_list(values):
182182
_IS_SUBMATCHER_LIST_ATTRIB = __name__ + '._IS_SUBMATCHER_LIST_ATTRIB'
183183

184184

185-
def submatcher_attrib(
186-
*args,
187-
**kwargs: Any): # TODO: make walk a kwarg when Py2 support is dropped.
185+
def submatcher_attrib(*args, walk: bool = True, **kwargs: Any):
188186
"""Creates an attr.ib that is marked as a submatcher.
189187
190188
This will cause the matcher to be automatically walked as part of the
@@ -199,15 +197,13 @@ def submatcher_attrib(
199197
Returns:
200198
An attr.ib()
201199
"""
202-
if kwargs.pop('walk', True):
200+
if walk:
203201
kwargs.setdefault('metadata', {})[_IS_SUBMATCHER_ATTRIB] = True
204202
kwargs.setdefault('converter', coerce)
205203
return attr.ib(*args, **kwargs)
206204

207205

208-
def submatcher_list_attrib(
209-
*args,
210-
**kwargs: Any): # TODO: make walk a kwarg when Py2 support is dropped.
206+
def submatcher_list_attrib(*args, walk: bool = True, **kwargs: Any):
211207
"""Creates an attr.ib that is marked as an iterable of submatchers.
212208
213209
This will cause the matcher to be automatically walked as part of the
@@ -222,7 +218,7 @@ def submatcher_list_attrib(
222218
Returns:
223219
An attr.ib()
224220
"""
225-
if kwargs.pop('walk', True):
221+
if walk:
226222
kwargs.setdefault('metadata', {})[_IS_SUBMATCHER_LIST_ATTRIB] = True
227223
kwargs.setdefault('converter', _coerce_list)
228224
return attr.ib(*args, **kwargs)
@@ -666,8 +662,8 @@ class MatchInfo(object):
666662
"""
667663
match = attr.ib(type=_match.Match)
668664
# TODO: also add a top-level `replacement` variable, replacing the magic root.
669-
bindings = attr.ib(factory=dict, type=Dict[str, _match.Match])
670-
replacements = attr.ib(factory=dict, type=Dict[str, _match.Match])
665+
bindings = attr.ib(factory=dict, type=Dict[str, BoundValue])
666+
replacements = attr.ib(factory=dict, type=Dict[str, formatting.Template])
671667

672668

673669
def _stringify_candidate(context, candidate):

refex/python/syntactic_template.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,8 +133,8 @@ class _BasePythonTemplate(formatting.Template):
133133
template: The source template
134134
"""
135135
template = attr.ib(type=Text)
136-
_lexical_template = attr.ib(repr=False, init=False) # type: _LexicalTemplate
137-
_ast_matcher = attr.ib(repr=False, init=False) # type: matcher.Matcher
136+
_lexical_template = attr.ib(repr=False, init=False, type=_LexicalTemplate)
137+
_ast_matcher = attr.ib(repr=False, init=False, type=matcher.Matcher)
138138

139139
def __attrs_post_init__(self):
140140
if not isinstance(self.template, six.text_type):

refex/rxerr_debug.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -46,18 +46,19 @@ def main(argv):
4646
source = failure['content']
4747
except KeyError:
4848
pass
49-
with tempfile.NamedTemporaryFile(
50-
mode='w', encoding='utf-8', suffix='.py', delete=False) as out_f:
51-
out_f.write(source)
52-
print('Content:', out_f.name)
49+
else:
50+
with tempfile.NamedTemporaryFile(
51+
mode='w', encoding='utf-8', suffix='.py', delete=False) as out_f:
52+
out_f.write(source)
53+
print('Content:', out_f.name)
5354
try:
5455
tb = failure['traceback']
5556
except KeyError:
5657
pass
5758
else:
58-
print(
59-
pygments.highlight(tb, lexers.PythonTracebackLexer(),
60-
formatters.Terminal256Formatter()))
59+
lexer = lexers.PythonTracebackLexer() # pytype: disable=module-attr
60+
formatter = formatters.Terminal256Formatter() # pytype: disable=module-attr
61+
print(pygments.highlight(tb, lexer, formatter))
6162

6263

6364
if __name__ == '__main__':

refex/search.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@ class CombinedSearcher(AbstractSearcher):
420420
# could walk once and only run the searchers that could possibly match
421421
# at a given point using an O(1) type lookup -- which would generally cut
422422
# down the number of results.
423-
searchers = attr.ib(type=Tuple[AbstractSearcher, ...], converter=tuple,)
423+
searchers = attr.ib(type=Sequence[AbstractSearcher], converter=tuple)
424424

425425
def parse(self, data: Text, filename: str):
426426
"""Parses using each sub-searcher, returning the most specific parsed file.
@@ -630,7 +630,7 @@ def find_dicts_parsed(
630630
def key_span_for_dict(
631631
self,
632632
parsed: parsed_file.ParsedFile,
633-
match_dict: Iterable[Mapping[MatchKey, match.Match]],
633+
match_dict: Mapping[MatchKey, match.Match],
634634
) -> Optional[Tuple[int, int]]:
635635
"""Returns the ``key_span`` that the final ``Substitution`` will have."""
636636
return None
@@ -682,12 +682,10 @@ def __attrs_post_init__(self):
682682
missing_labels = formatting.template_variables(
683683
self.templates) - pattern_labels
684684
if missing_labels:
685+
groups = ', '.join(f'`{g}`' for g in sorted(map(str, missing_labels)))
685686
raise ValueError(
686-
'The substitution template(s) referenced groups not available in the regex (`{self._compiled.pattern}`): {groups}'
687-
.format(
688-
self=self,
689-
groups=', '.join(
690-
'`{}`'.format(g) for g in sorted(map(str, missing_labels)))))
687+
f'The substitution template(s) referenced groups not available in the regex (`{self._compiled.pattern}`): {groups}'
688+
)
691689

692690
@classmethod
693691
def from_pattern(cls, pattern: str, templates: Optional[Dict[str, formatting.Template]]):
@@ -734,7 +732,7 @@ class BasePythonRewritingSearcher(BasePythonSearcher, BaseRewritingSearcher):
734732
_matcher = attr.ib()
735733

736734
@classmethod
737-
def from_matcher(cls, matcher, templates: Optional[Dict[str, formatting.Template]]):
735+
def from_matcher(cls, matcher, templates: Dict[str, formatting.Template]):
738736
"""Creates a searcher from an evaluated matcher, and adds a root label."""
739737
# We wrap the evaluated matcher in a SystemBind() that is sort of like
740738
# "group 0" for regexes.

refex/substitution.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def _validate(self):
150150
expected_type=six.text_type.__name__,
151151
actual_type=type(replacement).__name__))
152152

153-
def relative_to_span(self, start: int, end: int) -> "Substitution":
153+
def relative_to_span(self, start: int, end: int) -> Optional['Substitution']:
154154
"""Returns a new substitution that is offset relative to the provided span.
155155
156156
If ``sub`` is a :class:`Substitution` for ``s``, then

refex/test_rxerr_debug.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,24 @@ def test_argv(self):
2929
# Instead, we can just run shlex.split() over it as a quick safety check.
3030
self.assertEqual(shlex.split(stdout.getvalue()), ['Command:'] + argv)
3131

32+
def test_traceback(self):
33+
"""Tests that the traceback shows up, ish."""
34+
tb = ('Traceback (most recent call last):\n'
35+
' File "<stdin>", line 1, in <module>\n'
36+
'SomeError: description\n')
37+
path = self.create_tempfile(
38+
content=json.dumps({'failures': {
39+
'path': {
40+
'traceback': tb
41+
}
42+
}})).full_path
43+
stdout = io.StringIO()
44+
with contextlib.redirect_stdout(stdout):
45+
rxerr_debug.main(['rxerr_debug', path])
46+
stdout = stdout.getvalue()
47+
self.assertIn('SomeError', stdout)
48+
self.assertIn('description', stdout)
49+
3250

3351
if __name__ == '__main__':
3452
absltest.main()

0 commit comments

Comments
 (0)