MCPcopy Index your code
hub / github.com/going-doer/Paper2Code / parse_and_apply_changes

Function parse_and_apply_changes

codes/4_debugging.py:11–80  ·  view source on GitHub ↗

Apply SEARCH / REPLACE edits produced by the LLM to files in debug_dir.

(responses, debug_dir, save_num=1)

Source from the content-addressed store, hash-verified

9
10
11def parse_and_apply_changes(responses, debug_dir, save_num=1):
12 """Apply SEARCH / REPLACE edits produced by the LLM to files in debug_dir."""
13 for response in responses:
14 # Split into blocks per file
15 file_blocks = re.split(r"Filename:\s*([^\n]+)", response)
16 # Example: ['', 'file1.py', '...file1 content...', 'file2.py', '...file2 content...', ...]
17
18 if len(file_blocks) < 3:
19 print(f"❌ No filename patterns found in response:\n{response[:200]}...\n")
20 continue
21
22 # Process blocks per file (odd indices: filename, even indices: diff content)
23 for i in range(1, len(file_blocks), 2):
24 filename = file_blocks[i].strip()
25 file_content_block = file_blocks[i + 1]
26
27 filepath = os.path.join(debug_dir, filename)
28
29 # SEARCH/REPLACE pattern
30 search_replace_pattern = (
31 r"<<<<<<< SEARCH\n(.*?)\n=======\n(.*?)\n>>>>>>> REPLACE"
32 )
33 matches = re.findall(search_replace_pattern, file_content_block, re.DOTALL)
34
35 if not matches:
36 print(f"❌ No SEARCH/REPLACE patterns found for file: {filename}\n")
37 continue
38
39 # Check file existence
40 if not os.path.exists(filepath):
41 print(f"❌ File does not exist: {filepath}\n")
42 continue
43
44 # Read file
45 try:
46 with open(filepath, "r", encoding="utf-8") as f:
47 file_content = f.read()
48 except Exception as e:
49 print(f"❌ Error reading file {filepath}: {e}\n")
50 continue
51
52 modified = False
53
54 # Apply SEARCH/REPLACE
55 for idx, (search_text, replace_text) in enumerate(matches, 1):
56 search_text = search_text.strip()
57 replace_text = replace_text.strip()
58
59 if search_text in file_content:
60 file_content = file_content.replace(search_text, replace_text)
61 modified = True
62 print(f"✅ {filename}: Modification {idx} applied")
63 else:
64 print(
65 f"❌ {filename}: Search text for modification {idx} not found:\n"
66 f"{search_text[:200]}...\n"
67 )
68

Callers 1

4_debugging.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected