MCPcopy Create free account
hub / github.com/HKUDS/OpenSpace / apply_search_replace

Function apply_search_replace

openspace/skill_engine/patch.py:830–886  ·  view source on GitHub ↗

Apply SEARCH/REPLACE blocks to a single file's content. Uses the 6-level fuzzy matching chain from ``fuzzy_match`` for robust matching.

(
    patch_text: str,
    original: str,
    *,
    strict: bool = True,
)

Source from the content-addressed store, hash-verified

828
829# SEARCH/REPLACE (single-file DIFF)
830def apply_search_replace(
831 patch_text: str,
832 original: str,
833 *,
834 strict: bool = True,
835) -> tuple[str, int, Optional[str]]:
836 """Apply SEARCH/REPLACE blocks to a single file's content.
837
838 Uses the 6-level fuzzy matching chain from ``fuzzy_match`` for
839 robust matching.
840 """
841 new_text = original
842 num_applied = 0
843
844 blocks = list(PATCH_PATTERN.finditer(patch_text))
845 if not blocks:
846 return new_text, 0, None
847
848 for block in blocks:
849 search = _strip_trailing_ws(block.group(1))
850 replace = _strip_trailing_ws(block.group(2))
851
852 # Empty SEARCH → append at end
853 if not search.strip():
854 new_text = new_text.rstrip("\n") + "\n" + replace + "\n"
855 num_applied += 1
856 continue
857
858 # Use fuzzy matching chain
859 matched_search, pos = fuzzy_find_match(new_text, search)
860
861 if pos != -1:
862 new_text = new_text[:pos] + replace + new_text[pos + len(matched_search):]
863 num_applied += 1
864 continue
865
866 # Not found
867 if strict:
868 first_line = search.splitlines()[0].strip() if search.splitlines() else ""
869 similar = _find_similar_lines(first_line, new_text)
870 msg_parts = [
871 f"SEARCH text not found in {SKILL_FILENAME}",
872 "",
873 f"Looking for: {first_line!r}",
874 ]
875 if similar:
876 msg_parts.append("")
877 msg_parts.append("Similar lines found:")
878 for line, line_num in similar:
879 msg_parts.append(f" Line {line_num}: {line.strip()}")
880 msg_parts.extend([
881 "",
882 "Ensure the SEARCH block matches the file content exactly.",
883 ])
884 return new_text, num_applied, "\n".join(msg_parts)
885
886 return new_text, num_applied, None
887

Callers 1

Calls 3

_strip_trailing_wsFunction · 0.85
fuzzy_find_matchFunction · 0.85
_find_similar_linesFunction · 0.85

Tested by

no test coverage detected