use std::path::PathBuf;
use std::{env, io};
use which::which;
use crate::colorize::Colorize;
use crate::context::Shell;
struct UsePath {
native_path: PathBuf,
}
impl UsePath {
fn init() -> io::Result<Self> {
let exe_name = option_env!("CARGO_PKG_NAME").unwrap_or("use");
let native_path = which(exe_name).or_else(|_| env::current_exe())?;
Ok(Self { native_path })
}
fn str_path(&self) -> io::Result<&str> {
let current_exe = self
.native_path
.to_str()
.ok_or_else(|| io::Error::other("can't convert to str"))?;
Ok(current_exe)
}
fn sprint_pwsh(&self) -> io::Result<String> {
self.str_path()
.map(|s| s.replace('\'', "''"))
.map(|s| format!("'{s}'"))
}
fn sprint_cmdexe(&self) -> io::Result<String> {
self.str_path().map(|s| format!("\"{s}\""))
}
}
pub fn init_stub(shell: Shell) -> io::Result<()> {
let use_path = UsePath::init()?;
match shell {
Shell::Powershell => print!(
r#"Invoke-Expression (& {} init powershell --print-full-init | Out-String)"#,
use_path.sprint_pwsh()?
),
Shell::Cmd => print_script(CLINK_INIT, &use_path.sprint_cmdexe()?),
_ => {
eprintln!("{} Unsupported shell: {shell:?}", "error:".error());
return Err(io::Error::other("Unsupported shell"));
}
}
Ok(())
}
pub fn init_main(shell: Shell) -> io::Result<()> {
let use_path = UsePath::init()?;
match shell {
Shell::Powershell => print_script(POWERSHELL_INIT, &use_path.sprint_pwsh()?),
Shell::Cmd => print_script(CLINK_INIT, &use_path.sprint_cmdexe()?),
_ => {
eprintln!("{} Unsupported shell: {shell:?}", "error:".error());
return Err(io::Error::other("Unsupported shell"));
}
}
Ok(())
}
fn print_script(script: &str, path: &str) {
let path = path.replace("\\", "\\\\");
let script = script.replace("::USE::", path.as_str());
print!("{script}");
}
const POWERSHELL_INIT: &str = include_str!("use.ps1");
const CLINK_INIT: &str = include_str!("use.lua");