Skip to main content

oomtop_cli/commands/
mod.rs

1//! Subcommand implementations. Every command gets a [`Ctx`]: the layered config (UX §12.1.3) built from the
2//! global flags, the config paths it resolved to, and helpers to build the engine and format numbers.
3
4mod config;
5mod doctor;
6mod export;
7mod isolation;
8mod keys;
9mod measure;
10mod models;
11mod ports;
12mod profile;
13mod reclaim;
14mod stale;
15mod theme;
16mod tui;
17
18use crate::engine::Engine;
19use crate::{Cli, Cmd, GlobalOpts};
20use anyhow::{anyhow, Result};
21use oomtop_config::layered::{load_layered, LoadOptions, Loaded};
22use oomtop_config::paths::ConfigPaths;
23use oomtop_core::units::{format_bytes, UnitSystem};
24use std::io::{BufRead, IsTerminal, Write};
25
26/// A bad argument discovered after parsing (exit code 2, like clap's own usage errors).
27#[derive(Debug)]
28pub struct UsageError(pub String);
29
30impl std::fmt::Display for UsageError {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        f.write_str(&self.0)
33    }
34}
35
36impl std::error::Error for UsageError {}
37
38/// `Err(UsageError)` as an anyhow error.
39pub fn usage<T>(msg: impl Into<String>) -> Result<T> {
40    Err(anyhow::Error::new(UsageError(msg.into())))
41}
42
43pub struct Ctx {
44    pub global: GlobalOpts,
45    pub opts: LoadOptions,
46    pub loaded: Loaded,
47    /// `--no-learn`, `OOMTOP_NO_LEARN=1` or `personalization.learn = false`.
48    pub no_learn: bool,
49}
50
51impl Ctx {
52    pub fn new(global: GlobalOpts) -> Result<Self> {
53        let mut flags: Vec<(String, String)> = Vec::new();
54        for kv in &global.set {
55            let (k, v) = kv
56                .split_once('=')
57                .ok_or_else(|| UsageError(format!("--set expects KEY=VALUE, got {kv:?}")))?;
58            let k = k.trim();
59            if k.is_empty() {
60                return usage(format!("--set expects KEY=VALUE, got {kv:?}"));
61            }
62            flags.push((k.to_string(), v.trim().to_string()));
63        }
64        let quote = |s: &str| toml::Value::String(s.to_string()).to_string();
65        if let Some(t) = &global.theme {
66            flags.push(("appearance.theme".into(), quote(t)));
67        }
68        if let Some(c) = global.color {
69            flags.push(("appearance.color".into(), quote(c.as_str())));
70        }
71        if global.ascii {
72            flags.push(("appearance.glyphs".into(), quote("ascii")));
73        }
74        if global.no_learn {
75            flags.push(("personalization.learn".into(), "false".into()));
76        }
77        let opts = LoadOptions {
78            config_path: global.config.clone(),
79            flags,
80            ..Default::default()
81        };
82        let loaded = load_layered(&opts);
83        let no_learn = global.no_learn || !loaded.config.personalization.learn;
84        Ok(Ctx {
85            global,
86            opts,
87            loaded,
88            no_learn,
89        })
90    }
91
92    /// Reports config problems once on stderr (the offending layer was skipped). `creating_config`: the
93    /// command is about to create the `--config` file, so "not found" is not worth a warning.
94    fn warn_config_errors(&self, creating_config: bool) {
95        let missing = self.missing_explicit_config();
96        for e in &self.loaded.errors {
97            if creating_config && missing.is_some() && e.path.as_deref() == missing {
98                continue;
99            }
100            eprintln!("oomtop: config: {e}");
101        }
102    }
103
104    /// The file named by `--config` / `OOMTOP_CONFIG` when it does not exist.
105    fn missing_explicit_config(&self) -> Option<&std::path::Path> {
106        self.opts.explicit_config().filter(|p| !p.exists())
107    }
108
109    pub fn config(&self) -> &oomtop_config::Config {
110        &self.loaded.config
111    }
112
113    /// Paths of the effective user config directory (moves with `--config`).
114    pub fn paths(&self) -> ConfigPaths {
115        self.opts.paths()
116    }
117
118    pub fn units(&self) -> UnitSystem {
119        match self.loaded.config.format.memory_units {
120            oomtop_config::model::MemoryUnits::Si => UnitSystem::Si,
121            oomtop_config::model::MemoryUnits::Iec => UnitSystem::Iec,
122        }
123    }
124
125    /// Bytes in the configured units and decimals.
126    pub fn fmt(&self, b: u64) -> String {
127        format_bytes(b, self.units(), self.loaded.config.format.decimals as usize)
128    }
129
130    pub fn fmt_opt(&self, b: Option<u64>) -> String {
131        b.map(|b| self.fmt(b)).unwrap_or_else(|| "n/a".into())
132    }
133
134    pub fn replaying(&self) -> bool {
135        self.global.replay.is_some()
136    }
137
138    /// The state store (none while replaying: a fixture must never write this machine's journal).
139    pub fn state(&self) -> Option<oomtop_state::StateDb> {
140        if self.replaying() {
141            return None;
142        }
143        match oomtop_state::StateDb::open_default() {
144            Ok(mut db) => {
145                db.set_learning(!self.no_learn);
146                let p = &self.loaded.config.personalization;
147                db.set_limits(p.retention_days, p.log_max_mb);
148                Some(db)
149            }
150            Err(e) => {
151                eprintln!("oomtop: state: {e} (continuing without the lineage journal)");
152                None
153            }
154        }
155    }
156
157    /// The pipeline: live sampling of this machine, or `--replay FIXTURE`. `on_demand` = two samples 150 ms
158    /// apart per snapshot (one-shot commands and MCP), so CPU % and rates are real.
159    pub fn engine(&self, on_demand: bool) -> Result<Engine> {
160        self.build_engine(on_demand, false)
161    }
162
163    /// Like [`Ctx::engine`], for commands that must leave no trace (`reclaim --dry-run`): an existing state
164    /// store is read for the lineage journal — so the plan is the one a real run would make — and never
165    /// written; when there is none, none is created.
166    pub fn engine_read_only(&self, on_demand: bool) -> Result<Engine> {
167        self.build_engine(on_demand, true)
168    }
169
170    fn build_engine(&self, on_demand: bool, read_only: bool) -> Result<Engine> {
171        let state = if read_only && !oomtop_state::default_path().is_file() {
172            None
173        } else {
174            self.state()
175        };
176        let dir = self.opts.user_dir();
177        let mut e = match &self.global.replay {
178            Some(p) => Engine::replay_in(&self.loaded.config, p, Some(&dir)).map_err(|e| anyhow!(e))?,
179            None => Engine::live_in(
180                &self.loaded.config,
181                state,
182                on_demand,
183                self.global.offline || !self.loaded.config.adapters.enabled,
184                Some(&dir),
185            ),
186        };
187        e.set_learning(!self.no_learn);
188        if read_only {
189            e.set_state_read_only();
190        }
191        for err in &e.rule_errors {
192            eprintln!("oomtop: rules: {err}");
193        }
194        Ok(e)
195    }
196}
197
198/// Writes to stdout; a closed pipe (`| head`) is not an error.
199pub fn out(s: &str) {
200    let mut o = std::io::stdout().lock();
201    let _ = o.write_all(s.as_bytes());
202    let _ = o.flush();
203}
204
205pub fn json_pretty<T: serde::Serialize>(v: &T) -> Result<String> {
206    Ok(serde_json::to_string_pretty(v)? + "\n")
207}
208
209/// Writes to stderr (human text next to a machine-readable stdout).
210pub fn err_out(s: &str) {
211    let mut o = std::io::stderr().lock();
212    let _ = o.write_all(s.as_bytes());
213    let _ = o.flush();
214}
215
216/// Asks a yes/no question on the terminal. `Ok(None)` when stdin is not a terminal (no one to ask).
217pub fn confirm(question: &str) -> Result<Option<bool>> {
218    if !std::io::stdin().is_terminal() {
219        return Ok(None);
220    }
221    eprint!("{question} [y/N] ");
222    let _ = std::io::stderr().flush();
223    let mut line = String::new();
224    std::io::stdin().lock().read_line(&mut line)?;
225    Ok(Some(matches!(
226        line.trim().to_ascii_lowercase().as_str(),
227        "y" | "yes"
228    )))
229}
230
231pub fn dispatch(cli: Cli) -> Result<i32> {
232    let ctx = Ctx::new(cli.global)?;
233    // `config validate` / `doctor` report config errors themselves.
234    let reports_errors = matches!(
235        cli.command,
236        Some(Cmd::Config {
237            cmd: crate::ConfigCmd::Validate
238        }) | Some(Cmd::Doctor { .. })
239    );
240    // `config init | edit | set` create the file `--config` names; for everything else a missing explicit
241    // config file is a usage error (a typo must not silently mean "defaults").
242    let creating_config = matches!(
243        cli.command,
244        Some(Cmd::Config {
245            cmd: crate::ConfigCmd::Init { .. } | crate::ConfigCmd::Edit { .. } | crate::ConfigCmd::Set { .. }
246        })
247    );
248    if !creating_config {
249        if let Some(p) = ctx.missing_explicit_config() {
250            return usage(format!(
251                "config file not found: {} (named by --config / OOMTOP_CONFIG; create it with `oomtop --config {} config init`)",
252                p.display(),
253                p.display()
254            ));
255        }
256    }
257    if !reports_errors {
258        ctx.warn_config_errors(creating_config);
259    }
260    match cli.command {
261        None => tui::run(&ctx),
262        Some(Cmd::Headroom(a)) => measure::headroom(&ctx, a),
263        Some(Cmd::Why { json }) => measure::why(&ctx, json),
264        Some(Cmd::Models { json, no_hash }) => models::run(&ctx, json, no_hash),
265        Some(Cmd::Ports { json, exposed, links }) => ports::run(&ctx, json, exposed, links),
266        Some(Cmd::Reclaim(a)) => reclaim::run(&ctx, a),
267        Some(Cmd::Sandboxes { json }) => isolation::sandboxes(&ctx, json),
268        Some(Cmd::Ns { json }) => isolation::ns(&ctx, json),
269        Some(Cmd::Stale { json, limit }) => stale::run(&ctx, json, limit),
270        Some(Cmd::Json { compact }) => export::json(&ctx, compact),
271        Some(Cmd::Ndjson {
272            interval,
273            count,
274            discard,
275        }) => export::ndjson(&ctx, interval, count, discard),
276        Some(Cmd::Serve {
277            listen,
278            allow_host,
279            max_requests,
280        }) => export::serve(&ctx, listen, allow_host, max_requests),
281        Some(Cmd::Mcp { allow_actions }) => export::mcp(&ctx, allow_actions),
282        Some(Cmd::Doctor { json, no_probe }) => doctor::run(&ctx, json, no_probe),
283        Some(Cmd::Config { cmd }) => config::run(&ctx, cmd),
284        Some(Cmd::Theme { cmd }) => theme::run(&ctx, cmd),
285        Some(Cmd::Keys { cmd }) => keys::run(&ctx, cmd),
286        Some(Cmd::Profile { cmd }) => profile::run(&ctx, cmd),
287    }
288}