Skip to content

Commit

Permalink
Refactor to shell & inline comments for maintainence (#443)
Browse files Browse the repository at this point in the history
* feat: migrate some code

* feat: FromStr trait

* done stuff
  • Loading branch information
alexng353 authored Sep 26, 2023
1 parent 2952df1 commit 6b8ae2e
Showing 1 changed file with 35 additions and 13 deletions.
48 changes: 35 additions & 13 deletions src/commands/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,7 @@ pub async fn command(args: Args, _json: bool) -> Result<()> {

let shell = std::env::var("SHELL").unwrap_or(match std::env::consts::OS {
"windows" => match windows_shell_detection().await {
Some(WindowsShell::Powershell) => "powershell".to_string(),
Some(WindowsShell::Cmd) => "cmd".to_string(),
Some(WindowsShell::Powershell7) => "pwsh".to_string(),
Some(WindowsShell::NuShell) => "nu".to_string(),
Some(WindowsShell::ElvSh) => "elvish".to_string(),
Some(shell) => shell.to_string(),
None => "cmd".to_string(),
},
_ => "sh".to_string(),
Expand Down Expand Up @@ -164,9 +160,42 @@ enum WindowsShell {
ElvSh,
}

impl core::fmt::Display for WindowsShell {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
match *self {
WindowsShell::Powershell => write!(f, "powershell"),
WindowsShell::Cmd => write!(f, "cmd"),
WindowsShell::Powershell7 => write!(f, "pwsh"),
WindowsShell::NuShell => write!(f, "nu"),
WindowsShell::ElvSh => write!(f, "elvish"),
}
}
}

impl std::str::FromStr for WindowsShell {
type Err = ();

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"cmd" => Ok(WindowsShell::Cmd),
"powershell" => Ok(WindowsShell::Powershell),
"pwsh" => Ok(WindowsShell::Powershell7),
"nu" => Ok(WindowsShell::NuShell),
"elvish" => Ok(WindowsShell::ElvSh),
_ => Ok(WindowsShell::Cmd),
}
}
}

/// https://gist.github.com/mattn/253013/d47b90159cf8ffa4d92448614b748aa1d235ebe4
///
/// defaults to cmd if no parent process is found
///
// How to add new shells:
//
// 1. edit the WindowsShell enum and add the new shell
// 2. edit the impl Display for WindowsShell and add the new shell's stringified name (Powershell7 => "pwsh")
// 3. edit the impl FromStr for WindowsShell and add the new shell's stringified name (pwsh => Powershell7)
#[cfg(target_os = "windows")]
async fn windows_shell_detection() -> Option<WindowsShell> {
let (ppid, mut ppname) = unsafe {
Expand All @@ -186,14 +215,7 @@ async fn windows_shell_detection() -> Option<WindowsShell> {

let ppname = ppname.split(".").next().unwrap_or("cmd");

match ppname {
"cmd" => Some(WindowsShell::Cmd),
"powershell" => Some(WindowsShell::Powershell),
"pwsh" => Some(WindowsShell::Powershell7),
"nu" => Some(WindowsShell::NuShell),
"elvish" => Some(WindowsShell::ElvSh),
_ => Some(WindowsShell::Cmd),
}
ppname.parse::<WindowsShell>().ok()
}

#[cfg(not(target_os = "windows"))]
Expand Down

0 comments on commit 6b8ae2e

Please sign in to comment.