Helper class to find comments in a token stream. Can only find comments for gettext calls forwards. Once the comment from line 4 is found, a comment for line 1 will not return a usable value.
| 732 | |
| 733 | |
| 734 | class _CommentFinder: |
| 735 | """Helper class to find comments in a token stream. Can only |
| 736 | find comments for gettext calls forwards. Once the comment |
| 737 | from line 4 is found, a comment for line 1 will not return a |
| 738 | usable value. |
| 739 | """ |
| 740 | |
| 741 | def __init__( |
| 742 | self, tokens: t.Sequence[t.Tuple[int, str, str]], comment_tags: t.Sequence[str] |
| 743 | ) -> None: |
| 744 | self.tokens = tokens |
| 745 | self.comment_tags = comment_tags |
| 746 | self.offset = 0 |
| 747 | self.last_lineno = 0 |
| 748 | |
| 749 | def find_backwards(self, offset: int) -> t.List[str]: |
| 750 | try: |
| 751 | for _, token_type, token_value in reversed( |
| 752 | self.tokens[self.offset : offset] |
| 753 | ): |
| 754 | if token_type in ("comment", "linecomment"): |
| 755 | try: |
| 756 | prefix, comment = token_value.split(None, 1) |
| 757 | except ValueError: |
| 758 | continue |
| 759 | if prefix in self.comment_tags: |
| 760 | return [comment.rstrip()] |
| 761 | return [] |
| 762 | finally: |
| 763 | self.offset = offset |
| 764 | |
| 765 | def find_comments(self, lineno: int) -> t.List[str]: |
| 766 | if not self.comment_tags or self.last_lineno > lineno: |
| 767 | return [] |
| 768 | for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]): |
| 769 | if token_lineno > lineno: |
| 770 | return self.find_backwards(self.offset + idx) |
| 771 | return self.find_backwards(len(self.tokens)) |
| 772 | |
| 773 | |
| 774 | def babel_extract( |