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
use crate::formats::to::delimited::to_delimited_data;
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
    Category, Config, Example, PipelineData, ShellError, Signature, Span, Type, Value,
};

#[derive(Clone)]
pub struct ToTsv;

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

    fn signature(&self) -> Signature {
        Signature::build("to tsv")
            .input_output_types(vec![
                (Type::Record(vec![]), Type::String),
                (Type::Table(vec![]), Type::String),
            ])
            .switch(
                "noheaders",
                "do not output the column names as the first row",
                Some('n'),
            )
            .category(Category::Formats)
    }

    fn usage(&self) -> &str {
        "Convert table into .tsv text."
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Outputs an TSV string representing the contents of this table",
                example: "[[foo bar]; [1 2]] | to tsv",
                result: Some(Value::test_string("foo\tbar\n1\t2\n")),
            },
            Example {
                description: "Outputs an TSV string representing the contents of this record",
                example: "{a: 1 b: 2} | to tsv",
                result: Some(Value::test_string("a\tb\n1\t2\n")),
            },
        ]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        let head = call.head;
        let noheaders = call.has_flag(engine_state, stack, "noheaders")?;
        let config = engine_state.get_config();
        to_tsv(input, noheaders, head, config)
    }
}

fn to_tsv(
    input: PipelineData,
    noheaders: bool,
    head: Span,
    config: &Config,
) -> Result<PipelineData, ShellError> {
    to_delimited_data(noheaders, '\t', "TSV", input, head, config)
}

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

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

        test_examples(ToTsv {})
    }
}