From 955434a8c86cf8a2ae7e4d62e67441e281398d46 Mon Sep 17 00:00:00 2001 From: stuebinm Date: Wed, 30 Nov 2022 23:19:18 +0100 Subject: way to elaborate error messages (but miette is fun!) --- src/main.rs | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index 81a5067..feb6e9c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,9 @@ use protos::protos::gtfs_realtime::FeedMessage; use protobuf::Message; use clap::Parser; +// use anyhow::Context; +use miette::{WrapErr, IntoDiagnostic, miette}; +use reqwest::header::{HeaderValue, CONTENT_TYPE}; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] @@ -12,22 +15,42 @@ struct Args { url: String, /// emit the feed as json #[arg(long)] - json: bool + json: bool, + #[arg(long="ignore-nonfatal", short='i')] + ignore_nonfatal: bool } #[tokio::main] -async fn main() -> Result<(), Box> { +async fn main() -> miette::Result<()> { + let args = Args::parse(); let resp = reqwest::get(&args.url) - .await? - .bytes().await?; + .await.into_diagnostic().wrap_err("Request failed")? + .error_for_status().into_diagnostic()?; + + if !args.ignore_nonfatal { + let ct = HeaderValue::from_static("application/octet-stream"); + match resp.headers().get(CONTENT_TYPE) { + Some(content_type) if ct == content_type => (), + Some(other_type) => + Err(miette!("should be {:?}", ct)) + .wrap_err(format!("Bad Content-Type {:?}", other_type))?, + None => + Err(miette!("Content-Type header is missing"))? + } + } + + let resp = resp + .bytes().await.into_diagnostic()?; - let proto = FeedMessage::parse_from_bytes(&resp[..])?; + let proto = FeedMessage::parse_from_bytes(&resp[..]) + .into_diagnostic() + .wrap_err("Could not parse protobuf format")?; match args.json { true => - println!("{}", protobuf_json_mapping::print_to_string(&proto)?), + println!("{}", protobuf_json_mapping::print_to_string(&proto).into_diagnostic()?), false => println!("{}", protobuf::text_format::print_to_string_pretty(&proto)) } -- cgit v1.2.3