use std::sync::OnceLock;
static POSTURE: OnceLock<BootPosture> = OnceLock::new();
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BootPosture {
pub in_nix_shell: bool,
pub direnv_active: bool,
pub via_ssh: bool,
pub interactive: bool,
pub login: bool,
}
impl BootPosture {
#[must_use]
pub fn unknown() -> Self {
Self {
in_nix_shell: false,
direnv_active: false,
via_ssh: false,
interactive: false,
login: false,
}
}
}
pub fn detect() -> &'static BootPosture {
POSTURE.get_or_init(detect_inner)
}
fn detect_inner() -> BootPosture {
use std::io::IsTerminal;
let in_nix_shell = std::env::var_os("IN_NIX_SHELL").is_some();
let direnv_active = std::env::var_os("DIRENV_DIR").is_some();
let via_ssh =
std::env::var_os("SSH_CONNECTION").is_some() || std::env::var_os("SSH_CLIENT").is_some();
let interactive = std::io::stdin().is_terminal();
let login = std::env::args()
.next()
.is_some_and(|argv0| argv0.starts_with('-'));
BootPosture {
in_nix_shell,
direnv_active,
via_ssh,
interactive,
login,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unknown_is_all_false() {
let p = BootPosture::unknown();
assert!(!p.in_nix_shell);
assert!(!p.direnv_active);
assert!(!p.via_ssh);
assert!(!p.interactive);
assert!(!p.login);
}
#[test]
fn detect_returns_stable_reference() {
let a = detect() as *const _;
let b = detect() as *const _;
assert_eq!(a, b);
}
#[test]
fn detect_produces_a_value() {
let posture = detect();
let _ = posture.in_nix_shell;
let _ = posture.direnv_active;
let _ = posture.via_ssh;
let _ = posture.interactive;
let _ = posture.login;
}
}