1
2use std::io::{self, Write};
3use std::str::FromStr;
4
5use anyhow::{Context, bail};
6use serde::Serialize;
7use serde_json;
8use tonic::transport::Uri;
9
10pub fn default_scheme(default_scheme: &'static str, url: impl AsRef<str>) -> anyhow::Result<String> {
12 let url = url.as_ref();
13 let mut uri_parts = Uri::from_str(url).context("invalid url")?.into_parts();
14 if uri_parts.authority.is_none() {
15 bail!("invalid url '{}': missing authority", url);
16 }
17 if uri_parts.scheme.is_none() {
18 uri_parts.scheme = Some(default_scheme.parse().unwrap());
19 uri_parts.path_and_query = Some(uri_parts.path_and_query
21 .unwrap_or_else(|| "".parse().unwrap())
22 );
23 let new = Uri::from_parts(uri_parts).unwrap();
24 Ok(new.to_string())
25 } else {
26 Ok(url.to_owned())
27 }
28}
29
30pub fn output_json<T>(value: &T)
32where
33 T: ?Sized + Serialize,
34{
35 serde_json::to_writer_pretty(io::stdout(), value).expect("value is serializable");
36 write!(io::stdout(), "\n").expect("Failed to write newline to stdout");
37}