nu_command/platform/
whoami.rs

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