1- from typing import ClassVar , Collection
1+ from functools import cache
2+ from typing import ClassVar , Collection , cast
23
34import libcst as cst
45from libcst import MetadataDependent
@@ -23,13 +24,22 @@ def __init__(
2324 self .line_exclude = line_exclude
2425 self .line_include = line_include
2526
26- def filter_by_result (self , node ):
27+ def filter_by_result (self , node : cst .CSTNode ) -> bool :
28+ # Codemods with detectors will only run their transformations if there are results.
29+ return self .results is None or any (self .results_for_node (node ))
30+
31+ @cache
32+ def results_for_node (self , node : cst .CSTNode ) -> list [Result ]:
2733 pos_to_match = self .node_position (node )
28- if self .results is None :
29- # Returning True here means codemods without detectors (and results)
30- # will still run their transformations.
31- return True
32- return any (result .match_location (pos_to_match , node ) for result in self .results )
34+ return (
35+ [
36+ result
37+ for result in self .results
38+ if result .match_location (pos_to_match , node )
39+ ]
40+ if self .results
41+ else []
42+ )
3343
3444 def filter_by_path_includes_or_excludes (self , pos_to_match ):
3545 """
@@ -55,13 +65,17 @@ def node_position(self, node):
5565 # By default a function's position includes the entire
5666 # function definition. Instead, we will only use the first line
5767 # of the function definition.
58- params_end = self .get_metadata (PositionProvider , node .params ).end
68+ params_end = cast (
69+ CodeRange , self .get_metadata (PositionProvider , node .params )
70+ ).end
5971 return CodeRange (
60- start = self .get_metadata (PositionProvider , node ).start ,
72+ start = cast (
73+ CodeRange , self .get_metadata (PositionProvider , node )
74+ ).start ,
6175 end = CodePosition (params_end .line , params_end .column + 1 ),
6276 )
6377 case _:
64- return self .get_metadata (PositionProvider , node )
78+ return cast ( CodeRange , self .get_metadata (PositionProvider , node ) )
6579
6680 def lineno_for_node (self , node ):
6781 return self .node_position (node ).start .line
0 commit comments