import subprocess, sys, re sys.stdout.reconfigure(encoding='utf-8') res = subprocess.run(['git', 'diff', '-U3'], capture_output=True, text=True, encoding='utf-8') diff_text = res.stdout file_diffs = diff_text.split('diff --git ') print(f'Total file diffs: {len(file_diffs)-1}') merged_path = 'resources/knowledge/original/원가계산/건설공사_표준품셈/2026년_건설공사_표준품셈.md' with open(merged_path, 'r', encoding='utf-8') as f: text_merged = f.read() initial_len = len(text_merged) total_hunks = 0 applied_hunks = 0 for fd in file_diffs[1:]: lines = fd.split('\n') header = lines[0] filename = header.split(' ')[0][2:] raw_hunks = re.split(r'\n@@\s+[^@]+\s+@@\n', fd)[1:] total_hunks += len(raw_hunks) for h_idx, h in enumerate(raw_hunks): h_lines = h.split('\n') old_chunk_lines = [] new_chunk_lines = [] for l in h_lines: if l.startswith('---') or l.startswith('+++') or l.startswith('\\ No newline'): continue if l.startswith('-'): old_chunk_lines.append(l[1:]) elif l.startswith('+'): new_chunk_lines.append(l[1:]) elif l.startswith(' '): old_chunk_lines.append(l[1:]) new_chunk_lines.append(l[1:]) old_chunk = '\n'.join(old_chunk_lines) new_chunk = '\n'.join(new_chunk_lines) if text_merged.count(old_chunk) == 1: text_merged = text_merged.replace(old_chunk, new_chunk, 1) applied_hunks += 1 else: print(f"Warning: could not uniquely match hunk {h_idx} of {filename}") print(f"Total hunks: {total_hunks}, Applied to merged: {applied_hunks}") if applied_hunks == total_hunks: with open(merged_path, 'w', encoding='utf-8') as f: f.write(text_merged) print(f"SUCCESS: Merged file perfectly updated! Length: {initial_len} -> {len(text_merged)}") else: print("FAILED: Not all hunks were applied. Merged file was not modified.") sys.exit(1)