nu_command/platform/
whoami.rs

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