Debian Codegraph @

src/subcommands/diff.rs

raw symbols SCIP
1 use std::path::Path;
2
3 use crate::config::{self};
4
5 use crate::utils::git::retrieve_git_version;
6
7 use crate::subcommands::{SubCmdKind, SubCommand};
8 use std::ffi::OsString;
9
10 /// Build `git diff` command for the files provided on the command line. Fall back to
11 /// `diff` if the supplied "files" use process substitution.
12 pub fn build_diff_cmd(
13 minus_file: &Path,
14 plus_file: &Path,
15 config: &config::Config,
16 ) -> Result<SubCommand, i32> {
17 // suppress `dead_code` warning, values are accessed via `get_one::<PathBuf>("plus/minus_file")`
18 debug_assert!(config.minus_file.as_ref().unwrap() == minus_file);
19 debug_assert!(config.plus_file.as_ref().unwrap() == plus_file);
20
21 let mut diff_args = match shell_words::split(config.diff_args.trim()) {
22 Ok(words) => words,
23 Err(err) => {
24 eprintln!("Failed to parse diff args: {}: {err}", config.diff_args);
25 return Err(config.error_exit_code);
26 }
27 };
28 // Permit e.g. -@U1
29 if diff_args
30 .first()
31 .map(|arg| !arg.is_empty() && !arg.starts_with('-'))
32 .unwrap_or(false)
33 {
34 diff_args[0] = format!("-{}", diff_args[0])
35 }
36
37 let via_process_substitution =
38 |f: &Path| f.starts_with("/proc/self/fd/") || f.starts_with("/dev/fd/");
39
40 // https://stackoverflow.com/questions/22706714/why-does-git-diff-not-work-with-process-substitution
41 // git <2.42 does not support process substitution
42 let (differ, mut diff_cmd) = match retrieve_git_version() {
43 Some(version)
44 if version >= (2, 42)
45 || !(via_process_substitution(minus_file)
46 || via_process_substitution(plus_file)) =>
47 {
48 (
49 SubCmdKind::GitDiff,
50 vec!["git", "diff", "--no-index", "--color"],
51 )
52 }
53 _ => (
54 SubCmdKind::Diff,
55 if diff_args_set_unified_context(&diff_args) {
56 vec!["diff"]
57 } else {
58 vec!["diff", "-U3"]
59 },
60 ),
61 };
62
63 diff_cmd.extend(
64 diff_args
65 .iter()
66 .filter(|s| !s.is_empty())
67 .map(String::as_str),
68 );
69 diff_cmd.push("--");
70 let mut diff_cmd = diff_cmd.iter().map(OsString::from).collect::<Vec<_>>();
71 diff_cmd.push(minus_file.into());
72 diff_cmd.push(plus_file.into());
73 Ok(SubCommand::new(differ, diff_cmd))
74 }
75
76 /// Do the user-supplied `diff` args set the unified context?
77 fn diff_args_set_unified_context<I, S>(args: I) -> bool
78 where
79 I: IntoIterator<Item = S>,
80 S: AsRef<str>,
81 {
82 // This function is applied to `diff` args; not `git diff`.
83 for arg in args {
84 let arg = arg.as_ref();
85 if arg == "-u" || arg == "-U" {
86 // diff allows a space after -U (git diff does not)
87 return true;
88 }
89 if (arg.starts_with("-U") || arg.starts_with("-u"))
90 && arg.split_at(2).1.parse::<u32>().is_ok()
91 {
92 return true;
93 }
94 }
95 false
96 }
97
98 #[cfg(test)]
99 mod main_tests {
100 use std::ffi::OsString;
101 use std::io::Cursor;
102
103 use super::diff_args_set_unified_context;
104
105 use rstest::rstest;
106
107 #[rstest]
108 #[case(&["-u"], true)]
109 #[case(&["-u7"], true)]
110 #[case(&["-u77"], true)]
111 #[case(&["-ux"], false)]
112 #[case(&["-U"], true)]
113 #[case(&["-U7"], true)]
114 #[case(&["-U77"], true)]
115 #[case(&["-Ux"], false)]
116 fn test_unified_diff_arg_is_detected_in_diff_args(
117 #[case] diff_args: &[&str],
118 #[case] expected: bool,
119 ) {
120 assert_eq!(diff_args_set_unified_context(diff_args), expected)
121 }
122
123 enum ExpectDiff {
124 Yes,
125 No,
126 }
127
128 #[cfg(not(target_os = "windows"))]
129 #[rstest]
130 // #[case("/dev/null", "/dev/null", ExpectDiff::No)] https://github.com/dandavison/delta/pull/546#issuecomment-835852373
131 #[case("/etc/group", "/etc/passwd", ExpectDiff::Yes)]
132 #[case("/dev/null", "/etc/passwd", ExpectDiff::Yes)]
133 #[case("/etc/passwd", "/etc/passwd", ExpectDiff::No)]
134 fn test_diff_real_files(
135 #[case] file_a: &str,
136 #[case] file_b: &str,
137 #[case] expect_diff: ExpectDiff,
138 #[values(vec![], vec!["-@''"], vec!["-@-u"], vec!["-@-U99"], vec!["-@-U0"])] args: Vec<
139 &str,
140 >,
141 ) {
142 let mut writer = Cursor::new(vec![]);
143 let mut runargs = vec![OsString::from(file_a), OsString::from(file_b)];
144 runargs.extend(args.iter().map(OsString::from));
145 let exit_code = crate::run_app(runargs, Some(&mut writer));
146
147 assert_eq!(
148 exit_code.unwrap(),
149 match expect_diff {
150 ExpectDiff::Yes => 1,
151 ExpectDiff::No => 0,
152 }
153 );
154 assert_eq!(
155 std::str::from_utf8(writer.get_ref()).unwrap() != "",
156 match expect_diff {
157 ExpectDiff::Yes => true,
158 ExpectDiff::No => false,
159 }
160 );
161 }
162 }