-
-
Notifications
You must be signed in to change notification settings - Fork 221
/
mod.rs
384 lines (339 loc) · 11.5 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
//! This module implements the root command of the CLI tool.
use anyhow::{bail, Result};
use clap::{value_parser, Arg, ArgAction, ArgMatches, Command};
use clap_complete::{generate, Generator, Shell};
use log::{debug, info, set_logger, set_max_level, LevelFilter};
use std::borrow::Cow;
use std::io;
use std::process;
use std::{env, iter};
use crate::api::Api;
use crate::config::{Auth, Config};
use crate::constants::{ARCH, PLATFORM, VERSION};
use crate::utils::auth_token::{redact_token_from_string, AuthToken};
use crate::utils::logging::set_quiet_mode;
use crate::utils::logging::Logger;
use crate::utils::system::{init_backtrace, load_dotenv, print_error, QuietExit};
use crate::utils::update::run_sentrycli_update_nagger;
use crate::utils::value_parsers::auth_token_parser;
mod derive_parser;
macro_rules! each_subcommand {
($mac:ident) => {
$mac!(bash_hook);
$mac!(debug_files);
$mac!(deploys);
$mac!(events);
$mac!(files);
$mac!(info);
$mac!(issues);
$mac!(login);
$mac!(monitors);
$mac!(organizations);
$mac!(projects);
$mac!(react_native);
$mac!(releases);
$mac!(repos);
$mac!(send_event);
$mac!(send_envelope);
$mac!(send_metric);
$mac!(sourcemaps);
#[cfg(not(feature = "managed"))]
$mac!(uninstall);
#[cfg(not(feature = "managed"))]
$mac!(update);
$mac!(upload_dif);
$mac!(upload_dsym);
$mac!(upload_proguard);
};
}
macro_rules! import_subcommand {
($name:ident) => {
pub mod $name;
};
}
each_subcommand!(import_subcommand);
const ABOUT: &str = "
Command line utility for Sentry.
This tool helps you manage remote resources on a Sentry server like
sourcemaps, debug symbols or releases. Use `--help` on the subcommands
to learn more about them.";
// Commands we want to run the update nagger on
const UPDATE_NAGGER_CMDS: &[&str] = &[
"debug-files",
"deploys",
"events",
"files",
"info",
"issues",
"login",
"organizations",
"projects",
"releases",
"repos",
"sourcemaps",
];
/// The long auth token argument (--auth-token).
const AUTH_TOKEN_ARG: &str = "auth-token";
fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
}
fn preexecute_hooks() -> Result<bool> {
return sentry_react_native_xcode_wrap();
#[cfg(target_os = "macos")]
fn sentry_react_native_xcode_wrap() -> Result<bool> {
if let Ok(val) = env::var("__SENTRY_RN_WRAP_XCODE_CALL") {
if &val == "1" {
crate::commands::react_native::xcode::wrap_call()?;
return Ok(true);
}
}
Ok(false)
}
#[cfg(not(target_os = "macos"))]
fn sentry_react_native_xcode_wrap() -> Result<bool> {
Ok(false)
}
}
fn configure_args(config: &mut Config, matches: &ArgMatches) -> Result<()> {
if let Some(api_key) = matches.get_one::<String>("api_key") {
config.set_auth(Auth::Key(api_key.to_owned()))?;
}
if let Some(auth_token) = matches.get_one::<AuthToken>("auth_token") {
config.set_auth(Auth::Token(auth_token.to_owned()))?;
}
if let Some(url) = matches.get_one::<String>("url") {
config.set_base_url(url);
}
if let Some(headers) = matches.get_many::<String>("headers") {
let headers = headers.map(|h| h.to_owned()).collect();
config.set_headers(headers);
}
Ok(())
}
pub fn get_log_level(matches: &ArgMatches) -> Result<Option<LevelFilter>> {
match matches.get_one::<String>("log_level") {
Some(log_level) => match log_level.parse() {
Ok(log_level) => Ok(Some(log_level)),
Err(_) => {
bail!("Unknown log level: {}", log_level);
}
},
None => Ok(None),
}
}
fn app() -> Command {
Command::new("sentry-cli")
.version(VERSION)
.about(ABOUT)
.max_term_width(100)
.subcommand_required(true)
.arg_required_else_help(true)
.arg(Arg::new("url").value_name("URL").long("url").help(
"Fully qualified URL to the Sentry server.{n}\
[default: https://sentry.io/]",
))
.arg(
Arg::new("headers")
.long("header")
.value_name("KEY:VALUE")
.action(ArgAction::Append)
.global(true)
.help(
"Custom headers that should be attached to all requests{n}in key:value format.",
),
)
.arg(
Arg::new("auth_token")
.value_name("AUTH_TOKEN")
.long(AUTH_TOKEN_ARG)
.global(true)
.value_parser(auth_token_parser)
.help("Use the given Sentry auth token."),
)
.arg(
Arg::new("api_key")
.value_name("API_KEY")
.long("api-key")
.help("Use the given Sentry API key."),
)
.arg(
Arg::new("log_level")
.value_name("LOG_LEVEL")
.long("log-level")
.value_parser(["trace", "debug", "info", "warn", "error"])
.ignore_case(true)
.global(true)
.help("Set the log output verbosity."),
)
.arg(
Arg::new("quiet")
.long("quiet")
.visible_alias("silent")
.action(ArgAction::SetTrue)
.global(true)
.help("Do not print any output while preserving correct exit code. This flag is currently implemented only for selected subcommands."),
)
.arg(
Arg::new("allow_failure")
.long("allow-failure")
.action(ArgAction::SetTrue)
.global(true)
.hide(true)
.help("Always return 0 exit code."),
)
.subcommand(
Command::new("completions")
.about("Generate completions for the specified shell.")
.arg_required_else_help(true)
.arg(
Arg::new("shell")
.help("The shell to print completions for.")
.value_parser(value_parser!(Shell)),
)
)
}
fn add_commands(mut app: Command) -> Command {
macro_rules! add_subcommand {
($name:ident) => {{
let cmd = $name::make_command(Command::new(stringify!($name).replace("_", "-")));
app = app.subcommand(cmd);
}};
}
each_subcommand!(add_subcommand);
app
}
fn run_command(matches: &ArgMatches) -> Result<()> {
macro_rules! execute_subcommand {
($name:ident) => {{
let cmd = stringify!($name).replace("_", "-");
if let Some(sub_matches) = matches.subcommand_matches(&cmd) {
let rv = $name::execute(&sub_matches)?;
if UPDATE_NAGGER_CMDS.iter().any(|x| x == &cmd) {
run_sentrycli_update_nagger();
}
return Ok(rv);
}
}};
}
each_subcommand!(execute_subcommand);
unreachable!();
}
pub fn execute() -> Result<()> {
// special case for the xcode integration for react native. For more
// information see commands/react_native_xcode.rs
if preexecute_hooks()? {
return Ok(());
}
let mut cmd = app();
cmd = add_commands(cmd);
let matches = cmd.get_matches();
let log_level = get_log_level(&matches)?;
if let Some(log_level) = log_level {
set_max_level(log_level);
}
let mut config = Config::from_cli_config()?;
configure_args(&mut config, &matches)?;
set_quiet_mode(matches.get_flag("quiet"));
if let Some(log_level) = log_level {
config.set_log_level(log_level);
}
// bind the config to the process and fetch an immutable reference to it
config.bind_to_process();
if Config::current().get_filename().exists() {
info!(
"Loaded config from {}",
Config::current().get_filename().display()
);
}
debug!(
"sentry-cli version: {}, platform: \"{}\", architecture: \"{}\"",
VERSION, PLATFORM, ARCH
);
info!(
"sentry-cli was invoked with the following command line: {}",
env::args()
// Check whether the previous argument is "--auth-token"
.zip(
iter::once(false)
.chain(env::args().map(|arg| arg == format!("--{AUTH_TOKEN_ARG}")))
)
.map(|(a, is_auth_token_arg)| {
let redact_replacement = "[REDACTED]";
// Redact anything that comes after --auth-token
let redacted = if is_auth_token_arg {
Cow::Borrowed(redact_replacement)
} else if a.starts_with(&format!("--{AUTH_TOKEN_ARG}=")) {
Cow::Owned(format!("--{AUTH_TOKEN_ARG}={redact_replacement}"))
} else {
redact_token_from_string(&a, redact_replacement)
};
format!("\"{redacted}\"")
})
.collect::<Vec<_>>()
.join(" ")
);
if let Some(argmatches) = matches.subcommand_matches("completions") {
let mut cmd = app();
cmd = add_commands(cmd);
if let Some(generator) = argmatches.get_one::<Shell>("shell") {
eprintln!("Generating completion file for {generator}...");
print_completions(*generator, &mut cmd);
return Ok(());
}
}
match run_command(&matches) {
Ok(()) => Ok(()),
Err(e) => {
if Config::current().get_allow_failure(&matches) {
print_error(&e);
eprintln!("\nCommand failed, however, \"SENTRY_ALLOW_FAILURE\" variable or \"allow-failure\" flag was set. Exiting with 0 exit code.");
Ok(())
} else {
Err(e)
}
}
}
}
fn setup() {
init_backtrace();
// Store the result of loading the dotenv file. We must load the dotenv file
// before setting the log level, as the log level can be set in the dotenv
// file, but we should only log a warning after setting the log level.
let load_dotenv_result = load_dotenv();
// we use debug internally but our log handler then rejects to a lower limit.
// This is okay for our uses but not as efficient.
set_max_level(LevelFilter::Debug);
set_logger(&Logger).unwrap();
if let Err(e) = load_dotenv_result {
log::warn!("Failed to load .env file: {}", e);
}
}
/// Executes the command line application and exits the process.
pub fn main() {
setup();
let exit_code = match execute() {
Ok(()) => 0,
Err(err) => {
let code = if let Some(&QuietExit(code)) = err.downcast_ref() {
code
} else {
print_error(&err);
1
};
// if the user hit an error, it might be time to run the update
// nagger because maybe they tried to do something only newer
// versions support.
run_sentrycli_update_nagger();
code
}
};
// before we shut down we unbind the api to give the connection pool
// a chance to collect. Not doing so has shown to cause hung threads
// on windows.
Api::dispose_pool();
process::exit(exit_code);
}
#[test]
fn verify_app() {
app().debug_assert();
}