use std::path::PathBuf;
use anyhow::{Result, bail};
pub const LINE: &str = "Invoke-Expression (& kaeru init powershell | Out-String)";
pub const BASH_LINE: &str = "eval \"$(kaeru init bash)\"";
pub const COMMENT: &str =
"# kaeru brings your tabs back after the terminal closes. `kaeru uninstall` removes this.";
const UTF16_BOM: [u8; 2] = [0xFF, 0xFE];
const UTF16_BE_BOM: [u8; 2] = [0xFE, 0xFF];
const UTF8_BOM: [u8; 3] = [0xEF, 0xBB, 0xBF];
fn check_encoding(profile: &[u8]) -> Result<()> {
if profile.starts_with(&UTF16_BE_BOM) {
bail!(
"the profile is UTF-16 big-endian, which kaeru doesn't edit; add kaeru's line to it yourself"
);
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
PowerShell,
Bash,
}
impl Kind {
pub fn line(self) -> &'static str {
match self {
Kind::PowerShell => LINE,
Kind::Bash => BASH_LINE,
}
}
fn newline(self) -> &'static str {
match self {
Kind::PowerShell => "\r\n",
Kind::Bash => "\n",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Profile {
pub shell: &'static str,
pub path: PathBuf,
pub kind: Kind,
}
pub fn profiles() -> Vec<Profile> {
if !cfg!(windows) {
return Vec::new();
}
let mut found = Vec::new();
if let Some(documents) = dirs::document_dir() {
found.push(Profile {
shell: "Windows PowerShell",
path: documents
.join("WindowsPowerShell")
.join("Microsoft.PowerShell_profile.ps1"),
kind: Kind::PowerShell,
});
if super::on_path("pwsh.exe").is_some() {
found.push(Profile {
shell: "PowerShell 7",
path: documents
.join("PowerShell")
.join("Microsoft.PowerShell_profile.ps1"),
kind: Kind::PowerShell,
});
}
}
if git_bash_is_installed()
&& let Some(home) = bash_home()
{
found.push(Profile {
shell: "Git Bash",
path: home.join(".bashrc"),
kind: Kind::Bash,
});
}
found
}
pub fn bash_home() -> Option<PathBuf> {
std::env::var_os("HOME")
.map(PathBuf::from)
.filter(|home| home.is_absolute())
.or_else(dirs::home_dir)
}
fn git_bash_is_installed() -> bool {
let near_git = super::on_path("git.exe").is_some_and(|git| {
git.ancestors()
.skip(1)
.take(3)
.any(|folder| folder.join("git-bash.exe").is_file())
});
let default = std::env::var_os("ProgramFiles")
.map(PathBuf::from)
.is_some_and(|programs| programs.join("Git").join("git-bash.exe").is_file());
near_git || default
}
pub fn reads_bashrc(bash_profile: &str) -> bool {
bash_profile.lines().any(|line| {
let line = line.trim();
!line.starts_with('#') && line.contains(".bashrc")
})
}
pub fn has_line(profile: &[u8], kind: Kind) -> Result<bool> {
Ok(lines(profile)?
.iter()
.any(|line| line.trim() == kind.line()))
}
pub fn add_line(profile: &[u8], kind: Kind) -> Result<Vec<u8>> {
check_encoding(profile)?;
let newline = kind.newline();
let added = format!("{COMMENT}{newline}{}{newline}", kind.line());
if profile.starts_with(&UTF16_BOM) {
let mut text = utf16(profile)?;
if !text.is_empty() && !text.ends_with('\n') {
text.push_str(newline);
}
text.push_str(&added);
return Ok(to_utf16(&text));
}
let mut bytes = profile.to_vec();
if !bytes.is_empty() && !bytes.ends_with(b"\n") {
bytes.extend_from_slice(newline.as_bytes());
}
bytes.extend_from_slice(added.as_bytes());
Ok(bytes)
}
pub fn remove_line(profile: &[u8], kind: Kind) -> Result<Vec<u8>> {
check_encoding(profile)?;
let ours = |line: &str| {
let line = line.trim();
line == kind.line() || line == COMMENT
};
if profile.starts_with(&UTF16_BOM) {
let text = utf16(profile)?;
let kept: String = text
.split_inclusive('\n')
.filter(|line| !ours(line))
.collect();
return Ok(to_utf16(&kept));
}
let (mark, rest) = match profile.strip_prefix(&UTF8_BOM) {
Some(rest) => (&UTF8_BOM[..], rest),
None => (&[][..], profile),
};
let kept = rest
.split_inclusive(|&byte| byte == b'\n')
.filter(|line| !std::str::from_utf8(line).is_ok_and(ours))
.flatten()
.copied();
Ok(mark.iter().copied().chain(kept).collect())
}
fn lines(profile: &[u8]) -> Result<Vec<String>> {
check_encoding(profile)?;
if profile.starts_with(&UTF16_BOM) {
return Ok(utf16(profile)?.lines().map(String::from).collect());
}
let profile = profile.strip_prefix(&UTF8_BOM).unwrap_or(profile);
Ok(profile
.split(|&byte| byte == b'\n')
.map(|line| std::str::from_utf8(line).unwrap_or_default().to_string())
.collect())
}
fn utf16(profile: &[u8]) -> Result<String> {
let units: Vec<u16> = profile[UTF16_BOM.len()..]
.chunks(2)
.map(|pair| u16::from_le_bytes([pair[0], pair.get(1).copied().unwrap_or(0)]))
.collect();
match String::from_utf16(&units) {
Ok(text) => Ok(text),
Err(_) => bail!("the profile isn't valid UTF-16"),
}
}
fn to_utf16(text: &str) -> Vec<u8> {
UTF16_BOM
.into_iter()
.chain(text.encode_utf16().flat_map(u16::to_le_bytes))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_line_goes_at_the_end_of_a_profile() {
let profile = b"Set-Alias ll Get-ChildItem";
let added = add_line(profile, Kind::PowerShell).unwrap();
let text = String::from_utf8(added.clone()).unwrap();
assert!(text.starts_with("Set-Alias ll Get-ChildItem\r\n# kaeru"));
assert!(text.ends_with(&format!("{LINE}\r\n")));
assert!(has_line(&added, Kind::PowerShell).unwrap());
assert!(!has_line(profile, Kind::PowerShell).unwrap());
}
#[test]
fn an_empty_profile_gets_only_kaeru_s_lines() {
let added = add_line(b"", Kind::PowerShell).unwrap();
assert_eq!(added, format!("{COMMENT}\r\n{LINE}\r\n").into_bytes());
}
#[test]
fn removing_the_line_leaves_the_rest_as_it_was() {
let profile = b"Set-Alias ll Get-ChildItem\r\n";
let added = add_line(profile, Kind::PowerShell).unwrap();
assert_eq!(remove_line(&added, Kind::PowerShell).unwrap(), profile);
}
#[test]
fn a_profile_in_another_code_page_keeps_its_bytes() {
let profile = [b'#', b' ', 0xC7, 0xD1, 0xB1, 0xDB, b'\r', b'\n'];
let added = add_line(&profile, Kind::PowerShell).unwrap();
assert!(added.starts_with(&profile));
assert!(has_line(&added, Kind::PowerShell).unwrap());
assert_eq!(remove_line(&added, Kind::PowerShell).unwrap(), profile);
}
#[test]
fn a_utf16_profile_stays_utf16() {
let profile = to_utf16("Set-Alias ll Get-ChildItem\r\n");
let added = add_line(&profile, Kind::PowerShell).unwrap();
assert!(added.starts_with(&UTF16_BOM));
assert!(has_line(&added, Kind::PowerShell).unwrap());
assert_eq!(remove_line(&added, Kind::PowerShell).unwrap(), profile);
}
#[test]
fn a_utf8_mark_doesnt_hide_kaeru_s_first_line() {
let added = [&UTF8_BOM[..], &add_line(b"", Kind::PowerShell).unwrap()].concat();
assert!(has_line(&added, Kind::PowerShell).unwrap());
assert_eq!(remove_line(&added, Kind::PowerShell).unwrap(), UTF8_BOM);
}
#[test]
fn a_bashrc_gets_bash_s_line_with_unix_line_endings() {
let bashrc = b"alias ll='ls -l'";
let added = add_line(bashrc, Kind::Bash).unwrap();
let text = String::from_utf8(added.clone()).unwrap();
assert_eq!(text, format!("alias ll='ls -l'\n{COMMENT}\n{BASH_LINE}\n"));
assert!(has_line(&added, Kind::Bash).unwrap());
assert!(!has_line(&added, Kind::PowerShell).unwrap());
assert_eq!(
remove_line(&added, Kind::Bash).unwrap(),
b"alias ll='ls -l'\n"
);
}
#[test]
fn a_bash_profile_that_reads_bashrc_is_recognized() {
assert!(reads_bashrc("test -f ~/.bashrc && . ~/.bashrc\n"));
assert!(reads_bashrc(
"if [ -f \"$HOME/.bashrc\" ]; then\n source \"$HOME/.bashrc\"\nfi\n"
));
assert!(!reads_bashrc("# . ~/.bashrc\nexport EDITOR=vim\n"));
}
#[test]
fn a_utf16_big_endian_profile_is_left_alone() {
let profile = [&UTF16_BE_BOM[..], &[0x00, 0x23]].concat();
assert!(add_line(&profile, Kind::PowerShell).is_err());
assert!(remove_line(&profile, Kind::PowerShell).is_err());
}
}