use std::ffi::OsStr;
use std::path::Path;
use std::{env, io};
fn path_to_starship() -> io::Result<String> {
let current_exe = env::current_exe()?
.to_str()
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "can't convert to str"))?
.to_string();
Ok(current_exe)
}
pub fn init_stub(shell_name: &str) -> io::Result<()> {
log::debug!("Shell name: {}", shell_name);
let shell_basename = Path::new(shell_name).file_stem().and_then(OsStr::to_str);
let starship = path_to_starship()?.replace("\"", "\"'\"'\"");
let setup_stub = match shell_basename {
Some("bash") => {
let script = {
format!(
r#"if [ "${{BASH_VERSINFO[0]}}" -gt 4 ] || ([ "${{BASH_VERSINFO[0]}}" -eq 4 ] && [ "${{BASH_VERSINFO[1]}}" -ge 1 ])
then
source <("{}" init bash --print-full-init)
else
source /dev/stdin <<<"$("{}" init bash --print-full-init)"
fi"#,
starship, starship
)
};
Some(script)
}
Some("zsh") => {
let script = format!("source <(\"{}\" init zsh --print-full-init)", starship);
Some(script)
}
Some("fish") => {
let script = format!(
"source (\"{}\" init fish --print-full-init | psub)",
starship
);
Some(script)
}
None => {
println!(
"Invalid shell name provided: {}\\n\
If this issue persists, please open an \
issue in the starship repo: \\n\
https://github.com/starship/starship/issues/new\\n\"",
shell_name
);
None
}
Some(shell_basename) => {
println!(
"printf \"\\n{0} is not yet supported by starship.\\n\
For the time being, we support bash, zsh, and fish.\\n\
Please open an issue in the starship repo if you would like to \
see support for {0}:\\nhttps://github.com/starship/starship/issues/new\"\\n\\n",
shell_basename
);
None
}
};
if let Some(script) = setup_stub {
print!("{}", script);
};
Ok(())
}
pub fn init_main(shell_name: &str) -> io::Result<()> {
let starship_path = path_to_starship()?.replace("\"", "\"'\"'\"");
let setup_script = match shell_name {
"bash" => Some(BASH_INIT),
"zsh" => Some(ZSH_INIT),
"fish" => Some(FISH_INIT),
_ => {
println!(
"printf \"Shell name detection failed on phase two init.\\n\
This probably indicates a bug within starship: please open\\n\
an issue at https://github.com/starship/starship/issues/new\\n\""
);
None
}
};
if let Some(script) = setup_script {
let starship_path_string = format!("\"{}\"", starship_path);
let script = script.replace("::STARSHIP::", &starship_path_string);
print!("{}", script);
};
Ok(())
}
const BASH_INIT: &str = include_str!("starship.bash");
const ZSH_INIT: &str = include_str!("starship.zsh");
const FISH_INIT: &str = include_str!("starship.fish");