1use std::env::{self, ArgsOs};
4use std::fmt;
5use std::iter::Skip;
6
7pub const PROTOCOL_ENV: &str = "GUTIL_PLUGIN_PROTOCOL";
9pub const PROTOCOL_VERSION: &str = "1";
11
12pub struct Invocation {
14 args: Skip<ArgsOs>,
15}
16
17impl Invocation {
18 pub fn from_env() -> Result<Self, ProtocolError> {
25 Self::from_protocol(env::var(PROTOCOL_ENV))
26 }
27
28 fn from_protocol(protocol: Result<String, env::VarError>) -> Result<Self, ProtocolError> {
29 match protocol {
30 Ok(version) if version == PROTOCOL_VERSION => Ok(Self {
31 args: env::args_os().skip(1), }),
33 Err(env::VarError::NotPresent) => Err(ProtocolError::Missing),
34 _ => Err(ProtocolError::Unsupported),
35 }
36 }
37
38 pub fn into_args(self) -> Skip<ArgsOs> {
40 self.args
41 }
42}
43
44#[derive(Clone, Copy, Debug, Eq, PartialEq)]
46pub enum ProtocolError {
47 Missing,
49 Unsupported,
51}
52
53impl fmt::Display for ProtocolError {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 let message = match self {
56 Self::Missing => "start this plug-in with 'gutil plug-in use'",
57 Self::Unsupported => "unsupported gutil plug-in protocol version",
58 };
59 f.write_str(message)
60 }
61}
62
63impl std::error::Error for ProtocolError {}
64
65#[cfg(test)]
66mod tests {
67 use super::{env, Invocation, ProtocolError, PROTOCOL_VERSION};
68
69 #[test]
70 fn validates_launcher_version() {
71 assert!(Invocation::from_protocol(Ok(PROTOCOL_VERSION.to_owned()))
72 .map(Invocation::into_args)
73 .is_ok());
74 assert_eq!(
75 Invocation::from_protocol(Err(env::VarError::NotPresent)).err(),
76 Some(ProtocolError::Missing)
77 );
78 assert_eq!(
79 Invocation::from_protocol(Ok("999".to_owned())).err(),
80 Some(ProtocolError::Unsupported)
81 );
82 }
83}