win_open/shell.rs
1use crate::error::{Error, ErrorKind, Result};
2use std::fmt::Debug;
3use std::str::FromStr;
4
5/// Enum representing the different types of Windows shells that can be used.
6#[derive(Debug, Copy, Clone)]
7pub enum WindowsShell {
8 /// PowerShell (`pwsh`).
9 Powershell,
10
11 /// Nushell (`nu`).
12 Nushell,
13
14 /// Command Prompt (`cmd`).
15 Cmd,
16}
17
18impl WindowsShell {
19 /// Converts a `WindowsShell` variant into its corresponding shell command as a string.
20 ///
21 /// This method returns the string that represents the shell command for each variant.
22 ///
23 /// # Returns
24 /// A string slice representing the shell command (e.g., "pwsh", "nu", "cmd").
25 pub fn as_str(self) -> &'static str {
26 match self {
27 WindowsShell::Powershell => "pwsh", // PowerShell command
28 WindowsShell::Nushell => "nu", // Nushell command
29 WindowsShell::Cmd => "cmd", // Command Prompt command
30 }
31 }
32}
33
34impl TryInto<WindowsShell> for &str {
35 type Error = Error;
36
37 /// Attempts to convert a string slice (`&str`) into a `WindowsShell` enum.
38 ///
39 /// This method tries to match the input string (case insensitive) to a valid shell type.
40 /// If the input string matches one of the supported shell types, it returns the corresponding `WindowsShell` variant.
41 /// If not, it returns an error indicating that the shell was not recognized.
42 ///
43 /// # Parameters
44 /// - `self`: The input string representing the shell type to be converted.
45 ///
46 /// # Returns
47 /// - `Ok(WindowsShell::Powershell)` if the input matches "PWSH" or "POWERSHELL".
48 /// - `Ok(WindowsShell::Nushell)` if the input matches "NU" or "NUSHELL".
49 /// - `Ok(WindowsShell::Cmd)` if the input matches "CMD" or "COMMANDPROMPT".
50 /// - `Err(Error)` if the input does not match any known shell types.
51 fn try_into(self) -> Result<WindowsShell> {
52 match self.to_ascii_uppercase().as_str() {
53 "PWSH" | "POWERSHELL" => Ok(WindowsShell::Powershell),
54 "NU" | "NUSHELL" => Ok(WindowsShell::Nushell),
55 "CMD" | "COMMANDPROMPT" => Ok(WindowsShell::Cmd),
56 _ => Err(Error::new(ErrorKind::SHELL_NOT_FOUND, self)), // Error if shell is not found
57 }
58 }
59}
60
61impl FromStr for WindowsShell {
62 type Err = Error;
63
64 /// Attempts to parse a string slice into a `WindowsShell` enum.
65 ///
66 /// This method uses `try_into` to convert the input string into a corresponding `WindowsShell` variant.
67 /// It returns a `Result` containing either a valid `WindowsShell` or an error if the string is not recognized.
68 ///
69 /// # Parameters
70 /// - `shell`: The string slice representing the shell type.
71 ///
72 /// # Returns
73 /// - `Ok(WindowsShell)` if the string matches a valid shell type.
74 /// - `Err(Error)` if the string does not match any known shell types.
75 fn from_str(shell: &str) -> Result<Self> {
76 shell.try_into() // Delegate the conversion to the `try_into` implementation
77 }
78}