1use crate::error::{Error, Result};
6use crate::guard;
7use crate::out;
8use crate::parse::Matches;
9
10#[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
20pub 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 pub fn arg(&self, name: &str) -> Result<&str> {
42 self.matches.arg(name)
43 }
44 pub fn arg_opt(&self, name: &str) -> Option<&str> {
46 self.matches.arg_opt(name)
47 }
48 pub fn args(&self, name: &str) -> Vec<String> {
50 self.matches.args(name)
51 }
52 pub fn flag(&self, long: &str) -> bool {
54 self.matches.flag(long)
55 }
56 pub fn value(&self, long: &str) -> Option<&str> {
58 self.matches.value(long)
59 }
60 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 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 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 pub fn ok<S: AsRef<str>>(&self, msg: S) -> Result<()> {
97 self.success(msg);
98 Ok(())
99 }
100
101 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 pub fn require_root(&self) -> Result<()> {
120 guard::require_root(self.globals.sudo)
121 }
122
123 pub fn require_confirmation(&self, confirmed: bool) -> Result<()> {
126 guard::require_confirmation(confirmed, self.globals.dry_run)
127 }
128}