nushell/crates/nu-command/src/date/to_table.rs

169 lines
4.9 KiB
Rust
Raw Normal View History

use crate::date::utils::parse_date_from_string;
2021-10-31 06:54:51 +00:00
use chrono::{DateTime, Datelike, FixedOffset, Local, Timelike};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::Type;
use nu_protocol::{
Category, Example, PipelineData, ShellError::DatetimeParseError, Signature, Span, Value,
};
2021-10-31 06:54:51 +00:00
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"date to-table"
}
fn signature(&self) -> Signature {
Signature::build("date to-table")
.input_output_types(vec![
(Type::Date, Type::Table(vec![])),
(Type::String, Type::Table(vec![])),
])
.allow_variants_without_examples(true) // https://github.com/nushell/nushell/issues/7032
.category(Category::Date)
2021-10-31 06:54:51 +00:00
}
fn usage(&self) -> &str {
2022-04-01 08:09:30 +00:00
"Convert the date into a structured table."
2021-10-31 06:54:51 +00:00
}
fn search_terms(&self) -> Vec<&str> {
vec!["structured"]
}
2021-10-31 06:54:51 +00:00
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let head = call.head;
input.map(move |value| helper(value, head), engine_state.ctrlc.clone())
}
fn examples(&self) -> Vec<Example> {
let example_result_1 = || {
let span = Span::test_data();
let cols = vec![
"year".into(),
"month".into(),
"day".into(),
"hour".into(),
"minute".into(),
"second".into(),
"timezone".into(),
];
let 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,
},
];
Some(Value::List {
vals: vec![Value::Record { cols, vals, span }],
span,
})
};
2021-10-31 06:54:51 +00:00
vec![
Example {
description: "Convert the current date into a table.",
2021-10-31 06:54:51 +00:00
example: "date to-table",
result: None,
},
Example {
description: "Convert the date into a table.",
2021-10-31 06:54:51 +00:00
example: "date now | date to-table",
result: None,
},
Example {
description: "Convert a given date into a table.",
example: "'2020-04-12 22:10:57 +0200' | date to-table",
result: example_result_1(),
2021-10-31 06:54:51 +00:00
},
// TODO: This should work but does not; see https://github.com/nushell/nushell/issues/7032
// Example {
// description: "Convert a given date into a table.",
// example: "'2020-04-12 22:10:57 +0200' | into datetime | date to-table",
// result: example_result_1(),
// },
2021-10-31 06:54:51 +00:00
]
}
}
fn parse_date_into_table(date: Result<DateTime<FixedOffset>, Value>, head: Span) -> Value {
let cols = vec![
"year".into(),
"month".into(),
"day".into(),
"hour".into(),
"minute".into(),
"second".into(),
"timezone".into(),
];
match date {
Ok(x) => {
let vals = vec![
Reduced LOC by replacing several instances of `Value::Int {}`, `Value::Float{}`, `Value::Bool {}`, and `Value::String {}` with `Value::int()`, `Value::float()`, `Value::boolean()` and `Value::string()` (#7412) # Description While perusing Value.rs, I noticed the `Value::int()`, `Value::float()`, `Value::boolean()` and `Value::string()` constructors, which seem designed to make it easier to construct various Values, but which aren't used often at all in the codebase. So, using a few find-replaces regexes, I increased their usage. This reduces overall LOC because structures like this: ``` Value::Int { val: a, span: head } ``` are changed into ``` Value::int(a, head) ``` and are respected as such by the project's formatter. There are little readability concerns because the second argument to all of these is `span`, and it's almost always extremely obvious which is the span at every callsite. # User-Facing Changes None. # 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.
2022-12-09 16:37:51 +00:00
Value::int(x.year() as i64, head),
Value::int(x.month() as i64, head),
Value::int(x.day() as i64, head),
Value::int(x.hour() as i64, head),
Value::int(x.minute() as i64, head),
Value::int(x.second() as i64, head),
Value::string(x.offset().to_string(), head),
2021-10-31 06:54:51 +00:00
];
Value::List {
vals: vec![Value::Record {
cols,
vals,
span: head,
}],
2021-10-31 06:54:51 +00:00
span: head,
}
}
Err(e) => e,
}
}
fn helper(val: Value, head: Span) -> Value {
match val {
2021-12-19 07:46:13 +00:00
Value::String {
val,
span: val_span,
} => {
let date = parse_date_from_string(&val, val_span);
2021-10-31 06:54:51 +00:00
parse_date_into_table(date, head)
}
Value::Nothing { span: _ } => {
let now = Local::now();
let n = now.with_timezone(now.offset());
parse_date_into_table(Ok(n), head)
}
Value::Date { val, span: _ } => parse_date_into_table(Ok(val), head),
_ => Value::Error {
error: DatetimeParseError(head),
},
2021-10-31 06:54:51 +00:00
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}