Skip to main content

artifactize_core/platform/
hidden_input.rs

1//! Stdin detection and the platform's echo-only guard for secret prompts.
2
3use std::io::{self, IsTerminal};
4
5use super::os::{HiddenInput, VISIBLE_INPUT_FALLBACK};
6
7/// Whether stdin can be used for an interactive prompt rather than a pipe or file.
8pub fn stdin_is_terminal() -> bool {
9    io::stdin().is_terminal()
10}
11
12/// How to read a secret from stdin without changing how redirected input is handled.
13pub enum SecretInput {
14    /// Read silently, without a terminal prompt.
15    Redirected,
16    /// Echo is disabled until the guard drops.
17    Hidden(HiddenInput),
18    /// Echo could not be disabled and the platform permits a visible read after warning.
19    Visible(io::Error),
20}
21
22/// Choose the stdin mode for a secret, disabling echo before the caller prompts if possible.
23pub fn secret_input() -> io::Result<SecretInput> {
24    if !stdin_is_terminal() {
25        return Ok(SecretInput::Redirected);
26    }
27    match HiddenInput::new() {
28        Ok(guard) => Ok(SecretInput::Hidden(guard)),
29        Err(error) if VISIBLE_INPUT_FALLBACK => Ok(SecretInput::Visible(error)),
30        Err(error) => Err(error),
31    }
32}
33
34#[cfg(test)]
35mod tests;