use crate::error::{Error, Result};
use crate::guard;
use crate::out;
use crate::parse::Matches;
#[derive(Debug, Clone, Copy, Default)]
pub struct Globals {
pub quiet: bool,
pub verbose: u8,
pub json: bool,
pub dry_run: bool,
pub sudo: bool,
}
pub struct Ctx {
pub app_name: String,
pub command: String,
matches: Matches,
pub globals: Globals,
}
impl Ctx {
pub(crate) fn new(app_name: String, command: String, matches: Matches, globals: Globals) -> Self {
Ctx {
app_name,
command,
matches,
globals,
}
}
pub fn arg(&self, name: &str) -> Result<&str> {
self.matches.arg(name)
}
pub fn arg_opt(&self, name: &str) -> Option<&str> {
self.matches.arg_opt(name)
}
pub fn args(&self, name: &str) -> Vec<String> {
self.matches.args(name)
}
pub fn flag(&self, long: &str) -> bool {
self.matches.flag(long)
}
pub fn value(&self, long: &str) -> Option<&str> {
self.matches.value(long)
}
pub fn value_as<T: std::str::FromStr>(&self, long: &str) -> Result<Option<T>> {
match self.matches.value(long) {
None => Ok(None),
Some(v) => v
.parse::<T>()
.map(Some)
.map_err(|_| Error::usage(format!("invalid value for --{}: {}", long, v))),
}
}
pub fn is_dry_run(&self) -> bool {
self.globals.dry_run
}
pub fn is_json(&self) -> bool {
self.globals.json
}
pub fn info<S: AsRef<str>>(&self, msg: S) {
out::info(msg);
}
pub fn success<S: AsRef<str>>(&self, msg: S) {
out::success(msg);
}
pub fn warn<S: AsRef<str>>(&self, msg: S) {
out::warn(msg);
}
pub fn debug<S: AsRef<str>>(&self, level: u8, msg: S) {
out::debug(level, msg);
}
pub fn ok<S: AsRef<str>>(&self, msg: S) -> Result<()> {
self.success(msg);
Ok(())
}
pub fn action<S: AsRef<str>>(&self, msg: S) {
if self.globals.dry_run {
let t = crate::theme::active();
out::info(format!(
"{} {}",
crate::style::Color::Yellow.paint(&t.dry_run_prefix),
msg.as_ref()
));
} else {
out::info(msg);
}
}
pub fn require_root(&self) -> Result<()> {
guard::require_root(self.globals.sudo)
}
pub fn require_confirmation(&self, confirmed: bool) -> Result<()> {
guard::require_confirmation(confirmed, self.globals.dry_run)
}
}