whetstone-cli 3.19.1

Installer and CLI for Claude Code token optimization (Headroom + RTK + Memory)
use anyhow::{Context, Result};
use std::fs;
use std::path::PathBuf;

pub fn detect_profile() -> Option<PathBuf> {
    let home = dirs::home_dir()?;
    let shell = std::env::var("SHELL").unwrap_or_default();

    if shell.ends_with("zsh") {
        let p = home.join(".zshrc");
        if p.exists() {
            return Some(p);
        }
    }
    if shell.ends_with("bash") {
        let p = home.join(".bashrc");
        if p.exists() {
            return Some(p);
        }
    }

    for name in [".zshrc", ".bashrc", ".profile"] {
        let p = home.join(name);
        if p.exists() {
            return Some(p);
        }
    }
    None
}

/// `contents` with `line` appended, or `None` when it is already there.
fn with_line(contents: &str, line: &str) -> Option<String> {
    if contents.lines().any(|l| l == line) {
        return None;
    }
    let mut appended = contents.to_string();
    if !appended.is_empty() && !appended.ends_with('\n') {
        appended.push('\n');
    }
    appended.push_str(line);
    appended.push('\n');
    Some(appended)
}

/// `contents` without any copy of `line`, or `None` when it has none.
fn without_line(contents: &str, line: &str) -> Option<String> {
    if !contents.lines().any(|l| l == line) {
        return None;
    }
    Some(
        contents
            .split_inclusive('\n')
            .filter(|l| l.trim_end_matches('\n') != line)
            .collect(),
    )
}

pub fn ensure_in_profile(line: &str) -> Result<()> {
    let Some(profile) = detect_profile() else {
        crate::ui::warn(
            "could not detect shell profile — set ANTHROPIC_BASE_URL manually",
        );
        return Ok(());
    };

    let contents = fs::read_to_string(&profile)
        .with_context(|| format!("reading {}", profile.display()))?;
    let Some(appended) = with_line(&contents, line) else {
        return Ok(());
    };
    fs::write(&profile, appended)
        .with_context(|| format!("writing to {}", profile.display()))?;

    crate::ui::ok(&format!("appended to {}", profile.display()));
    Ok(())
}

pub fn ensure_path_contains_local_bin() -> Result<()> {
    ensure_in_profile("export PATH=\"$HOME/.local/bin:$PATH\"")
}

fn base_url_line(url: &str) -> String {
    format!("export ANTHROPIC_BASE_URL={url}")
}

pub fn set_anthropic_base_url(url: &str) -> Result<()> {
    std::env::set_var("ANTHROPIC_BASE_URL", url);
    ensure_in_profile(&base_url_line(url))
}

/// Undo [`set_anthropic_base_url`]: with the proxies gone, the line would
/// send every Anthropic client in a new shell to a dead port. Only the exact
/// line whetstone wrote is removed. Returns whether anything changed.
pub fn unset_anthropic_base_url(url: &str) -> Result<bool> {
    let Some(profile) = detect_profile() else {
        return Ok(false);
    };
    let contents = fs::read_to_string(&profile)
        .with_context(|| format!("reading {}", profile.display()))?;
    let Some(cleaned) = without_line(&contents, &base_url_line(url)) else {
        return Ok(false);
    };
    fs::write(&profile, cleaned)
        .with_context(|| format!("writing to {}", profile.display()))?;
    Ok(true)
}

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

    const LINE: &str = "export ANTHROPIC_BASE_URL=http://127.0.0.1:8787";

    #[test]
    fn appending_twice_leaves_one_line() {
        let once = with_line("alias ll='ls -l'", LINE).unwrap();
        assert_eq!(once, format!("alias ll='ls -l'\n{LINE}\n"));
        assert_eq!(with_line(&once, LINE), None);
    }

    #[test]
    fn a_longer_line_containing_ours_does_not_count_as_present() {
        let other = format!("# {LINE}\n");
        assert!(with_line(&other, LINE).is_some());
    }

    #[test]
    fn removing_takes_only_the_exact_line() {
        let contents =
            format!("a\n{LINE}\nexport ANTHROPIC_BASE_URL=https://mine\nb");
        assert_eq!(
            without_line(&contents, LINE).unwrap(),
            "a\nexport ANTHROPIC_BASE_URL=https://mine\nb"
        );
        assert_eq!(without_line("a\nb\n", LINE), None);
    }
}