use std::{io, str::FromStr};
use rscni_types::{
error::Error,
legacy,
types::{CNIResult, CNIResultWithVersion},
version::SpecVersion,
};
pub fn result_json(version: SpecVersion, result: CNIResult) -> Result<String, Error> {
if version.is_legacy() {
serde_json::to_string(&legacy::CNIResult::new(version, result))
} else {
serde_json::to_string(&CNIResultWithVersion::new(version, result))
}
.map_err(|e| Error::FailedToDecode(e.to_string()))
}
pub trait Env {
fn get<T>(name: &str) -> Result<Option<T>, Error>
where
T: FromStr,
T::Err: std::error::Error + 'static;
}
pub struct OsEnv;
impl Env for OsEnv {
fn get<T>(name: &str) -> Result<Option<T>, Error>
where
T: FromStr,
T::Err: std::error::Error + 'static,
{
match std::env::var(name) {
Err(std::env::VarError::NotPresent) => Ok(None),
Err(e) => Err(Error::InvalidEnvValue(e.to_string())),
Ok(v) if v.is_empty() => Ok(None),
Ok(v) => v
.parse()
.map(Some)
.map_err(|e: T::Err| Error::InvalidEnvValue(e.to_string())),
}
}
}
pub trait Io {
fn io_in() -> impl io::Read;
fn io_out() -> impl io::Write;
#[allow(dead_code)]
fn io_err() -> impl io::Write;
}
pub struct StdIo;
impl Io for StdIo {
fn io_in() -> impl io::Read {
io::stdin()
}
fn io_out() -> impl io::Write {
io::stdout()
}
fn io_err() -> impl io::Write {
io::stderr()
}
}