Skip to content

Commit

Permalink
Add support for determining current shell from environment
Browse files Browse the repository at this point in the history
Closes: #4446
  • Loading branch information
tmccombs committed Nov 3, 2022
1 parent 033438e commit 4350310
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions clap_complete/src/shells/shell.rs
@@ -1,5 +1,6 @@
use std::fmt::Display;
use std::str::FromStr;
use std::path::PathBuf;

use clap::builder::PossibleValue;
use clap::ValueEnum;
Expand Down Expand Up @@ -89,3 +90,35 @@ impl Generator for Shell {
}
}
}

impl Shell {
/// Determine the user's current shell from the environment
///
/// This will read the SHELL environment variable and try to determine which shell is in use
/// from that.
///
/// If SHELL is not set, then on windows, it will default to powershell, and on
/// other OSes it will return an error.
///
/// If SHELL is set, but contains a value that doesn't correspond to one of the supported shell
/// types, then an error is returned.
///
/// # Example:
///
/// ```ignore
/// use clap_complete::{generate, shells::Shell}
/// let mut cmd = build_cli();
/// generate(Shell::from_env().unwrap_or(Shell::Bash), "myapp", &mut std::io::stdout());
/// ```
pub fn from_env() -> Result<Shell, String> {
let env_shell = std::env::var_os("SHELL").map(PathBuf::from);
if let Some(shell) = env_shell.as_ref().and_then(|s| s.file_name()).and_then(|s| s.to_str()) {
Ok(shell.parse::<Shell>()?)
} else if cfg!(windows) {
// Assume powershell for windows
Ok(Shell::PowerShell)
} else {
Err("SHELL environment variable not set".to_string())
}
}
}

0 comments on commit 4350310

Please sign in to comment.