nushell/crates/nu-command/src/formats/to/tsv.rs
Artemiy b9419e0f36
To csv fix (#7850)
# Description

Fixes #7800 . 
`to csv` and `to tsv` no longer:
- accept anything but records and tables as input,
- accept lists that are not tables,
- accept tables and records with values that are not primitives (other
lists, tables and records).

# User-Facing Changes

Using `to csv` and `to tsv` on any of inputs mentioned above will result
in `cant_convert` error.

# Tests + Formatting

Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass

# After Submitting

If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.

Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2023-01-25 08:42:53 -06:00

83 lines
2.1 KiB
Rust

use crate::formats::to::delimited::to_delimited_data;
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("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 {})
}
}