Extract code blocks from the given text. py:a.py Args: text: The text to extract code blocks from. target_filename: The filename target to extract. file_wrapper: The file wrapper Returns: Tuple: 0: The extracted code bl
(
text: str,
target_filename: Optional[str] = None,
file_wrapper: Optional[List[str]] = None,
)
| 699 | |
| 700 | |
| 701 | def extract_code_blocks( |
| 702 | text: str, |
| 703 | target_filename: Optional[str] = None, |
| 704 | file_wrapper: Optional[List[str]] = None, |
| 705 | ) -> Tuple[List, str]: |
| 706 | """Extract code blocks from the given text. |
| 707 | |
| 708 | <result>py:a.py |
| 709 | </result> |
| 710 | |
| 711 | Args: |
| 712 | text: The text to extract code blocks from. |
| 713 | target_filename: The filename target to extract. |
| 714 | file_wrapper: The file wrapper |
| 715 | |
| 716 | Returns: |
| 717 | Tuple: |
| 718 | 0: The extracted code blocks. |
| 719 | 1: The left content of the input text. |
| 720 | """ |
| 721 | if not file_wrapper: |
| 722 | file_wrapper = ['<result>', '</result>'] |
| 723 | assert len(file_wrapper) == 2 |
| 724 | pattern = rf'{file_wrapper[0]}[a-zA-Z]*:([^\n\r`]+)\n(.*?){file_wrapper[1]}' |
| 725 | matches = re.findall(pattern, text, re.DOTALL) |
| 726 | result = [] |
| 727 | |
| 728 | for filename, code in matches: |
| 729 | filename = filename.strip() |
| 730 | if target_filename is None or filename == target_filename: |
| 731 | result.append({'filename': filename, 'code': code.strip()}) |
| 732 | |
| 733 | if target_filename is not None: |
| 734 | remove_pattern = rf'{file_wrapper[0]}[a-zA-Z]*:{re.escape(target_filename)}\n.*?{file_wrapper[1]}' |
| 735 | else: |
| 736 | remove_pattern = pattern |
| 737 | |
| 738 | remaining_text = re.sub(remove_pattern, '', text, flags=re.DOTALL) |
| 739 | remaining_text = re.sub(r'\n\s*\n\s*\n', '\n\n', remaining_text) |
| 740 | remaining_text = remaining_text.strip() |
| 741 | |
| 742 | return result, remaining_text |
| 743 | |
| 744 | |
| 745 | @contextmanager |
no outgoing calls
no test coverage detected