1use std::borrow::Cow;
4use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
5use std::fs;
6use std::str::FromStr;
7
8use thiserror::Error;
9
10use crate::apply::parse_patch;
11use crate::apply::{
12 apply_hunks_to_blob, apply_patch_to_index, apply_patch_to_index_and_write, ApplyOptions,
13 FilePatch, Hunk, HunkLine, IndexApplyOptions, IndexApplyOutcome,
14};
15use crate::crlf::worktree_conversion_is_identity;
16use crate::diff::structured::{
17 structured_file_diff, SideBytes, StructuredHunk, StructuredLine, StructuredLineKind,
18 StructuredSegment,
19};
20use crate::diff::{
21 collect_files_for_target, imara_unified_hunk_slices, include_file_in_diff,
22 read_worktree_side_bytes_for_diff, unified_hunk_body_for_diff_options,
23 unstaged_file_diffs_with_peer_hunks, unstaged_raw_changes_with_peer_hunks,
24 unstaged_raw_changes_with_peer_hunks_in, DiffOptions, DiffStatus, DiffTarget, FileChange,
25 FileDiff,
26};
27use crate::diff::{hunk_ids, DiffSide, HunkId};
28use crate::error::{ApplyError, Error};
29use crate::index::{Index, IndexLock, MODE_EXECUTABLE, MODE_GITLINK, MODE_REGULAR};
30use crate::objects::FileMode;
31use crate::objects::ObjectKind;
32use crate::porcelain::checkout::{
33 remove_empty_parent_dirs, smudge_bytes_for_worktree_path, write_smudged_blob_to_worktree,
34 write_to_worktree_cached, LeadingDirCache,
35};
36use crate::porcelain::index_from_tree::refresh_stage0_index_stats_for_paths;
37use crate::progress::{poll_cancel, CancelToken, ProgressPhase, ProgressSink};
38use crate::repo::Repository;
39use crate::repo::RepositoryError;
40use crate::worktree_rules::WorktreeRules;
41
42#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct LineRange {
47 pub path: String,
49 pub start: usize,
51 pub end: usize,
53}
54
55#[derive(Debug, Clone, Default, PartialEq, Eq)]
57pub struct HunkSelection {
58 pub ids: Vec<HunkId>,
60 pub ranges: Vec<LineRange>,
62}
63
64#[derive(Debug, Error)]
66#[non_exhaustive]
67pub enum HunkSelectError {
68 #[error("unknown hunk id {id}")]
70 UnknownId {
71 id: String,
73 },
74 #[error("stale hunk id {id}")]
76 StaleId {
77 id: HunkId,
79 path: Option<String>,
81 current_ids: Vec<HunkId>,
83 },
84 #[error("hunk id {id} is for the {actual_side} side, not {requested_side}")]
86 WrongSide {
87 id: HunkId,
89 actual_side: DiffSide,
91 requested_side: DiffSide,
93 },
94 #[error("hunks cannot be selected on the {side} side")]
96 UnselectableSide {
97 side: DiffSide,
99 },
100 #[error("binary file {path} has no selectable hunks")]
102 Binary {
103 path: String,
105 },
106 #[error("{0}")]
108 Apply(#[from] ApplyError),
109 #[error("line range {start}-{end} is out of bounds for {path} (file has {max_line} lines)")]
111 RangeOutOfBounds {
112 path: String,
114 start: usize,
116 end: usize,
118 max_line: usize,
120 },
121 #[error("line range selects nothing on {path}")]
123 RangeSelectsNothing {
124 path: String,
126 },
127 #[error("submodule {path} cannot be restored by hunk")]
129 Gitlink {
130 path: String,
132 },
133 #[error("invalid file mode {mode} for {path}")]
135 InvalidMode {
136 path: String,
138 mode: String,
140 },
141 #[error("patch names no path")]
143 MissingPath,
144 #[error("could not build patch for selected hunks")]
146 PatchBuild,
147}
148
149#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct StageHunksOutcome {
152 pub dry_run: bool,
154 pub staged_hunks: BTreeMap<String, Vec<HunkId>>,
156 pub staged_lines: BTreeMap<String, Vec<String>>,
158 pub added: Vec<String>,
160 pub modified: Vec<String>,
162 pub removed: Vec<String>,
164}
165
166impl StageHunksOutcome {
167 fn from_apply(
168 dry_run: bool,
169 staged_hunks: BTreeMap<String, Vec<HunkId>>,
170 staged_lines: BTreeMap<String, Vec<String>>,
171 apply: IndexApplyOutcome,
172 ) -> Self {
173 Self {
174 dry_run,
175 staged_hunks,
176 staged_lines,
177 added: apply.added,
178 modified: apply.modified,
179 removed: apply.removed,
180 }
181 }
182}
183
184pub(crate) fn unstaged_file_diffs(
190 repo: &Repository,
191 pathspecs: &[String],
192) -> std::result::Result<Vec<(FileDiff, Vec<StructuredHunk>)>, Error> {
193 let opts = DiffOptions::from_config(repo.config().snapshot()?.as_ref());
194 let (files, peers) = unstaged_file_diffs_with_peer_hunks(repo, pathspecs, opts)?;
195 Ok(files
196 .into_iter()
197 .map(|f| {
198 let peer = peers.get(&f.path).cloned().unwrap_or_default();
199 (f, peer)
200 })
201 .collect())
202}
203
204pub fn parse_hunk_id_list(tokens: &[String]) -> crate::error::Result<HunkSelection> {
210 let mut ids = Vec::new();
211 for token in tokens {
212 for part in token.split(',').map(str::trim).filter(|s| !s.is_empty()) {
213 ids.push(
214 HunkId::from_str(part).map_err(|_| HunkSelectError::UnknownId {
215 id: part.to_string(),
216 })?,
217 );
218 }
219 }
220 Ok(HunkSelection {
221 ids,
222 ranges: Vec::new(),
223 })
224}
225
226pub(crate) fn resolve_selection(
235 repo: &Repository,
236 side: DiffSide,
237 selection: &HunkSelection,
238 pathspecs: &[String],
239 diff_options: DiffOptions,
240) -> crate::error::Result<Vec<FilePatch>> {
241 Ok(resolve_selection_with_staged(repo, side, selection, pathspecs, diff_options)?.patches)
243}
244
245#[derive(Debug, Clone, Default)]
248pub(crate) struct ResolvedSelection {
249 pub(crate) patches: Vec<FilePatch>,
250 pub(crate) selected_hunks: BTreeMap<String, Vec<HunkId>>,
251 pub(crate) selected_lines: BTreeMap<String, Vec<String>>,
253 pub(crate) whole_files: BTreeSet<String>,
256}
257
258pub(crate) fn resolve_unstaged_selection(
265 repo: &Repository,
266 selection: &HunkSelection,
267 pathspecs: &[String],
268) -> crate::error::Result<ResolvedSelection> {
269 let diff_opts = diff_options_for_hunk_select(repo)?;
270 resolve_selection_with_staged(repo, DiffSide::Unstaged, selection, pathspecs, diff_opts)
271}
272
273fn merge_resolved(into: &mut ResolvedSelection, other: ResolvedSelection) {
274 for (path, ids) in other.selected_hunks {
275 into.selected_hunks.entry(path).or_default().extend(ids);
276 }
277 for (path, ranges) in other.selected_lines {
278 into.selected_lines.entry(path).or_default().extend(ranges);
279 }
280 into.whole_files.extend(other.whole_files);
281 for patch in other.patches {
282 if let Some(existing) = into
283 .patches
284 .iter_mut()
285 .find(|p| p.effective_path() == patch.effective_path())
286 {
287 existing.hunks.extend(patch.hunks);
288 existing.hunks.sort_by_key(|h| (h.new_start, h.old_start));
289 } else {
290 into.patches.push(patch);
291 }
292 }
293}
294
295fn resolve_selection_with_staged(
296 repo: &Repository,
297 side: DiffSide,
298 selection: &HunkSelection,
299 pathspecs: &[String],
300 diff_options: DiffOptions,
301) -> crate::error::Result<ResolvedSelection> {
302 resolve_selection_in(repo, None, side, selection, pathspecs, diff_options)
303}
304
305fn resolve_selection_in(
308 repo: &Repository,
309 index: Option<&mut Index>,
310 side: DiffSide,
311 selection: &HunkSelection,
312 pathspecs: &[String],
313 diff_options: DiffOptions,
314) -> crate::error::Result<ResolvedSelection> {
315 if selection.ids.is_empty() && selection.ranges.is_empty() {
316 return Ok(ResolvedSelection::default());
317 }
318 let opts = diff_options.with_word_level_inline(false);
320 let requested: HashSet<HunkId> = selection.ids.iter().cloned().collect();
321
322 match side {
323 DiffSide::Unstaged => {
324 let (changes, peer_hunks) = match index {
326 Some(index) => {
327 unstaged_raw_changes_with_peer_hunks_in(repo, index, pathspecs, opts.clone())?
328 }
329 None => unstaged_raw_changes_with_peer_hunks(repo, pathspecs, opts.clone())?,
330 };
331 let mut resolved = if requested.is_empty() {
332 ResolvedSelection::default()
333 } else {
334 resolve_unstaged(
335 repo,
336 &changes,
337 &peer_hunks,
338 pathspecs,
339 opts.clone(),
340 &requested,
341 )?
342 };
343 if !selection.ranges.is_empty() {
344 let line_part = resolve_line_ranges_unstaged(
345 &changes,
346 &peer_hunks,
347 &opts,
348 selection,
349 &requested,
350 )?;
351 merge_resolved(&mut resolved, line_part);
352 }
353 Ok(resolved)
354 }
355 DiffSide::Staged => {
356 if !selection.ranges.is_empty() {
357 return Err(HunkSelectError::RangeSelectsNothing {
358 path: selection.ranges[0].path.clone(),
359 }
360 .into());
361 }
362 resolve_staged(repo, pathspecs, opts, &requested)
363 }
364 DiffSide::Other => Err(HunkSelectError::UnselectableSide { side }.into()),
365 }
366}
367
368fn resolve_staged(
369 repo: &Repository,
370 pathspecs: &[String],
371 opts: DiffOptions,
372 requested: &HashSet<HunkId>,
373) -> crate::error::Result<ResolvedSelection> {
374 let files = collect_files_for_target(repo, &DiffTarget::IndexVsHead, pathspecs, opts)?;
375 resolve_on_files(
376 DiffSide::Staged,
377 files,
378 HashMap::new(),
379 requested,
380 pathspecs,
381 )
382}
383
384fn resolve_unstaged(
385 repo: &Repository,
386 changes: &[FileChange],
387 peer_hunks: &HashMap<String, Vec<StructuredHunk>>,
388 pathspecs: &[String],
389 opts: DiffOptions,
390 requested: &HashSet<HunkId>,
391) -> crate::error::Result<ResolvedSelection> {
392 let mut patches = Vec::new();
393 let mut staged_hunks = BTreeMap::new();
394 let mut whole_files = BTreeSet::new();
395 let mut found = HashSet::new();
396
397 for change in changes {
398 if change.binary {
399 continue;
400 }
401 let peer = peer_hunks
402 .get(&change.path)
403 .map(|h| h.as_slice())
404 .unwrap_or(&[]);
405 let resolved = resolve_file_change_by_unified_body(
406 DiffSide::Unstaged,
407 change,
408 peer,
409 requested,
410 &opts,
411 )?;
412 found.extend(resolved.matched);
413 if let Some(staged) = resolved.selected_ids {
414 staged_hunks.insert(change.path.clone(), staged);
415 }
416 if resolved.whole_file {
417 whole_files.insert(change.path.clone());
418 }
419 patches.extend(resolved.patches);
420 }
421
422 let missing: Vec<HunkId> = requested
423 .iter()
424 .filter(|id| !found.contains(*id))
425 .cloned()
426 .collect();
427 if let Some(id) = missing.first().cloned() {
428 if let Some(wrong) = find_id_on_staged_side(repo, pathspecs, opts.clone(), requested)? {
429 return Err(HunkSelectError::WrongSide {
430 id: wrong,
431 actual_side: DiffSide::Staged,
432 requested_side: DiffSide::Unstaged,
433 }
434 .into());
435 }
436 if pathspecs.len() == 1 {
437 let path = &pathspecs[0];
438 if changes.iter().any(|c| c.path == *path && c.binary) {
439 return Err(HunkSelectError::Binary { path: path.clone() }.into());
440 }
441 }
442 let files: Vec<FileDiff> = changes
443 .iter()
444 .filter(|c| !c.binary)
445 .map(|c| build_file_diff(c, &opts))
446 .collect();
447 let current_ids = current_ids_for_stale(DiffSide::Unstaged, pathspecs, &files, peer_hunks);
448 return Err(HunkSelectError::StaleId {
449 id,
450 path: stale_path_hint(pathspecs, &files),
451 current_ids,
452 }
453 .into());
454 }
455
456 Ok(ResolvedSelection {
457 patches,
458 selected_hunks: staged_hunks,
459 selected_lines: BTreeMap::new(),
460 whole_files,
461 })
462}
463
464fn side_text(bytes: &SideBytes) -> Cow<'_, str> {
465 if bytes.data.is_empty() {
466 return Cow::Borrowed("");
467 }
468 match std::str::from_utf8(&bytes.data) {
469 Ok(text) => Cow::Borrowed(text),
470 Err(_) => Cow::Owned(String::from_utf8_lossy(&bytes.data).into_owned()),
471 }
472}
473
474fn line_count(text: &str) -> usize {
475 let newlines = memchr::memchr_iter(b'\n', text.as_bytes()).count();
476 if text.is_empty() || text.ends_with('\n') {
477 newlines
478 } else {
479 newlines + 1
480 }
481}
482
483struct UnifiedHunkResolve {
485 patches: Vec<FilePatch>,
487 selected_ids: Option<Vec<HunkId>>,
489 matched: HashSet<HunkId>,
491 whole_file: bool,
493}
494
495fn resolve_file_change_by_unified_body(
496 side: DiffSide,
497 change: &FileChange,
498 peer_hunks: &[StructuredHunk],
499 requested: &HashSet<HunkId>,
500 diff_options: &DiffOptions,
501) -> crate::error::Result<UnifiedHunkResolve> {
502 let old_text = side_text(&change.old_bytes);
503 let new_text = side_text(&change.new_bytes);
504 let body =
505 unified_hunk_body_for_diff_options(old_text.as_ref(), new_text.as_ref(), diff_options);
506 let before_count = line_count(old_text.as_ref());
507 let after_count = line_count(new_text.as_ref());
508 let before_ends_nl = old_text.as_ref().ends_with('\n');
509 let after_ends_nl = new_text.as_ref().ends_with('\n');
510 let slices = imara_unified_hunk_slices(&body);
511 let ids = crate::diff::hunk_id::hunk_ids_for_unified_slices(
512 side,
513 &change.path,
514 &slices,
515 before_count,
516 after_count,
517 before_ends_nl,
518 after_ends_nl,
519 peer_hunks,
520 );
521 let mut selected_slices = Vec::new();
522 let mut staged_ids = Vec::new();
523 let mut matched = HashSet::new();
524 for (slice, id) in slices.iter().zip(ids.iter()) {
525 if requested.contains(id) {
526 selected_slices.push(*slice);
527 staged_ids.push(id.clone());
528 matched.insert(id.clone());
529 }
530 }
531 if selected_slices.is_empty() {
532 return Ok(UnifiedHunkResolve {
533 patches: Vec::new(),
534 selected_ids: None,
535 matched,
536 whole_file: false,
537 });
538 }
539 let whole_file = selected_slices.len() == slices.len();
540 let patch = file_patch_from_unified_slices(change, &selected_slices)?;
541 Ok(UnifiedHunkResolve {
542 patches: vec![patch],
543 selected_ids: Some(staged_ids),
544 matched,
545 whole_file,
546 })
547}
548
549fn file_patch_from_unified_slices(
550 change: &FileChange,
551 slices: &[&str],
552) -> crate::error::Result<FilePatch> {
553 let path = &change.path;
554 let is_new = change.old_mode == FileMode::ABSENT;
555 let mut is_deleted =
556 matches!(change.status, DiffStatus::Deleted) || change.new_mode == FileMode::ABSENT;
557 let is_rename = matches!(change.status, DiffStatus::Renamed);
558 let is_copy = matches!(change.status, DiffStatus::Copied);
559 if !is_new && !is_deleted && side_text(&change.new_bytes).trim().is_empty() {
560 let preimage = side_text(&change.old_bytes);
561 if !preimage.trim().is_empty() {
562 is_deleted = true;
563 }
564 }
565 let mut text = format!("diff --git a/{path} b/{path}\n");
566 if is_new {
567 text.push_str(&format!("new file mode {}\n", change.new_mode));
568 }
569 if is_deleted {
570 text.push_str(&format!("deleted file mode {}\n", change.old_mode));
571 }
572 let old = if is_new {
573 "/dev/null".to_string()
574 } else {
575 format!("a/{}", change.old_path.as_deref().unwrap_or(path.as_str()))
576 };
577 let new = if is_deleted {
578 "/dev/null".to_string()
579 } else {
580 format!("b/{}", path)
581 };
582 text.push_str(&format!("--- {old}\n+++ {new}\n"));
583 for slice in slices {
584 text.push_str(slice);
585 if !slice.ends_with('\n') {
586 text.push('\n');
587 }
588 }
589 let mut patches = parse_patch(&text, 1, path, false, None).map_err(map_parse_err)?;
590 let mut patch = patches.pop().ok_or(HunkSelectError::PatchBuild)?;
591 patch.is_new = false;
592 patch.is_deleted = is_deleted;
593 patch.is_rename = is_rename;
594 patch.is_copy = is_copy;
595 patch.old_path = if is_new {
596 None
597 } else {
598 change.old_path.clone().or_else(|| Some(path.clone()))
599 };
600 patch.new_path = if is_deleted { None } else { Some(path.clone()) };
601 patch.old_mode = Some(change.old_mode.to_string());
602 patch.new_mode = Some(change.new_mode.to_string());
603 Ok(patch)
604}
605
606fn build_file_diff(change: &FileChange, opts: &DiffOptions) -> FileDiff {
607 let structured = structured_file_diff(
608 change.old_mode,
609 change.new_mode,
610 &change.old_bytes,
611 &change.new_bytes,
612 opts.clone(),
613 );
614 FileDiff {
615 path: change.path.clone(),
616 old_path: change.old_path.clone(),
617 status: change.status,
618 old_mode: structured.old_mode,
619 new_mode: structured.new_mode,
620 old_oid: change.old_oid,
621 new_oid: change.new_oid,
622 binary: change.binary,
623 old_size: change.old_bytes.byte_len(),
624 new_size: change.new_bytes.byte_len(),
625 content_changed: change.content_changed,
626 old_encoding_lossy: structured.old_encoding_lossy,
627 new_encoding_lossy: structured.new_encoding_lossy,
628 hunks: structured.hunks,
629 line_stat: None,
630 }
631}
632
633fn find_id_on_staged_side(
634 repo: &Repository,
635 pathspecs: &[String],
636 opts: DiffOptions,
637 requested: &HashSet<HunkId>,
638) -> crate::error::Result<Option<HunkId>> {
639 let files = collect_files_for_target(repo, &DiffTarget::IndexVsHead, pathspecs, opts)?;
640 Ok(files.into_iter().find_map(|file| {
641 if file.binary {
642 return None;
643 }
644 hunk_ids(DiffSide::Staged, &file.path, &file.hunks, &[])
645 .into_iter()
646 .find(|id| requested.contains(id))
647 }))
648}
649
650fn resolve_on_files(
651 side: DiffSide,
652 files: Vec<FileDiff>,
653 peer_hunks: HashMap<String, Vec<StructuredHunk>>,
654 requested: &HashSet<HunkId>,
655 pathspecs: &[String],
656) -> crate::error::Result<ResolvedSelection> {
657 let mut found = HashSet::new();
658 let mut patches = Vec::new();
659 let mut staged_by_path: BTreeMap<String, Vec<HunkId>> = BTreeMap::new();
660
661 for file in &files {
662 if file.binary {
663 continue;
664 }
665 let peer = peer_hunks
666 .get(&file.path)
667 .map(|h| h.as_slice())
668 .unwrap_or(&[]);
669 let ids = hunk_ids(side, &file.path, &file.hunks, peer);
670 let mut selected = Vec::new();
671 let mut selected_ids = Vec::new();
672 for (hunk, id) in file.hunks.iter().zip(ids.iter()) {
673 if requested.contains(id) {
674 selected.push(hunk.clone());
675 selected_ids.push(id.clone());
676 found.insert(id.clone());
677 }
678 }
679 if selected.is_empty() {
680 continue;
681 }
682 staged_by_path.insert(file.path.clone(), selected_ids);
683 patches.push(file_patch_from_hunks(file, &selected)?);
684 }
685
686 let missing: Vec<HunkId> = requested
687 .iter()
688 .filter(|id| !found.contains(*id))
689 .cloned()
690 .collect();
691 if let Some(id) = missing.first().cloned() {
692 if let Some(path) = stale_path_hint(pathspecs, &files) {
693 if files
694 .iter()
695 .find(|f| f.path == path)
696 .is_some_and(|f| f.binary)
697 {
698 return Err(HunkSelectError::Binary { path }.into());
699 }
700 }
701 let current_ids = current_ids_for_stale(side, pathspecs, &files, &peer_hunks);
702 return Err(HunkSelectError::StaleId {
703 id,
704 path: stale_path_hint(pathspecs, &files),
705 current_ids,
706 }
707 .into());
708 }
709
710 Ok(ResolvedSelection {
711 patches,
712 selected_hunks: staged_by_path,
713 selected_lines: BTreeMap::new(),
714 whole_files: BTreeSet::new(),
715 })
716}
717
718fn stale_path_hint(pathspecs: &[String], files: &[FileDiff]) -> Option<String> {
719 if pathspecs.len() == 1 {
720 return Some(pathspecs[0].clone());
721 }
722 if files.len() == 1 {
723 return Some(files[0].path.clone());
724 }
725 None
726}
727
728fn current_ids_for_stale(
729 side: DiffSide,
730 pathspecs: &[String],
731 files: &[FileDiff],
732 peer_hunks: &HashMap<String, Vec<StructuredHunk>>,
733) -> Vec<HunkId> {
734 let path = stale_path_hint(pathspecs, files);
735 let Some(path) = path else {
736 return Vec::new();
737 };
738 let Some(file) = files.iter().find(|f| f.path == path) else {
739 return Vec::new();
740 };
741 if file.binary {
742 return Vec::new();
743 }
744 let peer = peer_hunks
745 .get(&file.path)
746 .map(|h| h.as_slice())
747 .unwrap_or(&[]);
748 hunk_ids(side, &file.path, &file.hunks, peer)
749}
750
751fn file_patch_from_hunks(
752 file: &FileDiff,
753 hunks: &[StructuredHunk],
754) -> crate::error::Result<FilePatch> {
755 if file.binary {
756 return Err(HunkSelectError::Binary {
757 path: file.path.clone(),
758 }
759 .into());
760 }
761 let is_new = false;
763 let is_deleted = matches!(file.status, DiffStatus::Deleted);
764 let is_rename = matches!(file.status, DiffStatus::Renamed);
765 let apply_hunks: Vec<Hunk> = hunks
766 .iter()
767 .enumerate()
768 .map(|(i, h)| structured_hunk_to_apply_hunk(h, i + 1))
769 .collect();
770 Ok(FilePatch {
771 diff_old_path: file.old_path.clone().or_else(|| Some(file.path.clone())),
772 diff_new_path: Some(file.path.clone()),
773 old_path: if is_new {
774 None
775 } else {
776 file.old_path.clone().or_else(|| Some(file.path.clone()))
777 },
778 new_path: if is_deleted {
779 None
780 } else {
781 Some(file.path.clone())
782 },
783 saw_old_header: true,
784 saw_new_header: true,
785 old_mode: file.old_mode.clone(),
786 new_mode: file.new_mode.clone(),
787 old_mode_line: None,
788 new_mode_line: None,
789 is_new,
790 is_deleted,
791 is_rename,
792 is_copy: matches!(file.status, DiffStatus::Copied),
793 similarity_index: None,
794 dissimilarity_index: None,
795 old_oid: None,
796 new_oid: None,
797 binary_patch: None,
798 is_binary: false,
799 hunks: apply_hunks,
800 ws_rule: 0,
801 is_toplevel_relative: true,
802 })
803}
804
805fn merge_intervals(ranges: &[(usize, usize)]) -> Vec<(usize, usize)> {
806 if ranges.is_empty() {
807 return Vec::new();
808 }
809 let mut sorted = ranges.to_vec();
810 sorted.sort_unstable_by_key(|(s, _)| *s);
811 let mut out = vec![sorted[0]];
812 for (start, end) in sorted.into_iter().skip(1) {
813 if let Some(last) = out.last_mut() {
814 if start <= last.1 + 1 {
815 last.1 = last.1.max(end);
816 continue;
817 }
818 }
819 out.push((start, end));
820 }
821 out
822}
823
824fn line_in_intervals(line: usize, intervals: &[(usize, usize)]) -> bool {
825 intervals
826 .iter()
827 .any(|(start, end)| line >= *start && line <= *end)
828}
829
830fn deletion_selected(removal_point: usize, intervals: &[(usize, usize)]) -> bool {
831 intervals
832 .iter()
833 .any(|(start, end)| removal_point >= *start && removal_point <= *end + 1)
834}
835
836fn count_new_side_lines(bytes: &[u8]) -> usize {
837 if bytes.is_empty() {
838 return 0;
839 }
840 let mut count = bytes.iter().filter(|&&b| b == b'\n').count();
841 if bytes.last() != Some(&b'\n') {
842 count += 1;
843 }
844 count
845}
846
847fn new_side_line_count(change: &FileChange) -> usize {
848 if matches!(change.status, DiffStatus::Deleted) {
849 return 0;
850 }
851 count_new_side_lines(&change.new_bytes.data)
852}
853
854fn range_label(start: usize, end: usize) -> String {
855 if start == end {
856 format!("{start}")
857 } else {
858 format!("{start}-{end}")
859 }
860}
861
862fn validate_line_ranges(
863 path: &str,
864 intervals: &[(usize, usize)],
865 max_line: usize,
866) -> crate::error::Result<()> {
867 for &(start, end) in intervals {
868 if start == 0 || end == 0 || start > end || end > max_line {
869 return Err(HunkSelectError::RangeOutOfBounds {
870 path: path.to_string(),
871 start,
872 end,
873 max_line,
874 }
875 .into());
876 }
877 }
878 Ok(())
879}
880
881fn filter_hunk_by_intervals(
882 hunk: &StructuredHunk,
883 intervals: &[(usize, usize)],
884) -> Option<StructuredHunk> {
885 let mut new_cur = hunk.new_start;
886 let mut old_cur = hunk.old_start;
887 let mut out_lines = Vec::new();
888 let mut any_change = false;
889
890 for line in &hunk.lines {
891 match line.kind {
892 StructuredLineKind::Context => {
893 let new_n = line.new.unwrap_or(new_cur);
894 let old_n = line.old.unwrap_or(old_cur);
895 out_lines.push(line.clone());
896 new_cur = new_n.saturating_add(1);
897 old_cur = old_n.saturating_add(1);
898 }
899 StructuredLineKind::Del => {
900 let removal = new_cur;
901 let old_n = line.old.unwrap_or(old_cur);
902 if deletion_selected(removal, intervals) {
903 out_lines.push(line.clone());
904 any_change = true;
905 } else {
906 let text: String = line.segments.iter().map(|s| s.text.as_str()).collect();
907 out_lines.push(StructuredLine {
908 kind: StructuredLineKind::Context,
909 old: Some(old_n),
910 new: Some(removal),
911 segments: vec![StructuredSegment {
912 text,
913 emphasis: false,
914 }],
915 no_newline_at_eof: line.no_newline_at_eof,
916 });
917 }
918 old_cur = old_n.saturating_add(1);
919 }
920 StructuredLineKind::Add => {
921 let new_n = line.new.unwrap_or(new_cur);
922 if line_in_intervals(new_n, intervals) {
923 out_lines.push(line.clone());
924 any_change = true;
925 }
926 new_cur = new_n.saturating_add(1);
927 }
928 }
929 }
930
931 if !any_change {
932 return None;
933 }
934
935 let mut filtered = StructuredHunk {
936 old_start: hunk.old_start,
937 new_start: hunk.new_start,
938 old_lines: hunk.old_lines,
939 new_lines: hunk.new_lines,
940 context: hunk.context.clone(),
941 lines: out_lines,
942 };
943 recount_structured_hunk(&mut filtered);
944 Some(filtered)
945}
946
947fn recount_structured_hunk(hunk: &mut StructuredHunk) {
948 let mut old_start = None;
949 let mut new_start = None;
950 let mut old_count = 0usize;
951 let mut new_count = 0usize;
952 let mut old_line = 0usize;
953 let mut new_line = 0usize;
954
955 for line in &mut hunk.lines {
956 match line.kind {
957 StructuredLineKind::Context => {
958 if old_start.is_none() {
959 old_start = line.old.or(Some(old_line));
960 new_start = line.new.or(Some(new_line));
961 }
962 old_count += 1;
963 new_count += 1;
964 if let Some(o) = line.old {
965 old_line = o.saturating_add(1);
966 } else {
967 old_line = old_line.saturating_add(1);
968 }
969 if let Some(n) = line.new {
970 new_line = n.saturating_add(1);
971 } else {
972 new_line = new_line.saturating_add(1);
973 }
974 }
975 StructuredLineKind::Del => {
976 if old_start.is_none() {
977 old_start = line.old.or(Some(old_line));
978 new_start = Some(new_line);
979 }
980 old_count += 1;
981 if let Some(o) = line.old {
982 old_line = o.saturating_add(1);
983 } else {
984 old_line = old_line.saturating_add(1);
985 }
986 }
987 StructuredLineKind::Add => {
988 if old_start.is_none() {
989 old_start = Some(old_line);
990 new_start = line.new.or(Some(new_line));
991 }
992 new_count += 1;
993 if let Some(n) = line.new {
994 new_line = n.saturating_add(1);
995 } else {
996 new_line = new_line.saturating_add(1);
997 }
998 }
999 }
1000 }
1001
1002 hunk.old_start = old_start.unwrap_or(1);
1003 hunk.new_start = new_start.unwrap_or(1);
1004 hunk.old_lines = old_count;
1005 hunk.new_lines = new_count;
1006}
1007
1008fn resolve_line_ranges_unstaged(
1009 changes: &[FileChange],
1010 peer_hunks: &HashMap<String, Vec<StructuredHunk>>,
1011 opts: &DiffOptions,
1012 selection: &HunkSelection,
1013 id_selected: &HashSet<HunkId>,
1014) -> crate::error::Result<ResolvedSelection> {
1015 let mut by_path: BTreeMap<String, Vec<(usize, usize)>> = BTreeMap::new();
1016 let mut labels: BTreeMap<String, Vec<String>> = BTreeMap::new();
1017 for range in &selection.ranges {
1018 by_path
1019 .entry(range.path.clone())
1020 .or_default()
1021 .push((range.start, range.end));
1022 labels
1023 .entry(range.path.clone())
1024 .or_default()
1025 .push(range_label(range.start, range.end));
1026 }
1027
1028 let mut patches = Vec::new();
1029 let mut staged_lines = BTreeMap::new();
1030
1031 for (path, raw_intervals) in by_path {
1032 let intervals = merge_intervals(&raw_intervals);
1033 let change = changes
1034 .iter()
1035 .find(|c| c.path == path)
1036 .ok_or_else(|| HunkSelectError::RangeSelectsNothing { path: path.clone() })?;
1037 if change.binary {
1038 return Err(HunkSelectError::Binary { path: path.clone() }.into());
1039 }
1040 let file = build_file_diff(change, opts);
1041 if !include_file_in_diff(&file, opts) {
1042 return Err(HunkSelectError::RangeSelectsNothing { path }.into());
1043 }
1044 validate_line_ranges(&path, &intervals, new_side_line_count(change))?;
1045 let peer = peer_hunks.get(&path).map(|h| h.as_slice()).unwrap_or(&[]);
1046 let ids = hunk_ids(DiffSide::Unstaged, &path, &file.hunks, peer);
1047 let mut partial = Vec::new();
1048 let mut selected_any = false;
1049 for (hunk, id) in file.hunks.iter().zip(ids.iter()) {
1050 if id_selected.contains(id) {
1051 continue;
1052 }
1053 if let Some(filtered) = filter_hunk_by_intervals(hunk, &intervals) {
1054 selected_any = true;
1055 partial.push(filtered);
1056 }
1057 }
1058 let id_covered_any = file
1059 .hunks
1060 .iter()
1061 .zip(ids.iter())
1062 .any(|(_, id)| id_selected.contains(id));
1063 if !selected_any && !id_covered_any {
1064 return Err(HunkSelectError::RangeSelectsNothing { path: path.clone() }.into());
1065 }
1066 if selected_any {
1067 patches.push(file_patch_from_hunks(&file, &partial)?);
1068 }
1069 if let Some(labs) = labels.remove(&path) {
1070 staged_lines.insert(path, labs);
1071 }
1072 }
1073
1074 Ok(ResolvedSelection {
1075 patches,
1076 selected_hunks: BTreeMap::new(),
1077 selected_lines: staged_lines,
1078 whole_files: BTreeSet::new(),
1079 })
1080}
1081
1082fn structured_hunk_to_apply_hunk(hunk: &StructuredHunk, first_body_line: usize) -> Hunk {
1083 let mut lines = Vec::new();
1084 for line in &hunk.lines {
1085 let text: String = line.segments.iter().map(|s| s.text.as_str()).collect();
1086 match line.kind {
1087 StructuredLineKind::Context => lines.push(HunkLine::Context(text)),
1088 StructuredLineKind::Add => lines.push(HunkLine::Add(text)),
1089 StructuredLineKind::Del => lines.push(HunkLine::Remove(text)),
1090 }
1091 if line.no_newline_at_eof {
1092 lines.push(HunkLine::NoNewline);
1093 }
1094 }
1095 Hunk {
1096 old_start: hunk.old_start,
1097 old_count: hunk.old_lines,
1098 new_start: hunk.new_start,
1099 new_count: hunk.new_lines,
1100 first_body_line,
1101 lines,
1102 }
1103}
1104
1105#[derive(Debug, Clone, PartialEq, Eq, Default)]
1107pub struct RestoreHunksOutcome {
1108 pub dry_run: bool,
1110 pub restored: Vec<String>,
1112 pub restored_hunks: BTreeMap<String, Vec<HunkId>>,
1114 pub restored_lines: BTreeMap<String, Vec<String>>,
1116 pub removed: Vec<String>,
1118}
1119
1120pub(crate) fn restore_hunks(
1133 repo: &Repository,
1134 selection: &HunkSelection,
1135 pathspecs: &[String],
1136 restore_staged: bool,
1137 restore_worktree: bool,
1138 dry_run: bool,
1139) -> crate::error::Result<RestoreHunksOutcome> {
1140 let diff_opts = diff_options_for_hunk_select(repo)?;
1141 let restore_worktree = restore_worktree || !restore_staged;
1142 let mut outcome = RestoreHunksOutcome {
1143 dry_run,
1144 ..RestoreHunksOutcome::default()
1145 };
1146 if restore_staged {
1147 let side = DiffSide::Staged;
1148 let resolved =
1149 resolve_selection_with_staged(repo, side, selection, pathspecs, diff_opts.clone())?;
1150 let apply = apply_patch_to_index_and_write(
1151 repo,
1152 &resolved.patches,
1153 &IndexApplyOptions {
1154 dry_run,
1155 reverse: true,
1156 head_tree_oid: repo.head_tree()?,
1157 },
1158 &crate::progress::CancelToken::never(),
1159 )?;
1160 outcome
1161 .restored
1162 .extend(apply.added.into_iter().chain(apply.modified));
1163 outcome.restored.sort();
1164 outcome.restored.dedup();
1165 outcome.restored_hunks = resolved.selected_hunks;
1166 outcome.restored_lines = resolved.selected_lines;
1167 }
1168 if restore_worktree {
1169 let handle = repo.index();
1172 let lock = if dry_run {
1173 None
1174 } else {
1175 Some(handle.begin_update()?)
1176 };
1177 let mut index = handle.load(&crate::index::IndexLoadOptions::default())?;
1178 let resolved = resolve_selection_in(
1179 repo,
1180 Some(&mut index),
1181 DiffSide::Unstaged,
1182 selection,
1183 pathspecs,
1184 diff_opts,
1185 )?;
1186 let rules = WorktreeRules::from_repository(repo, &index)?;
1187 let planned = plan_worktree_reverse(
1188 repo,
1189 &index,
1190 &rules,
1191 &resolved.patches,
1192 &resolved.whole_files,
1193 )?;
1194 match lock {
1195 Some(lock) => {
1196 commit_worktree_reverse(repo, lock, index, &rules, &planned, &mut outcome)?
1197 }
1198 None => {
1199 for plan in &planned {
1200 push_restored_path(&mut outcome.restored, &plan.path);
1201 }
1202 }
1203 }
1204 merge_restored_maps(&mut outcome.restored_hunks, resolved.selected_hunks);
1205 merge_restored_line_maps(&mut outcome.restored_lines, resolved.selected_lines);
1206 }
1207 Ok(outcome)
1208}
1209
1210fn merge_restored_maps(
1211 into: &mut BTreeMap<String, Vec<HunkId>>,
1212 other: BTreeMap<String, Vec<HunkId>>,
1213) {
1214 for (path, ids) in other {
1215 into.entry(path).or_default().extend(ids);
1216 }
1217}
1218
1219fn merge_restored_line_maps(
1220 into: &mut BTreeMap<String, Vec<String>>,
1221 other: BTreeMap<String, Vec<String>>,
1222) {
1223 for (path, ranges) in other {
1224 into.entry(path).or_default().extend(ranges);
1225 }
1226}
1227
1228fn push_restored_path(restored: &mut Vec<String>, path: &str) {
1229 if !restored.iter().any(|p| p == path) {
1230 restored.push(path.to_string());
1231 }
1232}
1233
1234struct WorktreeReversePlan {
1235 path: String,
1236 clean_bytes: Vec<u8>,
1237 mode: u32,
1238 may_match_index: bool,
1242}
1243
1244fn plan_worktree_reverse(
1249 repo: &Repository,
1250 index: &Index,
1251 rules: &WorktreeRules,
1252 patches: &[FilePatch],
1253 whole_files: &BTreeSet<String>,
1254) -> crate::error::Result<Vec<WorktreeReversePlan>> {
1255 let work_tree = repo
1256 .work_tree()
1257 .ok_or_else(|| Error::from(RepositoryError::RequiresWorkTree))?;
1258 let config = repo.config().snapshot()?;
1259 let mut out = Vec::with_capacity(patches.len());
1260 for patch in patches {
1261 let path = patch
1262 .effective_path()
1263 .ok_or(HunkSelectError::MissingPath)?
1264 .to_string();
1265 if patch.involves_gitlink() {
1266 return Err(HunkSelectError::Gitlink { path }.into());
1267 }
1268 let entry = index.get(path.as_bytes(), 0);
1269 let mode = entry.map(|e| e.mode).unwrap_or(MODE_REGULAR);
1270 if mode != MODE_REGULAR && mode != MODE_EXECUTABLE {
1271 return Err(HunkSelectError::Binary { path: path.clone() }.into());
1272 }
1273 let abs = crate::repo_relpath::worktree_abs(work_tree, &path);
1274 let clean = if patch.is_deleted || !abs.exists() {
1275 Vec::new()
1276 } else {
1277 read_worktree_side_bytes_for_diff(
1278 repo.odb(),
1279 work_tree,
1280 &path,
1281 mode,
1282 config.as_ref(),
1283 entry,
1284 Some(rules),
1285 )?
1286 };
1287 let new_clean = apply_hunks_to_blob(&clean, &patch.hunks, &ApplyOptions { reverse: true })
1288 .map_err(HunkSelectError::Apply)?;
1289 let may_match_index = whole_files.contains(&path);
1290 out.push(WorktreeReversePlan {
1291 path,
1292 clean_bytes: new_clean,
1293 mode,
1294 may_match_index,
1295 });
1296 }
1297 Ok(out)
1298}
1299
1300fn commit_worktree_reverse(
1306 repo: &Repository,
1307 mut lock: IndexLock,
1308 mut index: Index,
1309 rules: &WorktreeRules,
1310 planned: &[WorktreeReversePlan],
1311 outcome: &mut RestoreHunksOutcome,
1312) -> crate::error::Result<()> {
1313 let work_tree = repo
1314 .work_tree()
1315 .ok_or_else(|| Error::from(RepositoryError::RequiresWorkTree))?;
1316 let config = repo.config().snapshot()?;
1317 let mut dir_cache = LeadingDirCache::for_config(config.as_ref());
1318 let has_symlinks = dir_cache.has_symlinks();
1319 for plan in planned {
1320 let attrs = rules.file_attrs(&plan.path, false);
1321 let smudged;
1322 let worktree_bytes = if worktree_conversion_is_identity(rules.conversion(), &attrs) {
1323 plan.clean_bytes.as_slice()
1324 } else {
1325 let oid = repo
1328 .odb()
1329 .hash_algo()
1330 .hash_object(ObjectKind::Blob, &plan.clean_bytes)?;
1331 smudged = smudge_bytes_for_worktree_path(
1332 repo,
1333 rules,
1334 &plan.path,
1335 plan.mode,
1336 &plan.clean_bytes,
1337 &oid,
1338 )?;
1339 smudged.as_slice()
1340 };
1341 write_to_worktree_cached(
1342 work_tree,
1343 &plan.path,
1344 worktree_bytes,
1345 plan.mode,
1346 &mut dir_cache,
1347 has_symlinks,
1348 )?;
1349 push_restored_path(&mut outcome.restored, &plan.path);
1350 }
1351 let still_different: BTreeSet<&str> = planned
1352 .iter()
1353 .filter(|plan| !plan.may_match_index)
1354 .map(|plan| plan.path.as_str())
1355 .collect();
1356 let touched: BTreeSet<&str> = outcome
1357 .restored
1358 .iter()
1359 .map(String::as_str)
1360 .filter(|path| !still_different.contains(path))
1361 .collect();
1362 if refresh_stage0_index_stats_for_paths(repo, work_tree, &mut index, &touched)? {
1363 repo.index().commit_update(&mut lock, &mut index, false)?;
1364 }
1365 Ok(())
1366}
1367
1368#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1370pub struct WorktreeReverseApplyOptions {
1371 pub dry_run: bool,
1373}
1374
1375pub(crate) fn reverse_apply_patches_to_worktree(
1387 repo: &Repository,
1388 patches: &[FilePatch],
1389 opts: &WorktreeReverseApplyOptions,
1390 progress: &mut dyn ProgressSink,
1391 cancel: &CancelToken,
1392) -> std::result::Result<(), ApplyError> {
1393 let work_tree = repo.work_tree().ok_or_else(|| ApplyError::Failed {
1394 path: String::new(),
1395 message: "worktree reverse apply requires a working tree".into(),
1396 })?;
1397 let index = repo.load_index().map_err(|e| ApplyError::Failed {
1398 path: String::new(),
1399 message: e.to_string(),
1400 })?;
1401 let config = repo.config().snapshot().map_err(|e| ApplyError::Failed {
1402 path: String::new(),
1403 message: e.to_string(),
1404 })?;
1405 let rules = WorktreeRules::from_repository(repo, &index).map_err(|e| ApplyError::Failed {
1406 path: String::new(),
1407 message: e.to_string(),
1408 })?;
1409 progress.start(ProgressPhase::CheckingOutFiles, Some(patches.len() as u64));
1410 for patch in patches {
1411 poll_cancel(progress, cancel).map_err(|_| ApplyError::Cancelled)?;
1412 progress.inc(1);
1413 if patch.involves_gitlink() {
1414 let path = patch.effective_path().unwrap_or("<unknown>").to_string();
1415 return Err(ApplyError::Failed {
1416 path,
1417 message: "submodule/gitlink patches are not supported".into(),
1418 });
1419 }
1420 let path = patch
1421 .target_path()
1422 .map(str::to_string)
1423 .or_else(|| patch.effective_path().map(str::to_string))
1424 .ok_or_else(|| ApplyError::Failed {
1425 path: String::new(),
1426 message: "patch has no target path".into(),
1427 })?;
1428
1429 if patch.is_deleted {
1430 let Some(entry) = index.get(path.as_bytes(), 0) else {
1431 return Err(ApplyError::NotInIndex { path: path.clone() });
1432 };
1433 if entry.mode == MODE_GITLINK {
1434 continue;
1435 }
1436 if !opts.dry_run {
1437 write_smudged_blob_to_worktree(
1438 repo, work_tree, &rules, &path, &entry.oid, entry.mode,
1439 )
1440 .map_err(|e| ApplyError::Failed {
1441 path: path.clone(),
1442 message: e.to_string(),
1443 })?;
1444 }
1445 continue;
1446 }
1447
1448 if patch.is_new {
1449 if !opts.dry_run {
1450 let abs = crate::repo_relpath::worktree_abs(work_tree, &path);
1451 if let Ok(meta) = fs::symlink_metadata(&abs) {
1452 if meta.is_dir() {
1453 let _ = fs::remove_dir_all(&abs);
1454 } else {
1455 fs::remove_file(&abs).map_err(|e| ApplyError::Failed {
1456 path: path.clone(),
1457 message: e.to_string(),
1458 })?;
1459 }
1460 remove_empty_parent_dirs(work_tree, &abs);
1461 }
1462 }
1463 continue;
1464 }
1465
1466 let mode = index
1467 .get(path.as_bytes(), 0)
1468 .map(|e| e.mode)
1469 .unwrap_or(MODE_REGULAR);
1470 if mode == MODE_GITLINK {
1471 continue;
1472 }
1473 let index_entry = index.get(path.as_bytes(), 0);
1474 let base = read_worktree_side_bytes_for_diff(
1475 repo.odb(),
1476 work_tree,
1477 &path,
1478 mode,
1479 config.as_ref(),
1480 index_entry,
1481 Some(&rules),
1482 )
1483 .map_err(|e| ApplyError::Failed {
1484 path: path.clone(),
1485 message: e.to_string(),
1486 })?;
1487 let new_clean = apply_hunks_to_blob(&base, &patch.hunks, &ApplyOptions { reverse: true })?;
1488 if opts.dry_run {
1489 continue;
1490 }
1491 let oid = repo
1492 .odb()
1493 .write(ObjectKind::Blob, &new_clean)
1494 .map_err(|e| ApplyError::Failed {
1495 path: path.clone(),
1496 message: e.to_string(),
1497 })?;
1498 write_smudged_blob_to_worktree(repo, work_tree, &rules, &path, &oid, mode).map_err(
1499 |e| ApplyError::Failed {
1500 path: path.clone(),
1501 message: e.to_string(),
1502 },
1503 )?;
1504 }
1505 progress.finish();
1506 Ok(())
1507}
1508
1509pub(crate) fn diff_options_for_hunk_select(
1515 repo: &Repository,
1516) -> std::result::Result<DiffOptions, Error> {
1517 let config = repo.config().snapshot()?;
1518 Ok(DiffOptions::from_config(config.as_ref()))
1519}
1520
1521pub(crate) fn stage_hunks(
1530 repo: &Repository,
1531 side: DiffSide,
1532 selection: &HunkSelection,
1533 pathspecs: &[String],
1534 diff_options: DiffOptions,
1535 dry_run: bool,
1536 cancel: &crate::progress::CancelToken,
1537) -> crate::error::Result<StageHunksOutcome> {
1538 let handle = repo.index();
1541 let mut lock = if dry_run {
1542 None
1543 } else {
1544 Some(handle.begin_update()?)
1545 };
1546 crate::progress::poll_cancel(&mut crate::progress::NullProgress, cancel)?;
1547 let resolved = resolve_selection_in(repo, None, side, selection, pathspecs, diff_options)?;
1548 crate::progress::poll_cancel(&mut crate::progress::NullProgress, cancel)?;
1549 let mut index = handle.load(&crate::index::IndexLoadOptions::default())?;
1550 let apply = apply_patch_to_index(
1551 repo,
1552 &mut index,
1553 &resolved.patches,
1554 &IndexApplyOptions {
1555 dry_run,
1556 ..IndexApplyOptions::default()
1557 },
1558 )?;
1559 crate::progress::poll_cancel(&mut crate::progress::NullProgress, cancel)?;
1560 if let Some(lock) = lock.as_mut() {
1561 crate::progress::poll_cancel(&mut crate::progress::NullProgress, cancel)?;
1562 handle.commit_update(lock, &mut index, false)?;
1563 }
1564 Ok(StageHunksOutcome::from_apply(
1565 dry_run,
1566 resolved.selected_hunks,
1567 resolved.selected_lines,
1568 apply,
1569 ))
1570}
1571
1572fn map_parse_err(_err: Error) -> HunkSelectError {
1573 HunkSelectError::PatchBuild
1574}
1575
1576pub(crate) fn list_unstaged_hunk_ids(
1582 repo: &Repository,
1583 pathspecs: &[String],
1584 diff_options: DiffOptions,
1585) -> std::result::Result<BTreeMap<String, Vec<HunkId>>, Error> {
1586 let (changes, peer_hunks) =
1587 unstaged_raw_changes_with_peer_hunks(repo, pathspecs, diff_options.clone())?;
1588 let mut out = BTreeMap::new();
1589 for change in &changes {
1590 if change.binary {
1591 continue;
1592 }
1593 let peer = peer_hunks
1594 .get(&change.path)
1595 .map(|h| h.as_slice())
1596 .unwrap_or(&[]);
1597 let old_text = side_text(&change.old_bytes);
1598 let new_text = side_text(&change.new_bytes);
1599 let body =
1600 unified_hunk_body_for_diff_options(old_text.as_ref(), new_text.as_ref(), &diff_options);
1601 let slices = imara_unified_hunk_slices(&body);
1602 let ids = crate::diff::hunk_id::hunk_ids_for_unified_slices(
1603 DiffSide::Unstaged,
1604 &change.path,
1605 &slices,
1606 line_count(old_text.as_ref()),
1607 line_count(new_text.as_ref()),
1608 old_text.as_ref().ends_with('\n'),
1609 new_text.as_ref().ends_with('\n'),
1610 peer,
1611 );
1612 out.insert(change.path.clone(), ids);
1613 }
1614 Ok(out)
1615}
1616
1617#[cfg(test)]
1618mod tests {
1619 use super::*;
1620 use crate::diff::hunk_ids;
1621 use crate::diff::targets::hunk_diff_bundle;
1622 use crate::error::RefError;
1623 use crate::index::write_tree::write_tree_from_index;
1624 use crate::porcelain::add::{stage, StageOptions};
1625 use crate::progress::NullProgress;
1626 use crate::repo::{InitOptions, Repository};
1627 use std::process::Command;
1628
1629 fn git(dir: &std::path::Path, args: &[&str]) {
1630 let out = Command::new("git")
1631 .current_dir(dir)
1632 .args(args)
1633 .env("GIT_CONFIG_GLOBAL", "/dev/null")
1634 .env("GIT_CONFIG_SYSTEM", "/dev/null")
1635 .output()
1636 .expect("git");
1637 assert!(
1638 out.status.success(),
1639 "git {args:?}: {}",
1640 String::from_utf8_lossy(&out.stderr)
1641 );
1642 }
1643
1644 fn hunk_diff_opts() -> DiffOptions {
1645 DiffOptions::default()
1646 }
1647
1648 fn init_repo() -> (tempfile::TempDir, Repository) {
1649 let dir = tempfile::tempdir().expect("tempdir");
1650 git(dir.path(), &["init", "-q", "-b", "main"]);
1651 let (repo, _) = Repository::init(dir.path(), &InitOptions::default()).expect("init");
1652 (dir, repo)
1653 }
1654
1655 fn spaced_two_hunk_body() -> (String, String) {
1656 three_hunk_body()
1657 }
1658
1659 fn three_hunk_body() -> (String, String) {
1660 let mut base = String::new();
1661 for i in 0..30 {
1662 base.push_str(&format!("line{i}\n"));
1663 }
1664 let mut edited = base.clone();
1665 edited = edited.replacen("line5\n", "LINE5\n", 1);
1666 edited = edited.replacen("line13\n", "LINE13\n", 1);
1667 edited = edited.replacen("line21\n", "LINE21\n", 1);
1668 (base, edited)
1669 }
1670
1671 #[cfg_attr(
1672 not(feature = "full-tests"),
1673 ignore = "starts system git or is heavy; run with --features full-tests"
1674 )]
1675 #[test]
1676 fn stage_hunks_subset_matches_git_apply_cached() {
1677 let (dir, repo) = init_repo();
1678 let root = dir.path();
1679 let (base, edited) = spaced_two_hunk_body();
1680 std::fs::write(root.join("f.txt"), base).unwrap();
1681 git(root, &["add", "f.txt"]);
1682 git(root, &["commit", "-qm", "init"]);
1683
1684 std::fs::write(root.join("f.txt"), edited).unwrap();
1685 let (files, peers) =
1686 unstaged_file_diffs_with_peer_hunks(&repo, &[], DiffOptions::default()).unwrap();
1687 assert_eq!(files.len(), 1);
1688 let ids = hunk_ids(
1689 DiffSide::Unstaged,
1690 "f.txt",
1691 &files[0].hunks,
1692 peers.get("f.txt").map(|v| v.as_slice()).unwrap_or(&[]),
1693 );
1694 assert!(ids.len() >= 2);
1695 let selection = HunkSelection {
1696 ids: vec![ids[0].clone()],
1697 ranges: Vec::new(),
1698 };
1699
1700 let patch = resolve_selection(&repo, DiffSide::Unstaged, &selection, &[], hunk_diff_opts())
1701 .unwrap();
1702 let mut patch_text = String::new();
1703 for p in &patch {
1704 patch_text.push_str(&format_patch_for_git(p));
1705 }
1706
1707 stage_hunks(
1708 &repo,
1709 DiffSide::Unstaged,
1710 &selection,
1711 &[],
1712 hunk_diff_opts(),
1713 false,
1714 &crate::progress::CancelToken::never(),
1715 )
1716 .unwrap();
1717 let grit_tree = write_tree_from_index(repo.odb(), &repo.load_index().unwrap(), "").unwrap();
1718
1719 git(root, &["read-tree", "HEAD"]);
1720 let patch_path = root.join("partial.diff");
1721 std::fs::write(&patch_path, patch_text).unwrap();
1722 git(root, &["apply", "--cached", patch_path.to_str().unwrap()]);
1723 let git_tree = Command::new("git")
1724 .current_dir(root)
1725 .args(["write-tree"])
1726 .output()
1727 .expect("write-tree");
1728 let git_tree_hex = String::from_utf8_lossy(&git_tree.stdout).trim().to_string();
1729 assert_eq!(grit_tree.to_hex(), git_tree_hex);
1730 git(root, &["fsck"]);
1731 }
1732
1733 fn write_hunk_line(out: &mut String, prefix: char, text: &str) {
1734 out.push(prefix);
1735 if text.ends_with('\n') {
1736 out.push_str(text);
1737 } else {
1738 out.push_str(text);
1739 out.push('\n');
1740 }
1741 }
1742
1743 fn format_patch_for_git(patch: &FilePatch) -> String {
1744 let mut out = String::new();
1745 let path = patch.effective_path().unwrap_or("f");
1746 out.push_str(&format!("diff --git a/{path} b/{path}\n"));
1747 if patch.is_new {
1748 out.push_str("new file mode 100644\n");
1749 }
1750 let old = if patch.is_new {
1751 "/dev/null".to_string()
1752 } else {
1753 format!("a/{}", patch.old_path.as_deref().unwrap_or(path))
1754 };
1755 let new = if patch.is_deleted {
1756 "/dev/null".to_string()
1757 } else {
1758 format!("b/{}", patch.new_path.as_deref().unwrap_or(path))
1759 };
1760 out.push_str(&format!("--- {old}\n"));
1761 out.push_str(&format!("+++ {new}\n"));
1762 for h in &patch.hunks {
1763 out.push_str(&format!(
1764 "@@ -{},{} +{},{} @@\n",
1765 h.old_start, h.old_count, h.new_start, h.new_count
1766 ));
1767 for line in &h.lines {
1768 match line {
1769 HunkLine::Context(s) => write_hunk_line(&mut out, ' ', s),
1770 HunkLine::Add(s) => write_hunk_line(&mut out, '+', s),
1771 HunkLine::Remove(s) => write_hunk_line(&mut out, '-', s),
1772 HunkLine::NoNewline => out.push_str("\\ No newline at end of file\n"),
1773 }
1774 }
1775 }
1776 out
1777 }
1778
1779 #[cfg_attr(
1780 not(feature = "full-tests"),
1781 ignore = "starts system git or is heavy; run with --features full-tests"
1782 )]
1783 #[test]
1784 fn stage_hunks_sequential_ids_stay_valid() {
1785 let (dir, repo) = init_repo();
1786 let root = dir.path();
1787 let (base, edited) = spaced_two_hunk_body();
1788 std::fs::write(root.join("f.txt"), base).unwrap();
1789 git(root, &["add", "f.txt"]);
1790 git(root, &["commit", "-qm", "init"]);
1791 std::fs::write(root.join("f.txt"), edited).unwrap();
1792
1793 let (files, peers) =
1794 unstaged_file_diffs_with_peer_hunks(&repo, &[], DiffOptions::default()).unwrap();
1795 let ids = hunk_ids(
1796 DiffSide::Unstaged,
1797 "f.txt",
1798 &files[0].hunks,
1799 peers.get("f.txt").map(|v| v.as_slice()).unwrap_or(&[]),
1800 );
1801 assert_eq!(ids.len(), 3, "expected three hunks, got {}", ids.len());
1802 let id0 = ids[0].clone();
1803 let id2 = ids[2].clone();
1804 stage_hunks(
1805 &repo,
1806 DiffSide::Unstaged,
1807 &HunkSelection {
1808 ids: vec![id0],
1809 ranges: Vec::new(),
1810 },
1811 &[],
1812 hunk_diff_opts(),
1813 false,
1814 &crate::progress::CancelToken::never(),
1815 )
1816 .unwrap();
1817 stage_hunks(
1818 &repo,
1819 DiffSide::Unstaged,
1820 &HunkSelection {
1821 ids: vec![id2],
1822 ranges: Vec::new(),
1823 },
1824 &[],
1825 hunk_diff_opts(),
1826 false,
1827 &crate::progress::CancelToken::never(),
1828 )
1829 .unwrap();
1830 git(root, &["fsck"]);
1831 }
1832
1833 #[cfg_attr(
1834 not(feature = "full-tests"),
1835 ignore = "starts system git or is heavy; run with --features full-tests"
1836 )]
1837 #[test]
1838 fn stage_hunks_inter_hunk_context_matches_diff_ids() {
1839 let (dir, repo) = init_repo();
1840 let root = dir.path();
1841 git(root, &["config", "diff.interHunkContext", "1"]);
1842 let (base, _edited) = three_hunk_body();
1843 let mut edited_two = base.clone();
1844 edited_two = edited_two.replacen("line5\n", "LINE5\n", 1);
1845 edited_two = edited_two.replacen("line13\n", "LINE13\n", 1);
1846 std::fs::write(root.join("f.txt"), base).unwrap();
1847 git(root, &["add", "f.txt"]);
1848 git(root, &["commit", "-qm", "init"]);
1849 std::fs::write(root.join("f.txt"), edited_two).unwrap();
1850
1851 let opts = DiffOptions::from_config(repo.config().snapshot().unwrap().as_ref());
1852 let (files, peers) = unstaged_file_diffs_with_peer_hunks(&repo, &[], opts.clone()).unwrap();
1853 let ids = hunk_ids(
1854 DiffSide::Unstaged,
1855 "f.txt",
1856 &files[0].hunks,
1857 peers.get("f.txt").map(|v| v.as_slice()).unwrap_or(&[]),
1858 );
1859 assert_eq!(
1860 ids.len(),
1861 1,
1862 "interHunkContext=1 should merge edits at lines 5 and 13"
1863 );
1864 stage_hunks(
1865 &repo,
1866 DiffSide::Unstaged,
1867 &HunkSelection {
1868 ids: vec![ids[0].clone()],
1869 ranges: Vec::new(),
1870 },
1871 &[],
1872 opts,
1873 false,
1874 &crate::progress::CancelToken::never(),
1875 )
1876 .unwrap();
1877 git(root, &["fsck"]);
1878 }
1879
1880 #[cfg_attr(
1881 not(feature = "full-tests"),
1882 ignore = "starts system git or is heavy; run with --features full-tests"
1883 )]
1884 #[test]
1885 fn stage_hunks_text_to_binary_returns_binary_error() {
1886 let (dir, repo) = init_repo();
1887 let root = dir.path();
1888 let (base, edited) = spaced_two_hunk_body();
1889 std::fs::write(root.join("f.txt"), base).unwrap();
1890 git(root, &["add", "f.txt"]);
1891 git(root, &["commit", "-qm", "init"]);
1892 std::fs::write(root.join("f.txt"), edited).unwrap();
1893 let (files, peers) =
1894 unstaged_file_diffs_with_peer_hunks(&repo, &[], DiffOptions::default()).unwrap();
1895 let ids = hunk_ids(
1896 DiffSide::Unstaged,
1897 "f.txt",
1898 &files[0].hunks,
1899 peers.get("f.txt").map(|v| v.as_slice()).unwrap_or(&[]),
1900 );
1901 let id = ids[0].clone();
1902 let binary = b"before\0after".to_vec();
1903 std::fs::write(root.join("f.txt"), &binary).unwrap();
1904 let err = stage_hunks(
1905 &repo,
1906 DiffSide::Unstaged,
1907 &HunkSelection {
1908 ids: vec![id],
1909 ranges: Vec::new(),
1910 },
1911 &["f.txt".into()],
1912 hunk_diff_opts(),
1913 false,
1914 &crate::progress::CancelToken::never(),
1915 )
1916 .unwrap_err();
1917 assert!(
1918 matches!(
1919 err,
1920 crate::error::Error::Diff(crate::error::DiffError::HunkSelection(
1921 HunkSelectError::Binary { .. }
1922 ))
1923 ),
1924 "expected Binary, got {err:?}"
1925 );
1926 }
1927
1928 #[cfg_attr(
1929 not(feature = "full-tests"),
1930 ignore = "starts system git or is heavy; run with --features full-tests"
1931 )]
1932 #[test]
1933 fn stage_hunks_stale_id_rejected_index_untouched() {
1934 let (dir, repo) = init_repo();
1935 let root = dir.path();
1936 std::fs::write(root.join("f.txt"), b"one\n").unwrap();
1937 git(root, &["add", "f.txt"]);
1938 git(root, &["commit", "-qm", "init"]);
1939 std::fs::write(root.join("f.txt"), b"two\n").unwrap();
1940 let before = repo.load_index().unwrap();
1941 let stale = HunkId::from_str("000000000001").unwrap();
1942 let err = stage_hunks(
1943 &repo,
1944 DiffSide::Unstaged,
1945 &HunkSelection {
1946 ids: vec![stale.clone()],
1947 ranges: Vec::new(),
1948 },
1949 &[],
1950 hunk_diff_opts(),
1951 false,
1952 &crate::progress::CancelToken::never(),
1953 )
1954 .unwrap_err();
1955 assert!(matches!(
1956 err,
1957 crate::error::Error::Diff(crate::error::DiffError::HunkSelection(
1958 HunkSelectError::StaleId { .. }
1959 ))
1960 ));
1961 let after = repo.load_index().unwrap();
1962 assert_eq!(before.entries.len(), after.entries.len());
1963 }
1964
1965 #[cfg_attr(
1966 not(feature = "full-tests"),
1967 ignore = "starts system git or is heavy; run with --features full-tests"
1968 )]
1969 #[test]
1970 fn stage_hunks_staged_side_id_rejected() {
1971 let (dir, repo) = init_repo();
1972 let root = dir.path();
1973 std::fs::write(root.join("f.txt"), b"one\n").unwrap();
1974 git(root, &["add", "f.txt"]);
1975 git(root, &["commit", "-qm", "init"]);
1976 std::fs::write(root.join("f.txt"), b"two\n").unwrap();
1977 stage(
1978 &repo,
1979 &StageOptions::default(),
1980 &mut NullProgress,
1981 &crate::progress::CancelToken::never(),
1982 )
1983 .unwrap();
1984 let staged_files =
1985 collect_files_for_target(&repo, &DiffTarget::IndexVsHead, &[], DiffOptions::default())
1986 .unwrap();
1987 let staged_id = hunk_ids(DiffSide::Staged, "f.txt", &staged_files[0].hunks, &[])[0].clone();
1988 std::fs::write(root.join("f.txt"), b"three\n").unwrap();
1989 let err = stage_hunks(
1990 &repo,
1991 DiffSide::Unstaged,
1992 &HunkSelection {
1993 ids: vec![staged_id],
1994 ranges: Vec::new(),
1995 },
1996 &[],
1997 hunk_diff_opts(),
1998 false,
1999 &crate::progress::CancelToken::never(),
2000 )
2001 .unwrap_err();
2002 assert!(matches!(
2003 err,
2004 crate::error::Error::Diff(crate::error::DiffError::HunkSelection(
2005 HunkSelectError::WrongSide {
2006 actual_side: DiffSide::Staged,
2007 requested_side: DiffSide::Unstaged,
2008 ..
2009 }
2010 ))
2011 ));
2012 }
2013
2014 #[test]
2015 fn wrong_side_message_names_both_sides() {
2016 let err = HunkSelectError::WrongSide {
2017 id: HunkId::from_bytes([0xab; 6]),
2018 actual_side: DiffSide::Staged,
2019 requested_side: DiffSide::Unstaged,
2020 };
2021 assert_eq!(
2022 err.to_string(),
2023 "hunk id abababababab is for the staged side, not unstaged"
2024 );
2025 }
2026
2027 #[test]
2028 fn repository_error_keeps_typed_source() {
2029 let err = Error::Ref(RefError::InvalidHead);
2030 assert_eq!(
2031 err.to_string(),
2032 Error::Ref(RefError::InvalidHead).to_string()
2033 );
2034 assert!(matches!(err, Error::Ref(RefError::InvalidHead)));
2035 }
2036
2037 #[test]
2038 fn other_side_is_unselectable() {
2039 let dir = tempfile::tempdir().unwrap();
2040 let (repo, _) = Repository::init(dir.path(), &InitOptions::default()).unwrap();
2041 let by_id = HunkSelection {
2042 ids: vec![HunkId::from_bytes([1; 6])],
2043 ranges: Vec::new(),
2044 };
2045 let by_range = HunkSelection {
2046 ids: Vec::new(),
2047 ranges: vec![LineRange {
2048 path: "f.txt".into(),
2049 start: 1,
2050 end: 1,
2051 }],
2052 };
2053 for selection in [by_id, by_range] {
2054 let err = resolve_selection(&repo, DiffSide::Other, &selection, &[], hunk_diff_opts())
2055 .unwrap_err();
2056 assert!(
2057 matches!(
2058 err,
2059 crate::error::Error::Diff(crate::error::DiffError::HunkSelection(
2060 HunkSelectError::UnselectableSide {
2061 side: DiffSide::Other
2062 }
2063 ))
2064 ),
2065 "{err:?}"
2066 );
2067 }
2068 }
2069
2070 fn one_line_patch(path: &str) -> FilePatch {
2071 let text = format!(
2072 "diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -1 +1 @@\n-old\n+new\n"
2073 );
2074 parse_patch(&text, 1, path, false, None)
2075 .unwrap()
2076 .pop()
2077 .unwrap()
2078 }
2079
2080 fn plan_without_selection(
2081 repo: &Repository,
2082 patches: &[FilePatch],
2083 ) -> crate::error::Result<Vec<WorktreeReversePlan>> {
2084 let index = Index::new();
2085 let rules = WorktreeRules::from_repository(repo, &index)?;
2086 plan_worktree_reverse(repo, &index, &rules, patches, &BTreeSet::new())
2087 }
2088
2089 #[test]
2090 fn restore_plan_requires_work_tree() {
2091 let dir = tempfile::tempdir().unwrap();
2092 let (repo, _) = Repository::init(
2093 dir.path(),
2094 &InitOptions {
2095 bare: true,
2096 ..InitOptions::default()
2097 },
2098 )
2099 .unwrap();
2100 let err = plan_without_selection(&repo, &[one_line_patch("f.txt")])
2101 .err()
2102 .unwrap();
2103 match err {
2104 Error::Repository(RepositoryError::RequiresWorkTree) => {}
2105 other => panic!("expected Repository(RequiresWorkTree), got {other:?}"),
2106 }
2107 }
2108
2109 #[test]
2110 fn restore_plan_rejects_gitlink_and_pathless_patches() {
2111 let dir = tempfile::tempdir().unwrap();
2112 let (repo, _) = Repository::init(dir.path(), &InitOptions::default()).unwrap();
2113
2114 let mut gitlink = one_line_patch("sub");
2115 gitlink.new_mode = Some("160000".into());
2116 let err = plan_without_selection(&repo, &[gitlink]).err().unwrap();
2117 assert!(
2118 matches!(&err, crate::error::Error::Diff(crate::error::DiffError::HunkSelection(HunkSelectError::Gitlink { path })) if path == "sub"),
2119 "{err:?}"
2120 );
2121
2122 let mut pathless = one_line_patch("f.txt");
2123 pathless.old_path = None;
2124 pathless.new_path = None;
2125 let err = plan_without_selection(&repo, &[pathless]).err().unwrap();
2126 assert!(
2127 matches!(
2128 err,
2129 crate::error::Error::Diff(crate::error::DiffError::HunkSelection(
2130 HunkSelectError::MissingPath
2131 ))
2132 ),
2133 "{err:?}"
2134 );
2135 }
2136
2137 #[cfg_attr(
2138 not(feature = "full-tests"),
2139 ignore = "starts system git or is heavy; run with --features full-tests"
2140 )]
2141 #[test]
2142 fn stage_hunks_new_file_whole() {
2143 let (dir, repo) = init_repo();
2144 let root = dir.path();
2145 std::fs::write(root.join("base.txt"), b"keep\n").unwrap();
2146 git(root, &["add", "base.txt"]);
2147 git(root, &["commit", "-qm", "init"]);
2148 std::fs::write(root.join("new.txt"), b"hello\n").unwrap();
2149 stage(
2150 &repo,
2151 &StageOptions {
2152 pathspecs: vec!["new.txt".into()],
2153 intent_to_add: true,
2154 ..StageOptions::default()
2155 },
2156 &mut NullProgress,
2157 &crate::progress::CancelToken::never(),
2158 )
2159 .unwrap();
2160 let (files, peers) =
2161 unstaged_file_diffs_with_peer_hunks(&repo, &[], DiffOptions::default()).unwrap();
2162 let new_file = files
2163 .iter()
2164 .find(|f| f.path == "new.txt")
2165 .expect("new file in unstaged diff");
2166 assert!(
2167 !new_file.hunks.is_empty(),
2168 "new file should have structured hunks"
2169 );
2170 let ids = hunk_ids(
2171 DiffSide::Unstaged,
2172 "new.txt",
2173 &new_file.hunks,
2174 peers.get("new.txt").map(|v| v.as_slice()).unwrap_or(&[]),
2175 );
2176 stage_hunks(
2177 &repo,
2178 DiffSide::Unstaged,
2179 &HunkSelection {
2180 ids: ids.clone(),
2181 ranges: Vec::new(),
2182 },
2183 &[],
2184 hunk_diff_opts(),
2185 false,
2186 &crate::progress::CancelToken::never(),
2187 )
2188 .unwrap();
2189 assert!(repo.load_index().unwrap().get(b"new.txt", 0).is_some());
2190 git(root, &["fsck"]);
2191 }
2192
2193 fn stage_lines_and_compare_git(
2194 repo: &Repository,
2195 root: &std::path::Path,
2196 path: &str,
2197 ranges: Vec<LineRange>,
2198 ) {
2199 let selection = HunkSelection {
2200 ids: Vec::new(),
2201 ranges,
2202 };
2203 let patch = resolve_selection(
2204 &repo,
2205 DiffSide::Unstaged,
2206 &selection,
2207 &[path.into()],
2208 hunk_diff_opts(),
2209 )
2210 .unwrap();
2211 let mut patch_text = String::new();
2212 for p in &patch {
2213 patch_text.push_str(&format_patch_for_git(p));
2214 }
2215 let index_path = root.join(".git/index");
2216 let index_before = std::fs::read(&index_path).unwrap();
2217 stage_hunks(
2218 &repo,
2219 DiffSide::Unstaged,
2220 &selection,
2221 &[path.into()],
2222 hunk_diff_opts(),
2223 false,
2224 &crate::progress::CancelToken::never(),
2225 )
2226 .unwrap();
2227 let grit_tree = write_tree_from_index(repo.odb(), &repo.load_index().unwrap(), "").unwrap();
2228 std::fs::write(&index_path, index_before).unwrap();
2229 let patch_path = root.join("partial.diff");
2230 std::fs::write(&patch_path, patch_text).unwrap();
2231 git(root, &["apply", "--cached", patch_path.to_str().unwrap()]);
2232 let git_tree = Command::new("git")
2233 .current_dir(root)
2234 .args(["write-tree"])
2235 .output()
2236 .expect("write-tree");
2237 let git_tree_hex = String::from_utf8_lossy(&git_tree.stdout).trim().to_string();
2238 assert_eq!(grit_tree.to_hex(), git_tree_hex);
2239 git(root, &["fsck"]);
2240 }
2241
2242 #[cfg_attr(
2243 not(feature = "full-tests"),
2244 ignore = "starts system git or is heavy; run with --features full-tests"
2245 )]
2246 #[test]
2247 fn stage_hunks_whole_file_deletion_removes_index_entry() {
2248 let (dir, repo) = init_repo();
2249 let root = dir.path();
2250 std::fs::write(root.join("gone.txt"), b"keep\n").unwrap();
2251 git(root, &["add", "gone.txt"]);
2252 git(root, &["commit", "-qm", "init"]);
2253 std::fs::remove_file(root.join("gone.txt")).unwrap();
2254 let ids = list_unstaged_hunk_ids(&repo, &[], hunk_diff_opts())
2255 .unwrap()
2256 .remove("gone.txt")
2257 .expect("deletion in unstaged diff");
2258 stage_hunks(
2259 &repo,
2260 DiffSide::Unstaged,
2261 &HunkSelection {
2262 ids,
2263 ranges: Vec::new(),
2264 },
2265 &[],
2266 hunk_diff_opts(),
2267 false,
2268 &crate::progress::CancelToken::never(),
2269 )
2270 .unwrap();
2271 assert!(
2272 repo.load_index().unwrap().get(b"gone.txt", 0).is_none(),
2273 "index entry removed after staging delete hunk"
2274 );
2275 }
2276
2277 #[cfg_attr(
2278 not(feature = "full-tests"),
2279 ignore = "starts system git or is heavy; run with --features full-tests"
2280 )]
2281 #[test]
2282 fn directory_pathspec_keeps_staged_peer_hunk_ids() {
2283 let (dir, repo) = init_repo();
2284 let root = dir.path();
2285 std::fs::create_dir_all(root.join("pkg")).unwrap();
2286 let (base, edited) = spaced_two_hunk_body();
2287 std::fs::write(root.join("pkg/a.txt"), &base).unwrap();
2288 git(root, &["add", "pkg/a.txt"]);
2289 git(root, &["commit", "-qm", "init"]);
2290 std::fs::write(root.join("pkg/a.txt"), &edited).unwrap();
2291 let (files, peers) =
2292 unstaged_file_diffs_with_peer_hunks(&repo, &[], DiffOptions::default()).unwrap();
2293 let file = files.iter().find(|f| f.path == "pkg/a.txt").expect("a.txt");
2294 let ids = hunk_ids(
2295 DiffSide::Unstaged,
2296 "pkg/a.txt",
2297 &file.hunks,
2298 peers.get("pkg/a.txt").map(|v| v.as_slice()).unwrap_or(&[]),
2299 );
2300 stage_hunks(
2301 &repo,
2302 DiffSide::Unstaged,
2303 &HunkSelection {
2304 ids: vec![ids[0].clone()],
2305 ranges: Vec::new(),
2306 },
2307 &[],
2308 hunk_diff_opts(),
2309 false,
2310 &crate::progress::CancelToken::never(),
2311 )
2312 .unwrap();
2313 let file_pathspec = vec!["pkg/a.txt".to_string()];
2314 let dir_pathspec = vec!["pkg/".to_string()];
2315 let opts = hunk_diff_opts();
2316 let by_file = list_unstaged_hunk_ids(&repo, &file_pathspec, opts.clone()).unwrap();
2317 let by_dir = list_unstaged_hunk_ids(&repo, &dir_pathspec, opts).unwrap();
2318 assert_eq!(
2319 by_file.get("pkg/a.txt"),
2320 by_dir.get("pkg/a.txt"),
2321 "directory pathspec must include staged peer hunks when assigning ids"
2322 );
2323 }
2324
2325 #[cfg_attr(
2326 not(feature = "full-tests"),
2327 ignore = "starts system git or is heavy; run with --features full-tests"
2328 )]
2329 #[test]
2330 fn lines_selects_part_of_hunk() {
2331 let (dir, repo) = init_repo();
2332 let root = dir.path();
2333 std::fs::write(root.join("f.txt"), b"a\nb\nc\nd\n").unwrap();
2334 git(root, &["add", "f.txt"]);
2335 git(root, &["commit", "-qm", "init"]);
2336 std::fs::write(root.join("f.txt"), b"a\nB\nc\nD\n").unwrap();
2337 stage_lines_and_compare_git(
2338 &repo,
2339 root,
2340 "f.txt",
2341 vec![LineRange {
2342 path: "f.txt".into(),
2343 start: 2,
2344 end: 2,
2345 }],
2346 );
2347 }
2348
2349 #[cfg_attr(
2350 not(feature = "full-tests"),
2351 ignore = "starts system git or is heavy; run with --features full-tests"
2352 )]
2353 #[test]
2354 fn lines_unselected_deletion_becomes_context() {
2355 let (dir, repo) = init_repo();
2356 let root = dir.path();
2357 std::fs::write(root.join("f.txt"), b"keep\nremove\nstay\n").unwrap();
2358 git(root, &["add", "f.txt"]);
2359 git(root, &["commit", "-qm", "init"]);
2360 std::fs::write(root.join("f.txt"), b"keep\nstay\n").unwrap();
2361 stage_lines_and_compare_git(
2362 &repo,
2363 root,
2364 "f.txt",
2365 vec![LineRange {
2366 path: "f.txt".into(),
2367 start: 1,
2368 end: 1,
2369 }],
2370 );
2371 }
2372
2373 #[cfg_attr(
2374 not(feature = "full-tests"),
2375 ignore = "starts system git or is heavy; run with --features full-tests"
2376 )]
2377 #[test]
2378 fn lines_selected_deletion_at_range_edge() {
2379 let (dir, repo) = init_repo();
2380 let root = dir.path();
2381 std::fs::write(root.join("f.txt"), b"a\nb\nc\n").unwrap();
2382 git(root, &["add", "f.txt"]);
2383 git(root, &["commit", "-qm", "init"]);
2384 std::fs::write(root.join("f.txt"), b"a\nc\n").unwrap();
2385 stage_lines_and_compare_git(
2386 &repo,
2387 root,
2388 "f.txt",
2389 vec![LineRange {
2390 path: "f.txt".into(),
2391 start: 1,
2392 end: 1,
2393 }],
2394 );
2395 }
2396
2397 #[cfg_attr(
2398 not(feature = "full-tests"),
2399 ignore = "starts system git or is heavy; run with --features full-tests"
2400 )]
2401 #[test]
2402 fn lines_range_spanning_two_hunks() {
2403 let (dir, repo) = init_repo();
2404 let root = dir.path();
2405 let (base, edited) = three_hunk_body();
2406 std::fs::write(root.join("f.txt"), base).unwrap();
2407 git(root, &["add", "f.txt"]);
2408 git(root, &["commit", "-qm", "init"]);
2409 std::fs::write(root.join("f.txt"), edited).unwrap();
2410 stage_lines_and_compare_git(
2411 &repo,
2412 root,
2413 "f.txt",
2414 vec![LineRange {
2415 path: "f.txt".into(),
2416 start: 5,
2417 end: 14,
2418 }],
2419 );
2420 }
2421
2422 #[cfg_attr(
2423 not(feature = "full-tests"),
2424 ignore = "starts system git or is heavy; run with --features full-tests"
2425 )]
2426 #[test]
2427 fn glob_pathspec_includes_file_in_hunk_bundle() {
2428 let (dir, repo) = init_repo();
2429 let root = dir.path();
2430 std::fs::write(root.join("f.txt"), b"a\nb\n").unwrap();
2431 git(root, &["add", "f.txt"]);
2432 git(root, &["commit", "-qm", "init"]);
2433 std::fs::write(root.join("f.txt"), b"a\nB\n").unwrap();
2434 let bundle = hunk_diff_bundle(
2435 &repo,
2436 &crate::pathspec::Pathspec::scoped(
2437 [":(glob)*.txt"],
2438 crate::pathspec::PathspecGlobalFlags::default(),
2439 ),
2440 DiffOptions::default(),
2441 )
2442 .expect("bundle");
2443 assert!(
2444 bundle.unstaged.iter().any(|f| f.path == "f.txt"),
2445 "expected f.txt in bundle, got {:?}",
2446 bundle
2447 .unstaged
2448 .iter()
2449 .map(|f| f.path.as_str())
2450 .collect::<Vec<_>>()
2451 );
2452 }
2453
2454 #[cfg_attr(
2455 not(feature = "full-tests"),
2456 ignore = "starts system git or is heavy; run with --features full-tests"
2457 )]
2458 #[test]
2459 fn lines_pathspec_glob_stages() {
2460 let (dir, repo) = init_repo();
2461 let root = dir.path();
2462 std::fs::write(root.join("f.txt"), b"a\nb\n").unwrap();
2463 git(root, &["add", "f.txt"]);
2464 git(root, &["commit", "-qm", "init"]);
2465 std::fs::write(root.join("f.txt"), b"a\nB\n").unwrap();
2466 let selection = HunkSelection {
2467 ids: Vec::new(),
2468 ranges: vec![LineRange {
2469 path: "f.txt".into(),
2470 start: 2,
2471 end: 2,
2472 }],
2473 };
2474 stage_hunks(
2475 &repo,
2476 DiffSide::Unstaged,
2477 &selection,
2478 &[":(glob)*.txt".into()],
2479 hunk_diff_opts(),
2480 false,
2481 &crate::progress::CancelToken::never(),
2482 )
2483 .unwrap();
2484 git(root, &["fsck"]);
2485 }
2486
2487 #[cfg_attr(
2488 not(feature = "full-tests"),
2489 ignore = "starts system git or is heavy; run with --features full-tests"
2490 )]
2491 #[test]
2492 fn lines_mix_hunk_id_overlap_stages_via_id() {
2493 let (dir, repo) = init_repo();
2494 let root = dir.path();
2495 std::fs::write(root.join("f.txt"), b"one\n").unwrap();
2496 git(root, &["add", "f.txt"]);
2497 git(root, &["commit", "-qm", "init"]);
2498 std::fs::write(root.join("f.txt"), b"two\n").unwrap();
2499 let (files, peers) =
2500 unstaged_file_diffs_with_peer_hunks(&repo, &[], DiffOptions::default()).unwrap();
2501 let ids = hunk_ids(
2502 DiffSide::Unstaged,
2503 "f.txt",
2504 &files[0].hunks,
2505 peers.get("f.txt").map(|v| v.as_slice()).unwrap_or(&[]),
2506 );
2507 let selection = HunkSelection {
2508 ids: vec![ids[0].clone()],
2509 ranges: vec![LineRange {
2510 path: "f.txt".into(),
2511 start: 1,
2512 end: 1,
2513 }],
2514 };
2515 stage_hunks(
2516 &repo,
2517 DiffSide::Unstaged,
2518 &selection,
2519 &["f.txt".into()],
2520 hunk_diff_opts(),
2521 false,
2522 &crate::progress::CancelToken::never(),
2523 )
2524 .unwrap();
2525 git(root, &["fsck"]);
2526 }
2527
2528 #[cfg_attr(
2529 not(feature = "full-tests"),
2530 ignore = "starts system git or is heavy; run with --features full-tests"
2531 )]
2532 #[test]
2533 fn lines_unchanged_line_beyond_hunk_is_selects_nothing() {
2534 let (dir, repo) = init_repo();
2535 let root = dir.path();
2536 let mut base = String::new();
2537 for i in 1..=100 {
2538 base.push_str(&format!("line{i}\n"));
2539 }
2540 std::fs::write(root.join("f.txt"), &base).unwrap();
2541 git(root, &["add", "f.txt"]);
2542 git(root, &["commit", "-qm", "init"]);
2543 let mut edited = base.clone();
2544 edited = edited.replacen("line1\n", "LINE1\n", 1);
2545 std::fs::write(root.join("f.txt"), edited).unwrap();
2546 let err = stage_hunks(
2547 &repo,
2548 DiffSide::Unstaged,
2549 &HunkSelection {
2550 ids: Vec::new(),
2551 ranges: vec![LineRange {
2552 path: "f.txt".into(),
2553 start: 100,
2554 end: 100,
2555 }],
2556 },
2557 &[],
2558 hunk_diff_opts(),
2559 false,
2560 &crate::progress::CancelToken::never(),
2561 )
2562 .unwrap_err();
2563 assert!(
2564 matches!(
2565 err,
2566 crate::error::Error::Diff(crate::error::DiffError::HunkSelection(
2567 HunkSelectError::RangeSelectsNothing { .. }
2568 ))
2569 ),
2570 "expected RangeSelectsNothing, got {err:?}"
2571 );
2572 }
2573
2574 #[cfg_attr(
2575 not(feature = "full-tests"),
2576 ignore = "starts system git or is heavy; run with --features full-tests"
2577 )]
2578 #[test]
2579 fn lines_out_of_bounds_error() {
2580 let (dir, repo) = init_repo();
2581 let root = dir.path();
2582 std::fs::write(root.join("f.txt"), b"one\n").unwrap();
2583 git(root, &["add", "f.txt"]);
2584 git(root, &["commit", "-qm", "init"]);
2585 std::fs::write(root.join("f.txt"), b"two\n").unwrap();
2586 let err = stage_hunks(
2587 &repo,
2588 DiffSide::Unstaged,
2589 &HunkSelection {
2590 ids: Vec::new(),
2591 ranges: vec![LineRange {
2592 path: "f.txt".into(),
2593 start: 1,
2594 end: 99,
2595 }],
2596 },
2597 &[],
2598 hunk_diff_opts(),
2599 false,
2600 &crate::progress::CancelToken::never(),
2601 )
2602 .unwrap_err();
2603 assert!(matches!(
2604 err,
2605 crate::error::Error::Diff(crate::error::DiffError::HunkSelection(
2606 HunkSelectError::RangeOutOfBounds { .. }
2607 ))
2608 ));
2609 }
2610
2611 #[cfg(unix)]
2612 #[cfg_attr(
2613 not(feature = "full-tests"),
2614 ignore = "starts system git or is heavy; run with --features full-tests"
2615 )]
2616 #[test]
2617 fn lines_symlink_dangling_target_matches_git_apply_cached() {
2618 use std::os::unix::fs::symlink;
2619
2620 let (dir, repo) = init_repo();
2621 let root = dir.path();
2622 symlink("old-target", root.join("link")).expect("symlink");
2623 git(root, &["add", "link"]);
2624 git(root, &["commit", "-qm", "init"]);
2625 std::fs::remove_file(root.join("link")).expect("remove link");
2626 symlink("new-target", root.join("link")).expect("retarget");
2627 stage_lines_and_compare_git(
2628 &repo,
2629 root,
2630 "link",
2631 vec![LineRange {
2632 path: "link".into(),
2633 start: 1,
2634 end: 1,
2635 }],
2636 );
2637 }
2638
2639 fn numbered_lines(n: usize) -> String {
2640 (1..=n).map(|i| format!("line{i}\n")).collect()
2641 }
2642
2643 fn edit_every_tenth_line(base: &str) -> String {
2644 base.lines()
2645 .enumerate()
2646 .map(|(i, l)| {
2647 if i % 10 == 0 {
2648 format!("{}\n", l.to_uppercase())
2649 } else {
2650 format!("{l}\n")
2651 }
2652 })
2653 .collect()
2654 }
2655
2656 #[test]
2657 fn stage_lines_dry_run_writes_nothing_and_stages_only_the_range() {
2658 let dir = tempfile::tempdir().unwrap();
2659 let root = dir.path();
2660 let (repo, _) = Repository::init(root, &InitOptions::default()).unwrap();
2661 let base = numbered_lines(40);
2662 std::fs::write(root.join("f.txt"), &base).unwrap();
2663 std::fs::write(root.join("other.txt"), b"other\n").unwrap();
2664 stage(
2665 &repo,
2666 &StageOptions::default(),
2667 &mut NullProgress,
2668 &crate::progress::CancelToken::never(),
2669 )
2670 .unwrap();
2671 std::fs::write(root.join("f.txt"), edit_every_tenth_line(&base)).unwrap();
2672 std::fs::write(root.join("other.txt"), b"changed\n").unwrap();
2673 let selection = HunkSelection {
2674 ids: Vec::new(),
2675 ranges: vec![LineRange {
2676 path: "f.txt".into(),
2677 start: 1,
2678 end: 15,
2679 }],
2680 };
2681 let index_path = root.join(".git/index");
2682 let before = std::fs::read(&index_path).unwrap();
2683 let outcome = stage_hunks(
2684 &repo,
2685 DiffSide::Unstaged,
2686 &selection,
2687 &["f.txt".into()],
2688 hunk_diff_opts(),
2689 true,
2690 &crate::progress::CancelToken::never(),
2691 )
2692 .unwrap();
2693 assert!(outcome.dry_run);
2694 assert_eq!(outcome.modified, ["f.txt"]);
2695 assert_eq!(std::fs::read(&index_path).unwrap(), before);
2696 assert!(!root.join(".git/index.lock").exists());
2697
2698 let outcome = stage_hunks(
2699 &repo,
2700 DiffSide::Unstaged,
2701 &selection,
2702 &["f.txt".into()],
2703 hunk_diff_opts(),
2704 false,
2705 &crate::progress::CancelToken::never(),
2706 )
2707 .unwrap();
2708 assert_eq!(outcome.staged_lines["f.txt"], ["1-15"]);
2709 assert!(!root.join(".git/index.lock").exists());
2710 let index = repo.load_index().unwrap();
2711 let staged = repo
2712 .odb()
2713 .read(&index.get(b"f.txt", 0).unwrap().oid)
2714 .unwrap()
2715 .data;
2716 let expected: String = base
2717 .lines()
2718 .enumerate()
2719 .map(|(i, l)| {
2720 if i < 15 && i % 10 == 0 {
2721 format!("{}\n", l.to_uppercase())
2722 } else {
2723 format!("{l}\n")
2724 }
2725 })
2726 .collect();
2727 assert_eq!(String::from_utf8(staged).unwrap(), expected);
2728 let other = repo
2729 .odb()
2730 .read(&index.get(b"other.txt", 0).unwrap().oid)
2731 .unwrap()
2732 .data;
2733 assert_eq!(other, b"other\n", "unselected paths stay unstaged");
2734 }
2735
2736 #[cfg_attr(
2737 not(feature = "full-tests"),
2738 ignore = "starts system git or is heavy; run with --features full-tests"
2739 )]
2740 #[test]
2741 fn lines_with_literal_pathspec_among_other_dirty_files_match_git() {
2742 let (dir, repo) = init_repo();
2743 let root = dir.path();
2744 let base = numbered_lines(300);
2745 std::fs::write(root.join("big.txt"), &base).unwrap();
2746 std::fs::create_dir_all(root.join("sub")).unwrap();
2747 for i in 0..20 {
2748 std::fs::write(root.join(format!("sub/f{i}.txt")), format!("{i}\n")).unwrap();
2749 }
2750 git(root, &["add", "."]);
2751 git(root, &["commit", "-qm", "init"]);
2752 std::fs::write(root.join("big.txt"), edit_every_tenth_line(&base)).unwrap();
2753 std::fs::write(root.join("sub/f3.txt"), b"dirty\n").unwrap();
2754 stage_lines_and_compare_git(
2755 &repo,
2756 root,
2757 "big.txt",
2758 vec![
2759 LineRange {
2760 path: "big.txt".into(),
2761 start: 1,
2762 end: 105,
2763 },
2764 LineRange {
2765 path: "big.txt".into(),
2766 start: 251,
2767 end: 251,
2768 },
2769 ],
2770 );
2771 let out = Command::new("git")
2772 .current_dir(root)
2773 .args(["diff", "--name-only"])
2774 .output()
2775 .expect("git diff");
2776 let unstaged = String::from_utf8_lossy(&out.stdout);
2777 assert!(unstaged.lines().any(|l| l == "sub/f3.txt"), "{unstaged}");
2778 assert!(unstaged.lines().any(|l| l == "big.txt"), "{unstaged}");
2779 }
2780
2781 #[cfg_attr(
2782 not(feature = "full-tests"),
2783 ignore = "starts system git or is heavy; run with --features full-tests"
2784 )]
2785 #[test]
2786 fn lines_on_top_of_staged_change_match_git() {
2787 let (dir, repo) = init_repo();
2788 let root = dir.path();
2789 let base = numbered_lines(100);
2790 std::fs::write(root.join("f.txt"), &base).unwrap();
2791 git(root, &["add", "f.txt"]);
2792 git(root, &["commit", "-qm", "init"]);
2793 let edited = edit_every_tenth_line(&base);
2794 std::fs::write(root.join("f.txt"), &edited).unwrap();
2795 stage_hunks(
2796 &repo,
2797 DiffSide::Unstaged,
2798 &HunkSelection {
2799 ids: Vec::new(),
2800 ranges: vec![LineRange {
2801 path: "f.txt".into(),
2802 start: 1,
2803 end: 30,
2804 }],
2805 },
2806 &["f.txt".into()],
2807 hunk_diff_opts(),
2808 false,
2809 &crate::progress::CancelToken::never(),
2810 )
2811 .unwrap();
2812 git(root, &["commit", "-qm", "partial"]);
2813 stage_hunks(
2814 &repo,
2815 DiffSide::Unstaged,
2816 &HunkSelection {
2817 ids: Vec::new(),
2818 ranges: vec![LineRange {
2819 path: "f.txt".into(),
2820 start: 31,
2821 end: 60,
2822 }],
2823 },
2824 &["f.txt".into()],
2825 hunk_diff_opts(),
2826 false,
2827 &crate::progress::CancelToken::never(),
2828 )
2829 .unwrap();
2830 stage_lines_and_compare_git(
2831 &repo,
2832 root,
2833 "f.txt",
2834 vec![LineRange {
2835 path: "f.txt".into(),
2836 start: 61,
2837 end: 80,
2838 }],
2839 );
2840 }
2841
2842 #[cfg_attr(
2843 not(feature = "full-tests"),
2844 ignore = "starts system git or is heavy; run with --features full-tests"
2845 )]
2846 #[test]
2847 fn lines_without_pathspec_match_git() {
2848 let (dir, repo) = init_repo();
2849 let root = dir.path();
2850 let (base, edited) = three_hunk_body();
2851 std::fs::write(root.join("f.txt"), base).unwrap();
2852 std::fs::write(root.join("g.txt"), b"g\n").unwrap();
2853 git(root, &["add", "."]);
2854 git(root, &["commit", "-qm", "init"]);
2855 std::fs::write(root.join("f.txt"), &edited).unwrap();
2856 std::fs::write(root.join("g.txt"), b"G\n").unwrap();
2857 let selection = HunkSelection {
2858 ids: Vec::new(),
2859 ranges: vec![LineRange {
2860 path: "f.txt".into(),
2861 start: 10,
2862 end: 30,
2863 }],
2864 };
2865 let patch = resolve_selection(&repo, DiffSide::Unstaged, &selection, &[], hunk_diff_opts())
2866 .unwrap();
2867 let patch_text: String = patch.iter().map(format_patch_for_git).collect();
2868 stage_hunks(
2869 &repo,
2870 DiffSide::Unstaged,
2871 &selection,
2872 &[],
2873 hunk_diff_opts(),
2874 false,
2875 &crate::progress::CancelToken::never(),
2876 )
2877 .unwrap();
2878 let grit_tree = write_tree_from_index(repo.odb(), &repo.load_index().unwrap(), "").unwrap();
2879 git(root, &["read-tree", "HEAD"]);
2880 let patch_path = root.join("partial.diff");
2881 std::fs::write(&patch_path, patch_text).unwrap();
2882 git(root, &["apply", "--cached", patch_path.to_str().unwrap()]);
2883 let git_tree = Command::new("git")
2884 .current_dir(root)
2885 .args(["write-tree"])
2886 .output()
2887 .expect("write-tree");
2888 assert_eq!(
2889 grit_tree.to_hex(),
2890 String::from_utf8_lossy(&git_tree.stdout).trim()
2891 );
2892 git(root, &["fsck"]);
2893 }
2894
2895 #[cfg_attr(
2896 not(feature = "full-tests"),
2897 ignore = "starts system git or is heavy; run with --features full-tests"
2898 )]
2899 #[test]
2900 fn lines_no_eof_newline() {
2901 let (dir, repo) = init_repo();
2902 let root = dir.path();
2903 std::fs::write(root.join("f.txt"), b"old").unwrap();
2904 git(root, &["add", "f.txt"]);
2905 git(root, &["commit", "-qm", "init"]);
2906 std::fs::write(root.join("f.txt"), b"new").unwrap();
2907 stage_lines_and_compare_git(
2908 &repo,
2909 root,
2910 "f.txt",
2911 vec![LineRange {
2912 path: "f.txt".into(),
2913 start: 1,
2914 end: 1,
2915 }],
2916 );
2917 }
2918}