Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retrieve the events list for a project for v2 #1307

Merged
merged 5 commits into from
Aug 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
102 changes: 102 additions & 0 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1414,6 +1414,52 @@ impl Api {
Ok(rv)
}

/// List all events associated with an organization and a project
pub fn list_organization_project_events(
&self,
org: &str,
project: &str,
max_pages: usize,
) -> ApiResult<Vec<ProcessedEvent>> {
let mut rv = vec![];
let mut cursor = "".to_string();
let mut requests_no = 0;

loop {
requests_no += 1;

let resp = self.get(&format!(
"/projects/{}/{}/events/?cursor={}",
PathArg(org),
PathArg(project),
QueryArg(&cursor)
))?;

if resp.status() == 404 || (resp.status() == 400 && !cursor.is_empty()) {
if rv.is_empty() {
return Err(ApiErrorKind::OrganizationNotFound.into());
} else {
break;
}
}

let pagination = resp.pagination();
rv.extend(resp.convert::<Vec<ProcessedEvent>>()?.into_iter());

if requests_no == max_pages {
break;
}

if let Some(next) = pagination.into_next_cursor() {
cursor = next;
} else {
break;
}
}

Ok(rv)
}

/// List all repos associated with an organization
pub fn list_organization_repos(&self, org: &str) -> ApiResult<Vec<Repo>> {
let mut rv = vec![];
Expand Down Expand Up @@ -2604,7 +2650,12 @@ pub struct GitCommit {

#[derive(Clone, Debug, Deserialize)]
pub struct ProcessedEvent {
#[serde(alias = "eventID")]
pub event_id: Uuid,
#[serde(default, alias = "dateCreated")]
pub date_created: String,
#[serde(default)]
pub title: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub project: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
Expand All @@ -2613,4 +2664,55 @@ pub struct ProcessedEvent {
pub dist: Option<String>,
#[serde(default, skip_serializing_if = "Values::is_empty")]
pub exception: Values<Exception>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user: Option<ProcessedEventUser>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Vec<ProcessedEventTag>>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct ProcessedEventUser {
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ip_address: Option<String>,
}

impl fmt::Display for ProcessedEventUser {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(id) = &self.id {
write!(f, "ID: {}", id)?;
}

if let Some(username) = &self.username {
write!(f, "Username: {}", username)?;
}

if let Some(email) = &self.email {
write!(f, "Email: {}", email)?;
}

if let Some(ip_address) = &self.ip_address {
write!(f, "IP: {}", ip_address)?;
}

Ok(())
}
}

#[derive(Clone, Debug, Deserialize)]
pub struct ProcessedEventTag {
pub key: String,
pub value: String,
}

impl fmt::Display for ProcessedEventTag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}: {}", &self.key, &self.value)?;
Ok(())
}
}
102 changes: 102 additions & 0 deletions src/commands/events/list.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
use anyhow::Result;
use clap::{Arg, ArgMatches, Command};

use crate::api::Api;
use crate::config::Config;
use crate::utils::formatting::Table;

pub fn make_command(command: Command) -> Command {
command
.about("List all events in your organization.")
.arg(
Arg::with_name("show_user")
.long("show-user")
.short('U')
.help("Display the Users column."),
)
.arg(
Arg::with_name("show_tags")
.long("show-tags")
.short('T')
.help("Display the Tags column."),
)
.arg(
Arg::new("max_rows")
.long("max-rows")
.value_name("MAX_ROWS")
.value_parser(clap::value_parser!(usize))
.help("Maximum number of rows to print."),
)
.arg(
Arg::new("pages")
.long("pages")
.value_name("PAGES")
.default_value("5")
.value_parser(clap::value_parser!(usize))
.help("Maximum number of pages to fetch (100 events/page)."),
)
}

pub fn execute(matches: &ArgMatches) -> Result<()> {
let config = Config::current();
let org = config.get_org(matches)?;
let project = config.get_project(matches)?;
let pages = *matches.get_one("pages").unwrap();
let api = Api::current();

let events = api.list_organization_project_events(&org, &project, pages)?;

let mut table = Table::new();
let title_row = table.title_row().add("Event ID").add("Date").add("Title");

if matches.is_present("show_user") {
title_row.add("User");
}

if matches.is_present("show_tags") {
title_row.add("Tags");
}

let max_rows = std::cmp::min(
events.len(),
*matches.get_one("max_rows").unwrap_or(&std::usize::MAX),
);

if let Some(events) = events.get(..max_rows) {
for event in events {
let row = table.add_row();
row.add(&event.event_id)
.add(&event.date_created)
.add(&event.title);

if matches.is_present("show_user") {
if let Some(user) = &event.user {
row.add(user);
} else {
row.add("-");
}
}

if matches.is_present("show_tags") {
if let Some(tags) = &event.tags {
row.add(
tags.iter()
.map(|t| t.to_string())
.collect::<Vec<_>>()
.join("\n"),
);
} else {
row.add("-");
}
}
}
}

if table.is_empty() {
println!("No events found");
} else {
table.print();
}

Ok(())
}
45 changes: 45 additions & 0 deletions src/commands/events/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use anyhow::Result;
use clap::{ArgMatches, Command};

use crate::utils::args::ArgExt;

pub mod list;

macro_rules! each_subcommand {
($mac:ident) => {
$mac!(list);
};
}

