Skip to content

Commit 4d181ce

Browse files
committed
Refactor patch file processing to improve hunk extraction logic and ensure proper error handling for missing @@ markers.
1 parent 0db21f5 commit 4d181ce

File tree

1 file changed

+18
-16
lines changed

1 file changed

+18
-16
lines changed

src/patch_file_mcp/server.py

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#! /usr/bin/env python3
22
import sys
33
import argparse
4-
import re
54
from pathlib import Path
65

76
from fastmcp import FastMCP
@@ -72,24 +71,27 @@ def patch_file(
7271
if not any(str(pp).startswith(base) for base in allowed_directories):
7372
raise PermissionError(f"File {file_path} is not in allowed directories")
7473

75-
# Extract all hunks (sections starting with @@)
76-
# First try to find all hunks in the patch content
77-
hunks = re.findall(r'@@[^@]*(?:\n(?!@@)[^\n]*)*', patch_content)
74+
# Extract just the hunk part (starting with @@)
75+
lines = patch_content.splitlines()
76+
hunk_start = -1
7877

79-
if not hunks:
80-
# If no complete hunks found, check if the patch itself is a single hunk
81-
if patch_content.strip().startswith("@@"):
82-
hunks = [patch_content.strip()]
83-
else:
84-
raise RuntimeError(
85-
"No valid patch hunks found. Make sure the patch contains @@ line markers.\n"
86-
"You can use `write_file` tool to write the whole file content instead."
87-
)
78+
for i, line in enumerate(lines):
79+
if line.startswith("@@"):
80+
hunk_start = i
81+
break
8882

89-
# Join all hunks and create a standardized patch with proper headers
90-
hunks_content = '\n'.join(hunks)
83+
if hunk_start == -1:
84+
raise RuntimeError(
85+
"No @@ line markers found in the patch content.\n"
86+
"Make sure the patch follows the unified diff format with @@ line markers."
87+
)
88+
89+
# Use only the hunk part (remove any headers)
90+
hunk_content = "\n".join(lines[hunk_start:])
91+
92+
# Create a standardized patch with the correct filename
9193
filename = pp.name
92-
standardized_patch = f"--- {filename}\n+++ {filename}\n{hunks_content}"
94+
standardized_patch = f"--- {filename}\n+++ {filename}\n{hunk_content}"
9395
eprint(f"Created standardized patch for {filename}")
9496

9597
# Ensure patch_content is properly encoded

0 commit comments

Comments
 (0)