duodiff 0.7.0

A fast, cross-platform terminal user interface (TUI) directory comparison tool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use std::path::Path;
use std::process::Command;

pub static TEST_MUTEX: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ExternalDiffTool {
    Vim,
    Nvim,
    Code,
    Meld,
    BeyondCompare,
    SublimeMerge,
    Kaleidoscope,
    Difftastic,
}

/// The fixed, documented, platform-aware priority list of supported external diff tools.
pub const SUPPORTED_TOOLS: [ExternalDiffTool; 8] = [
    ExternalDiffTool::Vim,
    ExternalDiffTool::Nvim,
    ExternalDiffTool::Code,
    ExternalDiffTool::Meld,
    ExternalDiffTool::BeyondCompare,
    ExternalDiffTool::SublimeMerge,
    ExternalDiffTool::Kaleidoscope,
    ExternalDiffTool::Difftastic,
];

impl ExternalDiffTool {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Vim => "vim",
            Self::Nvim => "nvim",
            Self::Code => "code",
            Self::Meld => "meld",
            Self::BeyondCompare => "bcomp",
            Self::SublimeMerge => "smerge",
            Self::Kaleidoscope => "ksdiff",
            Self::Difftastic => "difft",
        }
    }

    pub fn is_available(&self) -> bool {
        is_tool_available(*self)
    }
}

impl std::str::FromStr for ExternalDiffTool {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_lowercase().as_str() {
            "vim" => Ok(Self::Vim),
            "nvim" => Ok(Self::Nvim),
            "code" => Ok(Self::Code),
            "meld" => Ok(Self::Meld),
            "bcomp" | "beyondcompare" => Ok(Self::BeyondCompare),
            "smerge" | "sublimemerge" => Ok(Self::SublimeMerge),
            "ksdiff" | "kaleidoscope" => Ok(Self::Kaleidoscope),
            "difft" | "difftastic" => Ok(Self::Difftastic),
            _ => Err(()),
        }
    }
}

impl ExternalDiffTool {
    pub fn diff_args(&self) -> &'static [&'static str] {
        match self {
            Self::Vim => &["-d"],
            Self::Nvim => &["-d"],
            Self::Code => &["--diff"],
            Self::Meld => &[],
            Self::BeyondCompare => &[],
            Self::SublimeMerge => &["diff"],
            Self::Kaleidoscope => &[],
            Self::Difftastic => &[],
        }
    }
}

#[cfg(unix)]
pub fn is_executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    if let Ok(meta) = path.metadata() {
        meta.is_file() && (meta.permissions().mode() & 0o111 != 0)
    } else {
        false
    }
}

#[cfg(windows)]
pub fn is_executable(path: &Path) -> bool {
    if let Ok(meta) = path.metadata() {
        meta.is_file()
    } else {
        false
    }
}

#[cfg(not(any(unix, windows)))]
pub fn is_executable(path: &Path) -> bool {
    path.is_file()
}

pub fn find_executable_in_dir(dir: &Path, cmd: &str) -> Option<std::path::PathBuf> {
    #[cfg(windows)]
    {
        let direct = dir.join(cmd);
        if direct.extension().is_some() && is_executable(&direct) {
            return Some(direct);
        }
        let pathext =
            std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string());
        for ext in pathext.split(';') {
            let ext = ext.trim();
            if ext.is_empty() {
                continue;
            }
            let ext_normalized = if ext.starts_with('.') { &ext[1..] } else { ext };
            let candidate = dir.join(format!("{cmd}.{ext_normalized}"));
            if is_executable(&candidate) {
                return Some(candidate);
            }
        }
        None
    }
    #[cfg(not(windows))]
    {
        let candidate = dir.join(cmd);
        if is_executable(&candidate) {
            Some(candidate)
        } else {
            None
        }
    }
}

pub fn resolve_executable(cmd: &str) -> Option<std::path::PathBuf> {
    let cmd_path = Path::new(cmd);
    if cmd_path.components().count() > 1 {
        if is_executable(cmd_path) {
            return Some(cmd_path.to_path_buf());
        }
        #[cfg(windows)]
        if cmd_path.extension().is_none() {
            if let Some(parent) = cmd_path.parent() {
                let file_name = cmd_path.file_name()?.to_str()?;
                return find_executable_in_dir(parent, file_name);
            }
        }
        return None;
    }

    if let Ok(path) = std::env::var("PATH") {
        for dir in std::env::split_paths(&path) {
            if let Some(found) = find_executable_in_dir(&dir, cmd) {
                return Some(found);
            }
        }
    }
    None
}

pub fn find_in_path(cmd: &str) -> bool {
    resolve_executable(cmd).is_some()
}

pub fn is_tool_available(tool: ExternalDiffTool) -> bool {
    find_in_path(tool.as_str())
}

pub fn detect_diff_tools() -> Vec<(ExternalDiffTool, bool)> {
    SUPPORTED_TOOLS
        .iter()
        .map(|tool| (*tool, is_tool_available(*tool)))
        .collect()
}

