Skip to main content

ipcez/
target.rs

1//! Target (local vs remote) detection from the `target` environment variable.
2//!
3//! Single responsibility: detect whether the process to communicate with is local or remote.
4
5use std::env;
6use std::error::Error;
7use std::fmt;
8
9/// Whether the process to communicate with is local or on a remote server.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum TargetKind {
12    Local,
13    Remote,
14}
15
16/// Error when detecting target from the `target` environment variable.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum TargetDetectionError {
19    /// The `target` environment variable was not set.
20    NotFound,
21    /// The `target` environment variable had an invalid value.
22    InvalidValue(String),
23}
24
25impl fmt::Display for TargetDetectionError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            TargetDetectionError::NotFound => {
29                write!(f, "environment variable \"target\" was not found")
30            }
31            TargetDetectionError::InvalidValue(v) => {
32                write!(
33                    f,
34                    "environment variable \"target\" had invalid value \"{}\"; expected \"local\" or \"remote\"",
35                    v
36                )
37            }
38        }
39    }
40}
41
42impl Error for TargetDetectionError {}
43
44/// Detects whether the target process is local or remote by reading the `target` environment variable.
45///
46/// Expects the variable to be set to `"local"` or `"remote"` (case-insensitive).
47/// Returns an error if the variable is missing or has any other value.
48pub fn detect_target_from_env() -> Result<TargetKind, TargetDetectionError> {
49    let raw = env::var("target").map_err(|_| TargetDetectionError::NotFound)?;
50    let value = raw.trim().to_lowercase();
51    match value.as_str() {
52        "local" => Ok(TargetKind::Local),
53        "remote" => Ok(TargetKind::Remote),
54        _ => Err(TargetDetectionError::InvalidValue(raw)),
55    }
56}