eclipse-cli 0.13.4

Command-line interface for eclipse
//! `/profile` and `eclipse profiles list`: which profile, from which file, under which home.
//!
//! One renderer, two callers — the composer's `/profile list` prints what `eclipse profiles list`
//! prints because it is the same function, and the same reason `settings_cli`, `cron_cli` and
//! `skills_cli` exist at all.
//!
//! Nothing here works out a path. The four answers come from [`Config::where_am_i`], which fills
//! them from `home_root`, `config_path` and `sessions_dir` — the functions the loader, `doctor`
//! and `/settings` already read. A verb that reports where a session is written is worth nothing
//! if it is the one place that derives the answer a second time.

use eclipse_core::config::{Config, EnvFn, Where};

/// `/profile`: the four answers for this process.
pub fn one(place: &Where) -> String {
    let mut out = format!(
        "profile: {}{}\n",
        place.name(),
        if place.is_default() {
            " (the default profile)"
        } else {
            ""
        }
    );
    out.push_str(&format!(
        "  config    {}\n",
        shown(
            place.config.as_deref(),
            "none: this session was started without a config file"
        )
    ));
    if let Some(overlay) = &place.overlay {
        out.push_str(&format!(
            "  overlay   {} — this profile's own, read after the base so it wins\n",
            overlay.display()
        ));
    }
    out.push_str(&format!(
        "  home      {}\n",
        shown(place.home.as_deref(), "unknown: HOME is not set")
    ));
    out.push_str(&format!(
        "  sessions  {}{}\n",
        shown(place.sessions.as_deref(), "unknown: HOME is not set"),
        match place.sessions.as_deref() {
            Some(dir) => format!(" ({})", sessions(dir)),
            None => String::new(),
        }
    ));
    out.push('\n');
    out.push_str(SWITCHES);
    out
}

/// `/profile <name>`: refused, and the reason is a fact about the store rather than a policy.
pub fn refusal(name: &str) -> String {
    format!(
        "not switching to {name}: a profile is a config file, a home and a session store, and this \
         session cannot change all three under one transcript. `/new` starts a fresh session; \
         `--profile {name}` starts one in that profile"
    )
}

/// `/profile list`: the same rows `eclipse profiles list` prints.
pub fn list(place: &Where, env: EnvFn) -> String {
    let current = place.name();
    let root = place.home.as_ref().map(|h| h.join("profiles"));
    let mut names = vec!["default".to_string()];
    if let Some(root) = &root {
        if let Ok(entries) = std::fs::read_dir(root) {
            let mut found: Vec<String> = entries
                .flatten()
                .filter(|e| e.path().is_dir())
                .map(|e| e.file_name().to_string_lossy().to_string())
                .collect();
            found.sort();
            for name in found {
                if !names.contains(&name) {
                    names.push(name);
                }
            }
        }
    }
    let mut out = String::new();
    for name in names {
        let marker = if name == current { "*" } else { " " };
        let mut bits = Vec::new();
        if let Some(dir) = &root {
            if dir.join(&name).join("config.toml").exists() {
                bits.push("config overlay".to_string());
            }
            if dir.join(&name).join("plugins").is_dir() {
                bits.push("own plugins".to_string());
            }
        }
        let sessions = of_profile(place, env, &name)
            .map(|d| sessions(&d))
            .unwrap_or_default();
        out.push_str(&format!(
            "{} {}  {}{}\n",
            marker,
            name,
            sessions,
            if bits.is_empty() {
                String::new()
            } else {
                format!(" — {}", bits.join(", "))
            }
        ));
    }
    out.push_str(
        "note: the profile is chosen with --profile or ECLIPSE_PROFILE; `default` uses the plain \
         state directory",
    );
    out
}

/// How a profile is switched, said the same way by the verb and by `/profile <name>`.
const SWITCHES: &str = "note: this session cannot switch profiles; `/new` starts a fresh session \
                         and `--profile <name>` starts one in that profile";

fn shown(path: Option<&std::path::Path>, missing: &str) -> String {
    match path {
        Some(p) => p.display().to_string(),
        None => missing.to_string(),
    }
}

/// `<n> sessions`: what `/resume` will offer, read the way `/resume` reads it.
///
/// Through the store when it exists — it is the one answer every surface lists from — and by
/// counting `.jsonl` files only for an install that has not been opened since the store moved to
/// a database (opening it here would import them, and a report that writes is not a report).
fn sessions(dir: &std::path::Path) -> String {
    let count = if eclipse_core::session::db_path(dir).exists() {
        eclipse_core::session::SessionStore::new(dir)
            .list()
            .map(|all| all.len())
            .unwrap_or(0)
    } else {
        std::fs::read_dir(dir)
            .map(|entries| {
                entries
                    .flatten()
                    .filter(|e| e.file_name().to_string_lossy().ends_with(".jsonl"))
                    .count()
            })
            .unwrap_or(0)
    };
    match count {
        0 => "no sessions yet".to_string(),
        1 => "1 session".to_string(),
        n => format!("{n} sessions"),
    }
}

