#!/usr/bin/env rust-script //! ```cargo //! [dependencies] //! anyhow = "1.0.69" //! dirs = "4.0.0" //! ``` use anyhow::Context; use std::{ fs::{self, File}, io::{BufRead, BufReader}, }; const ENV: &str = r#". "$HOME/.cargo/env""#; fn main() -> anyhow::Result<()> { let home = dirs::home_dir().context("can't find home directory")?; let mut login_path = home.clone(); login_path.push(".bash_login"); let login = BufReader::new(File::open(&login_path).context("failed to read ~/.bash_login")?); let mut bashrc_path = home.clone(); bashrc_path.push(".bashrc"); let bashrc = BufReader::new(File::open(&bashrc_path).context("failed to read ~/.bashrc")?); let mut empty = false; let mut new_bashrc = String::new(); for line in bashrc.lines() { let line = line.context("failed to read line in ~/.bashrc")?; if line.is_empty() && empty { continue; } empty = line.is_empty(); if line != ENV { new_bashrc.push_str(&line); new_bashrc.push('\n'); } } let mut empty = false; let mut new_login = String::new(); for line in login.lines() { let line = line.context("failed to read line in ~/.bash_login")?; if line.is_empty() && empty { continue; } empty = line.is_empty(); if line != ENV { new_login.push_str(&line); new_login.push('\n'); } if line == "# custom" { new_login.push('\n'); new_login.push_str(ENV); new_login.push_str("\n\n"); empty = true; } } fs::write(bashrc_path, &new_bashrc).context("failed to write new .bashrc")?; fs::write(login_path, &new_login).context("failed to write new .bash_login")?; Ok(()) }