mirror of
https://github.com/nushell/nushell.git
synced 2025-06-30 22:50:14 +02:00
Move format duration
/filesize
back into core (#9978)
# Description Those two commands are very complementary to `into duration` and `into filesize` when you want to coerce a particular string output. This keeps the old `format` command with its separate formatting syntax still in `nu-cmd-extra`. # User-Facing Changes `format filesize` is back accessible with the default build. The new `format duration` command is also available to everybody # Tests + Formatting
This commit is contained in:
committed by
GitHub
parent
23170ff368
commit
a0cecf7658
@ -192,7 +192,9 @@ pub fn add_shell_command_context(mut engine_state: EngineState) -> EngineState {
|
||||
StrSubstring,
|
||||
StrTrim,
|
||||
StrUpcase,
|
||||
FormatDate
|
||||
FormatDate,
|
||||
FormatDuration,
|
||||
FormatFilesize,
|
||||
};
|
||||
|
||||
// FileSystem
|
||||
|
197
crates/nu-command/src/strings/format/duration.rs
Normal file
197
crates/nu-command/src/strings/format/duration.rs
Normal file
@ -0,0 +1,197 @@
|
||||
use nu_cmd_base::input_handler::{operate, CmdArgument};
|
||||
use nu_engine::CallExt;
|
||||
use nu_protocol::ast::{Call, CellPath};
|
||||
use nu_protocol::engine::{Command, EngineState, Stack};
|
||||
use nu_protocol::{
|
||||
Category, Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value,
|
||||
};
|
||||
|
||||
struct Arguments {
|
||||
format_value: String,
|
||||
float_precision: usize,
|
||||
cell_paths: Option<Vec<CellPath>>,
|
||||
}
|
||||
|
||||
impl CmdArgument for Arguments {
|
||||
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
|
||||
self.cell_paths.take()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FormatDuration;
|
||||
|
||||
impl Command for FormatDuration {
|
||||
fn name(&self) -> &str {
|
||||
"format duration"
|
||||
}
|
||||
|
||||
fn signature(&self) -> Signature {
|
||||
Signature::build("format duration")
|
||||
.input_output_types(vec![
|
||||
(Type::Duration, Type::String),
|
||||
(
|
||||
Type::List(Box::new(Type::Duration)),
|
||||
Type::List(Box::new(Type::String)),
|
||||
),
|
||||
(Type::Table(vec![]), Type::Table(vec![])),
|
||||
])
|
||||
.allow_variants_without_examples(true)
|
||||
.required(
|
||||
"format value",
|
||||
SyntaxShape::String,
|
||||
"the unit in which to display the duration",
|
||||
)
|
||||
.rest(
|
||||
"rest",
|
||||
SyntaxShape::CellPath,
|
||||
"For a data structure input, format duration at the given cell paths",
|
||||
)
|
||||
.category(Category::Strings)
|
||||
}
|
||||
|
||||
fn usage(&self) -> &str {
|
||||
"Outputs duration with a specified unit of time."
|
||||
}
|
||||
|
||||
fn search_terms(&self) -> Vec<&str> {
|
||||
vec!["convert", "display", "pattern", "human readable"]
|
||||
}
|
||||
|
||||
fn run(
|
||||
&self,
|
||||
engine_state: &EngineState,
|
||||
stack: &mut Stack,
|
||||
call: &Call,
|
||||
input: PipelineData,
|
||||
) -> Result<PipelineData, ShellError> {
|
||||
let format_value = call
|
||||
.req::<Value>(engine_state, stack, 0)?
|
||||
.as_string()?
|
||||
.to_ascii_lowercase();
|
||||
let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?;
|
||||
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
|
||||
let float_precision = engine_state.config.float_precision as usize;
|
||||
let arg = Arguments {
|
||||
format_value,
|
||||
float_precision,
|
||||
cell_paths,
|
||||
};
|
||||
operate(
|
||||
format_value_impl,
|
||||
arg,
|
||||
input,
|
||||
call.head,
|
||||
engine_state.ctrlc.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<Example> {
|
||||
vec![
|
||||
Example {
|
||||
description: "Convert µs duration to the requested second duration as a string",
|
||||
example: "1000000µs | format duration sec",
|
||||
result: Some(Value::test_string("1 sec")),
|
||||
},
|
||||
Example {
|
||||
description: "Convert durations to µs duration as strings",
|
||||
example: "[1sec 2sec] | format duration µs",
|
||||
result: Some(Value::test_list(vec![
|
||||
Value::test_string("1000000 µs"),
|
||||
Value::test_string("2000000 µs"),
|
||||
])),
|
||||
},
|
||||
Example {
|
||||
description: "Convert duration to µs as a string if unit asked for was us",
|
||||
example: "1sec | format duration us",
|
||||
result: Some(Value::test_string("1000000 µs")),
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
fn format_value_impl(val: &Value, arg: &Arguments, span: Span) -> Value {
|
||||
match val {
|
||||
Value::Duration {
|
||||
val: inner,
|
||||
span: inner_span,
|
||||
} => {
|
||||
let duration = *inner;
|
||||
let float_precision = arg.float_precision;
|
||||
match convert_inner_to_unit(duration, &arg.format_value, span, *inner_span) {
|
||||
Ok(d) => {
|
||||
let unit = if &arg.format_value == "us" {
|
||||
"µs"
|
||||
} else {
|
||||
&arg.format_value
|
||||
};
|
||||
if d.fract() == 0.0 {
|
||||
Value::String {
|
||||
val: format!("{} {}", d, unit),
|
||||
span: *inner_span,
|
||||
}
|
||||
} else {
|
||||
Value::String {
|
||||
val: format!("{:.float_precision$} {}", d, unit),
|
||||
span: *inner_span,
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => Value::Error { error: Box::new(e) },
|
||||
}
|
||||
}
|
||||
Value::Error { .. } => val.clone(),
|
||||
_ => Value::Error {
|
||||
error: Box::new(ShellError::OnlySupportsThisInputType {
|
||||
exp_input_type: "filesize".into(),
|
||||
wrong_type: val.get_type().to_string(),
|
||||
dst_span: span,
|
||||
src_span: val.expect_span(),
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_inner_to_unit(
|
||||
val: i64,
|
||||
to_unit: &str,
|
||||
span: Span,
|
||||
value_span: Span,
|
||||
) -> Result<f64, ShellError> {
|
||||
match to_unit {
|
||||
"ns" => Ok(val as f64),
|
||||
"us" => Ok(val as f64 / 1000.0),
|
||||
"µs" => Ok(val as f64 / 1000.0), // Micro sign
|
||||
"μs" => Ok(val as f64 / 1000.0), // Greek small letter
|
||||
"ms" => Ok(val as f64 / 1000.0 / 1000.0),
|
||||
"sec" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0),
|
||||
"min" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0 / 60.0),
|
||||
"hr" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0 / 60.0 / 60.0),
|
||||
"day" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0 / 60.0 / 60.0 / 24.0),
|
||||
"wk" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0 / 60.0 / 60.0 / 24.0 / 7.0),
|
||||
"month" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0 / 60.0 / 60.0 / 24.0 / 30.0),
|
||||
"yr" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0 / 60.0 / 60.0 / 24.0 / 365.0),
|
||||
"dec" => Ok(val as f64 / 10.0 / 1000.0 / 1000.0 / 1000.0 / 60.0 / 60.0 / 24.0 / 365.0),
|
||||
|
||||
_ => Err(ShellError::CantConvertToDuration {
|
||||
details: to_unit.to_string(),
|
||||
dst_span: span,
|
||||
src_span: value_span,
|
||||
help: Some(
|
||||
"supported units are ns, us/µs, ms, sec, min, hr, day, wk, month, yr, and dec"
|
||||
.to_string(),
|
||||
),
|
||||
}),
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_examples() {
|
||||
use crate::test_examples;
|
||||
|
||||
test_examples(FormatDuration)
|
||||
}
|
||||
}
|
134
crates/nu-command/src/strings/format/filesize.rs
Normal file
134
crates/nu-command/src/strings/format/filesize.rs
Normal file
@ -0,0 +1,134 @@
|
||||
use nu_cmd_base::input_handler::{operate, CmdArgument};
|
||||
use nu_engine::CallExt;
|
||||
use nu_protocol::ast::{Call, CellPath};
|
||||
use nu_protocol::engine::{Command, EngineState, Stack};
|
||||
use nu_protocol::{
|
||||
format_filesize, Category, Example, PipelineData, ShellError, Signature, Span, SyntaxShape,
|
||||
Type, Value,
|
||||
};
|
||||
|
||||
struct Arguments {
|
||||
format_value: String,
|
||||
cell_paths: Option<Vec<CellPath>>,
|
||||
}
|
||||
|
||||
impl CmdArgument for Arguments {
|
||||
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
|
||||
self.cell_paths.take()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FormatFilesize;
|
||||
|
||||
impl Command for FormatFilesize {
|
||||
fn name(&self) -> &str {
|
||||
"format filesize"
|
||||
}
|
||||
|
||||
fn signature(&self) -> Signature {
|
||||
Signature::build("format filesize")
|
||||
.input_output_types(vec![
|
||||
(Type::Filesize, Type::String),
|
||||
(Type::Table(vec![]), Type::Table(vec![])),
|
||||
(Type::Record(vec![]), Type::Record(vec![])),
|
||||
])
|
||||
.allow_variants_without_examples(true)
|
||||
.required(
|
||||
"format value",
|
||||
SyntaxShape::String,
|
||||
"the format into which convert the file sizes",
|
||||
)
|
||||
.rest(
|
||||
"rest",
|
||||
SyntaxShape::CellPath,
|
||||
"For a data structure input, format filesizes at the given cell paths",
|
||||
)
|
||||
.category(Category::Strings)
|
||||
}
|
||||
|
||||
fn usage(&self) -> &str {
|
||||
"Converts a column of filesizes to some specified format."
|
||||
}
|
||||
|
||||
fn search_terms(&self) -> Vec<&str> {
|
||||
vec!["convert", "display", "pattern", "human readable"]
|
||||
}
|
||||
|
||||
fn run(
|
||||
&self,
|
||||
engine_state: &EngineState,
|
||||
stack: &mut Stack,
|
||||
call: &Call,
|
||||
input: PipelineData,
|
||||
) -> Result<PipelineData, ShellError> {
|
||||
let format_value = call
|
||||
.req::<Value>(engine_state, stack, 0)?
|
||||
.as_string()?
|
||||
.to_ascii_lowercase();
|
||||
let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?;
|
||||
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
|
||||
let arg = Arguments {
|
||||
format_value,
|
||||
cell_paths,
|
||||
};
|
||||
operate(
|
||||
format_value_impl,
|
||||
arg,
|
||||
input,
|
||||
call.head,
|
||||
engine_state.ctrlc.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<Example> {
|
||||
vec![
|
||||
Example {
|
||||
description: "Convert the size column to KB",
|
||||
example: "ls | format filesize KB size",
|
||||
result: None,
|
||||
},
|
||||
Example {
|
||||
description: "Convert the apparent column to B",
|
||||
example: "du | format filesize B apparent",
|
||||
result: None,
|
||||
},
|
||||
Example {
|
||||
description: "Convert the size data to MB",
|
||||
example: "4Gb | format filesize MB",
|
||||
result: Some(Value::test_string("4000.0 MB")),
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
fn format_value_impl(val: &Value, arg: &Arguments, span: Span) -> Value {
|
||||
match val {
|
||||
Value::Filesize { val, span } => Value::String {
|
||||
// don't need to concern about metric, we just format units by what user input.
|
||||
val: format_filesize(*val, &arg.format_value, None),
|
||||
span: *span,
|
||||
},
|
||||
Value::Error { .. } => val.clone(),
|
||||
_ => Value::Error {
|
||||
error: Box::new(ShellError::OnlySupportsThisInputType {
|
||||
exp_input_type: "filesize".into(),
|
||||
wrong_type: val.get_type().to_string(),
|
||||
dst_span: span,
|
||||
src_span: val.expect_span(),
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_examples() {
|
||||
use crate::test_examples;
|
||||
|
||||
test_examples(FormatFilesize)
|
||||
}
|
||||
}
|
@ -1,3 +1,7 @@
|
||||
mod date;
|
||||
mod duration;
|
||||
mod filesize;
|
||||
|
||||
pub use self::filesize::FormatFilesize;
|
||||
pub use date::FormatDate;
|
||||
pub use duration::FormatDuration;
|
||||
|
@ -10,7 +10,7 @@ mod str_;
|
||||
pub use char_::Char;
|
||||
pub use detect_columns::*;
|
||||
pub use encode_decode::*;
|
||||
pub use format::FormatDate;
|
||||
pub use format::*;
|
||||
pub use parse::*;
|
||||
pub use size::Size;
|
||||
pub use split::*;
|
||||
|
Reference in New Issue
Block a user