Skip to main content

cornerstone/
ctx.rs

1//! The context handed to every command body. It bundles the parsed arguments
2//! with the global state (quiet, verbose, dry-run, json) and convenience methods
3//! for output and guards, so a command body reads as pure logic.
4
5use crate::error::{Error, Result};
6use crate::guard;
7use crate::out;
8use crate::parse::Matches;
9
10/// Global switches resolved before the command runs.
11#[derive(Debug, Clone, Copy, Default)]
12pub struct Globals {
13    pub quiet: bool,
14    pub verbose: u8,
15    pub json: bool,
16    pub dry_run: bool,
17    pub sudo: bool,
18}
19
20/// Everything a command body needs. Borrow-friendly: methods take `&self`.
21pub struct Ctx {
22    pub app_name: String,
23    pub command: String,
24    matches: Matches,
25    pub globals: Globals,
26}
27
28impl Ctx {
29    pub(crate) fn new(app_name: String, command: String, matches: Matches, globals: Globals) -> Self {
30        Ctx {
31            app_name,
32            command,
33            matches,
34            globals,
35        }
36    }
37
38    // ---- argument access ----
39
40    /// A required positional argument.
41    pub fn arg(&self, name: &str) -> Result<&str> {
42        self.matches.arg(name)
43    }
44    /// An optional positional argument.
45    pub fn arg_opt(&self, name: &str) -> Option<&str> {
46        self.matches.arg_opt(name)
47    }
48    /// All values of a variadic positional.
49    pub fn args(&self, name: &str) -> Vec<String> {
50        self.matches.args(name)
51    }
52    /// Whether a boolean flag was set.
53    pub fn flag(&self, long: &str) -> bool {
54        self.matches.flag(long)
55    }
56    /// A value flag, if present (or its default).
57    pub fn value(&self, long: &str) -> Option<&str> {
58        self.matches.value(long)
59    }
60    /// A value flag parsed into any `FromStr` type.
61    pub fn value_as<T: std::str::FromStr>(&self, long: &str) -> Result<Option<T>> {
62        match self.matches.value(long) {
63            None => Ok(None),
64            Some(v) => v
65                .parse::<T>()
66                .map(Some)
67                .map_err(|_| Error::usage(format!("invalid value for --{}: {}", long, v))),
68        }
69    }
70
71    // ---- global state ----
72
73    pub fn is_dry_run(&self) -> bool {
74        self.globals.dry_run
75    }
76    pub fn is_json(&self) -> bool {
77        self.globals.json
78    }
79
80    // ---- output convenience (delegate to out::) ----
81
82    pub fn info<S: AsRef<str>>(&self, msg: S) {
83        out::info(msg);
84    }
85    pub fn success<S: AsRef<str>>(&self, msg: S) {
86        out::success(msg);
87    }
88    pub fn warn<S: AsRef<str>>(&self, msg: S) {
89        out::warn(msg);
90    }
91    pub fn debug<S: AsRef<str>>(&self, level: u8, msg: S) {
92        out::debug(level, msg);
93    }
94
95    /// Standard success return for a command that finished a unit of work.
96    pub fn ok<S: AsRef<str>>(&self, msg: S) -> Result<()> {
97        self.success(msg);
98        Ok(())
99    }
100
101    /// Print a line only when not in dry-run, prefixing with the theme's
102    /// dry-run marker when it is, so a dry run narrates what it *would* do.
103    pub fn action<S: AsRef<str>>(&self, msg: S) {
104        if self.globals.dry_run {
105            let t = crate::theme::active();
106            out::info(format!(
107                "{} {}",
108                crate::style::Color::Yellow.paint(&t.dry_run_prefix),
109                msg.as_ref()
110            ));
111        } else {
112            out::info(msg);
113        }
114    }
115
116    // ---- guards ----
117
118    /// Enforce a root requirement using the resolved `--sudo` global.
119    pub fn require_root(&self) -> Result<()> {
120        guard::require_root(self.globals.sudo)
121    }
122
123    /// Enforce destructive confirmation. `confirmed` is typically
124    /// `ctx.flag(DEFAULT_CONFIRM_FLAG)` (or your themed confirm-flag name).
125    pub fn require_confirmation(&self, confirmed: bool) -> Result<()> {
126        guard::require_confirmation(confirmed, self.globals.dry_run)
127    }
128}