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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
use nu_cmd_base::input_handler::{operate, CellPathOnlyArgs};
use nu_engine::CallExt;
use nu_protocol::{
    ast::{Call, CellPath},
    engine::{Command, EngineState, Stack},
    Category, Example, PipelineData, Record, ShellError, Signature, Span, SyntaxShape, Type, Value,
};

#[derive(Clone)]
pub struct SubCommand;

impl Command for SubCommand {
    fn name(&self) -> &str {
        "into decimal"
    }

    fn signature(&self) -> Signature {
        Signature::build("into decimal")
            .input_output_types(vec![
                (Type::Int, Type::Float),
                (Type::String, Type::Float),
                (Type::Bool, Type::Float),
                (Type::Float, Type::Float),
                (Type::Table(vec![]), Type::Table(vec![])),
                (Type::Record(vec![]), Type::Record(vec![])),
                (
                    Type::List(Box::new(Type::Any)),
                    Type::List(Box::new(Type::Float)),
                ),
            ])
            .rest(
                "rest",
                SyntaxShape::CellPath,
                "for a data structure input, convert data at the given cell paths",
            )
            .allow_variants_without_examples(true)
            .category(Category::Conversions)
    }

    fn usage(&self) -> &str {
        "deprecated: convert data into a floating point number."
    }

    fn extra_usage(&self) -> &str {
        "Use `into float` instead"
    }

    fn search_terms(&self) -> Vec<&str> {
        vec!["convert", "number", "floating"]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        nu_protocol::report_error_new(
            engine_state,
            &ShellError::GenericError(
                "Deprecated command".into(),
                "`into decimal` is deprecated and will be removed in 0.86.".into(),
                Some(call.head),
                Some("Use `into float` instead".into()),
                vec![],
            ),
        );
        let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?;
        let args = CellPathOnlyArgs::from(cell_paths);
        operate(action, args, input, call.head, engine_state.ctrlc.clone())
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Convert string to float in table",
                example: "[[num]; ['5.01']] | into decimal num",
                result: Some(Value::list(
                    vec![Value::test_record(Record {
                        cols: vec!["num".to_string()],
                        vals: vec![Value::test_float(5.01)],
                    })],
                    Span::test_data(),
                )),
            },
            Example {
                description: "Convert string to float",
                example: "'1.345' | into decimal",
                result: Some(Value::test_float(1.345)),
            },
            Example {
                description: "Coerce list of ints and floats to float",
                example: "[4 -5.9] | into decimal",
                result: Some(Value::test_list(vec![
                    Value::test_float(4.0),
                    Value::test_float(-5.9),
                ])),
            },
            Example {
                description: "Convert boolean to float",
                example: "true | into decimal",
                result: Some(Value::test_float(1.0)),
            },
        ]
    }
}

fn action(input: &Value, _args: &CellPathOnlyArgs, head: Span) -> Value {
    let span = input.span();
    match input {
        Value::Float { .. } => input.clone(),
        Value::String { val: s, .. } => {
            let other = s.trim();

            match other.parse::<f64>() {
                Ok(x) => Value::float(x, head),
                Err(reason) => Value::error(
                    ShellError::CantConvert {
                        to_type: "float".to_string(),
                        from_type: reason.to_string(),
                        span,
                        help: None,
                    },
                    span,
                ),
            }
        }
        Value::Int { val: v, .. } => Value::float(*v as f64, span),
        Value::Bool { val: b, .. } => Value::float(
            match b {
                true => 1.0,
                false => 0.0,
            },
            span,
        ),
        // Propagate errors by explicitly matching them before the final case.
        Value::Error { .. } => input.clone(),
        other => Value::error(
            ShellError::OnlySupportsThisInputType {
                exp_input_type: "string, integer or bool".into(),
                wrong_type: other.get_type().to_string(),
                dst_span: head,
                src_span: other.span(),
            },
            head,
        ),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use nu_protocol::Type::Error;

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

        test_examples(SubCommand {})
    }

    #[test]
    #[allow(clippy::approx_constant)]
    fn string_to_decimal() {
        let word = Value::test_string("3.1415");
        let expected = Value::test_float(3.1415);

        let actual = action(&word, &CellPathOnlyArgs::from(vec![]), Span::test_data());
        assert_eq!(actual, expected);
    }

    #[test]
    fn communicates_parsing_error_given_an_invalid_decimallike_string() {
        let decimal_str = Value::test_string("11.6anra");

        let actual = action(
            &decimal_str,
            &CellPathOnlyArgs::from(vec![]),
            Span::test_data(),
        );

        assert_eq!(actual.get_type(), Error);
    }

    #[test]
    fn int_to_decimal() {
        let decimal_str = Value::test_int(10);
        let expected = Value::test_float(10.0);
        let actual = action(
            &decimal_str,
            &CellPathOnlyArgs::from(vec![]),
            Span::test_data(),
        );

        assert_eq!(actual, expected);
    }
}