MediumEditing SystemsPython 3
Patch Conflict Detector
Apply optimistic multi-file patches atomically while rejecting stale or overlapping edits.
40m3 sample tests7 hidden tests
Implement apply_patches(files, patches), an atomic patch applier with optimistic conflict checks.
Requirements
filesmaps file path to text.- Each patch is
(path, start, end, expected_old_text, replacement). - Validate all patches before mutating anything.
- Raise
ValueErrorfor invalid ranges (start < 0,end < start, orend > len(text)), missing files, overlapping patches in the same file, and expected-text mismatches. - Adjacent ranges that only touch at an endpoint are allowed. Multiple empty inserts at the same offset are allowed; sort stably and apply right-to-left within each file.
- Apply patches from the end of each file so offsets stay stable.
- Return a new dictionary and leave input untouched.
Example
The first patch succeeds without changing files. The stale patch then fails against the same input, which remains untouched.
python
1files = {"app.py": "print('old')\n"}
2patches = [("app.py", 6, 11, "'old'", "'new'")]
3assert apply_patches(files, patches)["app.py"] == "print('new')\n"
4assert files["app.py"] == "print('old')\n"
5
6try:
7 apply_patches(files, [("app.py", 6, 11, "'stale'", "'new'")])
8except ValueError:
9 pass
10else:
11 raise AssertionError("expected stale patch conflict")
12
13assert files["app.py"] == "print('old')\n"Constraints
- No diff parser is required.
- Treat offsets as Python string indexes.
Editor