make to text work more intuitively (#5733)

This commit is contained in:
Darren Schroeder 2022-06-07 14:43:24 -05:00 committed by GitHub
parent 8c74b1e437
commit c57f41e5f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 46 additions and 5 deletions

View File

@ -1,7 +1,9 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use chrono_humanize::HumanTime;
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Value,
ast::Call,
engine::{Command, EngineState, Stack},
format_duration, format_filesize_from_conf, Category, Config, Example, IntoPipelineData,
PipelineData, ShellError, Signature, Value,
};
#[derive(Clone)]
@ -36,7 +38,8 @@ impl Command for ToText {
"\n"
};
let collected_input = input.collect_string(line_ending, config)?;
let collected_input = local_into_string(input.into_value(span), line_ending, config);
Ok(Value::String {
val: collected_input,
span,
@ -69,6 +72,44 @@ impl Command for ToText {
}
}
fn local_into_string(value: Value, separator: &str, config: &Config) -> String {
match value {
Value::Bool { val, .. } => val.to_string(),
Value::Int { val, .. } => val.to_string(),
Value::Float { val, .. } => val.to_string(),
Value::Filesize { val, .. } => format_filesize_from_conf(val, config),
Value::Duration { val, .. } => format_duration(val),
Value::Date { val, .. } => {
format!("{} ({})", val.to_rfc2822(), HumanTime::from(val))
}
Value::Range { val, .. } => {
format!(
"{}..{}",
local_into_string(val.from, ", ", config),
local_into_string(val.to, ", ", config)
)
}
Value::String { val, .. } => val,
Value::List { vals: val, .. } => val
.iter()
.map(|x| local_into_string(x.clone(), ", ", config))
.collect::<Vec<_>>()
.join(separator),
Value::Record { cols, vals, .. } => cols
.iter()
.zip(vals.iter())
.map(|(x, y)| format!("{}: {}", x, local_into_string(y.clone(), ", ", config)))
.collect::<Vec<_>>()
.join(separator),
Value::Block { val, .. } => format!("<Block {}>", val),
Value::Nothing { .. } => String::new(),
Value::Error { error } => format!("{:?}", error),
Value::Binary { val, .. } => format!("{:?}", val),
Value::CellPath { val, .. } => val.into_string(),
Value::CustomValue { val, .. } => val.value_string(),
}
}
#[cfg(test)]
mod test {
use super::*;

View File

@ -2361,7 +2361,7 @@ pub fn format_duration(duration: i64) -> String {
)
}
fn format_filesize_from_conf(num_bytes: i64, config: &Config) -> String {
pub fn format_filesize_from_conf(num_bytes: i64, config: &Config) -> String {
// We need to take into account config.filesize_metric so, if someone asks for KB
// filesize_metric is true, return KiB
format_filesize(