1use super::blob_apply::{apply_patch_to_blob, BlobApplyOptions};
4use super::FilePatch;
5use crate::error::{ApplyError, Error};
6use crate::index::{Index, IndexEntry, MODE_REGULAR};
7use crate::merge_diff::read_blob_at_path;
8use crate::objects::{ObjectId, ObjectKind};
9use crate::repo::Repository;
10use std::collections::BTreeMap;
11
12#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
14pub struct IndexApplyOptions {
15 pub dry_run: bool,
17 pub reverse: bool,
19 pub head_tree_oid: Option<ObjectId>,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq, Default)]
25pub struct IndexApplyOutcome {
26 pub added: Vec<String>,
28 pub modified: Vec<String>,
30 pub removed: Vec<String>,
32 pub dry_run: bool,
34}
35
36impl IndexApplyOutcome {
37 fn push_added(&mut self, path: String) {
38 if !self.added.contains(&path) {
39 self.added.push(path);
40 }
41 }
42
43 fn push_modified(&mut self, path: String) {
44 if !self.modified.contains(&path) && !self.added.contains(&path) {
45 self.modified.push(path);
46 }
47 }
48
49 fn push_removed(&mut self, path: String) {
50 if !self.removed.contains(&path) {
51 self.removed.push(path);
52 }
53 }
54
55 fn finalize(mut self) -> Self {
56 self.added.sort();
57 self.modified.sort();
58 self.removed.sort();
59 self
60 }
61}
62
63#[derive(Clone)]
64enum PlannedChange {
65 Upsert {
66 path: String,
67 oid: ObjectId,
68 mode: u32,
69 blob: Vec<u8>,
70 },
71 Remove {
72 path: String,
73 },
74}
75
76pub fn apply_patch_to_index(
80 repo: &Repository,
81 index: &mut Index,
82 patches: &[FilePatch],
83 opts: &IndexApplyOptions,
84) -> std::result::Result<IndexApplyOutcome, ApplyError> {
85 let mut trial: Option<Index> = None;
88 let mut outcome = IndexApplyOutcome {
89 dry_run: opts.dry_run,
90 ..IndexApplyOutcome::default()
91 };
92 let mut fn_table: BTreeMap<String, FnState> = BTreeMap::new();
93 let mut planned = Vec::new();
94
95 for (i, patch) in patches.iter().enumerate() {
96 if patch.involves_gitlink() {
97 let path = patch.effective_path().unwrap_or("<unknown>").to_string();
98 return Err(ApplyError::Failed {
99 path,
100 message: "submodule/gitlink patches are not supported".to_string(),
101 });
102 }
103 let view = trial.as_ref().unwrap_or(index);
104 let changes = plan_one_file_patch(repo, view, patch, opts, &mut fn_table, &mut outcome)?;
105 if i + 1 < patches.len() {
106 let trial = trial.get_or_insert_with(|| index.clone());
107 for change in &changes {
108 apply_planned_to_index(trial, change);
109 }
110 }
111 planned.extend(changes);
112 }
113
114 if !opts.dry_run {
115 for change in &planned {
116 if let PlannedChange::Upsert { blob, .. } = change {
117 repo.odb()
118 .write(ObjectKind::Blob, blob)
119 .map_err(|e| library_err_path("", e))?;
120 }
121 }
122 for change in &planned {
123 apply_planned_to_index(index, change);
124 }
125 }
126 Ok(outcome.finalize())
127}
128
129pub fn apply_patch_to_index_and_write(
131 repo: &Repository,
132 patches: &[FilePatch],
133 opts: &IndexApplyOptions,
134 cancel: &crate::progress::CancelToken,
135) -> std::result::Result<IndexApplyOutcome, ApplyError> {
136 let handle = repo.index();
137 let mut lock = handle.begin_update().map_err(|e| library_err_path("", e))?;
138 crate::progress::poll_cancel(&mut crate::progress::NullProgress, cancel)
139 .map_err(|e| library_err_path("", e))?;
140 let mut index = handle
141 .load(&crate::index::IndexLoadOptions::default())
142 .map_err(|e| library_err_path("", e))?;
143 let outcome = apply_patch_to_index(repo, &mut index, patches, opts)?;
144 crate::progress::poll_cancel(&mut crate::progress::NullProgress, cancel)
145 .map_err(|e| library_err_path("", e))?;
146 if opts.dry_run {
147 return Ok(outcome);
148 }
149 crate::progress::poll_cancel(&mut crate::progress::NullProgress, cancel)
150 .map_err(|e| library_err_path("", e))?;
151 handle
152 .commit_update(&mut lock, &mut index, false)
153 .map_err(|e| library_err_path("", e))?;
154 Ok(outcome)
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158enum FnState {
159 Active,
160 Deleted,
161}
162
163fn plan_one_file_patch(
164 repo: &Repository,
165 index: &Index,
166 patch: &FilePatch,
167 opts: &IndexApplyOptions,
168 fn_table: &mut BTreeMap<String, FnState>,
169 outcome: &mut IndexApplyOutcome,
170) -> std::result::Result<Vec<PlannedChange>, ApplyError> {
171 let target = patch
172 .target_path()
173 .map(str::to_string)
174 .or_else(|| patch.effective_path().map(str::to_string))
175 .ok_or_else(|| ApplyError::Failed {
176 path: String::new(),
177 message: "patch has no target path".to_string(),
178 })?;
179
180 if patch.is_deleted {
181 if opts.reverse {
182 let base_blob = read_preimage_blob(repo, index, patch, &target, opts)?;
183 let new_blob = apply_patch_to_blob(
184 &base_blob,
185 patch,
186 &BlobApplyOptions {
187 reverse: true,
188 ..BlobApplyOptions::default()
189 },
190 )?;
191 return finish_reverse_index_upsert(
192 repo, index, patch, &target, opts, fn_table, outcome, new_blob,
193 );
194 }
195 let base_blob = read_preimage_blob(repo, index, patch, &target, opts)?;
196 apply_patch_to_blob(
197 &base_blob,
198 patch,
199 &BlobApplyOptions {
200 reverse: opts.reverse,
201 ..BlobApplyOptions::default()
202 },
203 )?;
204 if index.get(target.as_bytes(), 0).is_none() {
205 return Err(ApplyError::NotInIndex {
206 path: target.clone(),
207 });
208 }
209 fn_table.insert(target.clone(), FnState::Deleted);
210 outcome.push_removed(target.clone());
211 return Ok(vec![PlannedChange::Remove { path: target }]);
212 }
213
214 if patch.is_new
215 && index.get(target.as_bytes(), 0).is_some()
216 && fn_table.get(&target).copied() != Some(FnState::Deleted)
217 {
218 return Err(ApplyError::Failed {
219 path: target.clone(),
220 message: "path already exists in index".to_string(),
221 });
222 }
223
224 let base_blob = read_preimage_blob(repo, index, patch, &target, opts)?;
225 let new_blob = apply_patch_to_blob(
226 &base_blob,
227 patch,
228 &BlobApplyOptions {
229 reverse: opts.reverse,
230 ..BlobApplyOptions::default()
231 },
232 )?;
233 if opts.reverse {
234 return finish_reverse_index_upsert(
235 repo, index, patch, &target, opts, fn_table, outcome, new_blob,
236 );
237 }
238 let mode = resolve_mode(index, patch, &target)?;
239 let oid = hash_blob(repo, &new_blob)?;
240
241 let mut out = Vec::new();
242 if patch.is_rename {
243 if let Some(old) = patch.source_path().map(str::to_string) {
244 if old != target
245 && fn_table.get(&old).copied() != Some(FnState::Deleted)
246 && index.get(old.as_bytes(), 0).is_some()
247 {
248 fn_table.insert(old.clone(), FnState::Deleted);
249 outcome.push_removed(old.clone());
250 out.push(PlannedChange::Remove { path: old });
251 }
252 }
253 }
254
255 let existed = index.get(target.as_bytes(), 0).is_some()
256 || fn_table.get(&target).copied() == Some(FnState::Active);
257 if existed {
258 outcome.push_modified(target.clone());
259 } else {
260 outcome.push_added(target.clone());
261 }
262 fn_table.insert(target.clone(), FnState::Active);
263
264 out.push(PlannedChange::Upsert {
265 path: target,
266 oid,
267 mode,
268 blob: new_blob,
269 });
270 Ok(out)
271}
272
273fn apply_planned_to_index(index: &mut Index, change: &PlannedChange) {
274 match change {
275 PlannedChange::Remove { path } => {
276 index.remove_path_all_stages(path.as_bytes());
277 }
278 PlannedChange::Upsert {
279 path, oid, mode, ..
280 } => {
281 upsert_index_entry(index, path, *oid, *mode);
282 }
283 }
284}
285
286fn read_preimage_blob(
287 repo: &Repository,
288 index: &Index,
289 patch: &FilePatch,
290 target: &str,
291 opts: &IndexApplyOptions,
292) -> std::result::Result<Vec<u8>, ApplyError> {
293 if patch.is_new {
294 return Ok(Vec::new());
295 }
296 let path = patch
297 .source_path()
298 .or_else(|| patch.effective_path())
299 .unwrap_or(target);
300 if path == "/dev/null" {
301 return Ok(Vec::new());
302 }
303 if let Some(entry) = index.get(path.as_bytes(), 0) {
304 return repo
305 .odb()
306 .read(&entry.oid)
307 .map(|o| o.data)
308 .map_err(|e| ApplyError::Failed {
309 path: path.to_string(),
310 message: e.to_string(),
311 });
312 }
313 if opts.reverse {
314 return Ok(Vec::new());
315 }
316 Err(ApplyError::NotInIndex {
317 path: path.to_string(),
318 })
319}
320
321#[allow(clippy::too_many_arguments)]
322fn finish_reverse_index_upsert(
323 repo: &Repository,
324 index: &Index,
325 patch: &FilePatch,
326 target: &str,
327 opts: &IndexApplyOptions,
328 fn_table: &mut BTreeMap<String, FnState>,
329 outcome: &mut IndexApplyOutcome,
330 new_blob: Vec<u8>,
331) -> std::result::Result<Vec<PlannedChange>, ApplyError> {
332 if should_drop_index_entry_on_reverse(repo, target, opts, &new_blob) {
333 if index.get(target.as_bytes(), 0).is_some()
334 || fn_table.get(target).copied() == Some(FnState::Active)
335 {
336 fn_table.insert(target.to_string(), FnState::Deleted);
337 outcome.push_removed(target.to_string());
338 return Ok(vec![PlannedChange::Remove {
339 path: target.to_string(),
340 }]);
341 }
342 return Ok(Vec::new());
343 }
344 let mode = resolve_mode(index, patch, target)?;
345 let oid = hash_blob(repo, &new_blob)?;
346 let existed = index.get(target.as_bytes(), 0).is_some()
347 || fn_table.get(target).copied() == Some(FnState::Active);
348 if existed {
349 outcome.push_modified(target.to_string());
350 } else {
351 outcome.push_added(target.to_string());
352 }
353 fn_table.insert(target.to_string(), FnState::Active);
354 Ok(vec![PlannedChange::Upsert {
355 path: target.to_string(),
356 oid,
357 mode,
358 blob: new_blob,
359 }])
360}
361
362fn should_drop_index_entry_on_reverse(
363 repo: &Repository,
364 path: &str,
365 opts: &IndexApplyOptions,
366 new_blob: &[u8],
367) -> bool {
368 if !new_blob.is_empty() {
369 return false;
370 }
371 let Some(tree) = opts.head_tree_oid else {
372 return true;
373 };
374 read_blob_at_path(repo.odb(), &tree, path).is_none()
375}
376
377fn resolve_mode(
378 index: &Index,
379 patch: &FilePatch,
380 target: &str,
381) -> std::result::Result<u32, ApplyError> {
382 if let Some(mode) = patch.new_mode.as_deref() {
383 return parse_mode(mode);
384 }
385 if patch.is_rename || patch.is_copy {
386 if let Some(src) = patch
387 .source_path()
388 .filter(|p| *p != "/dev/null")
389 .or_else(|| patch.old_path.as_deref().filter(|p| *p != "/dev/null"))
390 {
391 if let Some(entry) = index.get(src.as_bytes(), 0) {
392 return Ok(entry.mode);
393 }
394 }
395 }
396 if let Some(mode) = patch.old_mode.as_deref() {
397 return parse_mode(mode);
398 }
399 if let Some(entry) = index.get(target.as_bytes(), 0) {
400 return Ok(entry.mode);
401 }
402 Ok(MODE_REGULAR)
403}
404
405fn parse_mode(mode: &str) -> std::result::Result<u32, ApplyError> {
406 let trimmed = mode.trim();
407 u32::from_str_radix(trimmed, 8).map_err(|e| ApplyError::Failed {
408 path: String::new(),
409 message: format!("invalid mode '{trimmed}': {e}"),
410 })
411}
412
413fn hash_blob(repo: &Repository, data: &[u8]) -> std::result::Result<ObjectId, ApplyError> {
414 repo.odb()
415 .hash_algo()
416 .hash_object(ObjectKind::Blob, data)
417 .map_err(|e| ApplyError::Failed {
418 path: String::new(),
419 message: e.to_string(),
420 })
421}
422
423fn upsert_index_entry(index: &mut Index, path: &str, oid: ObjectId, mode: u32) {
424 let path_bytes = path.as_bytes().to_vec();
425 let flags = (path.len().min(0xfff) as u16) & 0x0fff;
426 let entry = IndexEntry {
427 ctime_sec: 0,
428 ctime_nsec: 0,
429 mtime_sec: 0,
430 mtime_nsec: 0,
431 dev: 0,
432 ino: 0,
433 mode: if mode == 0 { MODE_REGULAR } else { mode },
434 uid: 0,
435 gid: 0,
436 size: 0,
437 oid,
438 flags,
439 flags_extended: None,
440 path: path_bytes,
441 base_index_pos: 0,
442 };
443 index.add_or_replace(entry);
444}
445
446fn library_err_path(path: &str, err: Error) -> ApplyError {
447 if matches!(err, Error::Cancelled) {
448 return ApplyError::Cancelled;
449 }
450 ApplyError::Failed {
451 path: path.to_string(),
452 message: err.to_string(),
453 }
454}
455
456#[cfg(test)]
457mod tests {
458 use super::*;
459 use crate::apply::parse_patch;
460 use crate::config::environment::RepositoryOptions;
461 use crate::repo::Repository;
462 use std::process::Command;
463
464 fn init_repo(dir: &std::path::Path) {
465 Command::new("git")
466 .current_dir(dir)
467 .args(["init", "-q", "-b", "main"])
468 .status()
469 .unwrap();
470 }
471
472 #[cfg_attr(
473 not(feature = "full-tests"),
474 ignore = "starts system git or is heavy; run with --features full-tests"
475 )]
476 #[test]
477 fn index_apply_modify() {
478 let dir = tempfile::tempdir().unwrap();
479 init_repo(dir.path());
480 std::fs::write(dir.path().join("f.txt"), b"a\n").unwrap();
481 Command::new("git")
482 .current_dir(dir.path())
483 .args(["add", "f.txt"])
484 .status()
485 .unwrap();
486 let patch = parse_patch(
487 "diff --git a/f.txt b/f.txt\n\
488 --- a/f.txt\n\
489 +++ b/f.txt\n\
490 @@ -1 +1 @@\n\
491 -a\n\
492 +b\n",
493 1,
494 "p",
495 false,
496 None,
497 )
498 .unwrap();
499 let repo = Repository::discover(Some(dir.path()), &RepositoryOptions::default()).unwrap();
500 let mut index = repo.load_index().unwrap();
501 apply_patch_to_index(&repo, &mut index, &patch, &IndexApplyOptions::default()).unwrap();
502 let entry = index.get(b"f.txt", 0).unwrap();
503 let blob = repo.odb().read(&entry.oid).unwrap();
504 assert_eq!(blob.data, b"b\n");
505 assert!(entry.stat_cache_unset());
506 }
507
508 fn one_line_patch(path: &str, old: &str, new: &str) -> FilePatch {
509 let text = format!(
510 "diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -1 +1 @@\n-{old}\n+{new}\n"
511 );
512 parse_patch(&text, 1, "p", false, None)
513 .unwrap()
514 .pop()
515 .unwrap()
516 }
517
518 fn repo_with_index(files: &[(&str, &[u8])]) -> (tempfile::TempDir, Repository, Index) {
519 let dir = tempfile::tempdir().unwrap();
520 let (repo, _) =
521 Repository::init(dir.path(), &crate::repo::InitOptions::default()).expect("init");
522 let mut index = Index::new();
523 for (path, data) in files {
524 let oid = repo.odb().write(ObjectKind::Blob, data).unwrap();
525 upsert_index_entry(&mut index, path, oid, MODE_REGULAR);
526 }
527 (dir, repo, index)
528 }
529
530 #[test]
531 fn apply_patch_to_index_and_write_cancelled_leaves_index_untouched() {
532 use crate::progress::CancelToken;
533 use std::fs;
534
535 let (_dir, repo, mut index) = repo_with_index(&[("f.txt", b"a\n")]);
536 repo.write_index(&mut index).expect("write index");
537 let before = fs::read(repo.index_path()).expect("read index");
538 let cancel = CancelToken::new();
539 cancel.cancel();
540 let patch = one_line_patch("f.txt", "a", "b");
541 let err =
542 apply_patch_to_index_and_write(&repo, &[patch], &IndexApplyOptions::default(), &cancel)
543 .expect_err("cancelled");
544 assert_eq!(err, ApplyError::Cancelled);
545 assert_eq!(fs::read(repo.index_path()).expect("read index"), before);
546 }
547
548 fn blob_at(repo: &Repository, index: &Index, path: &str) -> Vec<u8> {
549 let entry = index.get(path.as_bytes(), 0).expect("entry");
550 repo.odb().read(&entry.oid).unwrap().data
551 }
552
553 #[test]
554 fn index_apply_several_patches_in_one_call() {
555 let (_dir, repo, mut index) =
556 repo_with_index(&[("a.txt", b"a\n"), ("b.txt", b"b\n"), ("c.txt", b"c\n")]);
557 let patches = [
558 one_line_patch("a.txt", "a", "A"),
559 one_line_patch("c.txt", "c", "C"),
560 ];
561 let outcome =
562 apply_patch_to_index(&repo, &mut index, &patches, &IndexApplyOptions::default())
563 .unwrap();
564 assert_eq!(outcome.modified, ["a.txt", "c.txt"]);
565 assert_eq!(blob_at(&repo, &index, "a.txt"), b"A\n");
566 assert_eq!(blob_at(&repo, &index, "b.txt"), b"b\n");
567 assert_eq!(blob_at(&repo, &index, "c.txt"), b"C\n");
568 }
569
570 #[test]
571 fn index_apply_failure_in_later_patch_leaves_index_untouched() {
572 let (_dir, repo, mut index) = repo_with_index(&[("a.txt", b"a\n"), ("b.txt", b"b\n")]);
573 let before = index.clone();
574 let patches = [
575 one_line_patch("a.txt", "a", "A"),
576 one_line_patch("b.txt", "not-b", "B"),
577 ];
578 let err = apply_patch_to_index(&repo, &mut index, &patches, &IndexApplyOptions::default())
579 .expect_err("second patch does not apply");
580 assert!(matches!(err, ApplyError::PatchFailed { .. }), "{err:?}");
581 assert_eq!(index.entries, before.entries);
582 let a_oid = repo
583 .odb()
584 .hash_algo()
585 .hash_object(ObjectKind::Blob, b"A\n")
586 .unwrap();
587 assert!(!repo.odb().exists(&a_oid), "no blob written on failure");
588 }
589
590 #[test]
591 fn index_apply_dry_run_reports_without_changing_index() {
592 let (_dir, repo, mut index) = repo_with_index(&[("a.txt", b"a\n")]);
593 let before = index.clone();
594 let outcome = apply_patch_to_index(
595 &repo,
596 &mut index,
597 &[one_line_patch("a.txt", "a", "A")],
598 &IndexApplyOptions {
599 dry_run: true,
600 ..IndexApplyOptions::default()
601 },
602 )
603 .unwrap();
604 assert!(outcome.dry_run);
605 assert_eq!(outcome.modified, ["a.txt"]);
606 assert_eq!(index.entries, before.entries);
607 }
608}