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
use chrono_humanize::HumanTime;
use nu_protocol::{
    ast::Call,
    engine::{Command, EngineState, Stack},
    format_duration, format_filesize_from_conf, Category, Config, Example, IntoPipelineData,
    PipelineData, ShellError, Signature, Value,
};

#[derive(Clone)]
pub struct ToText;

impl Command for ToText {
    fn name(&self) -> &str {
        "to text"
    }

    fn signature(&self) -> Signature {
        Signature::build("to text").category(Category::Formats)
    }

    fn usage(&self) -> &str {
        "Converts data into simple text."
    }

    fn run(
        &self,
        engine_state: &EngineState,
        _stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<nu_protocol::PipelineData, ShellError> {
        let span = call.head;
        let config = engine_state.get_config();

        let line_ending = if cfg!(target_os = "windows") {
            "\r\n"
        } else {
            "\n"
        };

        let collected_input = local_into_string(input.into_value(span), line_ending, config);

        Ok(Value::String {
            val: collected_input,
            span,
        }
        .into_pipeline_data())
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Outputs data as simple text",
                example: "1 | to text",
                result: Some(Value::test_string("1")),
            },
            Example {
                description: "Outputs external data as simple text",
                example: "git help -a | lines | find -r '^ ' |  to text",
                result: None,
            },
            Example {
                description: "Outputs records as simple text",
                example: "ls |  to text",
                result: None,
            },
        ]
    }

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

fn local_into_string(value: Value, separator: &str, config: &Config) -> String {
    match value {
        Value::Bool { val, .. } => val.to_string(),
        Value::Int { val, .. } => val.to_string(),
        Value::Float { val, .. } => val.to_string(),
        Value::Filesize { val, .. } => format_filesize_from_conf(val, config),
        Value::Duration { val, .. } => format_duration(val),
        Value::Date { val, .. } => {
            format!("{} ({})", val.to_rfc2822(), HumanTime::from(val))
        }
        Value::Range { val, .. } => {
            format!(
                "{}..{}",
                local_into_string(val.from, ", ", config),
                local_into_string(val.to, ", ", config)
            )
        }
        Value::String { val, .. } => val,
        Value::List { vals: val, .. } => val
            .iter()
            .map(|x| local_into_string(x.clone(), ", ", config))
            .collect::<Vec<_>>()
            .join(separator),
        Value::Record { cols, vals, .. } => cols
            .iter()
            .zip(vals.iter())
            .map(|(x, y)| format!("{}: {}", x, local_into_string(y.clone(), ", ", config)))
            .collect::<Vec<_>>()
            .join(separator),
        Value::Block { val, .. } => format!("<Block {}>", val),
        Value::Nothing { .. } => String::new(),
        Value::Error { error } => format!("{:?}", error),
        Value::Binary { val, .. } => format!("{:?}", val),
        Value::CellPath { val, .. } => val.into_string(),
        Value::CustomValue { val, .. } => val.value_string(),
    }
}

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

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

        test_examples(ToText {})
    }
}