1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use super::execute::{TxState, read_file_content};
use crate::ops::patch::{ApplyHunksOptions, apply_patch_with_loader};
use crate::plan::Operation;
/// Execute a patch operation within a transaction.
pub(crate) fn execute_patch_op(op: &Operation, tx: &mut TxState<'_>) -> anyhow::Result<usize> {
match op {
Operation::PatchApply {
diff,
on_stale,
allow_conflicts,
replace_all,
} => {
if *replace_all && !crate::ops::search_replace::looks_like_search_replace(diff) {
return Err(crate::exit::InvalidInputError {
msg: crate::ops::search_replace::REPLACE_ALL_ONLY_FOR_SEARCH_REPLACE.into(),
}
.into());
}
if crate::ops::begin_patch::looks_like_begin_patch(diff) {
if crate::ops::search_replace::has_search_replace_marker(diff) {
return Err(crate::exit::ParseErrorError {
msg: "mixed Begin Patch and SEARCH/REPLACE grammar is not supported".into(),
}
.into());
}
return execute_begin_patch(diff, tx);
}
if crate::ops::search_replace::looks_like_search_replace(diff) {
if crate::ops::begin_patch::has_col0_begin_patch_start(diff) {
return Err(crate::exit::ParseErrorError {
msg: "mixed Begin Patch and SEARCH/REPLACE grammar is not supported".into(),
}
.into());
}
return execute_search_replace(diff, *replace_all, tx);
}
let options = ApplyHunksOptions {
on_stale: *on_stale,
allow_conflicts: *allow_conflicts,
};
// Conflicts without allow_conflicts surface as ConflictsError from
// apply_patch_with_loader (ops/patch early-err). When allow_conflicts
// is true, content includes conflict markers and is staged normally.
let patched_files = apply_patch_with_loader(
diff,
|path| {
let file_path = tx.cwd.join(path);
tx.refuse_soft_non_text(&file_path, path)?;
// Content patches load through load_text_strict (follows a
// live file symlink; FIFO/socket refuse without hanging).
// Empty-hunk delete never reaches this loader
// (ops::patch short-circuits); the deletion snapshot below
// stays empty for symlink / FIFO / socket (#2290).
match read_file_content(tx.pending, tx.existed_before, &file_path) {
Ok(s) => Ok(s.to_string()),
Err(e)
if options.on_stale == crate::ops::patch::OnStale::Merge
&& crate::exit::classify_typed_error(&e)
.is_some_and(|(k, _)| k == "not_found") =>
{
// Merge check treats missing dest as empty; apply must too
// so dest occupancy matches dest_exists after the write.
Ok(String::new())
}
Err(e) => Err(e),
}
},
options,
)?;
for result in patched_files {
if result.is_deletion {
let file_path = tx.cwd.join(&result.path);
if !dest_exists(tx, &file_path) {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("file not found: {}", result.path),
)
.into());
}
crate::ops::file::ensure_unlinkable_not_directory(&file_path, &result.path)?;
// UTF-8 keeps a text snapshot. Binary and invalid UTF-8
// keep an empty pair only after open succeeds, so a
// regular file that cannot be opened is not staged
// (commit backup would drop the OS error). Special nodes
// stay empty and are not opened. Do not Strict-peel
// binary. Hunked loader already put text in pending;
// keep that original.
let stage_pair = if crate::ops::file::is_regular_file_for_backup(&file_path)
&& !tx.pending.contains_key(&file_path)
{
if let Some(content) = crate::files::read_text_file(&file_path) {
Some(content)
} else {
match std::fs::File::open(&file_path) {
Ok(file) => {
drop(file);
Some(String::new())
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("file not found: {}", result.path),
)
.into());
}
Err(e) => {
return Err(crate::exit::InvalidInputError {
msg: format!("failed to read {}: {e}", result.path),
}
.into());
}
}
}
} else {
None
};
tx.existed_before.insert(file_path.clone());
if let Some(content) = stage_pair {
tx.pending
.insert(file_path.clone(), (content.clone(), content));
} else if !crate::ops::file::is_regular_file_for_backup(&file_path) {
tx.pending
.insert(file_path.clone(), (String::new(), String::new()));
}
tx.deletions.insert(file_path.clone());
tx.write_targets.insert(file_path);
} else if let Some(ref from) = result.rename_from {
// Git rename: load was from `from`; stage rename + new content (#2101).
let from_path = tx.cwd.join(from);
let to_path = tx.cwd.join(&result.path);
// Refuse overwrite of an existing dest (parity with file.rename
// without force). Case-only renames still allowed.
if let Some(msg) = crate::ops::patch::dest_clobber_msg(
&result.path,
dest_exists(tx, &to_path),
Some(from.as_str()),
false,
false,
) {
return Err(crate::exit::AlreadyExistsError { msg }.into());
}
// Ensure source is in pending (loader already did); record rename
// so commit uses fs::rename then write dest content.
if !tx.existed_before.contains(&from_path)
&& crate::ops::file::path_entry_exists(&from_path)
{
tx.existed_before.insert(from_path.clone());
}
if crate::ops::file::path_entry_exists(&to_path)
&& !tx.existed_before.contains(&to_path)
{
// Dest exists only for case-only renames after the check above.
let _ = read_file_content(tx.pending, tx.existed_before, &to_path)?;
}
tx.renames.push((from_path.clone(), to_path.clone()));
tx.write_file(&to_path, result.content);
// Stage source delete (same as file.rename).
if let Some((original, _)) = tx.pending.get(&from_path) {
let orig = original.clone();
tx.pending.insert(from_path.clone(), (orig, String::new()));
} else {
tx.pending
.insert(from_path.clone(), (String::new(), String::new()));
}
tx.deletions.insert(from_path);
} else {
let file_path = tx.cwd.join(&result.path);
if let Some(msg) = crate::ops::patch::dest_clobber_msg(
&result.path,
dest_exists(tx, &file_path),
None,
result.copy_from.is_some(),
result.is_creation && result.copy_from.is_none(),
) {
return Err(crate::exit::AlreadyExistsError { msg }.into());
}
tx.write_file(&file_path, result.content);
}
}
Ok(0)
}
_ => unreachable!("execute_patch_op called with non-Patch operation"),
}
}
fn execute_begin_patch(diff: &str, tx: &mut TxState<'_>) -> anyhow::Result<usize> {
use crate::ops::begin_patch::{BeginPatchOp, apply_codex_hunks, parse_begin_patch};
let ops = parse_begin_patch(diff)?;
for op in ops {
match op {
BeginPatchOp::Add { path, content } => {
let dest = tx.cwd.join(&path);
if dest.is_dir() {
return Err(crate::exit::InvalidInputError {
msg: format!(
"{} is a directory; Begin Patch Add File needs a file path",
dest.display()
),
}
.into());
}
if dest_exists(tx, &dest) {
return Err(crate::exit::AlreadyExistsError {
msg: crate::ops::patch::create_dest_exists_msg(&path),
}
.into());
}
tx.write_file(&dest, content);
}
BeginPatchOp::Delete { path } => {
let dest = tx.cwd.join(&path);
if dest.is_dir() {
return Err(crate::exit::InvalidInputError {
msg: format!("{} is a directory, not a file", dest.display()),
}
.into());
}
if !dest_exists(tx, &dest) {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("file not found: {path}"),
)
.into());
}
// file_delete snapshot: do not follow symlink / FIFO / socket.
if crate::ops::file::is_regular_file_for_backup(&dest) {
let _ = read_file_content(tx.pending, tx.existed_before, &dest)?;
} else if !tx.pending.contains_key(&dest) {
tx.existed_before.insert(dest.clone());
tx.pending
.insert(dest.clone(), (String::new(), String::new()));
}
tx.deletions.insert(dest.clone());
tx.write_targets.insert(dest);
}
BeginPatchOp::Update {
path,
hunks,
move_to,
} => {
let dest = tx.cwd.join(&path);
if dest.is_dir() {
return Err(crate::exit::InvalidInputError {
msg: format!(
"{} is a directory; Begin Patch Update File needs a file path",
dest.display()
),
}
.into());
}
if !dest_exists(tx, &dest) {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("file not found: {path}"),
)
.into());
}
let original = read_file_content(tx.pending, tx.existed_before, &dest)?.to_string();
let updated = apply_codex_hunks(&original, &hunks)?;
if let Some(new_path) = move_to {
let new_dest = tx.cwd.join(&new_path);
if dest_exists(tx, &new_dest) {
return Err(crate::exit::AlreadyExistsError {
msg: format!(
"destination already exists: {} (Begin Patch Move refuses overwrite; remove dest)",
new_dest.display()
),
}
.into());
}
tx.renames.push((dest.clone(), new_dest.clone()));
tx.write_file(&new_dest, updated);
if let Some((orig, _)) = tx.pending.get(&dest) {
let orig = orig.clone();
tx.pending.insert(dest.clone(), (orig, String::new()));
} else {
tx.pending
.insert(dest.clone(), (String::new(), String::new()));
}
tx.deletions.insert(dest);
} else {
tx.write_file(&dest, updated);
}
}
}
}
Ok(0)
}
fn execute_search_replace(
diff: &str,
replace_all: bool,
tx: &mut TxState<'_>,
) -> anyhow::Result<usize> {
use crate::api::ReplaceOptions;
use crate::ops::search_replace::parse_search_replace_document;
let blocks = parse_search_replace_document(diff)
.map_err(|e| crate::exit::ParseErrorError { msg: e.message })?;
if blocks.is_empty() {
return Err(crate::exit::InvalidInputError {
msg: "no SEARCH/REPLACE blocks to apply".into(),
}
.into());
}
let replace_opts = ReplaceOptions {
unique: !replace_all,
require_change: true,
..ReplaceOptions::default()
};
struct Planned {
path: std::path::PathBuf,
new_content: String,
}
let mut planned: Vec<Planned> = Vec::new();
for block in blocks {
if block.old.is_empty() {
return Err(crate::exit::InvalidInputError {
msg: "SEARCH/REPLACE SEARCH block must not be empty (not a whole-file rewrite)"
.into(),
}
.into());
}
if block.path.trim().is_empty() {
return Err(crate::exit::InvalidInputError {
msg: crate::ops::search_replace::SEARCH_REPLACE_EMPTY_PATH.into(),
}
.into());
}
if std::path::Path::new(&block.path)
.components()
.any(|c| matches!(c, std::path::Component::ParentDir))
{
return Err(crate::exit::InvalidInputError {
msg: format!("SEARCH/REPLACE path must not contain '..': {}", block.path),
}
.into());
}
let dest = tx.cwd.join(&block.path);
if dest.is_dir() {
return Err(crate::exit::InvalidInputError {
msg: format!(
"{} is a directory; SEARCH/REPLACE needs a file path",
dest.display()
),
}
.into());
}
if let Some(idx) = planned.iter().position(|p| p.path == dest) {
let existing = &mut planned[idx];
let content_result = crate::api::replace_in_content(
&existing.new_content,
&block.old,
&block.new,
&replace_opts,
)?;
existing.new_content = content_result.new_content;
continue;
}
let original = read_file_content(tx.pending, tx.existed_before, &dest)?.to_string();
let content_result =
crate::api::replace_in_content(&original, &block.old, &block.new, &replace_opts)?;
planned.push(Planned {
path: dest,
new_content: content_result.new_content,
});
}
for item in planned {
tx.write_file(&item.path, item.new_content);
}
Ok(0)
}
fn dest_exists(tx: &TxState<'_>, path: &std::path::Path) -> bool {
!tx.deletions.contains(path)
&& (tx.pending.contains_key(path) || crate::ops::file::path_entry_exists(path))
}