use std::env::{self, ArgsOs};
use std::fmt;
use std::iter::Skip;
pub const PROTOCOL_ENV: &str = "GUTIL_PLUGIN_PROTOCOL";
pub const PROTOCOL_VERSION: &str = "1";
pub struct Invocation {
args: Skip<ArgsOs>,
}
impl Invocation {
pub fn from_env() -> Result<Self, ProtocolError> {
Self::from_protocol(env::var(PROTOCOL_ENV))
}
fn from_protocol(protocol: Result<String, env::VarError>) -> Result<Self, ProtocolError> {
match protocol {
Ok(version) if version == PROTOCOL_VERSION => Ok(Self {
args: env::args_os().skip(1), }),
Err(env::VarError::NotPresent) => Err(ProtocolError::Missing),
_ => Err(ProtocolError::Unsupported),
}
}
pub fn into_args(self) -> Skip<ArgsOs> {
self.args
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ProtocolError {
Missing,
Unsupported,
}
impl fmt::Display for ProtocolError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let message = match self {
Self::Missing => "start this plug-in with 'gutil plug-in use'",
Self::Unsupported => "unsupported gutil plug-in protocol version",
};
f.write_str(message)
}
}
impl std::error::Error for ProtocolError {}
#[cfg(test)]
mod tests {
use super::{env, Invocation, ProtocolError, PROTOCOL_VERSION};
#[test]
fn validates_launcher_version() {
assert!(Invocation::from_protocol(Ok(PROTOCOL_VERSION.to_owned()))
.map(Invocation::into_args)
.is_ok());
assert_eq!(
Invocation::from_protocol(Err(env::VarError::NotPresent)).err(),
Some(ProtocolError::Missing)
);
assert_eq!(
Invocation::from_protocol(Ok("999".to_owned())).err(),
Some(ProtocolError::Unsupported)
);
}
}