/// Where a profile's sessions are, for the count: its own `[sessions] dir` when its config loads,
/// else the state directory the layout names.
///
/// Through the loader rather than by joining a path, because a profile whose config moves its
/// sessions elsewhere has them *there* — and a list that counts an empty default directory beside
/// a verb that names the full one is the confusion this verb exists to end.
fn of_profile(place: &Where, env: EnvFn, name: &str) -> Option<std::path::PathBuf> {
    let profile = if name == "default" { None } else { Some(name) };
    let loaded = Config::load_with_profile(place.config.as_deref(), profile, env)
        .ok()
        .and_then(|cfg| cfg.sessions_dir(env).ok());
    loaded.or_else(|| eclipse_core::config::state_dir_for(env, profile).map(|d| d.join("sessions")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use eclipse_core::config::Config;
    use std::path::{Path, PathBuf};

    fn env_with(home: &Path) -> impl Fn(&str) -> Option<String> + '_ {
        move |k: &str| match k {
            "HOME" => Some(home.display().to_string()),
            _ => None,
        }
    }

    /// The three paths `/profile` prints are the three the loader and `doctor` print — asserted
    /// against the functions themselves, so a second derivation inside this module fails here
    /// rather than in a bug report about sessions under the wrong home.
    #[test]
    fn the_paths_are_the_ones_the_loader_and_doctor_report() {
        let home = tempfile::tempdir().unwrap();
        let cfg_text = "[sessions]\ndir = \"~/elsewhere/sessions\"\n";
        let cfg_path = home.path().join(".eclipse/config.toml");
        std::fs::create_dir_all(cfg_path.parent().unwrap()).unwrap();
        std::fs::write(&cfg_path, cfg_text).unwrap();
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let cfg = Config::load_with_profile(Some(&cfg_path), Some("lab"), env_fn).unwrap();

        let place = cfg.where_am_i(env_fn, Some(&cfg_path));
        let text = one(&place);

        let sessions = cfg.sessions_dir(env_fn).unwrap();
        let root = eclipse_core::config::home_root(env_fn).unwrap();
        assert_eq!(
            sessions,
            home.path().join("elsewhere/sessions"),
            "`[sessions] dir` with a ~ is expanded, not taken literally"
        );
        assert!(text.contains(&cfg_path.display().to_string()), "{text}");
        assert!(text.contains(&root.display().to_string()), "{text}");
        assert!(
            text.contains(&sessions.display().to_string()),
            "the sessions dir is the one the loader writes to: {text}"
        );
        assert_eq!(place.profile.as_deref(), Some("lab"));
        assert_eq!(place.home.as_deref(), Some(root.as_path()));
        assert_eq!(place.config.as_deref(), Some(cfg_path.as_path()));
        assert!(place.overlay.is_none(), "lab has no overlay here");

        // A profile with its own config.toml: the overlay is named, because it is the file that
        // wins over the base and the one a person edits to change this profile.
        let overlay = root.join("profiles/lab/config.toml");
        std::fs::create_dir_all(overlay.parent().unwrap()).unwrap();
        std::fs::write(&overlay, "[sessions]\ndir = \"~/elsewhere/sessions\"\n").unwrap();
        let with_overlay = cfg.where_am_i(env_fn, Some(&cfg_path));
        assert_eq!(with_overlay.overlay.as_deref(), Some(overlay.as_path()));
        let text = one(&with_overlay);
        assert!(
            text.contains(&format!("overlay   {}", overlay.display())),
            "{text}"
        );
        assert!(
            text.contains("read after the base so it wins"),
            "the file that wins is named as such: {text}"
        );

        // `doctor` names the same directory when it is missing — the finding and the verb are the
        // same answer, because there is one place that computes it.
        let findings = eclipse_core::doctor::check(&cfg, env_fn);
        let named = findings
            .iter()
            .map(|f| f.detail.clone())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(
            named.contains(&sessions.display().to_string()),
            "doctor says:\n{named}"
        );

        // And `/settings` heads its table with the same file.
        let settings = crate::settings_cli::table(&cfg_path, Some("lab"));
        assert!(
            settings.contains(&cfg_path.display().to_string()),
            "{settings}"
        );
    }

    #[test]
    fn a_session_without_a_config_file_or_a_home_says_so_instead_of_printing_nothing() {
        let place = Where::default();
        let text = one(&place);
        assert!(
            text.contains("profile: default (the default profile)"),
            "{text}"
        );
        assert!(text.contains("without a config file"), "{text}");
        assert!(text.contains("HOME is not set"), "{text}");
        assert!(text.contains("/new"), "{text}");
    }

    #[test]
    fn a_named_profile_says_which_it_is_and_that_it_is_not_the_default() {
        let place = Where {
            profile: Some("lab".into()),
            config: Some(PathBuf::from("/h/.eclipse/profiles/lab/config.toml")),
            overlay: None,
            home: Some(PathBuf::from("/h/.eclipse")),
            sessions: Some(PathBuf::from("/h/.eclipse/profiles/lab/state/sessions")),
        };
        let text = one(&place);
        assert!(text.starts_with("profile: lab\n"), "{text}");
        assert!(!text.contains("the default profile"), "{text}");
        assert!(
            text.contains("/h/.eclipse/profiles/lab/config.toml"),
            "{text}"
        );
    }

    /// A profile whose config moves its sessions counts them where they are: the loader is asked,
    /// not a path joined by hand.
    #[test]
    fn the_session_count_follows_where_that_profile_puts_them() {
        let home = tempfile::tempdir().unwrap();
        let root = home.path().join(".eclipse");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("config.toml"), "").unwrap();
        let overlay = root.join("profiles/lab/config.toml");
        std::fs::create_dir_all(overlay.parent().unwrap()).unwrap();
        std::fs::write(
            &overlay,
            format!(
                "[sessions]\ndir = \"{}\"\n",
                home.path().join("elsewhere").display()
            ),
        )
        .unwrap();
        let elsewhere = home.path().join("elsewhere");
        std::fs::create_dir_all(&elsewhere).unwrap();
        for n in 0..3 {
            std::fs::write(elsewhere.join(format!("s{n}.jsonl")), "").unwrap();
        }
        // The default state directory is empty on purpose: counting that would say `none`.
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let place = Where {
            profile: Some("lab".into()),
            config: Some(root.join("config.toml")),
            overlay: Some(overlay),
            home: Some(root),
            sessions: Some(elsewhere),
        };
        let text = list(&place, env_fn);
        assert!(
            text.lines()
                .any(|l| l.starts_with("* lab") && l.contains("3 sessions")),
            "{text}"
        );
    }

    #[test]
    fn the_list_marks_the_profile_in_effect_and_counts_each_store() {
        let home = tempfile::tempdir().unwrap();
        let root = home.path().join(".eclipse");
        for (name, files) in [("lab", 2), ("work", 0)] {
            std::fs::create_dir_all(root.join("profiles").join(name).join("plugins")).unwrap();
            std::fs::write(root.join("profiles").join(name).join("config.toml"), "").unwrap();
            let sessions = root.join("profiles").join(name).join("state/sessions");
            std::fs::create_dir_all(&sessions).unwrap();
            for n in 0..files {
                std::fs::write(sessions.join(format!("s{n}.jsonl")), "").unwrap();
            }
        }
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let place = Where {
            profile: Some("lab".into()),
            config: Some(root.join("profiles/lab/config.toml")),
            overlay: Some(root.join("profiles/lab/config.toml")),
            home: Some(root.clone()),
            sessions: Some(root.join("profiles/lab/state/sessions")),
        };
        let text = list(&place, env_fn);
        let line = |needle: &str| {
            text.lines()
                .find(|l| l.contains(needle))
                .unwrap_or_default()
                .to_string()
        };
        assert!(line(" lab ").starts_with("* lab"), "{text}");
        assert!(line(" lab ").contains("2 sessions"), "{text}");
        assert!(
            line(" lab ").contains("config overlay, own plugins"),
            "{text}"
        );
        assert!(line(" work ").starts_with("  work"), "{text}");
        assert!(line(" work ").contains("no sessions yet"), "{text}");
        assert!(line("default").starts_with("  default"), "{text}");
        assert!(text.contains("--profile or ECLIPSE_PROFILE"), "{text}");
    }

    #[test]
    fn the_refusal_names_the_two_ways_to_switch() {
        let said = refusal("lab");
        assert!(said.contains("lab"), "{said}");
        assert!(said.contains("`/new`"), "{said}");
        assert!(said.contains("`--profile lab`"), "{said}");
        assert!(
            !said.contains("/profile lab:"),
            "it is the reason, not the input"
        );
    }
}