use std::{collections::BTreeMap, fmt, net::SocketAddr, path::Path, str::FromStr, time::Duration};
use bytesize::ByteSize;
use serde::Deserialize;
use crate::config::{ConfigError, TextSource};
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct OptionalDuration(pub Option<Duration>);
impl fmt::Display for OptionalDuration {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Some(duration) => write!(formatter, "{}", humantime::format_duration(duration)),
None => formatter.write_str("off"),
}
}
}
pub fn parse_optional_duration(value: &str) -> Result<OptionalDuration, String> {
let trimmed = value.trim();
if trimmed.eq_ignore_ascii_case("off") || trimmed.eq_ignore_ascii_case("none") {
return Ok(OptionalDuration(None));
}
humantime::parse_duration(trimmed)
.map(|duration| OptionalDuration(Some(duration)))
.map_err(|error| error.to_string())
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct OptionalBytes(pub Option<ByteSize>);
impl fmt::Display for OptionalBytes {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Some(bytes) => write!(formatter, "{bytes}"),
None => formatter.write_str("unlimited"),
}
}
}
pub fn parse_optional_bytes(value: &str) -> Result<OptionalBytes, String> {
let trimmed = value.trim();
if trimmed.eq_ignore_ascii_case("unlimited") {
return Ok(OptionalBytes(None));
}
trimmed.parse().map(|bytes| OptionalBytes(Some(bytes)))
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct OptionalAddress(pub Option<SocketAddr>);
impl fmt::Display for OptionalAddress {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Some(address) => write!(formatter, "{address}"),
None => formatter.write_str("off"),
}
}
}
pub fn parse_optional_address(value: &str) -> Result<OptionalAddress, String> {
let trimmed = value.trim();
if trimmed.eq_ignore_ascii_case("off") {
return Ok(OptionalAddress(None));
}
trimmed
.parse()
.map(|address| OptionalAddress(Some(address)))
.map_err(|error| format!("{error}"))
}
#[derive(Debug, Deserialize)]
#[serde(transparent)]
pub struct TomlTable<T>(pub BTreeMap<String, T>);
impl<T> Default for TomlTable<T> {
fn default() -> Self {
Self(BTreeMap::new())
}
}
impl<T: serde::de::DeserializeOwned> FromStr for TomlTable<T> {
type Err = toml::de::Error;
fn from_str(value: &str) -> Result<Self, Self::Err> {
toml::from_str(value).map_err(|mut error| {
error.set_input(None);
error
})
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(transparent)]
pub struct TomlValue<T>(pub T);
impl<T: serde::de::DeserializeOwned> FromStr for TomlValue<T> {
type Err = toml::de::Error;
fn from_str(value: &str) -> Result<Self, Self::Err> {
#[derive(Deserialize)]
struct Wrapper<T> {
value: T,
}
toml::from_str::<Wrapper<T>>(&format!("value = {value}")).map(|wrapper| Self(wrapper.value))
}
}
pub fn read_credential(
label: &str,
source: Option<&TextSource>,
cli_file: Option<&Path>,
) -> Result<Option<String>, ConfigError> {
match cli_file {
Some(path) => TextSource::File(path.to_path_buf()).read(label).map(Some),
None => source.map(|source| source.read(label)).transpose(),
}
}