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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cli: add basic error reporting using anyhow #25

Merged
merged 1 commit into from
Dec 17, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
# Unreleased (Yet)

## v0.5.0 (2024-12-17)

- Added basic error reporting. For example, the CLI might now tell you:
- ```
Error:
Failed to parse response body as JSON

Caused by:
0: error decoding response body
1: missing field `webUrl2` at line 1 column 308
```
- ```
Error:
Failed to receive proper response

Caused by:
HTTP status client error (401 Unauthorized) for url (https://gitlab.vpn.cyberus-technology.de/api/graphql)
```

## v0.4.1 (2024-12-17)

- Better error reporting: it is now clearer if the request failed due to a
Expand Down
11 changes: 9 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ authors = [
]

[dependencies]
anyhow = "1.0.94"
chrono = { version = "0.4.38", default-features = false, features = ["clock", "std", "serde"] }
nu-ansi-term = "0.50.0"
reqwest = { version = "0.12.4", features = ["blocking", "json"] }
Expand Down
26 changes: 13 additions & 13 deletions src/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ SOFTWARE.
//! [`fetch_results`] is the entry point.

use crate::gitlab_api::types::Response;
use anyhow::Context;
use chrono::{DateTime, Local, NaiveDate, NaiveTime};
use reqwest::blocking::Client;
use reqwest::header::AUTHORIZATION;
Expand Down Expand Up @@ -61,7 +62,7 @@ fn fetch_result(
before: Option<&str>,
start_date: NaiveDate,
end_date: NaiveDate,
) -> Response {
) -> anyhow::Result<Response> {
let graphql_query = GRAPHQL_TEMPLATE
.replace("%USERNAME%", username)
.replace("%BEFORE%", before.unwrap_or_default())
Expand All @@ -85,19 +86,18 @@ fn fetch_result(
let url = format!("https://{host}/api/graphql", host = host);
let client = Client::new();

match client
let plain_response = client
.post(url)
.header(AUTHORIZATION, authorization)
.json(&payload)
.send()
.unwrap()
.context("Failed to send request")?
.error_for_status()
{
Ok(response) => response.json::<Response>().unwrap(),
Err(err) => {
panic!("Request to Gitlab failed: {err}")
}
}
.context("Failed to receive proper response")?;

plain_response
.json::<Response>()
.context("Failed to parse response body as JSON")
}

/// Fetches all results from the API with pagination in mind.
Expand All @@ -115,8 +115,8 @@ pub fn fetch_results(
token: &str,
start_date: NaiveDate,
end_date: NaiveDate,
) -> Response {
let base = fetch_result(username, host, token, None, start_date, end_date);
) -> anyhow::Result<Response> {
let base = fetch_result(username, host, token, None, start_date, end_date)?;

let mut aggregated = base;
while aggregated.data.timelogs.pageInfo.hasPreviousPage {
Expand All @@ -134,7 +134,7 @@ pub fn fetch_results(
),
start_date,
end_date,
);
)?;

// Ordering here is not that important, happens later anyway.
next.data
Expand All @@ -143,5 +143,5 @@ pub fn fetch_results(
.extend(aggregated.data.timelogs.nodes);
aggregated = next;
}
aggregated
Ok(aggregated)
}
17 changes: 12 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ use crate::cfg::get_cfg;
use crate::cli::CliArgs;
use crate::fetch::fetch_results;
use crate::gitlab_api::types::ResponseNode;
use anyhow::{anyhow, Context};
use chrono::{Datelike, NaiveDate, Weekday};
use nu_ansi_term::{Color, Style};
use std::error::Error;
Expand All @@ -58,18 +59,24 @@ mod views;

fn main() -> Result<(), Box<dyn Error>> {
let cfg = get_cfg()?;
assert!(cfg.before() >= cfg.after());
println!("Host : {}", cfg.host());
println!("Username : {}", cfg.username());
println!("Time Span: {} - {}", cfg.after(), cfg.before());
if cfg.before() < cfg.after() {
Err(anyhow!(
"The `--before` date must come after the `--after` date"
))
.context("Failed to validate config")?;
}

let response = fetch_results(
cfg.username(),
cfg.host(),
cfg.token(),
cfg.after(),
cfg.before(),
);
)?;

println!("Host : {}", cfg.host());
println!("Username : {}", cfg.username());
println!("Time Span: {} - {}", cfg.after(), cfg.before());

// All nodes but as vector to references.
// Simplifies the handling with other parts of the code, especially the
Expand Down
Loading