Skip to main content

nu_command/platform/
whoami.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::shell_error::generic::GenericError;
3use uucore::{localized_help_template, translate};
4
5#[derive(Clone)]
6pub struct Whoami;
7
8impl Command for Whoami {
9    fn name(&self) -> &str {
10        "whoami"
11    }
12
13    fn description(&self) -> &str {
14        "Get the current username using uutils/coreutils whoami."
15    }
16
17    fn signature(&self) -> Signature {
18        Signature::build("whoami")
19            .input_output_types(vec![(Type::Nothing, Type::String)])
20            .allow_variants_without_examples(true)
21            .category(Category::Platform)
22    }
23
24    fn search_terms(&self) -> Vec<&str> {
25        vec!["username", "coreutils"]
26    }
27
28    fn run(
29        &self,
30        _engine_state: &EngineState,
31        _stack: &mut Stack,
32        call: &Call,
33        _input: PipelineData,
34    ) -> Result<PipelineData, ShellError> {
35        // setup the uutils error translation
36        let _ = localized_help_template("touch");
37
38        let output = match uu_whoami::whoami() {
39            Ok(username) => username.to_string_lossy().to_string(),
40            Err(e) => {
41                return Err(ShellError::Generic(GenericError::new(
42                    format!("{e}"),
43                    translate!(&e.to_string()),
44                    call.head,
45                )));
46            }
47        };
48
49        Ok(Value::string(output, call.head).into_pipeline_data())
50    }
51
52    fn examples(&self) -> Vec<Example<'_>> {
53        vec![Example {
54            description: "Get the current username.",
55            example: "whoami",
56            result: None,
57        }]
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::Whoami;
64
65    #[test]
66    fn examples_work_as_expected() -> nu_test_support::Result {
67        nu_test_support::test().examples(Whoami)
68    }
69}