1use std::ffi::OsString;
6use std::path::PathBuf;
7
8use clap::{Args, Command, Parser, Subcommand, ValueEnum};
9use fs_mistrust::anon_home::PathExt as _;
10use once_cell::sync::Lazy;
11use tor_config::{ConfigurationSource, ConfigurationSources};
12use tor_config_path::CfgPathError;
13
14use crate::config::default_config_paths;
15
16static DEFAULT_CONFIG_PATHS: Lazy<Result<Vec<PathBuf>, CfgPathError>> =
20 Lazy::new(default_config_paths);
21
22#[derive(Clone, Debug, Parser)]
24#[command(author = "The Tor Project Developers")]
25#[command(version)]
26#[command(defer = cli_cmd_post_processing)]
27pub(crate) struct Cli {
28 #[command(subcommand)]
30 pub(crate) command: Commands,
31
32 #[clap(flatten)]
36 pub(crate) global: GlobalArgs,
37}
38
39fn cli_cmd_post_processing(cli: Command) -> Command {
43 fn fmt_help(help: Option<&str>, paths: &[PathBuf]) -> String {
45 let help = help.map(|x| format!("{x}\n\n")).unwrap_or("".to_string());
46 let paths: Vec<_> = paths
47 .iter()
48 .map(|x| x.anonymize_home().to_string())
49 .collect();
50 let paths = paths.join("\n");
51
52 const DESC: &str =
55 "If no paths are provided, the following config paths will be used if they exist:";
56 format!("{help}{DESC}\n\n{paths}")
57 }
58
59 match &*DEFAULT_CONFIG_PATHS {
61 Ok(paths) => cli.mut_arg("config", |arg| {
62 if let Some(help) = arg.get_long_help() {
63 let help = help.to_string();
64 arg.long_help(fmt_help(Some(&help), paths))
65 } else if let Some(help) = arg.get_help() {
66 let help = help.to_string();
67 arg.long_help(fmt_help(Some(&help), paths))
68 } else {
69 arg.long_help(fmt_help(None, paths))
70 }
71 }),
72 Err(_e) => cli,
73 }
74}
75
76#[derive(Clone, Debug, Subcommand)]
78pub(crate) enum Commands {
79 Run(RunArgs),
81 BuildInfo,
83}
84
85#[derive(Clone, Debug, Args)]
88pub(crate) struct GlobalArgs {
89 #[arg(long, short, global = true)]
91 #[arg(value_name = "LEVEL")]
92 pub(crate) log_level: Option<LogLevel>,
93
94 #[arg(long, global = true)]
96 pub(crate) disable_fs_permission_checks: bool,
97
98 #[arg(long = "option", short, global = true)]
100 #[arg(value_name = "KEY=VALUE")]
101 pub(crate) options: Vec<String>,
102
103 #[arg(long, short, global = true)]
108 #[arg(value_name = "PATH")]
109 config: Vec<OsString>,
110}
111
112impl GlobalArgs {
113 pub(crate) fn config(&self) -> Result<ConfigurationSources, CfgPathError> {
119 let mut cfg_sources = ConfigurationSources::try_from_cmdline(
121 || {
122 Ok(DEFAULT_CONFIG_PATHS
123 .as_ref()
124 .map_err(Clone::clone)?
125 .iter()
126 .map(ConfigurationSource::from_path))
127 },
128 &self.config,
129 &self.options,
130 )?;
131
132 if self.disable_fs_permission_checks {
137 cfg_sources.push_option("storage.permissions.dangerously_trust_everyone=true");
138 }
139
140 if let Some(log_level) = self.log_level {
141 cfg_sources.push_option(format!("logging.console={log_level}"));
142 }
143
144 Ok(cfg_sources)
145 }
146}
147
148#[derive(Clone, Debug, Args)]
150pub(crate) struct RunArgs {}
151
152#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
154pub(crate) enum LogLevel {
155 #[value(help = None)]
157 Error,
158 #[value(help = None)]
160 Warn,
161 #[value(help = None)]
163 Info,
164 #[value(help = None)]
166 Debug,
167 #[value(help = None)]
169 Trace,
170}
171
172impl std::fmt::Display for LogLevel {
173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174 match self {
175 Self::Error => write!(f, "error"),
176 Self::Warn => write!(f, "warn"),
177 Self::Info => write!(f, "info"),
178 Self::Debug => write!(f, "debug"),
179 Self::Trace => write!(f, "trace"),
180 }
181 }
182}
183
184impl From<LogLevel> for tracing::metadata::Level {
185 fn from(x: LogLevel) -> Self {
186 match x {
187 LogLevel::Error => Self::ERROR,
188 LogLevel::Warn => Self::WARN,
189 LogLevel::Info => Self::INFO,
190 LogLevel::Debug => Self::DEBUG,
191 LogLevel::Trace => Self::TRACE,
192 }
193 }
194}
195
196#[cfg(test)]
197mod test {
198 #![allow(clippy::bool_assert_comparison)]
200 #![allow(clippy::clone_on_copy)]
201 #![allow(clippy::dbg_macro)]
202 #![allow(clippy::mixed_attributes_style)]
203 #![allow(clippy::print_stderr)]
204 #![allow(clippy::print_stdout)]
205 #![allow(clippy::single_char_pattern)]
206 #![allow(clippy::unwrap_used)]
207 #![allow(clippy::unchecked_duration_subtraction)]
208 #![allow(clippy::useless_vec)]
209 #![allow(clippy::needless_pass_by_value)]
210 use super::*;
213
214 #[test]
215 fn common_flags() {
216 Cli::parse_from(["arti-relay", "build-info"]);
217 Cli::parse_from(["arti-relay", "run"]);
218
219 let cli = Cli::parse_from(["arti-relay", "--log-level", "warn", "run"]);
220 assert_eq!(cli.global.log_level, Some(LogLevel::Warn));
221 let cli = Cli::parse_from(["arti-relay", "run", "--log-level", "warn"]);
222 assert_eq!(cli.global.log_level, Some(LogLevel::Warn));
223
224 let cli = Cli::parse_from(["arti-relay", "--disable-fs-permission-checks", "run"]);
225 assert!(cli.global.disable_fs_permission_checks);
226 let cli = Cli::parse_from(["arti-relay", "run", "--disable-fs-permission-checks"]);
227 assert!(cli.global.disable_fs_permission_checks);
228 }
229
230 #[test]
231 fn clap_bug() {
232 let cli = Cli::parse_from(["arti-relay", "-o", "foo=1", "run"]);
233 assert_eq!(cli.global.options, vec!["foo=1"]);
234
235 let cli = Cli::parse_from(["arti-relay", "-o", "foo=1", "-o", "bar=2", "run"]);
236 assert_eq!(cli.global.options, vec!["foo=1", "bar=2"]);
237
238 let cli = Cli::parse_from(["arti-relay", "-o", "foo=1", "run", "-o", "bar=2"]);
241 assert_eq!(cli.global.options, vec!["bar=2"]);
242 }
243
244 #[test]
245 fn global_args_are_global() {
246 let cmd = Command::new("test");
247 let cmd = GlobalArgs::augment_args(cmd);
248
249 for arg in cmd.get_arguments() {
251 assert!(
252 arg.is_global_set(),
253 "'global' must be set for {:?}",
254 arg.get_long()
255 );
256 }
257 }
258}