perl-subprocess-runtime 0.13.1

Shared subprocess execution abstraction with OS and mock runtimes
Documentation
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//! Subprocess execution abstraction for provider purity
//!
//! This crate provides a trait-based abstraction for subprocess execution,
//! enabling testing with mock implementations and WASM compatibility.

#![deny(unsafe_code)]
#![cfg_attr(test, allow(clippy::panic, clippy::unwrap_used, clippy::expect_used))]
#![warn(rust_2018_idioms)]
#![warn(missing_docs)]
#![warn(clippy::all)]

use std::fmt;
#[cfg(all(not(target_arch = "wasm32"), windows))]
use std::path::Path;

/// Output from a subprocess execution
#[derive(Debug, Clone)]
pub struct SubprocessOutput {
    /// Standard output bytes
    pub stdout: Vec<u8>,
    /// Standard error bytes
    pub stderr: Vec<u8>,
    /// Exit status code (0 typically indicates success)
    pub status_code: i32,
}

impl SubprocessOutput {
    /// Returns true if the subprocess exited successfully (status code 0)
    pub fn success(&self) -> bool {
        self.status_code == 0
    }

    /// Returns stdout as a UTF-8 string, lossy converting invalid bytes
    pub fn stdout_lossy(&self) -> String {
        String::from_utf8_lossy(&self.stdout).into_owned()
    }

    /// Returns stderr as a UTF-8 string, lossy converting invalid bytes
    pub fn stderr_lossy(&self) -> String {
        String::from_utf8_lossy(&self.stderr).into_owned()
    }
}

/// Error type for subprocess execution failures
#[derive(Debug, Clone)]
pub struct SubprocessError {
    /// Human-readable error message
    pub message: String,
}

impl SubprocessError {
    /// Create a new subprocess error with the given message
    pub fn new(message: impl Into<String>) -> Self {
        Self { message: message.into() }
    }
}

impl fmt::Display for SubprocessError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for SubprocessError {}

/// Abstraction trait for subprocess execution.
pub trait SubprocessRuntime: Send + Sync {
    /// Execute a command with the given arguments and optional stdin.
    fn run_command(
        &self,
        program: &str,
        args: &[&str],
        stdin: Option<&[u8]>,
    ) -> Result<SubprocessOutput, SubprocessError>;
}

/// Default implementation using `std::process::Command`.
#[cfg(not(target_arch = "wasm32"))]
pub struct OsSubprocessRuntime {
    timeout_secs: Option<u64>,
}

#[cfg(not(target_arch = "wasm32"))]
impl OsSubprocessRuntime {
    /// Create a new OS subprocess runtime with no timeout.
    pub fn new() -> Self {
        Self { timeout_secs: None }
    }

