Skip to main content

gutil_plugin_sdk/
lib.rs

1//! Read the invocation of an gutil WebAssembly plug-in.
2
3use std::env::{self, ArgsOs};
4use std::fmt;
5use std::iter::Skip;
6
7/// Environment variable set by the gutil launcher.
8pub const PROTOCOL_ENV: &str = "GUTIL_PLUGIN_PROTOCOL";
9/// Protocol understood by this version of the SDK.
10pub const PROTOCOL_VERSION: &str = "1";
11
12/// The arguments forwarded to a plug-in, excluding the executable name.
13pub struct Invocation {
14    args: Skip<ArgsOs>,
15}
16
17impl Invocation {
18    /// Connect to gutil and capture the argument iterator.
19    ///
20    /// # Errors
21    ///
22    /// Returns an error if the process was started without a protocol version or
23    /// the supplied version is unsupported.
24    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), // nosemgrep: args-os, rust.lang.security.args-os.args-os
32            }),
33            Err(env::VarError::NotPresent) => Err(ProtocolError::Missing),
34            _ => Err(ProtocolError::Unsupported),
35        }
36    }
37
38    /// Return the arguments supplied by the WASI launcher.
39    pub fn into_args(self) -> Skip<ArgsOs> {
40        self.args
41    }
42}
43
44/// A launcher protocol mismatch.
45#[derive(Clone, Copy, Debug, Eq, PartialEq)]
46pub enum ProtocolError {
47    /// The launcher did not supply a protocol version.
48    Missing,
49    /// The launcher supplied a protocol version this SDK cannot read.
50    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}