diff --git a/crates/nu-command/src/formats/from/csv.rs b/crates/nu-command/src/formats/from/csv.rs index 89a4493b30..d0afc9cb54 100644 --- a/crates/nu-command/src/formats/from/csv.rs +++ b/crates/nu-command/src/formats/from/csv.rs @@ -1,5 +1,9 @@ -use super::delimited::{DelimitedReaderConfig, from_delimited_data, trim_from_str}; +use super::delimited::{ + DelimitedReaderConfig, INFER_EXTRA_DESC, INFER_FLAG_DESC, NO_INFER_FLAG_DESC, + from_delimited_data, infer_from_flags, no_infer_deprecation, trim_from_str, +}; use nu_engine::command_prelude::*; +use nu_protocol::DeprecationEntry; #[derive(Clone)] pub struct FromCsv; @@ -48,7 +52,8 @@ impl Command for FromCsv { "Allow the number of fields in records to be variable.", None, ) - .switch("no-infer", "No field type inferencing.", None) + .switch("infer", INFER_FLAG_DESC, None) + .switch("no-infer", NO_INFER_FLAG_DESC, None) .param( Flag::new("trim") .short('t') @@ -66,6 +71,14 @@ impl Command for FromCsv { "Parse text as .csv and create table." } + fn extra_description(&self) -> &str { + INFER_EXTRA_DESC + } + + fn deprecation_info(&self) -> Vec { + no_infer_deprecation() + } + fn run( &self, engine_state: &EngineState, @@ -79,28 +92,41 @@ impl Command for FromCsv { fn examples(&self) -> Vec> { vec![ Example { - description: "Convert comma-separated data to a table.", + description: "Convert comma-separated data to a table. Every field is a string.", example: "\"ColA,ColB\n1,2\" | from csv", result: Some(Value::test_list(vec![Value::test_record(record! { - "ColA" => Value::test_int(1), - "ColB" => Value::test_int(2), + "ColA" => Value::test_string("1"), + "ColB" => Value::test_string("2"), })])), }, + Example { + description: "Convert comma-separated data to a table, turning fields that parse as numbers into ints and floats.", + example: "\"ColA,ColB\n1,2.5\" | from csv --infer", + result: Some(Value::test_list(vec![Value::test_record(record! { + "ColA" => Value::test_int(1), + "ColB" => Value::test_float(2.5), + })])), + }, + Example { + description: "Open a CSV file and turn fields that parse as numbers into ints and floats. `open data.csv` alone keeps every field a string.", + example: "open --raw data.csv | from csv --infer", + result: None, + }, Example { description: "Convert comma-separated data to a table, allowing variable number of columns per row.", example: "\"ColA,ColB\n1,2\n3,4,5\n6\" | from csv --flexible", result: Some(Value::test_list(vec![ Value::test_record(record! { - "ColA" => Value::test_int(1), - "ColB" => Value::test_int(2), + "ColA" => Value::test_string("1"), + "ColB" => Value::test_string("2"), }), Value::test_record(record! { - "ColA" => Value::test_int(3), - "ColB" => Value::test_int(4), - "column2" => Value::test_int(5), + "ColA" => Value::test_string("3"), + "ColB" => Value::test_string("4"), + "column2" => Value::test_string("5"), }), Value::test_record(record! { - "ColA" => Value::test_int(6), + "ColA" => Value::test_string("6"), }), ])), }, @@ -182,7 +208,7 @@ fn from_csv( .get_flag(engine_state, stack, "escape")? .map(|v: Value| v.as_char()) .transpose()?; - let no_infer = call.has_flag(engine_state, stack, "no-infer")?; + let infer = infer_from_flags(engine_state, stack, call)?; let noheaders = call.has_flag(engine_state, stack, "noheaders")?; let flexible = call.has_flag(engine_state, stack, "flexible")?; let trim = trim_from_str(call.get_flag(engine_state, stack, "trim")?)?; @@ -194,7 +220,7 @@ fn from_csv( escape, noheaders, flexible, - no_infer, + infer, trim, }; @@ -229,14 +255,14 @@ mod test { // A real `name_1` column keeps its name; the repeat moves past it. nu_test_support::test() .run(r#""name,name,name_1\n1,2,3" | from csv | to nuon"#) - .expect_value_eq(r#"[[name, "name_2", "name_1"]; [1, 2, 3]]"#) + .expect_value_eq(r#"[[name, "name_2", "name_1"]; ["1", "2", "3"]]"#) } #[test] fn test_duplicate_headers_with_flexible() -> nu_test_support::Result { nu_test_support::test() .run(r#""a,a\n1,2,3" | from csv --flexible | to nuon"#) - .expect_value_eq(r#"[[a, "a_1", "column2"]; [1, 2, 3]]"#) + .expect_value_eq(r#"[[a, "a_1", "column2"]; ["1", "2", "3"]]"#) } #[test] @@ -244,7 +270,50 @@ mod test { // Several unlabeled header cells must not count as duplicates. nu_test_support::test() .run(r#""a,b,,\n1,2,3,4" | from csv | to nuon"#) - .expect_value_eq(r#"[[a, b, "column2", "column3"]; [1, 2, 3, 4]]"#) + .expect_value_eq(r#"[[a, b, "column2", "column3"]; ["1", "2", "3", "4"]]"#) + } + + #[test] + fn test_fields_are_strings_by_default() -> nu_test_support::Result { + // Leading zeros, exponents and `NaN` are kept as written: CSV has no + // types, and turning these into numbers loses the original text. + nu_test_support::test() + .run(r#""code\n0123\n28E37262\n942371E0\nNaN\n1.0" | from csv | get code | to nuon"#) + .expect_value_eq(r#"["0123", "28E37262", "942371E0", "NaN", "1.0"]"#) + } + + #[test] + fn test_infer_turns_numeric_fields_into_numbers() -> nu_test_support::Result { + nu_test_support::test() + .run(r#""a,b,c\n1,2.5,x" | from csv --infer | get 0 | values | each { describe } | to nuon"#) + .expect_value_eq("[int, float, string]") + } + + #[test] + fn test_no_infer_is_accepted_and_keeps_strings() -> nu_test_support::Result { + // The deprecated flag still parses and asks for what is now the default. + nu_test_support::test() + .run(r#""a\n0123" | from csv --no-infer | get 0.a"#) + .expect_value_eq("0123") + } + + #[test] + fn test_no_infer_flag_is_deprecated() -> nu_test_support::Result { + nu_test_support::test() + .run("scope commands | where name == 'from csv' | get 0.deprecation_info.flag.0") + .expect_value_eq("no-infer") + } + + #[test] + fn test_infer_and_no_infer_together_is_an_error() -> nu_test_support::Result { + let err = nu_test_support::test() + .run(r#""a\n1" | from csv --infer --no-infer"#) + .expect_shell_error()?; + assert!( + matches!(err, ShellError::IncompatibleParameters { .. }), + "expected IncompatibleParameters, got {err:?}" + ); + Ok(()) } #[test] @@ -262,7 +331,7 @@ mod test { // extra field must move past it instead of repeating it. nu_test_support::test() .run(r#""a,column2\n1,2,3" | from csv --flexible | to nuon"#) - .expect_value_eq(r#"[[a, "column2", "column3"]; [1, 2, 3]]"#) + .expect_value_eq(r#"[[a, "column2", "column3"]; ["1", "2", "3"]]"#) } #[test] diff --git a/crates/nu-command/src/formats/from/delimited.rs b/crates/nu-command/src/formats/from/delimited.rs index e42a89b7f3..cfd8621e68 100644 --- a/crates/nu-command/src/formats/from/delimited.rs +++ b/crates/nu-command/src/formats/from/delimited.rs @@ -1,6 +1,9 @@ use csv::{ReaderBuilder, Trim}; +use nu_engine::CallExt; use nu_protocol::{ - ByteStream, ListStream, PipelineData, ShellError, Signals, Span, Value, + ByteStream, DeprecationEntry, DeprecationType, ListStream, PipelineData, ReportMode, + ShellError, Signals, Span, Value, + engine::{Call, EngineState, Stack}, shell_error::bridge::ShellErrorBridge, }; use std::collections::{HashMap, HashSet}; @@ -25,7 +28,7 @@ fn from_delimited_stream( escape, noheaders, flexible, - no_infer, + infer, trim, }: DelimitedReaderConfig, input: ByteStream, @@ -83,7 +86,7 @@ fn from_delimited_stream( }; let columns = columns.clone(); let values = row.into_iter().map(|s| { - if no_infer { + if !infer { Value::string(s, span) } else if let Ok(i) = s.parse() { Value::int(i, span) @@ -136,10 +139,62 @@ pub(super) struct DelimitedReaderConfig { pub escape: Option, pub noheaders: bool, pub flexible: bool, - pub no_infer: bool, + /// Turn fields that parse as numbers into ints and floats. Off, every + /// field is a string. + pub infer: bool, pub trim: Trim, } +/// Help text of the `--infer` switch, shared by `from csv` and `from tsv`. +pub(super) const INFER_FLAG_DESC: &str = + "Convert fields that parse as numbers into ints and floats. Every field is a string otherwise."; + +/// Help text of the deprecated `--no-infer` switch, shared by `from csv` and `from tsv`. +pub(super) const NO_INFER_FLAG_DESC: &str = + "Keep every field a string (deprecated: this is the default now)."; + +/// Extra help text shared by `from csv` and `from tsv`. +pub(super) const INFER_EXTRA_DESC: &str = "Every field is read as a string, so values like `007` or `1E5` stay as written. Pass \ + `--infer` to turn fields that parse as numbers into ints and floats, or convert the \ + columns you need afterwards, e.g. `update id { into int }`. `open` and `http get` run \ + this command without flags, so read the file or response with `--raw` to use `--infer`."; + +/// Read `--infer`, and accept the deprecated `--no-infer` as a no-op since +/// keeping every field a string is the default. Passing both is an error. +pub(super) fn infer_from_flags( + engine_state: &EngineState, + stack: &mut Stack, + call: &Call, +) -> Result { + let infer = call.has_flag(engine_state, stack, "infer")?; + let no_infer = call.has_flag(engine_state, stack, "no-infer")?; + if infer && no_infer { + let flag_span = |name| call.get_flag_span(stack, name).unwrap_or(call.head); + return Err(ShellError::IncompatibleParameters { + left_message: "--infer".into(), + left_span: flag_span("infer"), + right_message: "--no-infer".into(), + right_span: flag_span("no-infer"), + }); + } + Ok(infer) +} + +/// The `--no-infer` deprecation, shared by `from csv` and `from tsv`. +pub(super) fn no_infer_deprecation() -> Vec { + vec![DeprecationEntry { + ty: DeprecationType::Flag("no-infer".into()), + report_mode: ReportMode::FirstUse, + since: Some("0.118.0".into()), + expected_removal: None, + help: Some( + "Every field is a string by default now, so the flag can be dropped. \ + Use `--infer` to turn numeric fields into ints and floats." + .into(), + ), + }] +} + pub(super) fn from_delimited_data( config: DelimitedReaderConfig, mut input: PipelineData, diff --git a/crates/nu-command/src/formats/from/tsv.rs b/crates/nu-command/src/formats/from/tsv.rs index 8bb4a9dbe2..809d458ac7 100644 --- a/crates/nu-command/src/formats/from/tsv.rs +++ b/crates/nu-command/src/formats/from/tsv.rs @@ -1,5 +1,9 @@ -use super::delimited::{DelimitedReaderConfig, from_delimited_data, trim_from_str}; +use super::delimited::{ + DelimitedReaderConfig, INFER_EXTRA_DESC, INFER_FLAG_DESC, NO_INFER_FLAG_DESC, + from_delimited_data, infer_from_flags, no_infer_deprecation, trim_from_str, +}; use nu_engine::command_prelude::*; +use nu_protocol::DeprecationEntry; #[derive(Clone)] pub struct FromTsv; @@ -40,7 +44,8 @@ impl Command for FromTsv { "Allow the number of fields in records to be variable.", None, ) - .switch("no-infer", "No field type inferencing.", None) + .switch("infer", INFER_FLAG_DESC, None) + .switch("no-infer", NO_INFER_FLAG_DESC, None) .param( Flag::new("trim") .short('t') @@ -57,6 +62,14 @@ impl Command for FromTsv { "Parse text as .tsv and create table." } + fn extra_description(&self) -> &str { + INFER_EXTRA_DESC + } + + fn deprecation_info(&self) -> Vec { + no_infer_deprecation() + } + fn run( &self, engine_state: &EngineState, @@ -70,13 +83,26 @@ impl Command for FromTsv { fn examples(&self) -> Vec> { vec![ Example { - description: "Convert tab-separated data to a table.", + description: "Convert tab-separated data to a table. Every field is a string.", example: "\"ColA\tColB\n1\t2\" | from tsv", result: Some(Value::test_list(vec![Value::test_record(record! { - "ColA" => Value::test_int(1), - "ColB" => Value::test_int(2), + "ColA" => Value::test_string("1"), + "ColB" => Value::test_string("2"), })])), }, + Example { + description: "Convert tab-separated data to a table, turning fields that parse as numbers into ints and floats.", + example: "\"ColA\tColB\n1\t2.5\" | from tsv --infer", + result: Some(Value::test_list(vec![Value::test_record(record! { + "ColA" => Value::test_int(1), + "ColB" => Value::test_float(2.5), + })])), + }, + Example { + description: "Open a TSV file and turn fields that parse as numbers into ints and floats. `open data.tsv` alone keeps every field a string.", + example: "open --raw data.tsv | from tsv --infer", + result: None, + }, Example { description: "Convert comma-separated data to a table, allowing variable number of columns per row and ignoring headers.", example: "\"value 1\nvalue 2\tdescription 2\" | from tsv --flexible --noheaders", @@ -140,7 +166,7 @@ fn from_tsv( .get_flag(engine_state, stack, "escape")? .map(|v: Value| v.as_char()) .transpose()?; - let no_infer = call.has_flag(engine_state, stack, "no-infer")?; + let infer = infer_from_flags(engine_state, stack, call)?; let noheaders = call.has_flag(engine_state, stack, "noheaders")?; let flexible = call.has_flag(engine_state, stack, "flexible")?; let trim = trim_from_str(call.get_flag(engine_state, stack, "trim")?)?; @@ -152,7 +178,7 @@ fn from_tsv( escape, noheaders, flexible, - no_infer, + infer, trim, }; @@ -181,6 +207,27 @@ mod test { .expect_value_eq(r#"[[name, "name_1"]; [Alice, Bob]]"#) } + #[test] + fn test_fields_are_strings_by_default() -> nu_test_support::Result { + nu_test_support::test() + .run(r#""code\n0123\n1E5" | from tsv | get code | to nuon"#) + .expect_value_eq(r#"["0123", "1E5"]"#) + } + + #[test] + fn test_infer_turns_numeric_fields_into_numbers() -> nu_test_support::Result { + nu_test_support::test() + .run(r#""a\tb\tc\n1\t2.5\tx" | from tsv --infer | get 0 | values | each { describe } | to nuon"#) + .expect_value_eq("[int, float, string]") + } + + #[test] + fn test_no_infer_flag_is_deprecated() -> nu_test_support::Result { + nu_test_support::test() + .run("scope commands | where name == 'from tsv' | get 0.deprecation_info.flag.0") + .expect_value_eq("no-infer") + } + #[test] fn test_content_type_metadata() { let mut engine_state = Box::new(EngineState::new()); diff --git a/crates/nu-command/tests/commands/open.rs b/crates/nu-command/tests/commands/open.rs index e721af2842..d65b6fdf17 100644 --- a/crates/nu-command/tests/commands/open.rs +++ b/crates/nu-command/tests/commands/open.rs @@ -397,7 +397,7 @@ fn open_wildcard() -> Result { fn open_multiple_files() -> Result { test() .cwd("tests/fixtures/formats") - .run("open caco3_plastics.csv caco3_plastics.tsv | get tariff_item | math sum") + .run("open caco3_plastics.csv caco3_plastics.tsv | get tariff_item | into int | math sum") .expect_value_eq(58309279992i64) } diff --git a/crates/nu-command/tests/format_conversions/csv.rs b/crates/nu-command/tests/format_conversions/csv.rs index 898a480ead..f4c45c54cf 100644 --- a/crates/nu-command/tests/format_conversions/csv.rs +++ b/crates/nu-command/tests/format_conversions/csv.rs @@ -66,12 +66,38 @@ fn table_to_csv_text_skipping_headers_after_conversion(playground: Playground) - #[test] fn table_to_csv_float_doesnt_become_int() -> Result { - let code = "[[a]; [1.0]] | to csv | from csv | get 0.a"; + // `to csv` has to write `1.0`, not `1`, for `--infer` to read a float back. + let code = "[[a]; [1.0]] | to csv | from csv --infer | get 0.a"; let outcome: Value = test().run(code)?; assert!(matches!(outcome, Value::Float { .. })); Ok(()) } +#[test] +fn open_keeps_fields_as_strings(playground: Playground) -> Result { + // `open` runs `from csv` without flags, so a file's fields come out as + // written: no leading zero or exponent is turned into a number. + playground.file( + "codes.csv", + indoc::indoc! {" + code,qty + 0123,1 + 28E37262,2 + "}, + )?; + + let code = " + open codes.csv + | get code + | to nuon + "; + + test() + .cwd(playground.path()) + .run(code) + .expect_value_eq(r#"["0123", "28E37262"]"#) +} + #[test] fn infers_types(playground: Playground) -> Result { playground.file( @@ -86,7 +112,8 @@ fn infers_types(playground: Playground) -> Result { )?; let code = " - open los_cuatro_mosqueteros.csv + open --raw los_cuatro_mosqueteros.csv + | from csv --infer | where rusty_luck > 0 | length "; @@ -558,7 +585,7 @@ fn from_csv_test_flexible_extra_vals() -> Result { echo "a,b\n1,2,3" | from csv --flexible | first | values | to nuon "#; - test().run(code).expect_value_eq("[1, 2, 3]") + test().run(code).expect_value_eq(r#"["1", "2", "3"]"#) } #[test] @@ -567,7 +594,7 @@ fn from_csv_test_flexible_missing_vals() -> Result { echo "a,b\n1" | from csv --flexible | first | values | to nuon "#; - test().run(code).expect_value_eq("[1]") + test().run(code).expect_value_eq(r#"["1"]"#) } #[test] diff --git a/crates/nu-command/tests/format_conversions/tsv.rs b/crates/nu-command/tests/format_conversions/tsv.rs index c0593bc160..5daf0bbb49 100644 --- a/crates/nu-command/tests/format_conversions/tsv.rs +++ b/crates/nu-command/tests/format_conversions/tsv.rs @@ -72,7 +72,8 @@ fn table_to_tsv_text_skipping_headers_after_conversion(playground: Playground) - #[test] fn table_to_tsv_float_doesnt_become_int() -> Result { - let code = "[[a]; [1.0]] | to tsv | from tsv | get 0.a | describe"; + // `to tsv` has to write `1.0`, not `1`, for `--infer` to read a float back. + let code = "[[a]; [1.0]] | to tsv | from tsv --infer | get 0.a | describe"; test().run(code).expect_value_eq("float") } diff --git a/crates/nu-std/std-rfc/tables/mod.nu b/crates/nu-std/std-rfc/tables/mod.nu index 110cca4a73..9e11efc28f 100644 --- a/crates/nu-std/std-rfc/tables/mod.nu +++ b/crates/nu-std/std-rfc/tables/mod.nu @@ -3,12 +3,13 @@ ls | group-by type { get name | path parse | get extension } --to-table | aggregate size } @example "group data by multiple columns, and run custom aggregate operations" { - open movies.csv + open --raw movies.csv + | from csv --infer | group-by Lead_Studio Genre --to-table | aggregate Worldwide_Gross Profitability --ops {avg: {math avg}, std: {math stddev}} } @example "run aggregate operations without grouping the input" { - open movies.csv | aggregate Year + open --raw movies.csv | from csv --infer | aggregate Year } export def aggregate [ --ops: record, # default = {min: {math min}, avg: {math avg}, max: {math max}, sum: {math sum}}