    /// Create a new OS subprocess runtime with the given wall-clock timeout.
    ///
    /// If the subprocess does not complete within `timeout_secs` seconds the
    /// call returns a `SubprocessError` with a "timed out" message and attempts
    /// to terminate the spawned process before returning.
    ///
    /// # Stdin size caveat
    ///
    /// Stdin data is written synchronously before the timeout poll loop begins.
    /// If the subprocess hangs before consuming stdin and the data exceeds the
    /// OS pipe buffer (~64 KiB on Linux), `run_command` will block in the write
    /// phase and the timeout will not fire.  For typical Perl source files this
    /// is not a concern.
    ///
    /// # Panics
    ///
    /// Panics if `timeout_secs` is zero (a zero-second timeout would time out
    /// every command immediately and is almost certainly a caller bug).
    pub fn with_timeout(timeout_secs: u64) -> Self {
        assert!(timeout_secs > 0, "timeout_secs must be greater than zero");
        Self { timeout_secs: Some(timeout_secs) }
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Default for OsSubprocessRuntime {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl SubprocessRuntime for OsSubprocessRuntime {
    fn run_command(
        &self,
        program: &str,
        args: &[&str],
        stdin: Option<&[u8]>,
    ) -> Result<SubprocessOutput, SubprocessError> {
        use std::io::Write;
        use std::process::{Command, Stdio};

        validate_command_input(program, args)?;

        let (resolved_program, resolved_args) = resolve_command_invocation(program, args);
        let mut cmd = Command::new(&resolved_program);
        cmd.args(resolved_args.iter().map(String::as_str));

        if stdin.is_some() {
            cmd.stdin(Stdio::piped());
        }

        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        let mut child = cmd
            .spawn()
            .map_err(|e| SubprocessError::new(format!("Failed to start {}: {}", program, e)))?;

        if let Some(input) = stdin
            && let Some(mut child_stdin) = child.stdin.take()
        {
            child_stdin.write_all(input).map_err(|e| {
                SubprocessError::new(format!("Failed to write to {} stdin: {}", program, e))
            })?;
        }

        match self.timeout_secs {
            None => {
                let output = child.wait_with_output().map_err(|e| {
                    SubprocessError::new(format!("Failed to wait for {}: {}", program, e))
                })?;
                Ok(SubprocessOutput {
                    stdout: output.stdout,
                    stderr: output.stderr,
                    status_code: output.status.code().unwrap_or(-1),
                })
            }
            Some(secs) => {
                use std::time::{Duration, Instant};

                let deadline = Instant::now() + Duration::from_secs(secs);
                loop {
                    if child
                        .try_wait()
                        .map_err(|e| {
                            SubprocessError::new(format!("Failed to poll {}: {}", program, e))
                        })?
                        .is_some()
                    {
                        let output = child.wait_with_output().map_err(|e| {
                            SubprocessError::new(format!("Failed to wait for {}: {}", program, e))
                        })?;
                        return Ok(SubprocessOutput {
                            stdout: output.stdout,
                            stderr: output.stderr,
                            status_code: output.status.code().unwrap_or(-1),
                        });
                    }

                    if Instant::now() >= deadline {
                        if let Err(kill_err) = child.kill() {
                            // Best effort: process may have already exited between `try_wait`
                            // and `kill`.
                            let already_exited = child
                                .try_wait()
                                .map_err(|e| {
                                    SubprocessError::new(format!(
                                        "Failed to poll {}: {}",
                                        program, e
                                    ))
                                })?
                                .is_some();
                            if !already_exited {
                                return Err(SubprocessError::new(format!(
                                    "subprocess timed out after {} seconds and failed to terminate {}: {}",
                                    secs, program, kill_err
                                )));
                            }
                        }
                        let _ = child.wait();
                        return Err(SubprocessError::new(format!(
                            "subprocess timed out after {} seconds",
                            secs
                        )));
                    }

                    std::thread::sleep(Duration::from_millis(50));
                }
            }
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn validate_command_input(program: &str, args: &[&str]) -> Result<(), SubprocessError> {
    if program.trim().is_empty() {
        return Err(SubprocessError::new("program name must not be empty"));
    }
    if program.contains('\0') {
        return Err(SubprocessError::new("program name must not contain NUL bytes"));
    }
    if args.iter().any(|arg| arg.contains('\0')) {
        return Err(SubprocessError::new("arguments must not contain NUL bytes"));
    }
    Ok(())
}

#[cfg(not(target_arch = "wasm32"))]
fn resolve_command_invocation(program: &str, args: &[&str]) -> (String, Vec<String>) {
    #[cfg(windows)]
    {
        let resolved_program =
            resolve_windows_program(program).unwrap_or_else(|| program.to_string());

        if windows_requires_cmd_shell(&resolved_program) {
            let command_line = std::iter::once(resolved_program.as_str())
                .chain(args.iter().copied())
                .map(windows_quote_for_cmd)
                .collect::<Vec<_>>()
                .join(" ");
            // /D  – disable AutoRun registry commands.
            // /V:OFF – disable delayed expansion so that !VAR! patterns in
            //          arguments are not expanded even when the caller's
            //          environment has delayed expansion enabled.
            // /S  – strip the outer quotes from the /C argument and re-parse
            //        the remainder, which lets each individual token retain its
            //        own double-quoting.
            let shell_args = vec![
                "/D".to_string(),
                "/V:OFF".to_string(),
                "/S".to_string(),
                "/C".to_string(),
                command_line,
            ];
            return ("cmd.exe".to_string(), shell_args);
        }

        (resolved_program, args.iter().map(|arg| (*arg).to_string()).collect())
    }

    #[cfg(not(windows))]
    {
        (program.to_string(), args.iter().map(|arg| (*arg).to_string()).collect())
    }
}

/// Quote a single argument for use inside a `cmd.exe /V:OFF /S /C "..."` command line.
///
/// ## cmd.exe quoting rules inside double-quoted regions
///
/// Once cmd.exe sees an opening `"` it enters a quoted region.  Inside that region:
///
/// - Shell metacharacters (`&`, `|`, `<`, `>`, `(`, `)`) are **literal** — no
///   `^` prefix is needed or correct.  Inserting `^` before them would deliver
///   a spurious `^` character to the program for every argument that legitimately
///   contains one of these characters.
/// - `^` itself is **literal** inside a quoted region.  It is NOT an escape prefix,
///   so it must not be doubled.  The original PR doubled it, which corrupted any
///   argument containing a `^` (e.g. `C:\tools\my^profile.txt` became
///   `C:\tools\my^^profile.txt`).
/// - `%` is still processed by the variable-substitution pass, which runs before
///   the shell-metachar pass and is not suppressed by quoting.  Double it (`%%`)
///   to produce a literal `%`.
/// - `!` would be processed by the delayed-expansion pass when `/V:ON` is in
///   effect.  We invoke cmd.exe with `/V:OFF` to suppress this entirely, so `!`
///   needs no escaping here.
/// - To embed a literal `"` inside a double-quoted cmd.exe token, use `""` (the
///   cmd.exe shell convention).  The `\"` form is for `CommandLineToArgvW` (the
///   Win32 C-runtime argv parser) which is a **different** parser from the
///   cmd.exe shell.  Using `\"` in cmd.exe context causes the shell to treat the
///   `\` as a literal character and the `"` as ending the current quoted region,
///   which breaks argument boundaries and can enable injection.
#[cfg(all(not(target_arch = "wasm32"), windows))]
fn windows_quote_for_cmd(arg: &str) -> String {
    let mut escaped = String::with_capacity(arg.len() + 2);
    escaped.push('"');
    for ch in arg.chars() {
        match ch {
            // % must be doubled: %VAR% expansion runs before the shell-metachar
            // pass and is not suppressed by double-quoting.
            '%' => escaped.push_str("%%"),
            // Use "" (doubled quote) to represent a literal " inside a
            // cmd.exe double-quoted token.  This is the cmd.exe shell convention.
            // The \" form (CommandLineToArgvW convention) would end the quoted
            // region from cmd.exe's perspective and enable injection.
            '"' => escaped.push_str("\"\""),
            // All other characters — including shell metacharacters (&, |, <,
            // >, (, )) and the caret (^) — are already literal inside a
            // double-quoted cmd.exe token.  No escaping is required or correct.
            _ => escaped.push(ch),
        }
    }
    escaped.push('"');
    escaped
}

#[cfg(all(not(target_arch = "wasm32"), windows))]
fn resolve_windows_program(program: &str) -> Option<String> {
    let program_path = Path::new(program);
    let has_separator = program.contains('\\') || program.contains('/');
    let has_extension = program_path.extension().is_some();

    if has_separator || has_extension {
        return Some(program.to_string());
    }

    let output = std::process::Command::new("where")
        .arg(program)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    String::from_utf8(output.stdout)
        .ok()?
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .max_by_key(|candidate| windows_program_priority(candidate))
        .map(String::from)
}

#[cfg(all(not(target_arch = "wasm32"), windows))]
fn windows_program_priority(candidate: &str) -> u8 {
    match Path::new(candidate)
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.to_ascii_lowercase())
    {
        Some(ext) if ext == "exe" => 5,
        Some(ext) if ext == "com" => 4,
        Some(ext) if ext == "cmd" => 3,
        Some(ext) if ext == "bat" => 2,
        Some(_) => 1,
        None => 0,
    }
}

#[cfg(all(not(target_arch = "wasm32"), windows))]
fn windows_requires_cmd_shell(program: &str) -> bool {
    Path::new(program)
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.eq_ignore_ascii_case("bat") || ext.eq_ignore_ascii_case("cmd"))
        .unwrap_or(false)
}

/// Mock subprocess runtime for testing.
pub mod mock {
    use super::*;
    use std::sync::{Arc, Mutex, MutexGuard};

    fn lock<'a, T>(mutex: &'a Mutex<T>) -> MutexGuard<'a, T> {
        match mutex.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }
    }

    /// A recorded command invocation.
    #[derive(Debug, Clone)]
    pub struct CommandInvocation {
        /// The program that was called.
        pub program: String,
        /// The arguments passed.
        pub args: Vec<String>,
        /// The stdin data provided.
        pub stdin: Option<Vec<u8>>,
    }

    /// Builder for mock responses.
    #[derive(Debug, Clone)]
    pub struct MockResponse {
        /// Stdout to return.
        pub stdout: Vec<u8>,
        /// Stderr to return.
        pub stderr: Vec<u8>,
        /// Status code to return.
        pub status_code: i32,
    }

    impl MockResponse {
        /// Create a successful mock response with the given stdout.
        pub fn success(stdout: impl Into<Vec<u8>>) -> Self {
            Self { stdout: stdout.into(), stderr: Vec::new(), status_code: 0 }
        }

        /// Create a failed mock response with the given stderr.
        pub fn failure(stderr: impl Into<Vec<u8>>, status_code: i32) -> Self {
            Self { stdout: Vec::new(), stderr: stderr.into(), status_code }
        }
    }

    /// Mock subprocess runtime for testing.
    pub struct MockSubprocessRuntime {
        invocations: Arc<Mutex<Vec<CommandInvocation>>>,
        responses: Arc<Mutex<Vec<MockResponse>>>,
        default_response: MockResponse,
    }

    impl MockSubprocessRuntime {
        /// Create a new mock runtime with a default successful response.
        pub fn new() -> Self {
            Self {
                invocations: Arc::new(Mutex::new(Vec::new())),
                responses: Arc::new(Mutex::new(Vec::new())),
                default_response: MockResponse::success(Vec::new()),
            }
        }

        /// Add a response to be returned for the next command.
        pub fn add_response(&self, response: MockResponse) {
            lock(&self.responses).push(response);
        }

        /// Set the default response when no queued responses remain.
        pub fn set_default_response(&mut self, response: MockResponse) {
            self.default_response = response;
        }

        /// Get all recorded invocations.
        pub fn invocations(&self) -> Vec<CommandInvocation> {
            lock(&self.invocations).clone()
        }

        /// Clear recorded invocations.
        pub fn clear_invocations(&self) {
            lock(&self.invocations).clear();
        }
    }

    impl Default for MockSubprocessRuntime {
        fn default() -> Self {
            Self::new()
        }
    }

    impl SubprocessRuntime for MockSubprocessRuntime {
        fn run_command(
            &self,
            program: &str,
            args: &[&str],
            stdin: Option<&[u8]>,
        ) -> Result<SubprocessOutput, SubprocessError> {
            lock(&self.invocations).push(CommandInvocation {
                program: program.to_string(),
                args: args.iter().map(|s| s.to_string()).collect(),
                stdin: stdin.map(|s| s.to_vec()),
            });

            let response = {
                let mut responses = lock(&self.responses);
                if responses.is_empty() {
                    self.default_response.clone()
                } else {
                    responses.remove(0)
                }
            };

            Ok(SubprocessOutput {
                stdout: response.stdout,
                stderr: response.stderr,
                status_code: response.status_code,
            })
        }
    }
}

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

