(
line: Line,
transform: Transformer,
mode: Mode,
features: Collection[Feature],
*,
line_str: str = "",
)
| 2048 | |
| 2049 | |
| 2050 | def run_transformer( |
| 2051 | line: Line, |
| 2052 | transform: Transformer, |
| 2053 | mode: Mode, |
| 2054 | features: Collection[Feature], |
| 2055 | *, |
| 2056 | line_str: str = "", |
| 2057 | ) -> list[Line]: |
| 2058 | if not line_str: |
| 2059 | line_str = line_to_string(line) |
| 2060 | result: list[Line] = [] |
| 2061 | for transformed_line in transform(line, features, mode): |
| 2062 | if str(transformed_line).strip("\n") == line_str: |
| 2063 | raise CannotTransform("Line transformer returned an unchanged result") |
| 2064 | |
| 2065 | result.extend(transform_line(transformed_line, mode=mode, features=features)) |
| 2066 | |
| 2067 | features_set = set(features) |
| 2068 | if ( |
| 2069 | Feature.FORCE_OPTIONAL_PARENTHESES in features_set |
| 2070 | or transform.__class__.__name__ != "rhs" |
| 2071 | or not line.bracket_tracker.invisible |
| 2072 | or any(bracket.value for bracket in line.bracket_tracker.invisible) |
| 2073 | or line.contains_multiline_strings() |
| 2074 | or result[0].contains_uncollapsable_type_comments() |
| 2075 | or result[0].contains_unsplittable_type_ignore() |
| 2076 | or is_line_short_enough(result[0], mode=mode) |
| 2077 | # result[0] only exceeds the length because of a comment attached to a |
| 2078 | # subscript opening bracket. Taking the FORCE_OPTIONAL_PARENTHESES |
| 2079 | # "second opinion" wraps the annotation in extra invisible parens and |
| 2080 | # migrates the comment outside the subscript, which then oscillates with |
| 2081 | # a deeper-bracket split on the next formatter pass (issue #4733). |
| 2082 | or _over_length_only_due_to_subscript_comment(result[0], mode) |
| 2083 | # If any leaves have no parents (which _can_ occur since |
| 2084 | # `transform(line)` potentially destroys the line's underlying node |
| 2085 | # structure), then we can't proceed. Doing so would cause the below |
| 2086 | # call to `append_leaves()` to fail. |
| 2087 | or any(leaf.parent is None for leaf in line.leaves) |
| 2088 | ): |
| 2089 | return result |
| 2090 | |
| 2091 | line_copy = line.clone() |
| 2092 | append_leaves(line_copy, line, line.leaves) |
| 2093 | features_fop = features_set | {Feature.FORCE_OPTIONAL_PARENTHESES} |
| 2094 | second_opinion = run_transformer( |
| 2095 | line_copy, transform, mode, features_fop, line_str=line_str |
| 2096 | ) |
| 2097 | if all(is_line_short_enough(ln, mode=mode) for ln in second_opinion): |
| 2098 | result = second_opinion |
| 2099 | return result |
no test coverage detected