MCPcopy
hub / github.com/psf/black / _merge_string_group

Method _merge_string_group

src/black/trans.py:546–599  ·  view source on GitHub ↗

Merges string groups (i.e. set of adjacent strings). Each index from `string_indices` designates one string group's first leaf in `line.leaves`. Returns: Ok(new_line), if ALL of the validation checks found in _validate_msg(...) pass.

(
        self, line: Line, string_indices: list[int]
    )

Source from the content-addressed store, hash-verified

544 return Ok(new_line)
545
546 def _merge_string_group(
547 self, line: Line, string_indices: list[int]
548 ) -> TResult[Line]:
549 """
550 Merges string groups (i.e. set of adjacent strings).
551
552 Each index from `string_indices` designates one string group's first
553 leaf in `line.leaves`.
554
555 Returns:
556 Ok(new_line), if ALL of the validation checks found in
557 _validate_msg(...) pass.
558 OR
559 Err(CannotTransform), otherwise.
560 """
561 LL = line.leaves
562
563 is_valid_index = is_valid_index_factory(LL)
564
565 # A dict of {string_idx: tuple[num_of_strings, string_leaf]}.
566 merged_string_idx_dict: dict[int, tuple[int, Leaf]] = {}
567 for string_idx in string_indices:
568 vresult = self._validate_msg(line, string_idx)
569 if isinstance(vresult, Err):
570 continue
571 merged_string_idx_dict[string_idx] = self._merge_one_string_group(
572 LL, string_idx, is_valid_index
573 )
574
575 if not merged_string_idx_dict:
576 return TErr("No string group is merged")
577
578 # Build the final line ('new_line') that this method will later return.
579 new_line = line.clone()
580 previous_merged_string_idx = -1
581 previous_merged_num_of_strings = -1
582 for i, leaf in enumerate(LL):
583 if i in merged_string_idx_dict:
584 previous_merged_string_idx = i
585 previous_merged_num_of_strings, string_leaf = merged_string_idx_dict[i]
586 new_line.append(string_leaf)
587
588 if (
589 previous_merged_string_idx
590 <= i
591 < previous_merged_string_idx + previous_merged_num_of_strings
592 ):
593 for comment_leaf in line.comments_after(leaf):
594 new_line.append(comment_leaf, preformatted=True)
595 continue
596
597 append_leaves(new_line, line, [leaf])
598
599 return Ok(new_line)
600
601 def _merge_one_string_group(
602 self, LL: list[Leaf], string_idx: int, is_valid_index: Callable[[int], bool]

Callers 1

do_transformMethod · 0.95

Calls 9

_validate_msgMethod · 0.95
append_leavesFunction · 0.90
OkClass · 0.90
is_valid_index_factoryFunction · 0.85
TErrFunction · 0.85
comments_afterMethod · 0.80
cloneMethod · 0.45
appendMethod · 0.45

Tested by

no test coverage detected