返回 CodeWhale
patch_preflight.rs
根目录 / crates / tools / src / patch_preflight.rs
1 use std::collections::HashSet;
2
3 use serde::{Deserialize, Serialize};
4 use serde_json::Value;
5
6 use crate::{ToolError, optional_bool, optional_str};
7
8 const FILE_LIST_LIMIT: usize = 6;
9
10 /// No-mutation summary of what an `apply_patch` input intends to touch.
11 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12 pub struct ApplyPatchPreflight {
13 pub touched_files: Vec<String>,
14 pub files_total: usize,
15 pub hunks_total: usize,
16 #[serde(default, skip_serializing_if = "Vec::is_empty")]
17 pub creates: Vec<String>,
18 #[serde(default, skip_serializing_if = "Vec::is_empty")]
19 pub deletes: Vec<String>,
20 #[serde(default, skip_serializing_if = "Option::is_none")]
21 pub path_override: Option<String>,
22 #[serde(default, skip_serializing_if = "Option::is_none")]
23 pub header_path_mismatch: Option<String>,
24 }
25
26 /// A single hunk in a unified diff
27 #[derive(Debug, Clone)]
28 pub struct Hunk {
29 pub old_start: usize,
30 pub old_count: usize,
31 pub new_start: usize,
32 pub new_count: usize,
33 pub lines: Vec<HunkLine>,
34 }
35
36 /// A line in a hunk
37 #[derive(Debug, Clone)]
38 pub enum HunkLine {
39 Context(String),
40 Add(String),
41 Remove(String),
42 }
43
44 #[derive(Debug, Clone)]
45 pub struct FilePatch {
46 pub path: String,
47 pub hunks: Vec<Hunk>,
48 pub delete_after: bool,
49 pub create_if_missing: bool,
50 /// The section's old header is `/dev/null`: it creates the file and has
51 /// nothing to anchor against, so it must not land on an existing one.
52 pub creates_new_file: bool,
53 }
54
55 #[derive(Debug, Default, Clone)]
56 struct PatchShape {
57 has_hunks: bool,
58 header_files: Vec<String>,
59 /// Some section's old header is `/dev/null` (a file creation).
60 creates_new_file: bool,
61 }
62
63 impl PatchShape {
64 fn file_count(&self) -> usize {
65 self.header_files.len()
66 }
67 }
68
69 #[derive(Debug, Clone)]
70 pub enum ApplyPatchPreflightKind {
71 Replace,
72 PathOverride {
73 path: String,
74 hunks: Vec<Hunk>,
75 creates_new_file: bool,
76 },
77 FilePatches(Vec<FilePatch>),
78 }
79
80 /// Canonicalized `apply_patch` payload mode.
81 ///
82 /// `replace` is the preferred spelling for full-file replacements. `changes`
83 /// remains a compatibility alias for callers that learned the original tool
84 /// schema before the clearer name was introduced.
85 #[derive(Debug, Clone, Copy)]
86 pub enum NormalizedApplyPatchInput<'a> {
87 Patch(&'a str),
88 Replacement {
89 entries: &'a [Value],
90 source_field: &'static str,
91 },
92 }
93
94 /// Validate mutual exclusivity and normalize the legacy `changes` alias.
95 ///
96 /// This is the single parser used by execution, preflight, policy, approval,
97 /// and UI consumers so every surface agrees on the accepted input contract.
98 pub fn normalize_apply_patch_input(
99 input: &Value,
100 ) -> Result<NormalizedApplyPatchInput<'_>, ToolError> {
101 let provided: Vec<&'static str> = ["patch", "replace", "changes"]
102 .into_iter()
103 .filter(|field| input.get(*field).is_some())
104 .collect();
105
106 if provided.len() > 1 {
107 let fields = provided
108 .iter()
109 .map(|field| format!("`{field}`"))
110 .collect::<Vec<_>>()
111 .join(", ");
112 return Err(ToolError::invalid_input(format!(
113 "Cannot use {fields} simultaneously. Choose exactly one of `patch`, `replace`, or the deprecated `changes` alias."
114 )));
115 }
116
117 let Some(field) = provided.first().copied() else {
118 return Err(ToolError::missing_field(
119 "patch, replace, or deprecated changes",
120 ));
121 };
122
123 if field == "patch" {
124 let patch = input
125 .get(field)
126 .and_then(Value::as_str)
127 .ok_or_else(|| ToolError::invalid_input("`patch` must be a string"))?;
128 return Ok(NormalizedApplyPatchInput::Patch(patch));
129 }
130
131 let entries = input.get(field).and_then(Value::as_array).ok_or_else(|| {
132 ToolError::invalid_input(format!(
133 "`{field}` must be an array of objects like {{path, content}}"
134 ))
135 })?;
136 if entries.is_empty() {
137 return Err(ToolError::invalid_input(format!(
138 "`{field}` cannot be empty"
139 )));
140 }
141
142 Ok(NormalizedApplyPatchInput::Replacement {
143 entries,
144 source_field: field,
145 })
146 }
147
148 #[derive(Debug, Clone)]
149 pub struct ApplyPatchPreflightPlan {
150 pub summary: ApplyPatchPreflight,
151 pub kind: ApplyPatchPreflightKind,
152 }
153
154 /// Parse `apply_patch` input into a reusable, no-mutation preflight summary.
155 ///
156 /// This deliberately stops before workspace resolution or file reads. It is
157 /// suitable for policy checks, audit logs, diagnostics hooks, and future undo
158 /// planning that must know the target files before mutation.
159 pub fn preflight_apply_patch(input: &Value) -> Result<ApplyPatchPreflight, ToolError> {
160 let normalized = normalize_apply_patch_input(input)?;
161 Ok(preflight_apply_patch_plan(input, normalized)?.summary)
162 }
163
164 pub fn preflight_apply_patch_plan(
165 input: &Value,
166 normalized: NormalizedApplyPatchInput<'_>,
167 ) -> Result<ApplyPatchPreflightPlan, ToolError> {
168 let create_if_missing = optional_bool(input, "create_if_missing", false)?;
169
170 if let NormalizedApplyPatchInput::Replacement {
171 entries,
172 source_field,
173 } = normalized
174 {
175 return Ok(ApplyPatchPreflightPlan {
176 summary: preflight_replace(entries, source_field)?,
177 kind: ApplyPatchPreflightKind::Replace,
178 });
179 }
180
181 let NormalizedApplyPatchInput::Patch(patch_text) = normalized else {
182 unreachable!("replacement input returned before patch parsing")
183 };
184 let path_override = optional_str(input, "path")?;
185 let patch_shape = inspect_patch_shape(patch_text);
186 validate_patch_shape(&patch_shape, path_override)?;
187 let header_path_mismatch =
188 path_override.and_then(|path| diff_header_mismatch(path, &patch_shape));
189
190 if let Some(path) = path_override {
191 let hunks = parse_unified_diff(patch_text)?;
192 if hunks.is_empty() {
193 return Err(ToolError::invalid_input(
194 "Patch did not contain any hunks (`@@ ... @@`). Provide a unified diff hunk.",
195 ));
196 }
197 return Ok(ApplyPatchPreflightPlan {
198 summary: ApplyPatchPreflight {
199 touched_files: vec![path.to_string()],
200 files_total: 1,
201 hunks_total: hunks.len(),
202 creates: if create_if_missing {
203 vec![path.to_string()]
204 } else {
205 Vec::new()
206 },
207 deletes: Vec::new(),
208 path_override: Some(path.to_string()),
209 header_path_mismatch,
210 },
211 kind: ApplyPatchPreflightKind::PathOverride {
212 path: path.to_string(),
213 hunks,
214 // `path` retargets the section; a `--- /dev/null` header
215 // still means "create", and must not land on an existing file.
216 creates_new_file: patch_shape.creates_new_file,
217 },
218 });
219 }
220
221 let file_patches = parse_unified_diff_files(patch_text, create_if_missing)?;
222 if file_patches.is_empty() {
223 return Err(ToolError::invalid_input(
224 "No valid file patches found. Ensure the patch includes `---`/`+++` headers or provide `path`.",
225 ));
226 }
227
228 let mut touched_files = Vec::new();
229 let mut creates = Vec::new();
230 let mut deletes = Vec::new();
231 let mut hunks_total = 0;
232 for file_patch in &file_patches {
233 if file_patch.hunks.is_empty() {
234 return Err(ToolError::invalid_input(format!(
235 "Patch section for `{}` has no hunks (`@@ ... @@`).",
236 file_patch.path
237 )));
238 }
239 push_unique(&mut touched_files, file_patch.path.clone());
240 hunks_total += file_patch.hunks.len();
241 if file_patch.create_if_missing && !file_patch.delete_after {
242 push_unique(&mut creates, file_patch.path.clone());
243 }
244 if file_patch.delete_after {
245 push_unique(&mut deletes, file_patch.path.clone());
246 }
247 }
248
249 Ok(ApplyPatchPreflightPlan {
250 summary: ApplyPatchPreflight {
251 files_total: file_patches.len(),
252 touched_files,
253 hunks_total,
254 creates,
255 deletes,
256 path_override: None,
257 header_path_mismatch,
258 },
259 kind: ApplyPatchPreflightKind::FilePatches(file_patches),
260 })
261 }
262
263 fn preflight_replace(
264 changes: &[Value],
265 source_field: &str,
266 ) -> Result<ApplyPatchPreflight, ToolError> {
267 let mut touched_files = Vec::new();
268 for change in changes {
269 let path = change
270 .get("path")
271 .and_then(Value::as_str)
272 .ok_or_else(|| ToolError::missing_field(format!("{source_field}[].path")))?;
273 let _content = change
274 .get("content")
275 .and_then(Value::as_str)
276 .ok_or_else(|| ToolError::missing_field(format!("{source_field}[].content")))?;
277 push_unique(&mut touched_files, path.to_string());
278 }
279
280 Ok(ApplyPatchPreflight {
281 files_total: changes.len(),
282 touched_files,
283 hunks_total: 0,
284 creates: Vec::new(),
285 deletes: Vec::new(),
286 path_override: None,
287 header_path_mismatch: None,
288 })
289 }
290
291 /// Parse a unified diff into hunks
292 pub fn parse_unified_diff(patch: &str) -> Result<Vec<Hunk>, ToolError> {
293 let mut hunks = Vec::new();
294 let mut lines = patch.lines().peekable();
295
296 // Skip header lines (---, +++ etc)
297 while let Some(line) = lines.peek() {
298 if line.starts_with("@@") {
299 break;
300 }
301 lines.next();
302 }
303
304 // Parse hunks
305 while let Some(line) = lines.next() {
306 if line.starts_with("@@") {
307 let hunk = parse_hunk_header(line, &mut lines)?;
308 hunks.push(hunk);
309 }
310 }
311
312 Ok(hunks)
313 }
314
315 fn parse_unified_diff_files(
316 patch: &str,
317 create_if_missing: bool,
318 ) -> Result<Vec<FilePatch>, ToolError> {
319 let mut files = Vec::new();
320 let mut lines = patch.lines().peekable();
321 let mut current: Option<FilePatch> = None;
322 let mut old_path: Option<String> = None;
323
324 while let Some(line) = lines.next() {
325 if line.starts_with("diff --git ") {
326 if let Some(file) = current.take() {
327 files.push(file);
328 }
329 old_path = None;
330 continue;
331 }
332
333 if let Some(stripped) = line.strip_prefix("--- ") {
334 old_path = Some(stripped.trim().to_string());
335 continue;
336 }
337
338 if let Some(stripped) = line.strip_prefix("+++ ") {
339 let new_path = Some(stripped.trim().to_string());
340 let (path, delete_after, create_flag) =
341 resolve_diff_paths(old_path.as_deref(), new_path.as_deref(), create_if_missing)?;
342 let creates_new_file = old_path.as_deref().is_some_and(is_dev_null_header);
343 old_path = None;
344 if let Some(file) = current.take() {
345 files.push(file);
346 }
347 current = Some(FilePatch {
348 path,
349 hunks: Vec::new(),
350 delete_after,
351 create_if_missing: create_flag,
352 creates_new_file,
353 });
354 continue;
355 }
356
357 if line.starts_with("@@") {
358 let Some(file) = current.as_mut() else {
359 if let Some(path) = old_path.as_deref() {
360 return Err(ToolError::invalid_input(format!(
361 "Patch hunk encountered after `--- {path}` but before a matching `+++` header. Each file section must include both headers."
362 )));
363 }
364 return Err(ToolError::invalid_input(
365 "Patch hunk encountered before any file header. Add `---`/`+++` headers or provide `path`.",
366 ));
367 };
368 let hunk = parse_hunk_header(line, &mut lines)?;
369 file.hunks.push(hunk);
370 }
371 }
372
373 if let Some(file) = current {
374 files.push(file);
375 }
376
377 Ok(files)
378 }
379
380 fn resolve_diff_paths(
381 old_path: Option<&str>,
382 new_path: Option<&str>,
383 create_if_missing: bool,
384 ) -> Result<(String, bool, bool), ToolError> {
385 let old_norm = old_path.and_then(normalize_diff_path);
386 let new_norm = new_path.and_then(normalize_diff_path);
387 let delete_after = new_norm.is_none();
388 let create_flag = create_if_missing || old_norm.is_none();
389 let path = new_norm
390 .or(old_norm)
391 .ok_or_else(|| ToolError::invalid_input("Patch is missing both old and new file paths"))?;
392 Ok((path, delete_after, create_flag))
393 }
394
395 fn is_dev_null_header(raw: &str) -> bool {
396 let raw = raw.split_once('\t').map_or(raw, |(path, _timestamp)| path);
397 matches!(raw.trim(), "/dev/null" | "dev/null")
398 }
399
400 fn normalize_diff_path(raw: &str) -> Option<String> {
401 let raw = raw.split_once('\t').map_or(raw, |(path, _timestamp)| path);
402 let raw = raw.trim();
403 if raw.is_empty() {
404 return None;
405 }
406 if raw == "/dev/null" || raw == "dev/null" {
407 return None;
408 }
409 let raw = raw
410 .strip_prefix("a/")
411 .or_else(|| raw.strip_prefix("b/"))
412 .unwrap_or(raw);
413 Some(raw.to_string())
414 }
415
416 /// Parse a hunk header and its content
417 fn parse_hunk_header<'a, I>(
418 header: &str,
419 lines: &mut std::iter::Peekable<I>,
420 ) -> Result<Hunk, ToolError>
421 where
422 I: Iterator<Item = &'a str> + Clone,
423 {
424 // Parse @@ -old_start,old_count +new_start,new_count @@
425 let parts: Vec<&str> = header.split_whitespace().collect();
426 if parts.len() < 3 {
427 return Err(ToolError::invalid_input(format!(
428 "Invalid hunk header: {header}. Expected numeric unified-diff form `@@ -old_start,old_count +new_start,new_count @@` (example: `@@ -12,3 +12,5 @@`)."
429 )));
430 }
431
432 let old_range = parts[1].trim_start_matches('-');
433 let new_range = parts[2].trim_start_matches('+');
434
435 let (old_start, old_count) = parse_range(old_range)?;
436 let (new_start, new_count) = parse_range(new_range)?;
437
438 // Parse hunk lines
439 let mut hunk_lines = Vec::new();
440 let mut old_remaining = old_count;
441 let mut new_remaining = new_count;
442
443 loop {
444 // `--- ` opens the next file section once this hunk's counts are
445 // spent, or when `+++ ` follows (a header after a miscounted hunk).
446 // Otherwise it is a removed line whose text starts `-- `. Reading it
447 // as a removal unconditionally glued a second section for the same
448 // file onto the first hunk (B7).
449 let next_file_header = {
450 let mut ahead = lines.clone();
451 ahead.next().is_some_and(|line| line.starts_with("--- "))
452 && ((old_remaining == 0 && new_remaining == 0)
453 || ahead.next().is_some_and(|line| line.starts_with("+++ ")))
454 };
455 if next_file_header {
456 break;
457 }
458 match lines.peek() {
459 Some(line) if line.starts_with("@@") => break,
460 Some(line) if line.starts_with('-') => {
461 hunk_lines.push(HunkLine::Remove(line[1..].to_string()));
462 old_remaining = old_remaining.saturating_sub(1);
463 lines.next();
464 }
465 Some(line) if line.starts_with('+') => {
466 hunk_lines.push(HunkLine::Add(line[1..].to_string()));
467 new_remaining = new_remaining.saturating_sub(1);
468 lines.next();
469 }
470 Some(line) if line.starts_with(' ') || line.is_empty() => {
471 let content = if line.is_empty() { "" } else { &line[1..] };
472 hunk_lines.push(HunkLine::Context(content.to_string()));
473 old_remaining = old_remaining.saturating_sub(1);
474 new_remaining = new_remaining.saturating_sub(1);
475 lines.next();
476 }
477 Some(line)
478 if line.starts_with("diff ")
479 || line.starts_with("--- ")
480 || line.starts_with("+++ ") =>
481 {
482 // Start of a new file patch - don't consume, let outer loop handle it
483 break;
484 }
485 Some(line) if !line.starts_with('\\') => {
486 // Treat as context line without leading space
487 hunk_lines.push(HunkLine::Context((*line).to_string()));
488 old_remaining = old_remaining.saturating_sub(1);
489 new_remaining = new_remaining.saturating_sub(1);
490 lines.next();
491 }
492 Some(_) => {
493 lines.next(); // Skip "\ No newline at end of file" etc
494 }
495 None => break,
496 }
497 }
498
499 Ok(Hunk {
500 old_start,
501 old_count,
502 new_start,
503 new_count,
504 lines: hunk_lines,
505 })
506 }
507
508 /// Parse a range like "10,5" or "10" into (start, count)
509 pub fn parse_range(range: &str) -> Result<(usize, usize), ToolError> {
510 let parts: Vec<&str> = range.split(',').collect();
511 let start = parts[0].parse::<usize>().map_err(|_| {
512 ToolError::invalid_input(format!(
513 "Invalid line number `{}` in hunk header. Expected numeric unified-diff form `@@ -old_start,old_count +new_start,new_count @@` (example: `@@ -12,3 +12,5 @@`); use positive integers like `12` or `12,3`.",
514 parts[0]
515 ))
516 })?;
517 let count = if parts.len() > 1 {
518 parts[1].parse::<usize>().map_err(|_| {
519 ToolError::invalid_input(format!(
520 "Invalid line count `{}` in hunk header. Expected numeric unified-diff form `@@ -old_start,old_count +new_start,new_count @@` (example: `@@ -12,3 +12,5 @@`); use positive integers like `3`.",
521 parts[1]
522 ))
523 })?
524 } else {
525 1
526 };
527 Ok((start, count))
528 }
529
530 fn inspect_patch_shape(patch: &str) -> PatchShape {
531 let mut shape = PatchShape::default();
532 let mut seen = HashSet::new();
533 let mut old_path: Option<String> = None;
534 let mut old_is_dev_null = false;
535 let mut hunk_old_remaining = 0usize;
536 let mut hunk_new_remaining = 0usize;
537
538 for line in patch.lines() {
539 if line.starts_with("@@") {
540 shape.has_hunks = true;
541 if let Some((old_count, new_count)) = hunk_line_counts_for_shape(line) {
542 hunk_old_remaining = old_count;
543 hunk_new_remaining = new_count;
544 }
545 continue;
546 }
547
548 if hunk_old_remaining > 0 || hunk_new_remaining > 0 {
549 advance_hunk_shape_counts(line, &mut hunk_old_remaining, &mut hunk_new_remaining);
550 continue;
551 }
552
553 if let Some(stripped) = line.strip_prefix("--- ") {
554 old_is_dev_null = is_dev_null_header(stripped);
555 old_path = normalize_diff_path(stripped);
556 continue;
557 }
558
559 if let Some(stripped) = line.strip_prefix("+++ ") {
560 shape.creates_new_file |= old_is_dev_null && !is_dev_null_header(stripped);
561 old_is_dev_null = false;
562 let new_path = normalize_diff_path(stripped);
563 let resolved = new_path.or(old_path.clone());
564 if let Some(path) = resolved
565 && seen.insert(path.clone())
566 {
567 shape.header_files.push(path);
568 }
569 old_path = None;
570 }
571 }
572
573 shape
574 }
575
576 fn hunk_line_counts_for_shape(header: &str) -> Option<(usize, usize)> {
577 let parts: Vec<&str> = header.split_whitespace().collect();
578 if parts.len() < 3 {
579 return None;
580 }
581 let (_, old_count) = parse_range(parts[1].trim_start_matches('-')).ok()?;
582 let (_, new_count) = parse_range(parts[2].trim_start_matches('+')).ok()?;
583 Some((old_count, new_count))
584 }
585
586 fn advance_hunk_shape_counts(line: &str, old_remaining: &mut usize, new_remaining: &mut usize) {
587 if line.starts_with('\\') {
588 return;
589 }
590 if line.starts_with('+') {
591 *new_remaining = new_remaining.saturating_sub(1);
592 } else if line.starts_with('-') {
593 *old_remaining = old_remaining.saturating_sub(1);
594 } else {
595 *old_remaining = old_remaining.saturating_sub(1);
596 *new_remaining = new_remaining.saturating_sub(1);
597 }
598 }
599
600 fn validate_patch_shape(shape: &PatchShape, path_override: Option<&str>) -> Result<(), ToolError> {
601 if !shape.has_hunks {
602 return Err(ToolError::invalid_input(
603 "Patch must include at least one hunk header in numeric unified-diff form (`@@ -old_start,old_count +new_start,new_count @@`, example: `@@ -12,3 +12,5 @@`).",
604 ));
605 }
606
607 match path_override {
608 Some(_) if shape.file_count() > 1 => Err(ToolError::invalid_input(format!(
609 "Patch references multiple files ({}) but `path` was provided. Remove `path` to apply a multi-file patch, or provide a single-file patch.",
610 format_file_list(&shape.header_files),
611 ))),
612 None if shape.file_count() == 0 => Err(ToolError::invalid_input(
613 "Patch contains hunks but no file headers (`---`/`+++`). Provide `path` or add headers.",
614 )),
615 _ => Ok(()),
616 }
617 }
618
619 fn diff_header_mismatch(path_override: &str, shape: &PatchShape) -> Option<String> {
620 if shape.file_count() != 1 {
621 return None;
622 }
623 let header_path = &shape.header_files[0];
624 let override_norm = normalize_diff_path(path_override).unwrap_or_else(|| path_override.into());
625 if &override_norm == header_path {
626 None
627 } else {
628 Some(format!(
629 "Note: patch headers reference `{header_path}` but `path` overrides to `{override_norm}`."
630 ))
631 }
632 }
633
634 pub fn format_file_list(files: &[String]) -> String {
635 if files.is_empty() {
636 return "<none>".to_string();
637 }
638 let mut shown: Vec<String> = files.iter().take(FILE_LIST_LIMIT).cloned().collect();
639 let remaining = files.len().saturating_sub(shown.len());
640 if remaining > 0 {
641 shown.push(format!("... (+{remaining} more)"));
642 }
643 shown.join(", ")
644 }
645
646 pub fn push_unique(target: &mut Vec<String>, value: String) {
647 if !target.iter().any(|existing| existing == &value) {
648 target.push(value);
649 }
650 }
651
651 lines RUST