onpath 0.2.0

Get your tools on the PATH — cross-shell, cross-platform, zero fuss
Documentation
use std::path::{Path, PathBuf};

use crate::config::Position;
use crate::context::SystemContext;
use crate::shell::{Shell, ShellKind};

pub struct Bash;

impl Shell for Bash {
    fn kind(&self) -> ShellKind {
        ShellKind::Bash
    }

    fn env_extension(&self) -> &'static str {
        ""
    }

    fn env_script(&self, dir: &Path, position: Position) -> String {
        super::posix_env_script(dir, position)
    }

    fn source_line(&self, env_script_path: &Path) -> String {
        super::posix_source_line(env_script_path)
    }

    fn rc_candidates(&self, ctx: &SystemContext) -> Vec<PathBuf> {
        let home = ctx.home_dir();
        vec![
            home.join(".bash_profile"),
            home.join(".bash_login"),
            home.join(".bashrc"),
        ]
    }

    fn primary_rc(&self, ctx: &SystemContext) -> PathBuf {
        ctx.home_dir().join(".bashrc")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn env_script_contains_guard() {
        let script = Bash.env_script(Path::new("/app/bin"), Position::Prepend);
        assert!(script.contains(r#"case ":${PATH}:""#));
        assert!(script.contains("/app/bin"));
    }

    #[test]
    fn rc_candidates_returns_all_bash_files() {
        let ctx = SystemContext::with_home(PathBuf::from("/home/user"));
        let candidates = Bash.rc_candidates(&ctx);
        assert_eq!(candidates.len(), 3);
        assert!(candidates.contains(&PathBuf::from("/home/user/.bash_profile")));
        assert!(candidates.contains(&PathBuf::from("/home/user/.bashrc")));
    }

    #[test]
    fn env_script_append() {
        let script = Bash.env_script(Path::new("/app/bin"), Position::Append);
        assert!(script.contains(r#"export PATH="$PATH:/app/bin""#));
    }

    #[test]
    fn primary_rc_is_bashrc() {
        let ctx = SystemContext::with_home(PathBuf::from("/home/user"));
        assert_eq!(Bash.primary_rc(&ctx), PathBuf::from("/home/user/.bashrc"));
    }
}