Skip to main content

nu_command/path/
type.rs

1use super::PathSubcommandArguments;
2use nu_engine::command_prelude::*;
3use nu_path::AbsolutePathBuf;
4use nu_protocol::{engine::StateWorkingSet, shell_error::io::IoError};
5use std::{io, path::Path};
6
7struct Arguments {
8    pwd: AbsolutePathBuf,
9}
10
11impl PathSubcommandArguments for Arguments {}
12
13#[derive(Clone)]
14pub struct PathType;
15
16impl Command for PathType {
17    fn name(&self) -> &str {
18        "path type"
19    }
20
21    fn signature(&self) -> Signature {
22        Signature::build("path type")
23            .input_output_types(vec![
24                (Type::String, Type::String),
25                (
26                    Type::List(Box::new(Type::String)),
27                    Type::List(Box::new(Type::String)),
28                ),
29            ])
30            .allow_variants_without_examples(true)
31            .category(Category::Path)
32    }
33
34    fn description(&self) -> &str {
35        "Get the type of the object a path refers to (e.g., file, dir, symlink)."
36    }
37
38    fn extra_description(&self) -> &str {
39        "This checks the file system to confirm the path's object type.
40If the path does not exist, null will be returned."
41    }
42
43    fn is_const(&self) -> bool {
44        true
45    }
46
47    fn run(
48        &self,
49        engine_state: &EngineState,
50        stack: &mut Stack,
51        call: &Call,
52        input: PipelineData,
53    ) -> Result<PipelineData, ShellError> {
54        let head = call.head;
55        let args = Arguments {
56            pwd: engine_state.cwd(Some(stack))?,
57        };
58
59        // This doesn't match explicit nulls
60        if let PipelineData::Empty = input {
61            return Err(ShellError::PipelineEmpty { dst_span: head });
62        }
63        input.map(
64            move |value| super::operate(&path_type, &args, value, head),
65            engine_state.signals(),
66        )
67    }
68
69    fn run_const(
70        &self,
71        working_set: &StateWorkingSet,
72        call: &Call,
73        input: PipelineData,
74    ) -> Result<PipelineData, ShellError> {
75        let head = call.head;
76        let args = Arguments {
77            pwd: working_set.permanent().cwd(None)?,
78        };
79
80        // This doesn't match explicit nulls
81        if let PipelineData::Empty = input {
82            return Err(ShellError::PipelineEmpty { dst_span: head });
83        }
84        input.map(
85            move |value| super::operate(&path_type, &args, value, head),
86            working_set.permanent().signals(),
87        )
88    }
89
90    fn examples(&self) -> Vec<Example<'_>> {
91        vec![
92            Example {
93                description: "Show type of a filepath.",
94                example: "'.' | path type",
95                result: Some(Value::test_string("dir")),
96            },
97            Example {
98                description: "Empty string is not a path.",
99                example: "'' | path type | is-empty",
100                result: Some(Value::test_bool(true)),
101            },
102            Example {
103                description: "Show type of filepaths in a list.",
104                example: "ls | get name | path type",
105                result: None,
106            },
107        ]
108    }
109}
110
111fn path_type(path: &Path, span: Span, args: &Arguments) -> Value {
112    // To the OS, an empty string is just the CWD,
113    // however logically we want to treat it as an invalid path.
114    if path == "" {
115        return Value::nothing(span);
116    }
117    let path = nu_path::expand_path_with(path, &args.pwd, true);
118    match path.symlink_metadata() {
119        Ok(metadata) => Value::string(get_file_type(&metadata), span),
120        Err(err) if err.kind() == io::ErrorKind::NotFound => Value::nothing(span),
121        Err(err) => Value::error(IoError::new(err, span, None).into(), span),
122    }
123}
124
125fn get_file_type(md: &std::fs::Metadata) -> &str {
126    let ft = md.file_type();
127    let mut file_type = "unknown";
128    if ft.is_dir() {
129        file_type = "dir";
130    } else if ft.is_file() {
131        file_type = "file";
132    } else if ft.is_symlink() {
133        file_type = "symlink";
134    } else {
135        #[cfg(unix)]
136        {
137            use std::os::unix::fs::FileTypeExt;
138            if ft.is_block_device() {
139                file_type = "block device";
140            } else if ft.is_char_device() {
141                file_type = "char device";
142            } else if ft.is_fifo() {
143                file_type = "pipe";
144            } else if ft.is_socket() {
145                file_type = "socket";
146            }
147        }
148    }
149    file_type
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn test_examples() -> nu_test_support::Result {
158        nu_test_support::test().examples(PathType)
159    }
160}