1use std::collections::BTreeSet;
4use std::path::Path;
5use std::sync::{Arc, Mutex};
6
7use thiserror::Error;
8
9use crate::config::ConfigSet;
10use crate::diff::changes::{
11 load_changes, load_object_changes, pathspec_restrict_paths_for_scan, staged_entries_in,
12 unstaged_entries_in, worktree_entries_in, FileChange, WorktreeSide,
13};
14use crate::diff::detail::LineStat;
15use crate::diff::structured::StructuredHunk;
16use crate::diff::{
17 apply_diff_filter, sort_entries_by_path, tree_diff_structured_parallel, DiffEntry, DiffOptions,
18 DiffStatus, TreeDiffStructured,
19};
20use crate::error::{DiffError, Error, PathspecResolveError, Result};
21use crate::index::Index;
22use crate::index::MODE_TREE;
23use crate::objects::FileMode;
24use crate::objects::ObjectId;
25use crate::parallel::{par_map, ParallelOp, ThreadPolicy};
26use crate::pathspec::resolve_pathspec;
27use crate::pathspec::{
28 exact_literal_pathspec_set, Pathspec, PathspecGlobalFlags, PathspecMatchContext,
29 PathspecMatcher,
30};
31use crate::porcelain::pathspec_match::{
32 ensure_pathspec_matches_known_in_repository, pathspec_matches_known_in_repository,
33};
34use crate::repo::Repository;
35use crate::repo::RepositoryError;
36use crate::rev_parse::peel_tags_to_commit;
37use crate::revwalk::merge_base::merge_base_for_diff_two_commits;
38use crate::revwalk::rev_parse::{
39 resolve_revision, resolve_revision_for_range_end, split_double_dot_range,
40 split_triple_dot_range,
41};
42use crate::state::resolve_head_for_repository;
43use crate::worktree::worktree_rules::WorktreeRules;
44
45#[non_exhaustive]
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum DiffTarget {
49 WorktreeVsHead,
51 WorktreeVsTree(ObjectId),
53 IndexVsHead,
55 WorktreeVsIndex,
57 Commit(ObjectId),
59 Trees {
61 old: Option<ObjectId>,
63 new: ObjectId,
65 },
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct FileDiff {
75 pub path: String,
77 pub old_path: Option<String>,
79 pub status: DiffStatus,
81 pub old_mode: Option<String>,
83 pub new_mode: Option<String>,
85 pub old_oid: ObjectId,
87 pub new_oid: ObjectId,
89 pub binary: bool,
91 pub old_size: u64,
93 pub new_size: u64,
95 pub content_changed: bool,
97 pub old_encoding_lossy: bool,
99 pub new_encoding_lossy: bool,
101 pub hunks: Vec<StructuredHunk>,
103 pub line_stat: Option<LineStat>,
105}
106
107#[derive(Debug, Clone)]
109pub struct DiffArguments {
110 pub target: DiffTarget,
112 pub pathspec: Pathspec,
114}
115
116#[derive(Debug, Clone, Default, PartialEq, Eq)]
120pub struct DiffRequest {
121 pub staged: bool,
123 pub unstaged: bool,
125 pub against: Option<String>,
127 pub positionals: Vec<String>,
129 pub paths: Vec<String>,
131 pub pathspec_file: Option<Vec<String>>,
136}
137
138#[non_exhaustive]
140#[derive(Debug, Error)]
141pub enum ResolveDiffArgumentsError {
142 #[error("--staged and --unstaged cannot be combined")]
144 StagedAndUnstaged,
145
146 #[error("--staged cannot be combined with revision arguments or --against")]
148 StagedWithRevisions,
149
150 #[error("--unstaged cannot be combined with revision arguments or --against")]
152 UnstagedWithRevisions,
153
154 #[error("at most two commits, or one two-dot range such as A..B")]
156 TooManyRevisions,
157
158 #[error("--against compares the worktree to a ref and takes no commit arguments")]
160 AgainstWithCommits,
161
162 #[error(
164 "a two-dot or three-dot range uses the other positional as a path limit; pass paths after `--`"
165 )]
166 RangeWithSecondRevision,
167
168 #[error("grit diff needs a working tree")]
170 NoWorkTree,
171
172 #[error("could not resolve '{spec}'")]
177 UnresolvedRevision {
178 spec: String,
180 #[source]
182 source: Box<crate::error::RevisionError>,
183 },
184
185 #[error("object {oid} does not name a commit")]
187 NotACommit {
188 oid: ObjectId,
190 },
191
192 #[error(transparent)]
194 Pathspec(#[from] PathspecResolveError),
195}
196
197impl From<ResolveDiffArgumentsError> for Error {
198 fn from(err: ResolveDiffArgumentsError) -> Self {
199 Self::Diff(DiffError::Arguments(err))
200 }
201}
202
203type ResolveResult<T> = Result<T>;
204
205pub(crate) fn resolve_diff_request(
244 repo: &Repository,
245 cwd_prefix: Option<&str>,
246 request: &DiffRequest,
247) -> ResolveResult<DiffArguments> {
248 let arguments = resolve_diff_request_in(repo, cwd_prefix, request)?;
249 let reads_worktree = matches!(
250 arguments.target,
251 DiffTarget::WorktreeVsHead | DiffTarget::WorktreeVsTree(_) | DiffTarget::WorktreeVsIndex
252 );
253 if reads_worktree && repo.work_tree().is_none() {
254 return Err(ResolveDiffArgumentsError::NoWorkTree.into());
255 }
256 Ok(arguments)
257}
258
259fn resolve_diff_request_in(
260 repo: &Repository,
261 cwd_prefix: Option<&str>,
262 request: &DiffRequest,
263) -> ResolveResult<DiffArguments> {
264 let (commits, path_args) = disambiguate_diff_revision_and_paths(
265 repo,
266 cwd_prefix,
267 request.positionals.clone(),
268 request.paths.clone(),
269 );
270 let file_paths = request.pathspec_file.as_deref().unwrap_or_default();
271 let path_tokens = [file_paths, path_args.as_slice()].concat();
272 if (request.pathspec_file.is_some() || !request.paths.is_empty())
273 && (path_tokens.is_empty() || path_tokens.iter().any(String::is_empty))
274 {
275 return Err(
276 ResolveDiffArgumentsError::Pathspec(PathspecResolveError::EmptyPathspec).into(),
277 );
278 }
279 let against = request.against.as_deref();
280
281 if request.staged && request.unstaged {
282 return Err(ResolveDiffArgumentsError::StagedAndUnstaged.into());
283 }
284 if request.staged || request.unstaged {
285 if !commits.is_empty() || against.is_some() {
286 return Err(if request.staged {
287 crate::error::Error::from(ResolveDiffArgumentsError::StagedWithRevisions)
288 } else {
289 crate::error::Error::from(ResolveDiffArgumentsError::UnstagedWithRevisions)
290 });
291 }
292 return Ok(DiffArguments {
293 target: if request.staged {
294 DiffTarget::IndexVsHead
295 } else {
296 DiffTarget::WorktreeVsIndex
297 },
298 pathspec: pathspec_from_resolved_specs(resolve_worktree_diff_pathspecs(
299 repo,
300 cwd_prefix,
301 &path_tokens,
302 )?),
303 });
304 }
305 if commits.len() > 2 {
306 return Err(ResolveDiffArgumentsError::TooManyRevisions.into());
307 }
308 if against.is_some() && !commits.is_empty() {
309 return Err(ResolveDiffArgumentsError::AgainstWithCommits.into());
310 }
311
312 let trees = |old: ObjectId, new: ObjectId, pathspec: Pathspec| DiffArguments {
313 target: DiffTarget::Trees {
314 old: Some(old),
315 new,
316 },
317 pathspec,
318 };
319 match commits.as_slice() {
320 [] => {
321 let pathspec = pathspec_from_resolved_specs(resolve_worktree_diff_pathspecs(
322 repo,
323 cwd_prefix,
324 &path_tokens,
325 )?);
326 let target = match against {
327 Some(spec) => DiffTarget::WorktreeVsTree(
328 repo.odb().commit_tree(&resolve_diff_commit(repo, spec)?)?,
329 ),
330 None => DiffTarget::WorktreeVsHead,
331 };
332 Ok(DiffArguments { target, pathspec })
333 }
334 [spec] => {
335 if let Some((base, tip)) = parse_commit_range(repo, spec)? {
336 let pathspec = resolve_commit_diff_pathspecs(repo, cwd_prefix, &path_tokens)?;
337 return Ok(trees(base, tip, pathspec));
338 }
339 match resolve_diff_commit(repo, spec) {
340 Ok(oid) => Ok(DiffArguments {
341 target: DiffTarget::Commit(oid),
342 pathspec: resolve_commit_diff_pathspecs(repo, cwd_prefix, &path_tokens)?,
343 }),
344 Err(_) if path_tokens.is_empty() => Ok(DiffArguments {
346 target: DiffTarget::WorktreeVsIndex,
347 pathspec: pathspec_from_resolved_specs(resolve_worktree_diff_pathspecs(
348 repo,
349 cwd_prefix,
350 std::slice::from_ref(spec),
351 )?),
352 }),
353 Err(err) => Err(err),
354 }
355 }
356 [first, second] => {
357 if let Some((base, tip)) = parse_commit_range(repo, first)? {
358 if !token_is_known_worktree_pathspec(repo, cwd_prefix, second) {
359 resolve_diff_commit(repo, second)?;
360 return Err(ResolveDiffArgumentsError::RangeWithSecondRevision.into());
361 }
362 let range_paths = [file_paths, std::slice::from_ref(second)].concat();
363 let pathspec = resolve_commit_diff_pathspecs(repo, cwd_prefix, &range_paths)?;
364 return Ok(trees(base, tip, pathspec));
365 }
366 let base = resolve_diff_commit(repo, first)?;
367 let tip = resolve_diff_commit(repo, second)?;
368 let pathspec = resolve_commit_diff_pathspecs(repo, cwd_prefix, &path_tokens)?;
369 Ok(trees(base, tip, pathspec))
370 }
371 _ => Err(ResolveDiffArgumentsError::TooManyRevisions.into()),
372 }
373}
374
375pub(crate) fn include_file_in_diff(file: &FileDiff, opts: &DiffOptions) -> bool {
376 if !opts.whitespace.is_active() || file.binary {
377 return true;
378 }
379 if matches!(
380 file.status,
381 DiffStatus::Renamed
382 | DiffStatus::Added
383 | DiffStatus::Deleted
384 | DiffStatus::Copied
385 | DiffStatus::TypeChanged
386 ) {
387 return true;
388 }
389 if file.old_mode != file.new_mode {
390 return true;
391 }
392 !file.hunks.is_empty()
393}
394
395pub(crate) fn collect_files_for_target(
396 repo: &Repository,
397 target: &DiffTarget,
398 pathspecs: &[String],
399 opts: DiffOptions,
400) -> Result<Vec<FileDiff>> {
401 let config = repo.config().snapshot()?;
402 let thread_policy = repo.thread_policy();
403 let rename_threshold = opts.renames.threshold_percent().unwrap_or(101);
405
406 let files = match target {
407 DiffTarget::WorktreeVsHead => {
408 let head_tree = resolve_head_for_repository(repo)?.tree(repo.odb())?;
409 let changes = filter_file_changes(
410 worktree_changes(repo, head_tree.as_ref(), rename_threshold, pathspecs)?,
411 repo,
412 pathspecs,
413 )?;
414 file_diffs_from_worktree_changes(changes, &config, &thread_policy, opts.clone())?
415 }
416 DiffTarget::WorktreeVsTree(tree) => {
417 let changes = filter_file_changes(
418 worktree_changes(repo, Some(tree), rename_threshold, pathspecs)?,
419 repo,
420 pathspecs,
421 )?;
422 file_diffs_from_worktree_changes(changes, &config, &thread_policy, opts.clone())?
423 }
424 DiffTarget::IndexVsHead => {
425 let index = repo.load_index()?;
426 let head_tree = resolve_head_for_repository(repo)?.tree(repo.odb())?;
427 let restrict =
428 pathspec_restrict_paths_for_scan(repo, &index, pathspecs, head_tree.as_ref())?;
429 let changes = filter_file_changes(
430 staged_changes(repo, rename_threshold, restrict)?,
431 repo,
432 pathspecs,
433 )?;
434 file_diffs_from_worktree_changes(changes, &config, &thread_policy, opts.clone())?
435 }
436 DiffTarget::WorktreeVsIndex => {
437 let changes = filter_file_changes(
438 unstaged_changes(repo, rename_threshold, pathspecs)?,
439 repo,
440 pathspecs,
441 )?;
442 file_diffs_from_worktree_changes(changes, &config, &thread_policy, opts.clone())?
443 }
444 DiffTarget::Commit(oid) => {
445 let items = commit_changes(
446 repo,
447 oid,
448 pathspecs,
449 &config,
450 &thread_policy,
451 opts.clone(),
452 rename_threshold,
453 )?;
454 filter_and_map_tree_structured(items, repo, pathspecs, opts)?
455 }
456 DiffTarget::Trees { old, new } => {
457 let items = if let Some(base) = old {
458 tree_commit_changes(
459 repo,
460 base,
461 new,
462 pathspecs,
463 &config,
464 &thread_policy,
465 opts.clone(),
466 rename_threshold,
467 )?
468 } else {
469 empty_tree_to_side_changes(
470 repo,
471 new,
472 pathspecs,
473 &config,
474 &thread_policy,
475 opts.clone(),
476 rename_threshold,
477 )?
478 };
479 filter_and_map_tree_structured(items, repo, pathspecs, opts)?
480 }
481 };
482 Ok(files)
483}
484
485pub(crate) fn stored_target_entries(
489 repo: &Repository,
490 target: &DiffTarget,
491 pathspecs: &[String],
492 options: &DiffOptions,
493) -> Result<Option<super::core::DiffEntriesResult>> {
494 let rename_threshold = options.rename_threshold_u32();
495 let entries = match target {
496 DiffTarget::Commit(oid) => {
497 let config = repo.config().snapshot()?;
498 commit_diff_entries(
499 repo,
500 oid,
501 pathspecs,
502 &config,
503 &repo.thread_policy(),
504 rename_threshold,
505 )?
506 }
507 DiffTarget::Trees { old, new } => {
508 let config = repo.config().snapshot()?;
509 let thread_policy = repo.thread_policy();
510 match old {
511 Some(base) => tree_commit_diff_entries(
512 repo,
513 base,
514 new,
515 pathspecs,
516 &config,
517 &thread_policy,
518 rename_threshold,
519 )?,
520 None => empty_tree_to_side_diff_entries(
521 repo,
522 new,
523 pathspecs,
524 &config,
525 &thread_policy,
526 rename_threshold,
527 )?,
528 }
529 }
530 DiffTarget::WorktreeVsHead
531 | DiffTarget::WorktreeVsTree(_)
532 | DiffTarget::IndexVsHead
533 | DiffTarget::WorktreeVsIndex => return Ok(None),
534 };
535 Ok(Some(entries))
536}
537
538pub(crate) fn limit_target_entries(
540 repo: &Repository,
541 mut result: super::core::DiffEntriesResult,
542 pathspecs: &[String],
543 options: &DiffOptions,
544) -> Result<super::core::DiffEntriesResult> {
545 let entries = if pathspecs.is_empty() {
546 result.entries
547 } else {
548 let matcher = repo.pathspec_matcher(pathspecs)?;
549 result
550 .entries
551 .into_iter()
552 .filter(|entry| diff_entry_matches(&matcher, entry))
553 .collect()
554 };
555 result.entries = apply_diff_filter(entries, options.filter);
556 Ok(result)
557}
558
559fn filter_and_map_tree_structured(
560 items: Vec<TreeDiffStructured>,
561 repo: &Repository,
562 pathspecs: &[String],
563 opts: DiffOptions,
564) -> Result<Vec<FileDiff>> {
565 Ok(filter_tree_diff(items, repo, pathspecs)?
566 .into_iter()
567 .map(file_diff_from_tree_structured)
568 .filter(|f| include_file_in_diff(f, &opts))
569 .collect())
570}
571
572fn file_diff_from_tree_structured(t: TreeDiffStructured) -> FileDiff {
573 let e = t.entry;
574 let path = e
575 .new_path
576 .clone()
577 .or_else(|| e.old_path.clone())
578 .unwrap_or_default();
579 let old_path = e.old_path.filter(|op| *op != path);
580 FileDiff {
581 path,
582 old_path,
583 status: e.status,
584 old_mode: t.structured.old_mode,
585 new_mode: t.structured.new_mode,
586 old_oid: e.old_oid,
587 new_oid: e.new_oid,
588 binary: t.binary,
589 old_size: t.old_size,
590 new_size: t.new_size,
591 content_changed: e.old_oid != e.new_oid,
592 old_encoding_lossy: t.structured.old_encoding_lossy,
593 new_encoding_lossy: t.structured.new_encoding_lossy,
594 hunks: t.structured.hunks,
595 line_stat: None,
596 }
597}
598
599fn file_diffs_from_worktree_changes(
600 changes: Vec<FileChange>,
601 config: &ConfigSet,
602 thread_policy: &ThreadPolicy,
603 opts: DiffOptions,
604) -> Result<Vec<FileDiff>> {
605 let opts = opts.cap_word_level_inline_for_changed_files(changes.len());
606 let mut par_opts = thread_policy.resolve(ParallelOp::DiffContent, config);
607 par_opts.min_items = 0;
608 let est_bytes = changes.len().saturating_mul(8192);
609 Ok(par_map(&changes, par_opts, est_bytes, |fc| {
610 build_file_diff(fc, opts.clone())
611 })
612 .into_iter()
613 .filter(|f| include_file_in_diff(f, &opts))
614 .collect())
615}
616
617fn build_file_diff(fc: &FileChange, diff_options: DiffOptions) -> FileDiff {
618 let structured = fc.structured(diff_options);
619 FileDiff {
620 path: fc.path.clone(),
621 old_path: fc.old_path.clone(),
622 status: fc.status,
623 old_mode: structured.old_mode,
624 new_mode: structured.new_mode,
625 old_oid: fc.old_oid,
626 new_oid: fc.new_oid,
627 binary: fc.binary,
628 old_size: fc.old_bytes.byte_len(),
629 new_size: fc.new_bytes.byte_len(),
630 content_changed: fc.content_changed,
631 old_encoding_lossy: structured.old_encoding_lossy,
632 new_encoding_lossy: structured.new_encoding_lossy,
633 hunks: structured.hunks,
634 line_stat: None,
635 }
636}
637
638fn token_is_diff_revision(repo: &Repository, token: &str) -> bool {
639 resolve_diff_commit(repo, token).is_ok()
640 || parse_commit_range(repo, token).ok().flatten().is_some()
641}
642
643fn token_is_known_worktree_pathspec(
644 repo: &Repository,
645 cwd_prefix: Option<&str>,
646 token: &str,
647) -> bool {
648 let Ok(resolved) = repo.resolve_worktree_pathspec(token, cwd_prefix) else {
649 return false;
650 };
651 pathspec_matches_known_in_repository(repo, &resolved).unwrap_or(false)
652}
653
654fn disambiguate_diff_revision_and_paths(
656 repo: &Repository,
657 cwd_prefix: Option<&str>,
658 mut commits: Vec<String>,
659 mut paths: Vec<String>,
660) -> (Vec<String>, Vec<String>) {
661 if !paths.is_empty() {
662 return (commits, paths);
663 }
664 let is_path = |token: &str| token_is_known_worktree_pathspec(repo, cwd_prefix, token);
665 match commits.as_slice() {
666 [first, second]
667 if token_is_diff_revision(repo, first)
668 && !token_is_diff_revision(repo, second)
669 && is_path(second) =>
670 {
671 paths.extend(commits.pop());
672 }
673 [only] if !token_is_diff_revision(repo, only) && is_path(only) => {
674 paths.extend(commits.pop());
675 }
676 _ => {}
677 }
678 if paths.is_empty() {
679 while let [_, .., tail] = commits.as_slice() {
680 if token_is_diff_revision(repo, tail) || !is_path(tail) {
681 break;
682 }
683 paths.extend(commits.pop());
684 }
685 }
686 (commits, paths)
687}
688
689fn pathspec_resolution_root(repo: &Repository) -> &Path {
690 repo.work_tree().unwrap_or_else(|| repo.git_dir())
691}
692
693fn resolve_worktree_diff_pathspecs(
695 repo: &Repository,
696 cwd_prefix: Option<&str>,
697 raw_paths: &[String],
698) -> ResolveResult<Vec<String>> {
699 if raw_paths.is_empty() {
700 return Ok(Vec::new());
701 }
702 if repo.work_tree().is_none() {
703 return Err(ResolveDiffArgumentsError::NoWorkTree.into());
704 }
705 raw_paths
706 .iter()
707 .map(|pathspec| {
708 let resolved = repo
709 .resolve_worktree_pathspec(pathspec, cwd_prefix)
710 .map_err(ResolveDiffArgumentsError::Pathspec)?;
711 ensure_pathspec_matches_known_in_repository(repo, pathspec, &resolved)?;
712 Ok(resolved)
713 })
714 .collect()
715}
716
717fn pathspec_from_resolved_specs(specs: Vec<String>) -> Pathspec {
719 if specs.is_empty() {
720 Pathspec::entire_tree(PathspecGlobalFlags::default())
721 } else {
722 Pathspec::scoped(specs, PathspecGlobalFlags::default())
723 }
724}
725
726pub(crate) fn resolve_commit_diff_pathspecs(
744 repo: &Repository,
745 cwd_prefix: Option<&str>,
746 raw_paths: &[String],
747) -> ResolveResult<Pathspec> {
748 let specs: Vec<String> = if repo.work_tree().is_none() {
749 let root = pathspec_resolution_root(repo);
750 raw_paths
751 .iter()
752 .map(|pathspec| resolve_pathspec(pathspec, root, cwd_prefix))
753 .collect()
754 } else {
755 raw_paths
756 .iter()
757 .map(|pathspec| {
758 Ok(repo
759 .resolve_worktree_pathspec(pathspec, cwd_prefix)
760 .map_err(ResolveDiffArgumentsError::Pathspec)?)
761 })
762 .collect::<ResolveResult<Vec<_>>>()?
763 };
764 Ok(pathspec_from_resolved_specs(specs))
765}
766
767fn filter_file_changes(
768 changes: Vec<FileChange>,
769 repo: &Repository,
770 specs: &[String],
771) -> Result<Vec<FileChange>> {
772 if specs.is_empty() {
773 return Ok(changes);
774 }
775 let matcher = repo.pathspec_matcher(specs)?;
776 Ok(changes
777 .into_iter()
778 .filter(|c| matcher.matches_change(&c.path, c.old_path.as_deref()))
779 .collect())
780}
781
782fn diff_entry_matches(matcher: &PathspecMatcher<'_>, entry: &DiffEntry) -> bool {
783 let path = entry
784 .new_path
785 .as_deref()
786 .or(entry.old_path.as_deref())
787 .unwrap_or("");
788 matcher.matches_change(path, entry.old_path.as_deref())
789}
790
791fn filter_tree_diff(
792 items: Vec<TreeDiffStructured>,
793 repo: &Repository,
794 specs: &[String],
795) -> Result<Vec<TreeDiffStructured>> {
796 if specs.is_empty() {
797 return Ok(items);
798 }
799 let matcher = repo.pathspec_matcher(specs)?;
800 Ok(items
801 .into_iter()
802 .filter(|item| diff_entry_matches(&matcher, &item.entry))
803 .collect())
804}
805
806fn unstaged_changes(
807 repo: &Repository,
808 rename_threshold: u32,
809 pathspecs: &[String],
810) -> Result<Vec<FileChange>> {
811 let mut index = repo.load_index()?;
812 let restrict = pathspec_restrict_paths_for_scan(repo, &index, pathspecs, None)?;
813 unstaged_changes_inner(repo, &mut index, rename_threshold, restrict)
814}
815
816fn unstaged_changes_inner(
817 repo: &Repository,
818 index: &mut Index,
819 rename_threshold: u32,
820 restrict_to_paths: Option<Arc<BTreeSet<String>>>,
821) -> Result<Vec<FileChange>> {
822 let work_tree = repo.work_tree().ok_or(RepositoryError::RequiresWorkTree)?;
823 let rules = Arc::new(Mutex::new(WorktreeRules::from_repository(repo, index)?));
824 let entries = unstaged_entries_in(
825 repo,
826 index,
827 work_tree,
828 &rules,
829 rename_threshold,
830 restrict_to_paths,
831 )?;
832 let side = WorktreeSide {
833 work_tree,
834 index,
835 rules: &rules,
836 };
837 load_changes(repo.odb(), entries, Some(&side))
838}
839
840pub(super) fn diff_index_to_tree_for_paths(
841 repo: &Repository,
842 index: &Index,
843 head_tree: Option<&ObjectId>,
844 paths: &BTreeSet<String>,
845) -> Result<Vec<DiffEntry>> {
846 let odb = repo.odb();
847 let mut result = Vec::new();
848 for path in paths {
849 let index_entry = index.get(path.as_bytes(), 0);
850 if index_entry.is_some_and(|e| e.intent_to_add()) {
851 continue;
852 }
853 let tree_side = match head_tree {
854 Some(t) => odb
855 .tree_entry_at_path(t, path.as_bytes())?
856 .map(|e| (e.oid, e.mode)),
857 None => None,
858 };
859 let (idx_oid, idx_mode) = index_entry
860 .map(|e| (e.oid, e.mode))
861 .unwrap_or((ObjectId::zero(), 0));
862 let (tree_oid, tree_mode) = tree_side.unwrap_or((ObjectId::zero(), 0));
863 if index_entry.is_none() && tree_side.is_none() {
864 continue;
865 }
866 if index_entry.is_some() && tree_side.is_none() {
867 result.push(DiffEntry {
868 status: DiffStatus::Added,
869 old_path: None,
870 new_path: Some(path.clone()),
871 old_mode: FileMode::ABSENT,
872 new_mode: FileMode::new(idx_mode),
873 old_oid: ObjectId::zero(),
874 new_oid: idx_oid,
875 score: None,
876 });
877 continue;
878 }
879 if index_entry.is_none() {
880 result.push(DiffEntry {
881 status: DiffStatus::Deleted,
882 old_path: Some(path.clone()),
883 new_path: None,
884 old_mode: FileMode::new(tree_mode),
885 new_mode: FileMode::ABSENT,
886 old_oid: tree_oid,
887 new_oid: ObjectId::zero(),
888 score: None,
889 });
890 continue;
891 }
892 if idx_oid != tree_oid || idx_mode != tree_mode {
893 result.push(DiffEntry {
894 status: DiffStatus::for_content_change(tree_mode, idx_mode),
895 old_path: Some(path.clone()),
896 new_path: Some(path.clone()),
897 old_mode: FileMode::new(tree_mode),
898 new_mode: FileMode::new(idx_mode),
899 old_oid: tree_oid,
900 new_oid: idx_oid,
901 score: None,
902 });
903 }
904 }
905 Ok(result)
906}
907
908fn staged_changes(
909 repo: &Repository,
910 rename_threshold: u32,
911 restrict_to_paths: Option<Arc<BTreeSet<String>>>,
912) -> Result<Vec<FileChange>> {
913 let index = repo.load_index()?;
914 let entries = staged_entries_in(repo, &index, rename_threshold, restrict_to_paths.as_deref())?;
915 load_object_changes(repo, &entries)
916}
917
918fn worktree_changes(
919 repo: &Repository,
920 base_tree: Option<&ObjectId>,
921 rename_threshold: u32,
922 pathspecs: &[String],
923) -> Result<Vec<FileChange>> {
924 let work_tree = repo.work_tree().ok_or(RepositoryError::RequiresWorkTree)?;
925 let mut index = repo.load_index()?;
926 let restrict = pathspec_restrict_paths_for_scan(repo, &index, pathspecs, base_tree)?;
927 let rules = Arc::new(Mutex::new(WorktreeRules::from_repository(repo, &index)?));
928 let entries = worktree_entries_in(
929 repo,
930 &mut index,
931 work_tree,
932 &rules,
933 base_tree,
934 rename_threshold,
935 restrict,
936 )?;
937 let side = WorktreeSide {
938 work_tree,
939 index: &index,
940 rules: &rules,
941 };
942 load_changes(repo.odb(), entries, Some(&side))
943}
944
945fn pathspec_matcher_for_stored_diff<'a>(
946 repo: &'a Repository,
947 pathspecs: &'a [String],
948) -> Result<Option<crate::pathspec::PathspecMatcher<'a>>> {
949 if pathspecs.is_empty() {
950 Ok(None)
951 } else {
952 Ok(Some(repo.pathspec_matcher(pathspecs)?))
953 }
954}
955
956fn tree_commit_diff_entries(
957 repo: &Repository,
958 base: &ObjectId,
959 tip: &ObjectId,
960 pathspecs: &[String],
961 config: &ConfigSet,
962 thread_policy: &ThreadPolicy,
963 rename_threshold: u32,
964) -> Result<super::core::DiffEntriesResult> {
965 let odb = repo.odb();
966 let base_tree = super::core::tree_oid_for_diff_side(odb, base)?;
967 let tip_tree = super::core::tree_oid_for_diff_side(odb, tip)?;
968 let pathspec_matcher = pathspec_matcher_for_stored_diff(repo, pathspecs)?;
969 let mut result = super::core::diff_trees_with_renames_for_pathspecs_and_policy_result(
970 odb,
971 Some(&base_tree),
972 Some(&tip_tree),
973 "",
974 pathspecs,
975 pathspec_matcher.as_ref(),
976 rename_threshold,
977 config,
978 thread_policy,
979 )?;
980 sort_entries_by_path(&mut result.entries);
981 Ok(result)
982}
983
984#[allow(clippy::too_many_arguments)]
985fn tree_commit_changes(
986 repo: &Repository,
987 base: &ObjectId,
988 tip: &ObjectId,
989 pathspecs: &[String],
990 config: &ConfigSet,
991 thread_policy: &ThreadPolicy,
992 diff_options: DiffOptions,
993 rename_threshold: u32,
994) -> Result<Vec<TreeDiffStructured>> {
995 let result = tree_commit_diff_entries(
996 repo,
997 base,
998 tip,
999 pathspecs,
1000 config,
1001 thread_policy,
1002 rename_threshold,
1003 )?;
1004 tree_diff_structured_parallel(
1005 repo.odb(),
1006 result.entries,
1007 config,
1008 thread_policy,
1009 diff_options,
1010 )
1011}
1012
1013fn commit_diff_entries(
1014 repo: &Repository,
1015 oid: &ObjectId,
1016 pathspecs: &[String],
1017 config: &ConfigSet,
1018 thread_policy: &ThreadPolicy,
1019 rename_threshold: u32,
1020) -> Result<super::core::DiffEntriesResult> {
1021 let commit = repo.read_commit_with_replace(oid)?;
1022 let new_tree = commit.tree;
1023 let parent_ctx = crate::shallow::EffectiveCommitParents::load(repo);
1024 let effective_parents = parent_ctx.for_commit(*oid, &commit.parents);
1025 let old_tree = match effective_parents.first() {
1026 Some(parent) => Some(repo.read_commit_with_replace(parent)?.tree),
1027 None => None,
1028 };
1029
1030 let pathspec_matcher = pathspec_matcher_for_stored_diff(repo, pathspecs)?;
1031 let mut result = super::core::diff_trees_with_renames_for_pathspecs_and_policy_result(
1032 repo.odb(),
1033 old_tree.as_ref(),
1034 Some(&new_tree),
1035 "",
1036 pathspecs,
1037 pathspec_matcher.as_ref(),
1038 rename_threshold,
1039 config,
1040 thread_policy,
1041 )?;
1042 sort_entries_by_path(&mut result.entries);
1043 Ok(result)
1044}
1045
1046#[allow(clippy::too_many_arguments)]
1047fn commit_changes(
1048 repo: &Repository,
1049 oid: &ObjectId,
1050 pathspecs: &[String],
1051 config: &ConfigSet,
1052 thread_policy: &ThreadPolicy,
1053 diff_options: DiffOptions,
1054 rename_threshold: u32,
1055) -> Result<Vec<TreeDiffStructured>> {
1056 let result = commit_diff_entries(
1057 repo,
1058 oid,
1059 pathspecs,
1060 config,
1061 thread_policy,
1062 rename_threshold,
1063 )?;
1064 tree_diff_structured_parallel(
1065 repo.odb(),
1066 result.entries,
1067 config,
1068 thread_policy,
1069 diff_options,
1070 )
1071}
1072
1073fn empty_tree_to_side_diff_entries(
1074 repo: &Repository,
1075 side: &ObjectId,
1076 pathspecs: &[String],
1077 config: &ConfigSet,
1078 thread_policy: &ThreadPolicy,
1079 rename_threshold: u32,
1080) -> Result<super::core::DiffEntriesResult> {
1081 let tip_tree = super::core::tree_oid_for_diff_side(repo.odb(), side)?;
1082 let pathspec_matcher = pathspec_matcher_for_stored_diff(repo, pathspecs)?;
1083 let mut result = super::core::diff_trees_with_renames_for_pathspecs_and_policy_result(
1084 repo.odb(),
1085 None,
1086 Some(&tip_tree),
1087 "",
1088 pathspecs,
1089 pathspec_matcher.as_ref(),
1090 rename_threshold,
1091 config,
1092 thread_policy,
1093 )?;
1094 sort_entries_by_path(&mut result.entries);
1095 Ok(result)
1096}
1097
1098#[allow(clippy::too_many_arguments)]
1099fn empty_tree_to_side_changes(
1100 repo: &Repository,
1101 side: &ObjectId,
1102 pathspecs: &[String],
1103 config: &ConfigSet,
1104 thread_policy: &ThreadPolicy,
1105 diff_options: DiffOptions,
1106 rename_threshold: u32,
1107) -> Result<Vec<TreeDiffStructured>> {
1108 let result = empty_tree_to_side_diff_entries(
1109 repo,
1110 side,
1111 pathspecs,
1112 config,
1113 thread_policy,
1114 rename_threshold,
1115 )?;
1116 tree_diff_structured_parallel(
1117 repo.odb(),
1118 result.entries,
1119 config,
1120 thread_policy,
1121 diff_options,
1122 )
1123}
1124
1125fn peel_diff_commit(repo: &Repository, oid: ObjectId) -> ResolveResult<ObjectId> {
1126 Ok(peel_tags_to_commit(repo, oid)?
1127 .map_err(|oid| ResolveDiffArgumentsError::NotACommit { oid })?)
1128}
1129
1130fn resolve_diff_commit(repo: &Repository, spec: &str) -> ResolveResult<ObjectId> {
1132 let oid = resolve_revision(repo, spec).map_err(|err| match err {
1133 crate::error::Error::Revision(source) => ResolveDiffArgumentsError::UnresolvedRevision {
1134 spec: spec.to_owned(),
1135 source: Box::new(source),
1136 }
1137 .into(),
1138 other => other,
1139 })?;
1140 peel_diff_commit(repo, oid)
1141}
1142
1143fn resolve_diff_range_end(repo: &Repository, spec: &str) -> ResolveResult<ObjectId> {
1145 let spec = if spec.is_empty() { "HEAD" } else { spec };
1146 peel_diff_commit(repo, resolve_revision_for_range_end(repo, spec)?)
1147}
1148
1149fn parse_commit_range(
1151 repo: &Repository,
1152 spec: &str,
1153) -> ResolveResult<Option<(ObjectId, ObjectId)>> {
1154 if let Some((left, right)) = split_triple_dot_range(spec) {
1155 let left = resolve_diff_range_end(repo, left)?;
1156 let right = resolve_diff_range_end(repo, right)?;
1157 let base = merge_base_for_diff_two_commits(repo, left, right)?;
1158 return Ok(Some((base, right)));
1159 }
1160 let Some((left, right)) = split_double_dot_range(spec) else {
1161 return Ok(None);
1162 };
1163 Ok(Some((
1164 resolve_diff_range_end(repo, left)?,
1165 resolve_diff_range_end(repo, right)?,
1166 )))
1167}
1168
1169pub(crate) type UnstagedDiffWithPeers = (
1171 Vec<FileDiff>,
1172 std::collections::HashMap<String, Vec<StructuredHunk>>,
1173);
1174
1175pub(crate) type UnstagedRawWithPeers = (
1176 Vec<FileChange>,
1177 std::collections::HashMap<String, Vec<StructuredHunk>>,
1178);
1179
1180pub(crate) fn unstaged_raw_changes_with_peer_hunks(
1182 repo: &Repository,
1183 pathspecs: &[String],
1184 opts: DiffOptions,
1185) -> Result<UnstagedRawWithPeers> {
1186 let mut index = repo.load_index()?;
1187 unstaged_raw_changes_with_peer_hunks_in(repo, &mut index, pathspecs, opts)
1188}
1189
1190pub(crate) fn unstaged_raw_changes_with_peer_hunks_in(
1194 repo: &Repository,
1195 index: &mut Index,
1196 pathspecs: &[String],
1197 opts: DiffOptions,
1198) -> Result<UnstagedRawWithPeers> {
1199 let rename_threshold = opts.renames.threshold_percent().unwrap_or(101);
1200 let literal_paths = exact_literal_pathspec_set(pathspecs, PathspecMatchContext::default());
1201 let head_tree = match literal_paths {
1202 Some(_) => resolve_head_for_repository(repo)?.tree(repo.odb())?,
1203 None => None,
1204 };
1205 let peer_hunks = staged_peer_hunks_for_pathspecs(
1206 repo,
1207 index,
1208 head_tree,
1209 literal_paths.as_ref(),
1210 pathspecs,
1211 opts.clone(),
1212 rename_threshold,
1213 )?;
1214 let restrict = literal_paths.filter(|paths| {
1215 paths
1216 .iter()
1217 .all(|p| path_is_exact_tracked_file(repo, index, head_tree, p).unwrap_or(false))
1218 });
1219 let unstaged = if let Some(paths) = restrict {
1220 unstaged_changes_inner(repo, index, rename_threshold, Some(Arc::new(paths)))?
1221 } else {
1222 filter_file_changes(
1223 unstaged_changes_inner(repo, index, rename_threshold, None)?,
1224 repo,
1225 pathspecs,
1226 )?
1227 };
1228 Ok((unstaged, peer_hunks))
1229}
1230
1231fn path_has_staged_delta_vs_head_with_index(
1232 repo: &Repository,
1233 index: &Index,
1234 head_tree: Option<ObjectId>,
1235 path: &str,
1236) -> Result<bool> {
1237 let path_bytes = path.as_bytes();
1238 if index.get(path_bytes, 2).is_some() || index.get(path_bytes, 3).is_some() {
1239 return Ok(true);
1240 }
1241 let head_blob = match head_tree {
1242 Some(tree) => repo
1243 .odb()
1244 .tree_entry_at_path(&tree, path_bytes)?
1245 .map(|e| e.oid),
1246 None => None,
1247 };
1248 let Some(idx_entry) = index.get(path_bytes, 0) else {
1249 return Ok(head_blob.is_some());
1250 };
1251 match head_blob {
1252 None => Ok(true),
1253 Some(h) => Ok(idx_entry.oid != h),
1254 }
1255}
1256
1257fn path_is_exact_tracked_file(
1258 repo: &Repository,
1259 index: &Index,
1260 head_tree: Option<ObjectId>,
1261 path: &str,
1262) -> Result<bool> {
1263 let path_bytes = path.as_bytes();
1264 if let Some(entry) = index.get(path_bytes, 0) {
1265 return Ok(entry.mode != MODE_TREE);
1266 }
1267 match head_tree {
1268 Some(tree) => Ok(repo.odb().tree_entry_at_path(&tree, path_bytes)?.is_some()),
1269 None => Ok(false),
1270 }
1271}
1272
1273fn staged_peer_hunks_for_pathspecs(
1276 repo: &Repository,
1277 index: &Index,
1278 head_tree: Option<ObjectId>,
1279 literal_paths: Option<&BTreeSet<String>>,
1280 pathspecs: &[String],
1281 opts: DiffOptions,
1282 rename_threshold: u32,
1283) -> Result<std::collections::HashMap<String, Vec<StructuredHunk>>> {
1284 if let Some(literal_paths) = literal_paths {
1285 let all_exact_files = literal_paths
1286 .iter()
1287 .all(|p| path_is_exact_tracked_file(repo, index, head_tree, p).unwrap_or(false));
1288 if all_exact_files
1289 && literal_paths.iter().all(|p| {
1290 path_has_staged_delta_vs_head_with_index(repo, index, head_tree, p)
1291 .map(|delta| !delta)
1292 .unwrap_or(false)
1293 })
1294 {
1295 return Ok(std::collections::HashMap::new());
1296 }
1297 }
1298 let staged = filter_file_changes(
1299 staged_changes(repo, rename_threshold, None)?,
1300 repo,
1301 pathspecs,
1302 )?;
1303 Ok(staged
1304 .iter()
1305 .map(|fc| {
1306 let structured = fc.structured(opts.clone());
1307 (fc.path.clone(), structured.hunks)
1308 })
1309 .collect())
1310}
1311
1312pub(crate) fn unstaged_file_diffs_with_peer_hunks(
1314 repo: &Repository,
1315 pathspecs: &[String],
1316 opts: DiffOptions,
1317) -> Result<UnstagedDiffWithPeers> {
1318 let config = repo.config().snapshot()?;
1319 let thread_policy = repo.thread_policy();
1320 let rename_threshold = opts.renames.threshold_percent().unwrap_or(101);
1321 let staged = filter_file_changes(
1322 staged_changes(repo, rename_threshold, None)?,
1323 repo,
1324 pathspecs,
1325 )?;
1326 let peer_hunks: std::collections::HashMap<String, Vec<StructuredHunk>> = staged
1327 .iter()
1328 .map(|fc| {
1329 let structured = fc.structured(opts.clone());
1330 (fc.path.clone(), structured.hunks)
1331 })
1332 .collect();
1333 let unstaged = filter_file_changes(
1334 unstaged_changes(repo, rename_threshold, pathspecs)?,
1335 repo,
1336 pathspecs,
1337 )?;
1338 let files = file_diffs_from_worktree_changes(unstaged, &config, &thread_policy, opts)?;
1339 Ok((files, peer_hunks))
1340}
1341
1342pub struct HunkDiffBundle {
1344 pub unstaged: Vec<FileDiff>,
1346 pub peer_hunks: std::collections::HashMap<String, Vec<StructuredHunk>>,
1348}
1349
1350pub(crate) fn hunk_diff_bundle(
1359 repo: &Repository,
1360 pathspec: &Pathspec,
1361 opts: DiffOptions,
1362) -> Result<HunkDiffBundle> {
1363 let config = repo.config().snapshot()?;
1364 let thread_policy = repo.thread_policy();
1365 let (unstaged_fc, peer_hunks) =
1366 unstaged_raw_changes_with_peer_hunks(repo, pathspec.specs(), opts.clone())?;
1367 let unstaged = file_diffs_from_worktree_changes(unstaged_fc, &config, &thread_policy, opts)?;
1368 Ok(HunkDiffBundle {
1369 unstaged,
1370 peer_hunks,
1371 })
1372}
1373
1374#[cfg(test)]
1375mod tests {
1376 use super::*;
1377
1378 #[test]
1379 fn include_file_omits_whitespace_only_modified() {
1380 let file = FileDiff {
1381 path: "x.txt".into(),
1382 old_path: None,
1383 status: DiffStatus::Modified,
1384 old_mode: Some("100644".into()),
1385 new_mode: Some("100644".into()),
1386 old_oid: ObjectId::from_hex("0000000000000000000000000000000000000001").unwrap(),
1387 new_oid: ObjectId::from_hex("0000000000000000000000000000000000000002").unwrap(),
1388 binary: false,
1389 old_size: 0,
1390 new_size: 0,
1391 content_changed: true,
1392 old_encoding_lossy: false,
1393 new_encoding_lossy: false,
1394 hunks: Vec::new(),
1395 line_stat: None,
1396 };
1397 let opts =
1398 DiffOptions::default().with_whitespace(crate::diff::WhitespaceMode::ignore_all_space());
1399 assert!(!include_file_in_diff(&file, &opts));
1400 }
1401
1402 #[test]
1403 fn include_file_omits_ws_only_even_when_content_changed_false() {
1404 let oid = ObjectId::from_hex("0000000000000000000000000000000000000001").unwrap();
1405 let file = FileDiff {
1406 path: "x.txt".into(),
1407 old_path: None,
1408 status: DiffStatus::Modified,
1409 old_mode: Some("100644".into()),
1410 new_mode: Some("100644".into()),
1411 old_oid: oid,
1412 new_oid: oid,
1413 binary: false,
1414 old_size: 0,
1415 new_size: 0,
1416 content_changed: false,
1417 old_encoding_lossy: false,
1418 new_encoding_lossy: false,
1419 hunks: Vec::new(),
1420 line_stat: None,
1421 };
1422 let opts =
1423 DiffOptions::default().with_whitespace(crate::diff::WhitespaceMode::ignore_all_space());
1424 assert!(!include_file_in_diff(&file, &opts));
1425 }
1426
1427 #[test]
1428 fn include_file_keeps_mode_only_under_whitespace() {
1429 let oid = ObjectId::from_hex("0000000000000000000000000000000000000001").unwrap();
1430 let file = FileDiff {
1431 path: "x.txt".into(),
1432 old_path: None,
1433 status: DiffStatus::Modified,
1434 old_mode: Some("100644".into()),
1435 new_mode: Some("100755".into()),
1436 old_oid: oid,
1437 new_oid: oid,
1438 binary: false,
1439 old_size: 0,
1440 new_size: 0,
1441 content_changed: false,
1442 old_encoding_lossy: false,
1443 new_encoding_lossy: false,
1444 hunks: Vec::new(),
1445 line_stat: None,
1446 };
1447 let opts =
1448 DiffOptions::default().with_whitespace(crate::diff::WhitespaceMode::ignore_all_space());
1449 assert!(include_file_in_diff(&file, &opts));
1450 }
1451
1452 #[test]
1453 fn include_file_keeps_whitespace_only_rename() {
1454 let file = FileDiff {
1455 path: "new.txt".into(),
1456 old_path: Some("old.txt".into()),
1457 status: DiffStatus::Renamed,
1458 old_mode: Some("100644".into()),
1459 new_mode: Some("100644".into()),
1460 old_oid: ObjectId::from_hex("0000000000000000000000000000000000000001").unwrap(),
1461 new_oid: ObjectId::from_hex("0000000000000000000000000000000000000001").unwrap(),
1462 binary: false,
1463 old_size: 0,
1464 new_size: 0,
1465 content_changed: false,
1466 old_encoding_lossy: false,
1467 new_encoding_lossy: false,
1468 hunks: Vec::new(),
1469 line_stat: None,
1470 };
1471 let opts =
1472 DiffOptions::default().with_whitespace(crate::diff::WhitespaceMode::ignore_all_space());
1473 assert!(include_file_in_diff(&file, &opts));
1474 }
1475
1476 #[test]
1477 fn worktree_targets_have_no_stored_entries() {
1478 let dir = tempfile::tempdir().expect("tempdir");
1479 let (repo, _) =
1480 Repository::init(dir.path(), &crate::repo::InitOptions::default()).expect("init");
1481 for target in [
1482 DiffTarget::WorktreeVsHead,
1483 DiffTarget::WorktreeVsTree(ObjectId::zero()),
1484 DiffTarget::IndexVsHead,
1485 DiffTarget::WorktreeVsIndex,
1486 ] {
1487 let entries = stored_target_entries(&repo, &target, &[], &DiffOptions::default())
1488 .expect("no object reads");
1489 assert_eq!(entries, None, "{target:?}");
1490 }
1491 }
1492
1493 #[test]
1494 fn limit_target_entries_applies_pathspecs_then_diff_filter() {
1495 let dir = tempfile::tempdir().expect("tempdir");
1496 let (repo, _) =
1497 Repository::init(dir.path(), &crate::repo::InitOptions::default()).expect("init");
1498 let entry = |status: DiffStatus, path: &str| DiffEntry {
1499 status,
1500 old_path: (status != DiffStatus::Added).then(|| path.to_owned()),
1501 new_path: (status != DiffStatus::Deleted).then(|| path.to_owned()),
1502 old_mode: FileMode::REGULAR,
1503 new_mode: FileMode::REGULAR,
1504 old_oid: ObjectId::zero(),
1505 new_oid: ObjectId::zero(),
1506 score: None,
1507 };
1508 let entries = crate::diff::DiffEntriesResult {
1509 entries: vec![
1510 entry(DiffStatus::Added, "a.txt"),
1511 entry(DiffStatus::Deleted, "dir/b.txt"),
1512 entry(DiffStatus::Modified, "dir/c.rs"),
1513 ],
1514 ..Default::default()
1515 };
1516 let paths = |kept: Vec<DiffEntry>| -> Vec<String> {
1517 kept.iter()
1518 .map(|e| {
1519 e.new_path
1520 .clone()
1521 .or(e.old_path.clone())
1522 .unwrap_or_default()
1523 })
1524 .collect()
1525 };
1526 let all = DiffOptions::default();
1527 let kept = limit_target_entries(&repo, entries.clone(), &[], &all).expect("limit");
1528 assert_eq!(paths(kept.entries), ["a.txt", "dir/b.txt", "dir/c.rs"]);
1529
1530 let kept =
1531 limit_target_entries(&repo, entries.clone(), &["dir".to_owned()], &all).expect("dir");
1532 assert_eq!(paths(kept.entries), ["dir/b.txt", "dir/c.rs"]);
1533
1534 let added_or_deleted = all.with_filter(Some("AD".parse().expect("filter")));
1535 let kept =
1536 limit_target_entries(&repo, entries.clone(), &[], &added_or_deleted).expect("filter");
1537 assert_eq!(paths(kept.entries), ["a.txt", "dir/b.txt"]);
1538
1539 let kept = limit_target_entries(&repo, entries, &["dir".to_owned()], &added_or_deleted)
1540 .expect("both");
1541 assert_eq!(paths(kept.entries), ["dir/b.txt"]);
1542 }
1543
1544 #[test]
1545 fn failed_revision_with_file_paths_keeps_revision_error() {
1546 let dir = tempfile::tempdir().expect("tempdir");
1547 let (repo, _) =
1548 Repository::init(dir.path(), &crate::repo::InitOptions::default()).expect("init");
1549 let request = DiffRequest {
1550 positionals: vec!["unknown-revision".into()],
1551 pathspec_file: Some(vec!["selected.txt".into()]),
1552 ..DiffRequest::default()
1553 };
1554 let err = resolve_diff_request(&repo, None, &request).expect_err("unknown revision");
1555 assert!(
1556 matches!(err, crate::error::Error::Diff(DiffError::Arguments(ResolveDiffArgumentsError::UnresolvedRevision { spec, .. })) if spec == "unknown-revision")
1557 );
1558 }
1559
1560 #[test]
1561 fn resolve_errors_staged_and_unstaged() {
1562 let dir = tempfile::tempdir().expect("tempdir");
1563 let (repo, _) =
1564 crate::repo::Repository::init(dir.path(), &crate::repo::InitOptions::default())
1565 .expect("init");
1566 let request = DiffRequest {
1567 staged: true,
1568 unstaged: true,
1569 ..DiffRequest::default()
1570 };
1571 let err = resolve_diff_request(&repo, None, &request).unwrap_err();
1572 assert!(matches!(
1573 err,
1574 crate::error::Error::Diff(DiffError::Arguments(
1575 ResolveDiffArgumentsError::StagedAndUnstaged
1576 ))
1577 ));
1578 }
1579}