uv_shell/
runnable.rs

1//! Utilities for running executables and scripts. Particularly in Windows.
2
3use std::env::consts::EXE_EXTENSION;
4use std::ffi::OsStr;
5use std::path::Path;
6use std::process::Command;
7
8use uv_fs::with_added_extension;
9
10#[derive(Debug)]
11pub enum WindowsRunnable {
12    /// Windows PE (.exe)
13    Executable,
14    /// `PowerShell` script (.ps1)
15    PowerShell,
16    /// Command Prompt NT script (.cmd)
17    Command,
18    /// Command Prompt script (.bat)
19    Batch,
20}
21
22impl WindowsRunnable {
23    /// Returns a list of all supported Windows runnable types.
24    fn all() -> &'static [Self] {
25        &[
26            Self::Executable,
27            Self::PowerShell,
28            Self::Command,
29            Self::Batch,
30        ]
31    }
32
33    /// Returns the extension for a given Windows runnable type.
34    fn to_extension(&self) -> &'static str {
35        match self {
36            Self::Executable => EXE_EXTENSION,
37            Self::PowerShell => "ps1",
38            Self::Command => "cmd",
39            Self::Batch => "bat",
40        }
41    }
42
43    /// Determines the runnable type from a given Windows file extension.
44    fn from_extension(ext: &str) -> Option<Self> {
45        match ext {
46            EXE_EXTENSION => Some(Self::Executable),
47            "ps1" => Some(Self::PowerShell),
48            "cmd" => Some(Self::Command),
49            "bat" => Some(Self::Batch),
50            _ => None,
51        }
52    }
53
54    /// Returns a [`Command`] to run the given type under the appropriate Windows runtime.
55    fn as_command(&self, runnable_path: &Path) -> Command {
56        match self {
57            Self::Executable => Command::new(runnable_path),
58            Self::PowerShell => {
59                let mut cmd = Command::new("powershell");
60                cmd.arg("-NoLogo").arg("-File").arg(runnable_path);
61                cmd
62            }
63            Self::Command | Self::Batch => {
64                let mut cmd = Command::new("cmd");
65                cmd.arg("/q").arg("/c").arg(runnable_path);
66                cmd
67            }
68        }
69    }
70
71    /// Handle console and legacy setuptools scripts for Windows.
72    ///
73    /// Returns [`Command`] that can be used to invoke a supported runnable on Windows
74    /// under the scripts path of an interpreter environment.
75    pub fn from_script_path(script_path: &Path, runnable_name: &OsStr) -> Command {
76        let script_path = script_path.join(runnable_name);
77
78        // Honor explicit extension if provided and recognized.
79        if let Some(script_type) = script_path
80            .extension()
81            .and_then(OsStr::to_str)
82            .and_then(Self::from_extension)
83            .filter(|_| script_path.is_file())
84        {
85            return script_type.as_command(&script_path);
86        }
87
88        // Guess the extension when an explicit one is not provided.
89        // We also add the extension when missing since for some types (e.g. PowerShell) it must be explicit.
90        Self::all()
91            .iter()
92            .map(|script_type| {
93                (
94                    script_type,
95                    with_added_extension(&script_path, script_type.to_extension()),
96                )
97            })
98            .find(|(_, script_path)| script_path.is_file())
99            .map(|(script_type, script_path)| script_type.as_command(&script_path))
100            .unwrap_or_else(|| Command::new(runnable_name))
101    }
102}
103
104#[cfg(test)]
105mod tests {
106
107    #[cfg(target_os = "windows")]
108    use super::WindowsRunnable;
109    #[cfg(target_os = "windows")]
110    use fs_err as fs;
111    #[cfg(target_os = "windows")]
112    use std::ffi::OsStr;
113    #[cfg(target_os = "windows")]
114    use std::io;
115
116    /// Helper function to create a temporary directory with test files
117    #[cfg(target_os = "windows")]
118    fn create_test_environment() -> io::Result<tempfile::TempDir> {
119        let temp_dir = tempfile::tempdir()?;
120        let scripts_dir = temp_dir.path().join("Scripts");
121        fs::create_dir_all(&scripts_dir)?;
122
123        // Create test executable files
124        fs::write(scripts_dir.join("python.exe"), "")?;
125        fs::write(scripts_dir.join("awslabs.cdk-mcp-server.exe"), "")?;
126        fs::write(scripts_dir.join("org.example.tool.exe"), "")?;
127        fs::write(scripts_dir.join("multi.dot.package.name.exe"), "")?;
128        fs::write(scripts_dir.join("script.ps1"), "")?;
129        fs::write(scripts_dir.join("batch.bat"), "")?;
130        fs::write(scripts_dir.join("command.cmd"), "")?;
131        fs::write(scripts_dir.join("explicit.ps1"), "")?;
132
133        Ok(temp_dir)
134    }
135
136    #[cfg(target_os = "windows")]
137    #[test]
138    fn test_from_script_path_single_dot_package() {
139        let temp_dir = create_test_environment().expect("Failed to create test environment");
140        let scripts_dir = temp_dir.path().join("Scripts");
141
142        // Test package name with single dot (awslabs.cdk-mcp-server)
143        let command =
144            WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("awslabs.cdk-mcp-server"));
145
146        // The command should be constructed with the correct executable path
147        let expected_path = scripts_dir.join("awslabs.cdk-mcp-server.exe");
148        assert_eq!(command.get_program(), expected_path.as_os_str());
149    }
150
151    #[cfg(target_os = "windows")]
152    #[test]
153    fn test_from_script_path_multiple_dots_package() {
154        let temp_dir = create_test_environment().expect("Failed to create test environment");
155        let scripts_dir = temp_dir.path().join("Scripts");
156
157        // Test package name with multiple dots (org.example.tool)
158        let command =
159            WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("org.example.tool"));
160
161        let expected_path = scripts_dir.join("org.example.tool.exe");
162        assert_eq!(command.get_program(), expected_path.as_os_str());
163
164        // Test another multi-dot package
165        let command =
166            WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("multi.dot.package.name"));
167
168        let expected_path = scripts_dir.join("multi.dot.package.name.exe");
169        assert_eq!(command.get_program(), expected_path.as_os_str());
170    }
171
172    #[cfg(target_os = "windows")]
173    #[test]
174    fn test_from_script_path_simple_package_name() {
175        let temp_dir = create_test_environment().expect("Failed to create test environment");
176        let scripts_dir = temp_dir.path().join("Scripts");
177
178        // Test simple package name without dots
179        let command = WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("python"));
180
181        let expected_path = scripts_dir.join("python.exe");
182        assert_eq!(command.get_program(), expected_path.as_os_str());
183    }
184
185    #[cfg(target_os = "windows")]
186    #[test]
187    fn test_from_script_path_explicit_extensions() {
188        let temp_dir = create_test_environment().expect("Failed to create test environment");
189        let scripts_dir = temp_dir.path().join("Scripts");
190
191        // Test explicit .ps1 extension
192        let command = WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("explicit.ps1"));
193
194        let expected_path = scripts_dir.join("explicit.ps1");
195        assert_eq!(command.get_program(), "powershell");
196
197        // Verify the arguments contain the script path
198        let args: Vec<&OsStr> = command.get_args().collect();
199        assert!(args.contains(&OsStr::new("-File")));
200        assert!(args.contains(&expected_path.as_os_str()));
201
202        // Test explicit .bat extension
203        let command = WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("batch.bat"));
204        assert_eq!(command.get_program(), "cmd");
205
206        // Test explicit .cmd extension
207        let command = WindowsRunnable::from_script_path(&scripts_dir, OsStr::new("command.cmd"));
208        assert_eq!(command.get_program(), "cmd");
209    }
210}