pub fn open_diff(
    tool: &ExternalDiffTool,
    left_path: &Path,
    right_path: &Path,
) -> Result<(), std::io::Error> {
    let mut command = Command::new(tool.as_str());
    for arg in tool.diff_args() {
        command.arg(arg);
    }
    command.arg(left_path);
    command.arg(right_path);

    let mut child = command
        .stdin(std::process::Stdio::inherit())
        .stdout(std::process::Stdio::inherit())
        .stderr(std::process::Stdio::inherit())
        .spawn()?;
    child.wait()?;
    Ok(())
}

/// GUI editors fork and return immediately unless given a "wait" flag, so `Command::wait()`
/// returns before the user saves and duodiff resumes on stale content. Keyed by basename so a
/// full path or a `.exe` suffix still matches.
fn editor_is_gui(program: &str) -> bool {
    let basename = program.rsplit(['/', '\\']).next().unwrap_or(program);
    let base = Path::new(basename)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or(basename)
        .to_ascii_lowercase();
    matches!(
        base.as_str(),
        "code"
            | "code-insiders"
            | "codium"
            | "vscodium"
            | "cursor"
            | "windsurf"
            | "zed"
            | "subl"
            | "sublime_text"
    )
}

/// Splits a `$VISUAL`/`$EDITOR` string into `(program, args)`, injecting a wait flag for known
/// GUI editors that don't already have one. Terminal editors are left untouched. Returns `None`
/// only when the string is blank (no program).
fn editor_command(editor: &str) -> Option<(String, Vec<String>)> {
    let mut parts = editor.split_whitespace();
    let program = parts.next()?.to_string();
    let mut args: Vec<String> = parts.map(str::to_string).collect();

    if editor_is_gui(&program) && !args.iter().any(|a| a == "--wait" || a == "-w") {
        args.push("--wait".to_string());
    }

    Some((program, args))
}

