nu_command/platform/
is_terminal.rs

1use nu_engine::command_prelude::*;
2use std::io::IsTerminal as _;
3
4#[derive(Clone)]
5pub struct IsTerminal;
6
7impl Command for IsTerminal {
8    fn name(&self) -> &str {
9        "is-terminal"
10    }
11
12    fn signature(&self) -> Signature {
13        Signature::build("is-terminal")
14            .input_output_type(Type::Nothing, Type::Bool)
15            .switch("stdin", "Check if stdin is a terminal", Some('i'))
16            .switch("stdout", "Check if stdout is a terminal", Some('o'))
17            .switch("stderr", "Check if stderr is a terminal", Some('e'))
18            .category(Category::Platform)
19    }
20
21    fn description(&self) -> &str {
22        "Check if stdin, stdout, or stderr is a terminal."
23    }
24
25    fn examples(&self) -> Vec<Example> {
26        vec![Example {
27            description: r#"Return "terminal attached" if standard input is attached to a terminal, and "no terminal" if not."#,
28            example: r#"if (is-terminal --stdin) { "terminal attached" } else { "no terminal" }"#,
29            result: Some(Value::test_string("terminal attached")),
30        }]
31    }
32
33    fn search_terms(&self) -> Vec<&str> {
34        vec!["input", "output", "stdin", "stdout", "stderr", "tty"]
35    }
36
37    fn run(
38        &self,
39        engine_state: &EngineState,
40        stack: &mut Stack,
41        call: &Call,
42        _input: PipelineData,
43    ) -> Result<PipelineData, ShellError> {
44        let stdin = call.has_flag(engine_state, stack, "stdin")?;
45        let stdout = call.has_flag(engine_state, stack, "stdout")?;
46        let stderr = call.has_flag(engine_state, stack, "stderr")?;
47
48        let is_terminal = match (stdin, stdout, stderr) {
49            (true, false, false) => std::io::stdin().is_terminal(),
50            (false, true, false) => std::io::stdout().is_terminal(),
51            (false, false, true) => std::io::stderr().is_terminal(),
52            (false, false, false) => {
53                return Err(ShellError::MissingParameter {
54                    param_name: "one of --stdin, --stdout, --stderr".into(),
55                    span: call.head,
56                });
57            }
58            _ => {
59                return Err(ShellError::IncompatibleParametersSingle {
60                    msg: "Only one stream may be checked".into(),
61                    span: call.arguments_span(),
62                });
63            }
64        };
65
66        Ok(PipelineData::Value(
67            Value::bool(is_terminal, call.head),
68            None,
69        ))
70    }
71}