pub fn make_command(mut command: Command) -> Command {
macro_rules! add_subcommand {
($name:ident) => {{
command = command.subcommand(crate::commands::events::$name::make_command(
Command::new(stringify!($name).replace('_', "-")),
));
}};
}

command = command
boozec marked this conversation as resolved.
Show resolved Hide resolved
.about("Manage events on Sentry.")
.subcommand_required(true)
.arg_required_else_help(true)
.org_arg()
.project_arg(true);
each_subcommand!(add_subcommand);
command
}

pub fn execute(matches: &ArgMatches) -> Result<()> {
macro_rules! execute_subcommand {
($name:ident) => {{
if let Some(sub_matches) =
matches.subcommand_matches(&stringify!($name).replace('_', "-"))
{
return crate::commands::events::$name::execute(&sub_matches);
}
}};
}
each_subcommand!(execute_subcommand);
unreachable!();
}
2 changes: 2 additions & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ macro_rules! each_subcommand {
$mac!(bash_hook);
$mac!(debug_files);
$mac!(deploys);
$mac!(events);
$mac!(files);
$mac!(info);
$mac!(issues);
Expand Down Expand Up @@ -62,6 +63,7 @@ to learn more about them.";
const UPDATE_NAGGER_CMDS: &[&str] = &[
"debug-files",
"deploys",
"events",
"files",
"info",
"issues",
Expand Down
27 changes: 27 additions & 0 deletions tests/integration/_cases/events/events-help.trycmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
```
$ sentry-cli events --help
? success
sentry-cli[EXE]-events
Manage events on Sentry.

USAGE:
sentry-cli[EXE] events [OPTIONS] <SUBCOMMAND>

OPTIONS:
--auth-token <AUTH_TOKEN> Use the given Sentry auth token.
-h, --help Print help information
--header <KEY:VALUE> Custom headers that should be attached to all requests
in key:value format.
--log-level <LOG_LEVEL> Set the log output verbosity. [possible values: trace, debug,
info, warn, error]
-o, --org <ORG> The organization slug
-p, --project <PROJECT> The project slug.
--quiet Do not print any output while preserving correct exit code.
This flag is currently implemented only for selected
subcommands. [aliases: silent]

SUBCOMMANDS:
help Print this message or the help of the given subcommand(s)
list List all events in your organization.

```
6 changes: 6 additions & 0 deletions tests/integration/_cases/events/events-list-empty.trycmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
```
$ sentry-cli events list
? success
No events found

```
28 changes: 28 additions & 0 deletions tests/integration/_cases/events/events-list-help.trycmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
```
$ sentry-cli events list --help
? success
sentry-cli[EXE]-events-list
List all events in your organization.

USAGE:
sentry-cli[EXE] events list [OPTIONS]

OPTIONS:
--auth-token <AUTH_TOKEN> Use the given Sentry auth token.
-h, --help Print help information
--header <KEY:VALUE> Custom headers that should be attached to all requests
in key:value format.
--log-level <LOG_LEVEL> Set the log output verbosity. [possible values: trace, debug,
info, warn, error]
--max-rows <MAX_ROWS> Maximum number of rows to print.
-o, --org <ORG> The organization slug
-p, --project <PROJECT> The project slug.
--pages <PAGES> Maximum number of pages to fetch (100 events/page). [default:
5]
--quiet Do not print any output while preserving correct exit code.
This flag is currently implemented only for selected
subcommands. [aliases: silent]
-T, --show-tags Display the Tags column.
-U, --show-user Display the Users column.

```
27 changes: 27 additions & 0 deletions tests/integration/_cases/events/events-no-subcommand.trycmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
```
$ sentry-cli events
? failed
sentry-cli[EXE]-events
Manage events on Sentry.

USAGE:
sentry-cli[EXE] events [OPTIONS] <SUBCOMMAND>

OPTIONS:
--auth-token <AUTH_TOKEN> Use the given Sentry auth token.
-h, --help Print help information
--header <KEY:VALUE> Custom headers that should be attached to all requests
in key:value format.
--log-level <LOG_LEVEL> Set the log output verbosity. [possible values: trace, debug,
info, warn, error]
-o, --org <ORG> The organization slug
-p, --project <PROJECT> The project slug.
--quiet Do not print any output while preserving correct exit code.
This flag is currently implemented only for selected
subcommands. [aliases: silent]

SUBCOMMANDS:
help Print this message or the help of the given subcommand(s)
list List all events in your organization.

```
1 change: 1 addition & 0 deletions tests/integration/_cases/help/help-windows.trycmd
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ OPTIONS:
SUBCOMMANDS:
debug-files Locate, analyze or upload debug information files. [aliases: dif]
deploys Manage deployments for Sentry releases.
events Manage events on Sentry.
files Manage release artifacts.
help Print this message or the help of the given subcommand(s)
info Print information about the Sentry server.
Expand Down
1 change: 1 addition & 0 deletions tests/integration/_cases/help/help.trycmd
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ OPTIONS:
SUBCOMMANDS:
debug-files Locate, analyze or upload debug information files. [aliases: dif]
deploys Manage deployments for Sentry releases.
events Manage events on Sentry.
files Manage release artifacts.
help Print this message or the help of the given subcommand(s)
info Print information about the Sentry server.
Expand Down