// Keep the compatibility for open_editor as it might be used elsewhere (like editing single files)
pub fn open_editor(file_path: &Path) -> Result<(), std::io::Error> {
    let editor_var = std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| "vim".to_string());
    let Some((program, args)) = editor_command(&editor_var) else {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "VISUAL or EDITOR is empty",
        ));
    };
    let mut command = Command::new(program);
    command.args(&args);
    command.arg(file_path);
    let mut child = command
        .stdin(std::process::Stdio::inherit())
        .stdout(std::process::Stdio::inherit())
        .stderr(std::process::Stdio::inherit())
        .spawn()?;
    child.wait()?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_open_editor_success() {
        let _guard = crate::test_support::lock_env_tests();
        std::env::remove_var("VISUAL");
        #[cfg(not(target_os = "windows"))]
        std::env::set_var("EDITOR", "true");
        #[cfg(target_os = "windows")]
        std::env::set_var("EDITOR", "cargo --version");
        let result = open_editor(Path::new("dummy"));
        assert!(result.is_ok());
    }

    #[test]
    fn test_open_editor_visual_preference() {
        let _guard = crate::test_support::lock_env_tests();
        #[cfg(not(target_os = "windows"))]
        {
            std::env::set_var("VISUAL", "true");
            std::env::set_var("EDITOR", "non_existent_command_xyz");
        }
        #[cfg(target_os = "windows")]
        {
            std::env::set_var("VISUAL", "cargo --version");
            std::env::set_var("EDITOR", "non_existent_command_xyz");
        }
        let result = open_editor(Path::new("dummy"));
        assert!(result.is_ok());
    }

    #[test]
    fn editor_command_injects_wait_for_gui_editors() {
        for ed in ["zed", "code", "code-insiders", "cursor", "windsurf", "subl"] {
            let (program, args) = editor_command(ed).unwrap();
            assert_eq!(program, ed);
            assert!(
                args.iter().any(|a| a == "--wait" || a == "-w"),
                "expected a wait flag for GUI editor {ed:?}, got {args:?}"
            );
        }
    }

    #[test]
    fn editor_command_matches_gui_editor_by_basename() {
        let (program, args) = editor_command("/usr/local/bin/zed -n").unwrap();
        assert_eq!(program, "/usr/local/bin/zed");
        assert_eq!(args, vec!["-n", "--wait"]);
    }

    #[test]
    fn editor_command_leaves_terminal_editors_untouched() {
        for ed in ["vi", "vim", "nvim", "nano", "emacs", "hx"] {
            let (program, args) = editor_command(ed).unwrap();
            assert_eq!(program, ed);
            assert!(
                args.is_empty(),
                "terminal editor {ed:?} should get no injected flag, got {args:?}"
            );
        }
    }

    #[test]
    fn editor_command_keeps_an_existing_wait_flag() {
        let (_, args) = editor_command("code --wait").unwrap();
        assert_eq!(args, vec!["--wait"]);
        let (_, args) = editor_command("subl -w").unwrap();
        assert_eq!(args, vec!["-w"]);
    }

    #[test]
    fn editor_command_blank_is_none() {
        assert!(editor_command("").is_none());
        assert!(editor_command("   ").is_none());
    }

    #[test]
    fn editor_is_gui_matches_known_gui_editors() {
        for ed in [
            "zed",
            "code",
            "code-insiders",
            "codium",
            "vscodium",
            "cursor",
            "windsurf",
            "subl",
            "sublime_text",
        ] {
            assert!(
                editor_is_gui(ed),
                "{ed} should be recognised as a GUI editor"
            );
        }
    }

    #[test]
    fn editor_is_gui_rejects_terminal_editors() {
        for ed in ["vi", "vim", "nvim", "nano", "emacs", "hx"] {
            assert!(
                !editor_is_gui(ed),
                "{ed} should not be recognised as a GUI editor"
            );
        }
    }

    #[test]
    fn editor_is_gui_matches_by_basename_from_full_path() {
        assert!(editor_is_gui("/usr/local/bin/zed"));
        assert!(editor_is_gui("C:\\Tools\\code.exe"));
    }

    #[test]
    fn test_diff_tool_conversions() {
        use std::str::FromStr;
        assert_eq!(ExternalDiffTool::from_str("vim"), Ok(ExternalDiffTool::Vim));
        assert_eq!(
            ExternalDiffTool::from_str("Nvim"),
            Ok(ExternalDiffTool::Nvim)
        );
        assert_eq!(
            ExternalDiffTool::from_str("code"),
            Ok(ExternalDiffTool::Code)
        );
        assert_eq!(
            ExternalDiffTool::from_str("meld"),
            Ok(ExternalDiffTool::Meld)
        );
        assert_eq!(
            ExternalDiffTool::from_str("bcomp"),
            Ok(ExternalDiffTool::BeyondCompare)
        );
        assert_eq!(
            ExternalDiffTool::from_str("smerge"),
            Ok(ExternalDiffTool::SublimeMerge)
        );
        assert_eq!(
            ExternalDiffTool::from_str("ksdiff"),
            Ok(ExternalDiffTool::Kaleidoscope)
        );
        assert_eq!(
            ExternalDiffTool::from_str("difft"),
            Ok(ExternalDiffTool::Difftastic)
        );
        assert_eq!(ExternalDiffTool::from_str("unknown"), Err(()));
    }

    #[test]
    fn test_supported_tools_order_is_stable() {
        assert_eq!(
            SUPPORTED_TOOLS,
            [
                ExternalDiffTool::Vim,
                ExternalDiffTool::Nvim,
                ExternalDiffTool::Code,
                ExternalDiffTool::Meld,
                ExternalDiffTool::BeyondCompare,
                ExternalDiffTool::SublimeMerge,
                ExternalDiffTool::Kaleidoscope,
                ExternalDiffTool::Difftastic,
            ]
        );
    }

    #[test]
    fn test_resolve_executable_in_custom_path() {
        let temp = tempfile::tempdir().unwrap();
        let bin_dir = temp.path().join("bin");
        std::fs::create_dir_all(&bin_dir).unwrap();

        // Non-executable file on Unix / directory
        let sub_dir = bin_dir.join("dirtool");
        std::fs::create_dir_all(&sub_dir).unwrap();

        #[cfg(unix)]
        {
            let non_exec = bin_dir.join("nonexec");
            std::fs::write(&non_exec, "echo hello").unwrap();

            let exec = bin_dir.join("myexec");
            std::fs::write(&exec, "#!/bin/sh\necho hi").unwrap();
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&exec).unwrap().permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&exec, perms).unwrap();

            let _guard = crate::test_support::PathEnvGuard::set(&bin_dir);
            assert!(!find_in_path("nonexec"));
            assert!(!find_in_path("dirtool"));
            assert!(find_in_path("myexec"));
            assert_eq!(resolve_executable("myexec"), Some(exec));
        }

        #[cfg(windows)]
        {
            let exec_exe = bin_dir.join("myexec.exe");
            std::fs::write(&exec_exe, "binary").unwrap();
            let exec_bat = bin_dir.join("mybat.bat");
            std::fs::write(&exec_bat, "@echo off").unwrap();

            let _guard = crate::test_support::PathEnvGuard::set(&bin_dir);
            assert!(!find_in_path("dirtool"));
            assert!(find_in_path("myexec"));
            let resolved_exec = resolve_executable("myexec").expect("myexec should resolve");
            assert_eq!(
                resolved_exec.to_string_lossy().to_lowercase(),
                exec_exe.to_string_lossy().to_lowercase()
            );
            assert!(find_in_path("mybat"));
            let resolved_bat = resolve_executable("mybat").expect("mybat should resolve");
            assert_eq!(
                resolved_bat.to_string_lossy().to_lowercase(),
                exec_bat.to_string_lossy().to_lowercase()
            );
        }
    }
}