1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
use nu_engine::command_prelude::*;
use nu_protocol::{
    ast::{Expr, Expression},
    DataSource, PipelineMetadata,
};

#[derive(Clone)]
pub struct Metadata;

impl Command for Metadata {
    fn name(&self) -> &str {
        "metadata"
    }

    fn usage(&self) -> &str {
        "Get the metadata for items in the stream."
    }

    fn signature(&self) -> nu_protocol::Signature {
        Signature::build("metadata")
            .input_output_types(vec![(Type::Any, Type::record())])
            .allow_variants_without_examples(true)
            .optional(
                "expression",
                SyntaxShape::Any,
                "The expression you want metadata for.",
            )
            .category(Category::Debug)
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        let arg = call.positional_nth(0);
        let head = call.head;

        match arg {
            Some(Expression {
                expr: Expr::FullCellPath(full_cell_path),
                span,
                ..
            }) => {
                if full_cell_path.tail.is_empty() {
                    match &full_cell_path.head {
                        Expression {
                            expr: Expr::Var(var_id),
                            ..
                        } => {
                            let origin = stack.get_var_with_origin(*var_id, *span)?;

                            Ok(
                                build_metadata_record(&origin, input.metadata().as_ref(), head)
                                    .into_pipeline_data(),
                            )
                        }
                        _ => {
                            let val: Value = call.req(engine_state, stack, 0)?;
                            Ok(build_metadata_record(&val, input.metadata().as_ref(), head)
                                .into_pipeline_data())
                        }
                    }
                } else {
                    let val: Value = call.req(engine_state, stack, 0)?;
                    Ok(build_metadata_record(&val, input.metadata().as_ref(), head)
                        .into_pipeline_data())
                }
            }
            Some(_) => {
                let val: Value = call.req(engine_state, stack, 0)?;
                Ok(build_metadata_record(&val, input.metadata().as_ref(), head)
                    .into_pipeline_data())
            }
            None => {
                let mut record = Record::new();
                if let Some(x) = input.metadata().as_ref() {
                    match x {
                        PipelineMetadata {
                            data_source: DataSource::Ls,
                        } => record.push("source", Value::string("ls", head)),
                        PipelineMetadata {
                            data_source: DataSource::HtmlThemes,
                        } => record.push("source", Value::string("into html --list", head)),
                        PipelineMetadata {
                            data_source: DataSource::FilePath(path),
                        } => record.push(
                            "source",
                            Value::string(path.to_string_lossy().to_string(), head),
                        ),
                    }
                }

                Ok(Value::record(record, head).into_pipeline_data())
            }
        }
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Get the metadata of a variable",
                example: "let a = 42; metadata $a",
                result: None,
            },
            Example {
                description: "Get the metadata of the input",
                example: "ls | metadata",
                result: None,
            },
        ]
    }
}

fn build_metadata_record(arg: &Value, metadata: Option<&PipelineMetadata>, head: Span) -> Value {
    let mut record = Record::new();

    let span = arg.span();
    record.push(
        "span",
        Value::record(
            record! {
                "start" => Value::int(span.start as i64,span),
                "end" => Value::int(span.end as i64, span),
            },
            head,
        ),
    );

    if let Some(x) = metadata {
        match x {
            PipelineMetadata {
                data_source: DataSource::Ls,
            } => record.push("source", Value::string("ls", head)),
            PipelineMetadata {
                data_source: DataSource::HtmlThemes,
            } => record.push("source", Value::string("into html --list", head)),
            PipelineMetadata {
                data_source: DataSource::FilePath(path),
            } => record.push(
                "source",
                Value::string(path.to_string_lossy().to_string(), head),
            ),
        }
    }

    Value::record(record, head)
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_examples() {
        use crate::test_examples;

        test_examples(Metadata {})
    }
}