    #[test]
    fn test_subprocess_output_success() {
        let output = SubprocessOutput { stdout: vec![1, 2, 3], stderr: vec![], status_code: 0 };
        assert!(output.success());
    }

    #[test]
    fn test_subprocess_output_failure() {
        let output = SubprocessOutput { stdout: vec![], stderr: b"error".to_vec(), status_code: 1 };
        assert!(!output.success());
        assert_eq!(output.stderr_lossy(), "error");
    }

    #[test]
    fn test_subprocess_error_display() {
        let error = SubprocessError::new("test error");
        assert_eq!(format!("{}", error), "test error");
    }

    #[test]
    fn test_mock_runtime() {
        use mock::*;

        let runtime = MockSubprocessRuntime::new();
        runtime.add_response(MockResponse::success(b"formatted code".to_vec()));

        let result = runtime.run_command("perltidy", &["-st"], Some(b"my $x = 1;"));

        assert!(result.is_ok());
        let output = perl_tdd_support::must(result);
        assert!(output.success());
        assert_eq!(output.stdout_lossy(), "formatted code");

        let invocations = runtime.invocations();
        assert_eq!(invocations.len(), 1);
        assert_eq!(invocations[0].program, "perltidy");
        assert_eq!(invocations[0].args, vec!["-st"]);
        assert_eq!(invocations[0].stdin, Some(b"my $x = 1;".to_vec()));
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_os_runtime_echo() {
        let runtime = OsSubprocessRuntime::new();
        #[cfg(windows)]
        let result = runtime.run_command("cmd.exe", &["/C", "echo", "hello"], None);
        #[cfg(not(windows))]
        let result = runtime.run_command("echo", &["hello"], None);

        assert!(result.is_ok());
        let output = perl_tdd_support::must(result);
        assert!(output.success());
        assert!(output.stdout_lossy().trim() == "hello");
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_os_runtime_nonexistent() {
        let runtime = OsSubprocessRuntime::new();

        let result = runtime.run_command("nonexistent_program_xyz", &[], None);

        assert!(result.is_err());
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_os_runtime_rejects_empty_program_name() {
        let runtime = OsSubprocessRuntime::new();
        let result = runtime.run_command("   ", &["--version"], None);
        assert!(result.is_err());
        let err = result.expect_err("empty program name must be rejected");
        assert!(err.message.contains("must not be empty"));
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_os_runtime_rejects_nul_bytes_in_program_or_args() {
        let runtime = OsSubprocessRuntime::new();

        let bad_program = runtime.run_command("perl\0", &["--version"], None);
        assert!(bad_program.is_err());
        let bad_program_err = bad_program.expect_err("NUL in program must be rejected");
        assert!(bad_program_err.message.contains("NUL"));

        let bad_arg = runtime.run_command("perl", &["-e", "print \"ok\"\0"], None);
        assert!(bad_arg.is_err());
        let bad_arg_err = bad_arg.expect_err("NUL in arg must be rejected");
        assert!(bad_arg_err.message.contains("NUL"));
    }

    #[cfg(windows)]
    #[test]
    fn test_resolve_command_invocation_uses_cmd_for_batch_wrappers() {
        let (program, args) =
            resolve_command_invocation(r"C:\Strawberry\perl\bin\perltidy.bat", &["-st", "-se"]);

        assert_eq!(program, "cmd.exe");
        assert_eq!(
            args,
            vec![
                "/D".to_string(),
                "/V:OFF".to_string(),
                "/S".to_string(),
                "/C".to_string(),
                "\"C:\\Strawberry\\perl\\bin\\perltidy.bat\" \"-st\" \"-se\"".to_string(),
            ]
        );
    }

    /// Verify that cmd.exe shell metacharacters are handled correctly inside
    /// double-quoted tokens.
    ///
    /// Inside a cmd.exe double-quoted region, shell metacharacters (`&`, `|`,
    /// `<`, `>`, `(`, `)`) are already literal — no `^` prefix is used.
    /// `^` is also literal and must not be doubled.
    /// `%` is doubled to prevent `%VAR%` expansion.
    /// `"` is doubled (`""`) per the cmd.exe shell convention.
    #[cfg(windows)]
    #[test]
    fn test_windows_quote_for_cmd_metacharacters_are_literal_inside_quotes() {
        // Metacharacters & | < > are passed through literally — no ^ prefix.
        // ^ is literal — must NOT be doubled.
        // % is doubled to prevent %VAR% expansion.
        // " is doubled (cmd.exe "" convention), not backslash-escaped.
        let quoted = windows_quote_for_cmd(r#"profile&name|1>%TEMP%^"x""#);
        assert_eq!(quoted, r#""profile&name|1>%%TEMP%%^""x""""#);
    }

    /// Verify that a caret in an argument is not doubled.
    ///
    /// The original PR erroneously included `'^'` in the metacharacter match
    /// arm, which caused `windows_quote_for_cmd("foo^bar")` to return
    /// `"foo^^bar"` — delivering two carets to the program.  Inside a
    /// cmd.exe double-quoted region `^` is literal and must not be escaped.
    #[cfg(windows)]
    #[test]
    fn test_windows_quote_for_cmd_caret_not_doubled() {
        let quoted = windows_quote_for_cmd(r"foo^bar");
        assert_eq!(quoted, r#""foo^bar""#);
    }

    /// Verify that an embedded double-quote uses the cmd.exe `""` convention.
    ///
    /// The original PR used `\"` which is the `CommandLineToArgvW` / C-runtime
    /// convention.  In cmd.exe context the backslash is literal and the `"`
    /// terminates the quoted region, breaking argument boundaries.
    #[cfg(windows)]
    #[test]
    fn test_windows_quote_for_cmd_embedded_quote_uses_doubling() {
        let quoted = windows_quote_for_cmd(r#"arg"with"quotes"#);
        // cmd.exe convention: "" represents a literal " inside a quoted token.
        assert_eq!(quoted, r#""arg""with""quotes""#);
    }

    /// Verify that an attacker-controlled injection attempt is rendered inert.
    ///
    /// An arg like `&calc.exe` must not break out of the quoted token.
    /// After quoting, cmd.exe sees `&` as a literal character inside the
    /// double-quoted region.
    #[cfg(windows)]
    #[test]
    fn test_windows_quote_for_cmd_injection_attempt_is_inert() {
        let quoted = windows_quote_for_cmd("&calc.exe");
        assert_eq!(quoted, "\"&calc.exe\"");
    }

    /// Verify that /V:OFF is present in the cmd.exe argument list.
    ///
    /// Without /V:OFF, cmd.exe with delayed expansion enabled would expand
    /// `!VAR!` patterns inside arguments, which is an information-disclosure
    /// vector and, in edge cases, an injection vector.
    #[cfg(windows)]
    #[test]
    fn test_resolve_command_invocation_includes_v_off_flag() {
        let (program, args) =
            resolve_command_invocation(r"C:\tools\perlcritic.bat", &["--profile=!TEMP!"]);

        assert_eq!(program, "cmd.exe");
        assert!(
            args.contains(&"/V:OFF".to_string()),
            "/V:OFF must be present to disable delayed expansion; got: {:?}",
            args
        );
    }

    #[cfg(windows)]
    #[test]
    fn test_resolve_command_invocation_preserves_executable_paths() {
        let (program, args) =
            resolve_command_invocation(r"C:\tools\perlcritic.exe", &["--version"]);

        assert_eq!(program, r"C:\tools\perlcritic.exe");
        assert_eq!(args, vec!["--version".to_string()]);
    }

    #[cfg(windows)]
    #[test]
    fn test_windows_program_priority_prefers_real_wrappers_over_extensionless_shims() {
        let mut candidates = vec![
            r"C:\Strawberry\perl\bin\perltidy".to_string(),
            r"C:\Strawberry\perl\bin\perltidy.bat".to_string(),
            r"C:\tools\perltidy.exe".to_string(),
        ];
        candidates.sort_by_key(|candidate| windows_program_priority(candidate));

        assert_eq!(candidates.last().map(String::as_str), Some(r"C:\tools\perltidy.exe"));
        assert!(
            windows_program_priority(r"C:\Strawberry\perl\bin\perltidy.bat")
                > windows_program_priority(r"C:\Strawberry\perl\bin\perltidy")
        );
    }
}