nushell/crates/nu-command/src/conversions/into/record.rs
JT 1e3e034021
Spanned Value step 1: span all value cases (#10042)
# Description

This doesn't really do much that the user could see, but it helps get us
ready to do the steps of the refactor to split the span off of Value, so
that values can be spanless. This allows us to have top-level values
that can hold both a Value and a Span, without requiring that all values
have them.

We expect to see significant memory reduction by removing so many
unnecessary spans from values. For example, a table of 100,000 rows and
5 columns would have a savings of ~8megs in just spans that are almost
always duplicated.

# User-Facing Changes

Nothing yet

# 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 -A clippy::result_large_err` to check that
you're using the standard code style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# 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.
-->
2023-08-25 08:48:05 +12:00

244 lines
8.3 KiB
Rust

use chrono::{DateTime, Datelike, FixedOffset, Timelike};
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
format_duration_as_timeperiod, record, Category, Example, IntoPipelineData, PipelineData,
Record, ShellError, Signature, Span, Type, Value,
};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"into record"
}
fn signature(&self) -> Signature {
Signature::build("into record")
.input_output_types(vec![
(Type::Date, Type::Record(vec![])),
(Type::Duration, Type::Record(vec![])),
(Type::List(Box::new(Type::Any)), Type::Record(vec![])),
(Type::Range, Type::Record(vec![])),
(Type::Record(vec![]), Type::Record(vec![])),
(Type::Table(vec![]), Type::Record(vec![])),
])
.category(Category::Conversions)
}
fn usage(&self) -> &str {
"Convert value to record."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
into_record(engine_state, call, input)
}
fn examples(&self) -> Vec<Example> {
let span = Span::test_data();
vec![
Example {
description: "Convert from one row table to record",
example: "[[value]; [false]] | into record",
result: Some(Value::test_record(Record {
cols: vec!["value".to_string()],
vals: vec![Value::bool(false, span)],
})),
},
Example {
description: "Convert from list to record",
example: "[1 2 3] | into record",
result: Some(Value::test_record(Record {
cols: vec!["0".to_string(), "1".to_string(), "2".to_string()],
vals: vec![
Value::Int { val: 1, span },
Value::Int { val: 2, span },
Value::Int { val: 3, span },
],
})),
},
Example {
description: "Convert from range to record",
example: "0..2 | into record",
result: Some(Value::test_record(Record {
cols: vec!["0".to_string(), "1".to_string(), "2".to_string()],
vals: vec![
Value::Int { val: 0, span },
Value::Int { val: 1, span },
Value::Int { val: 2, span },
],
})),
},
Example {
description: "convert duration to record (weeks max)",
example: "(-500day - 4hr - 5sec) | into record",
result: Some(Value::test_record(Record {
cols: vec![
"week".into(),
"day".into(),
"hour".into(),
"second".into(),
"sign".into(),
],
vals: vec![
Value::Int { val: 71, span },
Value::Int { val: 3, span },
Value::Int { val: 4, span },
Value::Int { val: 5, span },
Value::String {
val: "-".into(),
span,
},
],
})),
},
Example {
description: "convert record to record",
example: "{a: 1, b: 2} | into record",
result: Some(Value::test_record(Record {
cols: vec!["a".to_string(), "b".to_string()],
vals: vec![Value::Int { val: 1, span }, Value::Int { val: 2, span }],
})),
},
Example {
description: "convert date to record",
example: "2020-04-12T22:10:57+02:00 | into record",
result: Some(Value::test_record(Record {
cols: vec![
"year".into(),
"month".into(),
"day".into(),
"hour".into(),
"minute".into(),
"second".into(),
"timezone".into(),
],
vals: vec![
Value::Int { val: 2020, span },
Value::Int { val: 4, span },
Value::Int { val: 12, span },
Value::Int { val: 22, span },
Value::Int { val: 10, span },
Value::Int { val: 57, span },
Value::String {
val: "+02:00".to_string(),
span,
},
],
})),
},
]
}
}
fn into_record(
engine_state: &EngineState,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let input = input.into_value(call.head);
let input_type = input.get_type();
let res = match input {
Value::Date { val, span } => parse_date_into_record(val, span),
Value::Duration { val, span } => parse_duration_into_record(val, span),
Value::List { mut vals, span } => match input_type {
Type::Table(..) if vals.len() == 1 => vals.pop().expect("already checked 1 item"),
_ => Value::record(
vals.into_iter()
.enumerate()
.map(|(idx, val)| (format!("{idx}"), val))
.collect(),
span,
),
},
Value::Range { val, span } => Value::record(
val.into_range_iter(engine_state.ctrlc.clone())?
.enumerate()
.map(|(idx, val)| (format!("{idx}"), val))
.collect(),
span,
),
Value::Record { val, span } => Value::Record { val, span },
Value::Error { .. } => input,
other => Value::Error {
error: Box::new(ShellError::OnlySupportsThisInputType {
exp_input_type: "string".into(),
wrong_type: other.get_type().to_string(),
dst_span: call.head,
src_span: other.span(),
}),
span: call.head,
},
};
Ok(res.into_pipeline_data())
}
fn parse_date_into_record(date: DateTime<FixedOffset>, span: Span) -> Value {
Value::record(
record! {
"year" => Value::int(date.year() as i64, span),
"month" => Value::int(date.month() as i64, span),
"day" => Value::int(date.day() as i64, span),
"hour" => Value::int(date.hour() as i64, span),
"minute" => Value::int(date.minute() as i64, span),
"second" => Value::int(date.second() as i64, span),
"timezone" => Value::string(date.offset().to_string(), span),
},
span,
)
}
fn parse_duration_into_record(duration: i64, span: Span) -> Value {
let (sign, periods) = format_duration_as_timeperiod(duration);
let mut record = Record::new();
for p in periods {
let num_with_unit = p.to_text().to_string();
let split = num_with_unit.split(' ').collect::<Vec<&str>>();
record.push(
match split[1] {
"ns" => "nanosecond",
"µs" => "microsecond",
"ms" => "millisecond",
"sec" => "second",
"min" => "minute",
"hr" => "hour",
"day" => "day",
"wk" => "week",
_ => "unknown",
},
Value::int(split[0].parse().unwrap_or(0), span),
);
}
record.push(
"sign",
Value::string(if sign == -1 { "-" } else { "+" }, span),
);
Value::record(record, span)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}