allow str from to convert more things to string (#2977)

* allow str from to convert more things to string

* fixed FileSize so it reports with units configured

* added tests
This commit is contained in:
Darren Schroeder 2021-01-29 07:43:35 -06:00 committed by GitHub
parent d0a2a02eea
commit 47c4b8e88a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 638 additions and 441 deletions

View File

@ -6,8 +6,8 @@ use nu_protocol::{
};
use nu_source::Tagged;
use num_bigint::{BigInt, BigUint, ToBigInt};
// TODO num_format::SystemLocale once platform-specific dependencies are stable (see Cargo.toml)
use nu_data::base::shape::InlineShape;
use num_format::Locale;
use num_traits::{Pow, Signed};
use std::iter;
@ -127,6 +127,14 @@ pub fn action(
}
}
Primitive::Decimal(dec) => format_decimal(dec.clone(), digits, group_digits),
Primitive::String(a_string) => a_string.to_string(),
Primitive::Boolean(a_bool) => a_bool.to_string(),
Primitive::Date(a_date) => a_date.format("%c").to_string(),
Primitive::FilePath(a_filepath) => a_filepath.as_path().display().to_string(),
Primitive::Filesize(a_filesize) => {
let byte_string = InlineShape::format_bytes(a_filesize);
byte_string.1
}
_ => {
return Err(ShellError::unimplemented(
"str from for non-numeric primitives",

View File

@ -0,0 +1,158 @@
use nu_test_support::playground::{Dirs, Playground};
use nu_test_support::{nu, pipeline};
#[test]
fn from_range() {
let actual = nu!(
cwd: ".", pipeline(
r#"
echo 1..5 | str from | to json
"#
)
);
assert_eq!(actual.out, "[\"1\",\"2\",\"3\",\"4\",\"5\"]");
}
#[test]
fn from_number() {
let actual = nu!(
cwd: ".", pipeline(
r#"
echo 5 | str from
"#
)
);
assert_eq!(actual.out, "5");
}
#[test]
fn from_decimal() {
let actual = nu!(
cwd: ".", pipeline(
r#"
echo 1.5 | str from
"#
)
);
assert_eq!(actual.out, "1.5");
}
#[test]
fn from_boolean() {
let actual = nu!(
cwd: ".", pipeline(
r#"
echo $true | str from
"#
)
);
assert_eq!(actual.out, "true");
}
#[test]
fn from_string() {
let actual = nu!(
cwd: ".", pipeline(
r#"
echo "one" | str from
"#
)
);
assert_eq!(actual.out, "one");
}
#[test]
fn from_filename() {
Playground::setup("from_filename", |dirs, sandbox| {
sandbox.with_files(vec![FileWithContentToBeTrimmed(
"sample.toml",
r#"
[dependency]
name = "nu"
"#,
)]);
let actual = nu!(
cwd: dirs.test(),
"ls sample.toml | get name | str from"
);
assert_eq!(actual.out, "sample.toml");
})
}
#[test]
fn from_filesize() {
Playground::setup("from_filesize", |dirs, sandbox| {
sandbox.with_files(vec![FileWithContentToBeTrimmed(
"sample.toml",
r#"
[dependency]
name = "nu"
"#,
)]);
let actual = nu!(
cwd: dirs.test(),
"ls sample.toml | get size | str from"
);
assert_eq!(actual.out, "25 B");
})
}
#[test]
fn from_decimal_correct_trailing_zeros() {
let actual = nu!(
cwd: ".", pipeline(
r#"
= 1.23000 | str from -d 3
"#
));
assert!(actual.out.contains("1.230"));
}
#[test]
fn from_int_decimal_correct_trailing_zeros() {
let actual = nu!(
cwd: ".", pipeline(
r#"
= 1.00000 | str from -d 3
"#
));
assert!(actual.out.contains("1.000"));
}
#[test]
fn from_int_decimal_trim_trailing_zeros() {
let actual = nu!(
cwd: ".", pipeline(
r#"
= 1.00000 | str from | format "{$it} flat"
"#
));
assert!(actual.out.contains("1 flat")); // "1" would match "1.0"
}
#[test]
fn from_table() {
let actual = nu!(
cwd: ".", pipeline(
r#"
echo '[{"name": "foo", "weight": 32.377}, {"name": "bar", "weight": 15.2}]'
| from json
| str from weight -d 2
"#
));
assert!(actual.out.contains("32.38"));
assert!(actual.out.contains("15.20"));
}

View File

@ -343,57 +343,6 @@ fn substrings_the_input_and_treats_end_index_as_length_if_blank_end_index_given(
})
}
#[test]
fn from_decimal_correct_trailing_zeros() {
let actual = nu!(
cwd: ".", pipeline(
r#"
= 1.23000 | str from -d 3
"#
));
assert!(actual.out.contains("1.230"));
}
#[test]
fn from_int_decimal_correct_trailing_zeros() {
let actual = nu!(
cwd: ".", pipeline(
r#"
= 1.00000 | str from -d 3
"#
));
assert!(actual.out.contains("1.000"));
}
#[test]
fn from_int_decimal_trim_trailing_zeros() {
let actual = nu!(
cwd: ".", pipeline(
r#"
= 1.00000 | str from | format "{$it} flat"
"#
));
assert!(actual.out.contains("1 flat")); // "1" would match "1.0"
}
#[test]
fn from_table() {
let actual = nu!(
cwd: ".", pipeline(
r#"
echo '[{"name": "foo", "weight": 32.377}, {"name": "bar", "weight": 15.2}]'
| from json
| str from weight -d 2
"#
));
assert!(actual.out.contains("32.38"));
assert!(actual.out.contains("15.20"));
}
#[test]
fn str_reverse() {
let actual = nu!(

View File

@ -1,4 +1,4 @@
pub(crate) mod shape;
pub mod shape;
use bigdecimal::BigDecimal;
use chrono::{DateTime, FixedOffset, Utc};

View File

@ -1,10 +1,9 @@
// use crate::config::{Conf, NuConfig};
use bigdecimal::BigDecimal;
use chrono::{DateTime, FixedOffset};
use indexmap::map::IndexMap;
use nu_protocol::RangeInclusion;
use nu_protocol::{format_primitive, ColumnPath, Dictionary, Primitive, UntaggedValue, Value};
use nu_source::{b, DebugDocBuilder, PrettyDebug, Tag};
use nu_source::{DbgDocBldr, DebugDocBuilder, PrettyDebug, Tag};
use num_bigint::BigInt;
use num_format::{Locale, ToFormattedString};
use serde::{Deserialize, Serialize};
@ -128,6 +127,70 @@ impl InlineShape {
column: None,
}
}
pub fn format_bytes(bytesize: &u64) -> (DbgDocBldr, String) {
// get the config value, if it doesn't exist make it 'auto' so it works how it originally did
let filesize_format_var = crate::config::config(Tag::unknown())
.expect("unable to get the config.toml file")
.get("filesize_format")
.map(|val| val.convert_to_string().to_ascii_lowercase())
.unwrap_or_else(|| "auto".to_string());
// if there is a value, match it to one of the valid values for byte units
let filesize_format = match filesize_format_var.as_str() {
"b" => (byte_unit::ByteUnit::B, ""),
"kb" => (byte_unit::ByteUnit::KB, ""),
"kib" => (byte_unit::ByteUnit::KiB, ""),
"mb" => (byte_unit::ByteUnit::MB, ""),
"mib" => (byte_unit::ByteUnit::MiB, ""),
"gb" => (byte_unit::ByteUnit::GB, ""),
"gib" => (byte_unit::ByteUnit::GiB, ""),
"tb" => (byte_unit::ByteUnit::TB, ""),
"tib" => (byte_unit::ByteUnit::TiB, ""),
"pb" => (byte_unit::ByteUnit::PB, ""),
"pib" => (byte_unit::ByteUnit::PiB, ""),
"eb" => (byte_unit::ByteUnit::EB, ""),
"eib" => (byte_unit::ByteUnit::EiB, ""),
"zb" => (byte_unit::ByteUnit::ZB, ""),
"zib" => (byte_unit::ByteUnit::ZiB, ""),
_ => (byte_unit::ByteUnit::B, "auto"),
};
let byte = byte_unit::Byte::from_bytes(*bytesize as u128);
let byte = if filesize_format.0 == byte_unit::ByteUnit::B && filesize_format.1 == "auto" {
byte.get_appropriate_unit(false)
} else {
byte.get_adjusted_unit(filesize_format.0)
};
match byte.get_unit() {
byte_unit::ByteUnit::B => {
let locale_byte = byte.get_value() as u64;
let locale_byte_string = locale_byte.to_formatted_string(&Locale::en);
if filesize_format.1 == "auto" {
let doc = (DbgDocBldr::primitive(locale_byte_string)
+ DbgDocBldr::space()
+ DbgDocBldr::kind("B"))
.group();
(doc.clone(), InlineShape::render_doc(&doc))
} else {
let doc = (DbgDocBldr::primitive(locale_byte_string)).group();
(doc.clone(), InlineShape::render_doc(&doc))
}
}
_ => {
let doc = DbgDocBldr::primitive(byte.format(1));
(doc.clone(), InlineShape::render_doc(&doc))
}
}
}
pub fn render_doc(doc: &DebugDocBuilder) -> String {
let mut w = Vec::new();
doc.to_doc()
.render(1000, &mut w)
.expect("Error rendering bytes");
String::from_utf8_lossy(&w).to_string()
}
}
impl PrettyDebug for FormatInlineShape {
@ -135,11 +198,12 @@ impl PrettyDebug for FormatInlineShape {
let column = &self.column;
match &self.shape {
InlineShape::Nothing => b::blank(),
InlineShape::Int(int) => b::primitive(format!("{}", int)),
InlineShape::Decimal(decimal) => {
b::description(format_primitive(&Primitive::Decimal(decimal.clone()), None))
}
InlineShape::Nothing => DbgDocBldr::blank(),
InlineShape::Int(int) => DbgDocBldr::primitive(format!("{}", int)),
InlineShape::Decimal(decimal) => DbgDocBldr::description(format_primitive(
&Primitive::Decimal(decimal.clone()),
None,
)),
InlineShape::Range(range) => {
let (left, left_inclusion) = &range.from;
let (right, right_inclusion) = &range.to;
@ -153,63 +217,22 @@ impl PrettyDebug for FormatInlineShape {
),
};
left.clone().format().pretty() + b::operator(op) + right.clone().format().pretty()
left.clone().format().pretty()
+ DbgDocBldr::operator(op)
+ right.clone().format().pretty()
}
InlineShape::Bytesize(bytesize) => {
// get the config value, if it doesn't exist make it 'auto' so it works how it originally did
let filesize_format_var = crate::config::config(Tag::unknown())
.expect("unable to get the config.toml file")
.get("filesize_format")
.map(|val| val.convert_to_string().to_ascii_lowercase())
.unwrap_or_else(|| "auto".to_string());
// if there is a value, match it to one of the valid values for byte units
let filesize_format = match filesize_format_var.as_str() {
"b" => (byte_unit::ByteUnit::B, ""),
"kb" => (byte_unit::ByteUnit::KB, ""),
"kib" => (byte_unit::ByteUnit::KiB, ""),
"mb" => (byte_unit::ByteUnit::MB, ""),
"mib" => (byte_unit::ByteUnit::MiB, ""),
"gb" => (byte_unit::ByteUnit::GB, ""),
"gib" => (byte_unit::ByteUnit::GiB, ""),
"tb" => (byte_unit::ByteUnit::TB, ""),
"tib" => (byte_unit::ByteUnit::TiB, ""),
"pb" => (byte_unit::ByteUnit::PB, ""),
"pib" => (byte_unit::ByteUnit::PiB, ""),
"eb" => (byte_unit::ByteUnit::EB, ""),
"eib" => (byte_unit::ByteUnit::EiB, ""),
"zb" => (byte_unit::ByteUnit::ZB, ""),
"zib" => (byte_unit::ByteUnit::ZiB, ""),
_ => (byte_unit::ByteUnit::B, "auto"),
};
let byte = byte_unit::Byte::from_bytes(*bytesize as u128);
let byte =
if filesize_format.0 == byte_unit::ByteUnit::B && filesize_format.1 == "auto" {
byte.get_appropriate_unit(false)
} else {
byte.get_adjusted_unit(filesize_format.0)
};
match byte.get_unit() {
byte_unit::ByteUnit::B => {
let locale_byte = byte.get_value() as u64;
let locale_byte_string = locale_byte.to_formatted_string(&Locale::en);
if filesize_format.1 == "auto" {
(b::primitive(locale_byte_string) + b::space() + b::kind("B")).group()
} else {
(b::primitive(locale_byte_string)).group()
}
}
_ => b::primitive(byte.format(1)),
}
let bytes = InlineShape::format_bytes(bytesize);
bytes.0
}
InlineShape::String(string) => b::primitive(string),
InlineShape::Line(string) => b::primitive(string),
InlineShape::ColumnPath(path) => {
b::intersperse(path.iter().map(|member| member.pretty()), b::keyword("."))
}
InlineShape::GlobPattern(pattern) => b::primitive(pattern),
InlineShape::Boolean(boolean) => b::primitive(
InlineShape::String(string) => DbgDocBldr::primitive(string),
InlineShape::Line(string) => DbgDocBldr::primitive(string),
InlineShape::ColumnPath(path) => DbgDocBldr::intersperse(
path.iter().map(|member| member.pretty()),
DbgDocBldr::keyword("."),
),
InlineShape::GlobPattern(pattern) => DbgDocBldr::primitive(pattern),
InlineShape::Boolean(boolean) => DbgDocBldr::primitive(
match (boolean, column) {
(true, None) => "Yes",
(false, None) => "No",
@ -220,45 +243,47 @@ impl PrettyDebug for FormatInlineShape {
}
.to_owned(),
),
InlineShape::Date(date) => b::primitive(nu_protocol::format_date(date)),
InlineShape::Duration(duration) => b::description(format_primitive(
InlineShape::Date(date) => DbgDocBldr::primitive(nu_protocol::format_date(date)),
InlineShape::Duration(duration) => DbgDocBldr::description(format_primitive(
&Primitive::Duration(duration.clone()),
None,
)),
InlineShape::FilePath(path) => b::primitive(path.display()),
InlineShape::Binary(length) => b::opaque(format!("<binary: {} bytes>", length)),
InlineShape::Row(row) => b::delimit(
InlineShape::FilePath(path) => DbgDocBldr::primitive(path.display()),
InlineShape::Binary(length) => {
DbgDocBldr::opaque(format!("<binary: {} bytes>", length))
}
InlineShape::Row(row) => DbgDocBldr::delimit(
"[",
b::kind("row")
+ b::space()
DbgDocBldr::kind("row")
+ DbgDocBldr::space()
+ if row.map.keys().len() <= 6 {
b::intersperse(
DbgDocBldr::intersperse(
row.map.keys().map(|key| match key {
Column::String(string) => b::description(string),
Column::Value => b::blank(),
Column::String(string) => DbgDocBldr::description(string),
Column::Value => DbgDocBldr::blank(),
}),
b::space(),
DbgDocBldr::space(),
)
} else {
b::description(format!("{} columns", row.map.keys().len()))
DbgDocBldr::description(format!("{} columns", row.map.keys().len()))
},
"]",
)
.group(),
InlineShape::Table(rows) => b::delimit(
InlineShape::Table(rows) => DbgDocBldr::delimit(
"[",
b::kind("table")
+ b::space()
+ b::primitive(rows.len())
+ b::space()
+ b::description("rows"),
DbgDocBldr::kind("table")
+ DbgDocBldr::space()
+ DbgDocBldr::primitive(rows.len())
+ DbgDocBldr::space()
+ DbgDocBldr::description("rows"),
"]",
)
.group(),
InlineShape::Block => b::opaque("block"),
InlineShape::Error => b::error("error"),
InlineShape::BeginningOfStream => b::blank(),
InlineShape::EndOfStream => b::blank(),
InlineShape::Block => DbgDocBldr::opaque("block"),
InlineShape::Error => DbgDocBldr::error("error"),
InlineShape::BeginningOfStream => DbgDocBldr::blank(),
InlineShape::EndOfStream => DbgDocBldr::blank(),
}
}
}

View File

@ -1,6 +1,6 @@
use derive_new::new;
use nu_protocol::{Dictionary, MaybeOwned, Primitive, UntaggedValue, Value};
use nu_source::{b, DebugDocBuilder, PrettyDebug, Spanned, Tag};
use nu_source::{DbgDocBldr, DebugDocBuilder, PrettyDebug, Spanned, Tag};
#[derive(Debug, new)]
struct DebugEntry<'a> {
@ -10,7 +10,10 @@ struct DebugEntry<'a> {
impl<'a> PrettyDebug for DebugEntry<'a> {
fn pretty(&self) -> DebugDocBuilder {
(b::key(self.key.to_string()) + b::equals() + self.value.pretty().into_value()).group()
(DbgDocBldr::key(self.key.to_string())
+ DbgDocBldr::equals()
+ self.value.pretty().into_value())
.group()
}
}

View File

@ -8,7 +8,7 @@ use nu_errors::ShellError;
use nu_parser::ParserScope;
use nu_protocol::hir::Block;
use nu_protocol::{ReturnSuccess, Signature, UntaggedValue};
use nu_source::{b, DebugDocBuilder, PrettyDebugWithSource, Span, Tag};
use nu_source::{DbgDocBldr, DebugDocBuilder, PrettyDebugWithSource, Span, Tag};
use nu_stream::{OutputStream, ToOutputStream};
use std::sync::Arc;
@ -172,12 +172,12 @@ pub struct Command(Arc<dyn WholeStreamCommand>);
impl PrettyDebugWithSource for Command {
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
b::typed(
DbgDocBldr::typed(
"whole stream command",
b::description(self.name())
+ b::space()
+ b::equals()
+ b::space()
DbgDocBldr::description(self.name())
+ DbgDocBldr::space()
+ DbgDocBldr::equals()
+ DbgDocBldr::space()
+ self.signature().pretty_debug(source),
)
}

View File

@ -3,7 +3,9 @@ use bigdecimal::BigDecimal;
use codespan_reporting::diagnostic::{Diagnostic, Label};
use derive_new::new;
use getset::Getters;
use nu_source::{b, DebugDocBuilder, HasFallibleSpan, PrettyDebug, Span, Spanned, SpannedItem};
use nu_source::{
DbgDocBldr, DebugDocBuilder, HasFallibleSpan, PrettyDebug, Span, Spanned, SpannedItem,
};
use num_bigint::BigInt;
use num_traits::ToPrimitive;
use serde::{Deserialize, Serialize};
@ -144,31 +146,31 @@ impl PrettyDebug for ArgumentError {
fn pretty(&self) -> DebugDocBuilder {
match self {
ArgumentError::MissingMandatoryFlag(flag) => {
b::description("missing `")
+ b::description(flag)
+ b::description("` as mandatory flag")
DbgDocBldr::description("missing `")
+ DbgDocBldr::description(flag)
+ DbgDocBldr::description("` as mandatory flag")
}
ArgumentError::UnexpectedArgument(name) => {
b::description("unexpected `")
+ b::description(&name.item)
+ b::description("` is not supported")
DbgDocBldr::description("unexpected `")
+ DbgDocBldr::description(&name.item)
+ DbgDocBldr::description("` is not supported")
}
ArgumentError::UnexpectedFlag(name) => {
b::description("unexpected `")
+ b::description(&name.item)
+ b::description("` is not supported")
DbgDocBldr::description("unexpected `")
+ DbgDocBldr::description(&name.item)
+ DbgDocBldr::description("` is not supported")
}
ArgumentError::MissingMandatoryPositional(pos) => {
b::description("missing `")
+ b::description(pos)
+ b::description("` as mandatory positional argument")
DbgDocBldr::description("missing `")
+ DbgDocBldr::description(pos)
+ DbgDocBldr::description("` as mandatory positional argument")
}
ArgumentError::MissingValueForName(name) => {
b::description("missing value for flag `")
+ b::description(name)
+ b::description("`")
DbgDocBldr::description("missing value for flag `")
+ DbgDocBldr::description(name)
+ DbgDocBldr::description("`")
}
ArgumentError::InvalidExternalWord => b::description("invalid word"),
ArgumentError::InvalidExternalWord => DbgDocBldr::description("invalid word"),
}
}
}
@ -187,73 +189,77 @@ impl PrettyDebug for ShellError {
fn pretty(&self) -> DebugDocBuilder {
match &self.error {
ProximateShellError::SyntaxError { problem } => {
b::error("Syntax Error")
+ b::space()
+ b::delimit("(", b::description(&problem.item), ")")
DbgDocBldr::error("Syntax Error")
+ DbgDocBldr::space()
+ DbgDocBldr::delimit("(", DbgDocBldr::description(&problem.item), ")")
}
ProximateShellError::UnexpectedEof { .. } => b::error("Unexpected end"),
ProximateShellError::UnexpectedEof { .. } => DbgDocBldr::error("Unexpected end"),
ProximateShellError::TypeError { expected, actual } => {
b::error("Type Error")
+ b::space()
+ b::delimit(
DbgDocBldr::error("Type Error")
+ DbgDocBldr::space()
+ DbgDocBldr::delimit(
"(",
b::description("expected:")
+ b::space()
+ b::description(expected)
+ b::description(",")
+ b::space()
+ b::description("actual:")
+ b::space()
+ b::option(actual.item.as_ref().map(b::description)),
DbgDocBldr::description("expected:")
+ DbgDocBldr::space()
+ DbgDocBldr::description(expected)
+ DbgDocBldr::description(",")
+ DbgDocBldr::space()
+ DbgDocBldr::description("actual:")
+ DbgDocBldr::space()
+ DbgDocBldr::option(actual.item.as_ref().map(DbgDocBldr::description)),
")",
)
}
ProximateShellError::MissingProperty { subpath, expr } => {
b::error("Missing Property")
+ b::space()
+ b::delimit(
DbgDocBldr::error("Missing Property")
+ DbgDocBldr::space()
+ DbgDocBldr::delimit(
"(",
b::description("expr:")
+ b::space()
+ b::description(&expr.item)
+ b::description(",")
+ b::space()
+ b::description("subpath:")
+ b::space()
+ b::description(&subpath.item),
DbgDocBldr::description("expr:")
+ DbgDocBldr::space()
+ DbgDocBldr::description(&expr.item)
+ DbgDocBldr::description(",")
+ DbgDocBldr::space()
+ DbgDocBldr::description("subpath:")
+ DbgDocBldr::space()
+ DbgDocBldr::description(&subpath.item),
")",
)
}
ProximateShellError::InvalidIntegerIndex { subpath, .. } => {
b::error("Invalid integer index")
+ b::space()
+ b::delimit(
DbgDocBldr::error("Invalid integer index")
+ DbgDocBldr::space()
+ DbgDocBldr::delimit(
"(",
b::description("subpath:") + b::space() + b::description(&subpath.item),
DbgDocBldr::description("subpath:")
+ DbgDocBldr::space()
+ DbgDocBldr::description(&subpath.item),
")",
)
}
ProximateShellError::MissingValue { reason, .. } => {
b::error("Missing Value")
+ b::space()
+ b::delimit(
DbgDocBldr::error("Missing Value")
+ DbgDocBldr::space()
+ DbgDocBldr::delimit(
"(",
b::description("reason:") + b::space() + b::description(reason),
DbgDocBldr::description("reason:")
+ DbgDocBldr::space()
+ DbgDocBldr::description(reason),
")",
)
}
ProximateShellError::ArgumentError { command, error } => {
b::error("Argument Error")
+ b::space()
+ b::delimit(
DbgDocBldr::error("Argument Error")
+ DbgDocBldr::space()
+ DbgDocBldr::delimit(
"(",
b::description("command:")
+ b::space()
+ b::description(&command.item)
+ b::description(",")
+ b::space()
+ b::description("error:")
+ b::space()
DbgDocBldr::description("command:")
+ DbgDocBldr::space()
+ DbgDocBldr::description(&command.item)
+ DbgDocBldr::description(",")
+ DbgDocBldr::space()
+ DbgDocBldr::description("error:")
+ DbgDocBldr::space()
+ error.pretty(),
")",
)
@ -263,48 +269,49 @@ impl PrettyDebug for ShellError {
actual_kind,
operation,
} => {
b::error("Range Error")
+ b::space()
+ b::delimit(
DbgDocBldr::error("Range Error")
+ DbgDocBldr::space()
+ DbgDocBldr::delimit(
"(",
b::description("expected:")
+ b::space()
DbgDocBldr::description("expected:")
+ DbgDocBldr::space()
+ kind.pretty()
+ b::description(",")
+ b::space()
+ b::description("actual:")
+ b::space()
+ b::description(&actual_kind.item)
+ b::description(",")
+ b::space()
+ b::description("operation:")
+ b::space()
+ b::description(operation),
+ DbgDocBldr::description(",")
+ DbgDocBldr::space()
+ DbgDocBldr::description("actual:")
+ DbgDocBldr::space()
+ DbgDocBldr::description(&actual_kind.item)
+ DbgDocBldr::description(",")
+ DbgDocBldr::space()
+ DbgDocBldr::description("operation:")
+ DbgDocBldr::space()
+ DbgDocBldr::description(operation),
")",
)
}
ProximateShellError::Diagnostic(_) => b::error("diagnostic"),
ProximateShellError::Diagnostic(_) => DbgDocBldr::error("diagnostic"),
ProximateShellError::CoerceError { left, right } => {
b::error("Coercion Error")
+ b::space()
+ b::delimit(
DbgDocBldr::error("Coercion Error")
+ DbgDocBldr::space()
+ DbgDocBldr::delimit(
"(",
b::description("left:")
+ b::space()
+ b::description(&left.item)
+ b::description(",")
+ b::space()
+ b::description("right:")
+ b::space()
+ b::description(&right.item),
DbgDocBldr::description("left:")
+ DbgDocBldr::space()
+ DbgDocBldr::description(&left.item)
+ DbgDocBldr::description(",")
+ DbgDocBldr::space()
+ DbgDocBldr::description("right:")
+ DbgDocBldr::space()
+ DbgDocBldr::description(&right.item),
")",
)
}
ProximateShellError::UntaggedRuntimeError { reason } => {
b::error("Unknown Error") + b::delimit("(", b::description(reason), ")")
DbgDocBldr::error("Unknown Error")
+ DbgDocBldr::delimit("(", DbgDocBldr::description(reason), ")")
}
ProximateShellError::ExternalPlaceholderError => {
b::error("non-zero external exit code")
DbgDocBldr::error("non-zero external exit code")
}
}
}
@ -676,7 +683,7 @@ impl From<Range<usize>> for ExpectedRange {
impl PrettyDebug for ExpectedRange {
fn pretty(&self) -> DebugDocBuilder {
b::description(match self {
DbgDocBldr::description(match self {
ExpectedRange::I8 => "an 8-bit signed integer",
ExpectedRange::I16 => "a 16-bit signed integer",
ExpectedRange::I32 => "a 32-bit signed integer",
@ -694,7 +701,7 @@ impl PrettyDebug for ExpectedRange {
ExpectedRange::BigDecimal => "a decimal",
ExpectedRange::BigInt => "an integer",
ExpectedRange::Range { start, end } => {
return b::description(format!("{} to {}", start, end))
return DbgDocBldr::description(format!("{} to {}", start, end))
}
})
}

View File

@ -12,7 +12,7 @@ use derive_new::new;
use nu_errors::ParseError;
use nu_source::{
b, DebugDocBuilder, HasSpan, PrettyDebug, PrettyDebugRefineKind, PrettyDebugWithSource,
DbgDocBldr, DebugDocBuilder, HasSpan, PrettyDebug, PrettyDebugRefineKind, PrettyDebugWithSource,
};
use nu_source::{IntoSpanned, Span, Spanned, SpannedItem, Tag};
@ -390,9 +390,9 @@ impl Member {
impl PrettyDebugWithSource for Member {
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
match self {
Member::String(outer, _) => b::value(outer.slice(source)),
Member::Int(int, _) => b::value(format!("{}", int)),
Member::Bare(span) => b::value(span.span.slice(source)),
Member::String(outer, _) => DbgDocBldr::value(outer.slice(source)),
Member::Int(int, _) => DbgDocBldr::value(format!("{}", int)),
Member::Bare(span) => DbgDocBldr::value(span.span.slice(source)),
}
}
}
@ -416,8 +416,8 @@ pub enum Number {
impl PrettyDebug for Number {
fn pretty(&self) -> DebugDocBuilder {
match self {
Number::Int(int) => b::primitive(int),
Number::Decimal(decimal) => b::primitive(decimal),
Number::Int(int) => DbgDocBldr::primitive(int),
Number::Decimal(decimal) => DbgDocBldr::primitive(decimal),
}
}
}
@ -508,7 +508,7 @@ impl ToBigInt for Number {
impl PrettyDebug for Unit {
fn pretty(&self) -> DebugDocBuilder {
b::keyword(self.as_str())
DbgDocBldr::keyword(self.as_str())
}
}
@ -715,31 +715,35 @@ impl PrettyDebugWithSource for SpannedExpression {
.into_spanned(self.span)
.refined_pretty_debug(refine, source),
Expression::ExternalWord => {
b::delimit("e\"", b::primitive(self.span.slice(source)), "\"").group()
DbgDocBldr::delimit("e\"", DbgDocBldr::primitive(self.span.slice(source)), "\"")
.group()
}
Expression::Synthetic(s) => match s {
Synthetic::String(_) => {
b::delimit("s\"", b::primitive(self.span.slice(source)), "\"").group()
}
Synthetic::String(_) => DbgDocBldr::delimit(
"s\"",
DbgDocBldr::primitive(self.span.slice(source)),
"\"",
)
.group(),
},
Expression::Variable(_, _) => b::keyword(self.span.slice(source)),
Expression::Variable(_, _) => DbgDocBldr::keyword(self.span.slice(source)),
Expression::Binary(binary) => binary.pretty_debug(source),
Expression::Range(range) => range.pretty_debug(source),
Expression::Block(_) => b::opaque("block"),
Expression::Invocation(_) => b::opaque("invocation"),
Expression::Garbage => b::opaque("garbage"),
Expression::List(list) => b::delimit(
Expression::Block(_) => DbgDocBldr::opaque("block"),
Expression::Invocation(_) => DbgDocBldr::opaque("invocation"),
Expression::Garbage => DbgDocBldr::opaque("garbage"),
Expression::List(list) => DbgDocBldr::delimit(
"[",
b::intersperse(
DbgDocBldr::intersperse(
list.iter()
.map(|item| item.refined_pretty_debug(refine, source)),
b::space(),
DbgDocBldr::space(),
),
"]",
),
Expression::Table(_headers, cells) => b::delimit(
Expression::Table(_headers, cells) => DbgDocBldr::delimit(
"[",
b::intersperse(
DbgDocBldr::intersperse(
cells
.iter()
.map(|row| {
@ -747,19 +751,21 @@ impl PrettyDebugWithSource for SpannedExpression {
.map(|item| item.refined_pretty_debug(refine, source))
})
.flatten(),
b::space(),
DbgDocBldr::space(),
),
"]",
),
Expression::Path(path) => path.pretty_debug(source),
Expression::FilePath(path) => b::typed("path", b::primitive(path.display())),
Expression::ExternalCommand(external) => {
b::keyword("^") + b::keyword(external.name.span.slice(source))
Expression::FilePath(path) => {
DbgDocBldr::typed("path", DbgDocBldr::primitive(path.display()))
}
Expression::Command => b::keyword(self.span.slice(source)),
Expression::ExternalCommand(external) => {
DbgDocBldr::keyword("^") + DbgDocBldr::keyword(external.name.span.slice(source))
}
Expression::Command => DbgDocBldr::keyword(self.span.slice(source)),
Expression::Boolean(boolean) => match boolean {
true => b::primitive("$yes"),
false => b::primitive("$no"),
true => DbgDocBldr::primitive("$yes"),
false => DbgDocBldr::primitive("$no"),
},
},
}
@ -770,47 +776,54 @@ impl PrettyDebugWithSource for SpannedExpression {
Expression::Literal(literal) => {
literal.clone().into_spanned(self.span).pretty_debug(source)
}
Expression::ExternalWord => {
b::typed("external word", b::primitive(self.span.slice(source)))
}
Expression::ExternalWord => DbgDocBldr::typed(
"external word",
DbgDocBldr::primitive(self.span.slice(source)),
),
Expression::Synthetic(s) => match s {
Synthetic::String(s) => b::typed("synthetic", b::primitive(format!("{:?}", s))),
Synthetic::String(s) => {
DbgDocBldr::typed("synthetic", DbgDocBldr::primitive(format!("{:?}", s)))
}
},
Expression::Variable(_, _) => b::keyword(self.span.slice(source)),
Expression::Variable(_, _) => DbgDocBldr::keyword(self.span.slice(source)),
Expression::Binary(binary) => binary.pretty_debug(source),
Expression::Range(range) => range.pretty_debug(source),
Expression::Block(_) => b::opaque("block"),
Expression::Invocation(_) => b::opaque("invocation"),
Expression::Garbage => b::opaque("garbage"),
Expression::List(list) => b::delimit(
Expression::Block(_) => DbgDocBldr::opaque("block"),
Expression::Invocation(_) => DbgDocBldr::opaque("invocation"),
Expression::Garbage => DbgDocBldr::opaque("garbage"),
Expression::List(list) => DbgDocBldr::delimit(
"[",
b::intersperse(
DbgDocBldr::intersperse(
list.iter().map(|item| item.pretty_debug(source)),
b::space(),
DbgDocBldr::space(),
),
"]",
),
Expression::Table(_headers, cells) => b::delimit(
Expression::Table(_headers, cells) => DbgDocBldr::delimit(
"[",
b::intersperse(
DbgDocBldr::intersperse(
cells
.iter()
.map(|row| row.iter().map(|item| item.pretty_debug(source)))
.flatten(),
b::space(),
DbgDocBldr::space(),
),
"]",
),
Expression::Path(path) => path.pretty_debug(source),
Expression::FilePath(path) => b::typed("path", b::primitive(path.display())),
Expression::ExternalCommand(external) => b::typed(
Expression::FilePath(path) => {
DbgDocBldr::typed("path", DbgDocBldr::primitive(path.display()))
}
Expression::ExternalCommand(external) => DbgDocBldr::typed(
"command",
b::keyword("^") + b::primitive(external.name.span.slice(source)),
DbgDocBldr::keyword("^") + DbgDocBldr::primitive(external.name.span.slice(source)),
),
Expression::Command => b::typed("command", b::primitive(self.span.slice(source))),
Expression::Command => {
DbgDocBldr::typed("command", DbgDocBldr::primitive(self.span.slice(source)))
}
Expression::Boolean(boolean) => match boolean {
true => b::primitive("$yes"),
false => b::primitive("$no"),
true => DbgDocBldr::primitive("$yes"),
false => DbgDocBldr::primitive("$no"),
},
}
}
@ -846,12 +859,12 @@ pub struct Binary {
impl PrettyDebugWithSource for Binary {
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
b::delimit(
DbgDocBldr::delimit(
"<",
self.left.pretty_debug(source)
+ b::space()
+ b::keyword(self.op.span.slice(source))
+ b::space()
+ DbgDocBldr::space()
+ DbgDocBldr::keyword(self.op.span.slice(source))
+ DbgDocBldr::space()
+ self.right.pretty_debug(source),
">",
)
@ -881,15 +894,15 @@ pub struct Range {
impl PrettyDebugWithSource for Range {
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
b::delimit(
DbgDocBldr::delimit(
"<",
(if let Some(left) = &self.left {
left.pretty_debug(source)
} else {
DebugDocBuilder::blank()
}) + b::space()
+ b::keyword(self.operator.span().slice(source))
+ b::space()
}) + DbgDocBldr::space()
+ DbgDocBldr::keyword(self.operator.span().slice(source))
+ DbgDocBldr::space()
+ (if let Some(right) = &self.right {
right.pretty_debug(source)
} else {
@ -955,13 +968,15 @@ impl PrettyDebugWithSource for SpannedLiteral {
PrettyDebugRefineKind::WithContext => match &self.literal {
Literal::Number(number) => number.pretty(),
Literal::Size(number, unit) => (number.pretty() + unit.pretty()).group(),
Literal::String(string) => b::primitive(format!("{:?}", string)), //string.slice(source))),
Literal::GlobPattern(pattern) => b::primitive(pattern),
Literal::String(string) => DbgDocBldr::primitive(format!("{:?}", string)), //string.slice(source))),
Literal::GlobPattern(pattern) => DbgDocBldr::primitive(pattern),
Literal::ColumnPath(path) => {
b::intersperse_with_source(path.iter(), b::space(), source)
DbgDocBldr::intersperse_with_source(path.iter(), DbgDocBldr::space(), source)
}
Literal::Bare(bare) => b::delimit("b\"", b::primitive(bare), "\""),
Literal::Operator(operator) => b::primitive(format!("{:?}", operator)),
Literal::Bare(bare) => {
DbgDocBldr::delimit("b\"", DbgDocBldr::primitive(bare), "\"")
}
Literal::Operator(operator) => DbgDocBldr::primitive(format!("{:?}", operator)),
},
}
}
@ -970,20 +985,22 @@ impl PrettyDebugWithSource for SpannedLiteral {
match &self.literal {
Literal::Number(number) => number.pretty(),
Literal::Size(number, unit) => {
b::typed("size", (number.pretty() + unit.pretty()).group())
DbgDocBldr::typed("size", (number.pretty() + unit.pretty()).group())
}
Literal::String(string) => b::typed(
Literal::String(string) => DbgDocBldr::typed(
"string",
b::primitive(format!("{:?}", string)), //string.slice(source))),
DbgDocBldr::primitive(format!("{:?}", string)), //string.slice(source))),
),
Literal::GlobPattern(pattern) => b::typed("pattern", b::primitive(pattern)),
Literal::ColumnPath(path) => b::typed(
Literal::GlobPattern(pattern) => {
DbgDocBldr::typed("pattern", DbgDocBldr::primitive(pattern))
}
Literal::ColumnPath(path) => DbgDocBldr::typed(
"column path",
b::intersperse_with_source(path.iter(), b::space(), source),
DbgDocBldr::intersperse_with_source(path.iter(), DbgDocBldr::space(), source),
),
Literal::Bare(bare) => b::typed("bare", b::primitive(bare)),
Literal::Bare(bare) => DbgDocBldr::typed("bare", DbgDocBldr::primitive(bare)),
Literal::Operator(operator) => {
b::typed("operator", b::primitive(format!("{:?}", operator)))
DbgDocBldr::typed("operator", DbgDocBldr::primitive(format!("{:?}", operator)))
}
}
}
@ -998,8 +1015,11 @@ pub struct Path {
impl PrettyDebugWithSource for Path {
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
self.head.pretty_debug(source)
+ b::operator(".")
+ b::intersperse(self.tail.iter().map(|m| m.pretty()), b::operator("."))
+ DbgDocBldr::operator(".")
+ DbgDocBldr::intersperse(
self.tail.iter().map(|m| m.pretty()),
DbgDocBldr::operator("."),
)
}
}
@ -1225,9 +1245,13 @@ impl NamedValue {
impl PrettyDebugWithSource for NamedValue {
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
match self {
NamedValue::AbsentSwitch => b::typed("switch", b::description("absent")),
NamedValue::PresentSwitch(_) => b::typed("switch", b::description("present")),
NamedValue::AbsentValue => b::description("absent"),
NamedValue::AbsentSwitch => {
DbgDocBldr::typed("switch", DbgDocBldr::description("absent"))
}
NamedValue::PresentSwitch(_) => {
DbgDocBldr::typed("switch", DbgDocBldr::description("present"))
}
NamedValue::AbsentValue => DbgDocBldr::description("absent"),
NamedValue::Value(_, value) => value.pretty_debug(source),
}
}
@ -1236,9 +1260,9 @@ impl PrettyDebugWithSource for NamedValue {
match refine {
PrettyDebugRefineKind::ContextFree => self.pretty_debug(source),
PrettyDebugRefineKind::WithContext => match self {
NamedValue::AbsentSwitch => b::value("absent"),
NamedValue::PresentSwitch(_) => b::value("present"),
NamedValue::AbsentValue => b::value("absent"),
NamedValue::AbsentSwitch => DbgDocBldr::value("absent"),
NamedValue::PresentSwitch(_) => DbgDocBldr::value("present"),
NamedValue::AbsentValue => DbgDocBldr::value("absent"),
NamedValue::Value(_, value) => value.refined_pretty_debug(refine, source),
},
}
@ -1324,22 +1348,22 @@ impl PrettyDebugWithSource for Call {
PrettyDebugRefineKind::WithContext => {
self.head
.refined_pretty_debug(PrettyDebugRefineKind::WithContext, source)
+ b::preceded_option(
Some(b::space()),
+ DbgDocBldr::preceded_option(
Some(DbgDocBldr::space()),
self.positional.as_ref().map(|pos| {
b::intersperse(
DbgDocBldr::intersperse(
pos.iter().map(|expr| {
expr.refined_pretty_debug(
PrettyDebugRefineKind::WithContext,
source,
)
}),
b::space(),
DbgDocBldr::space(),
)
}),
)
+ b::preceded_option(
Some(b::space()),
+ DbgDocBldr::preceded_option(
Some(DbgDocBldr::space()),
self.named.as_ref().map(|named| {
named.refined_pretty_debug(PrettyDebugRefineKind::WithContext, source)
}),
@ -1349,7 +1373,7 @@ impl PrettyDebugWithSource for Call {
}
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
b::typed(
DbgDocBldr::typed(
"call",
self.refined_pretty_debug(PrettyDebugRefineKind::WithContext, source),
)
@ -1538,19 +1562,19 @@ impl PrettyDebugWithSource for NamedArguments {
fn refined_pretty_debug(&self, refine: PrettyDebugRefineKind, source: &str) -> DebugDocBuilder {
match refine {
PrettyDebugRefineKind::ContextFree => self.pretty_debug(source),
PrettyDebugRefineKind::WithContext => b::intersperse(
PrettyDebugRefineKind::WithContext => DbgDocBldr::intersperse(
self.named.iter().map(|(key, value)| {
b::key(key)
+ b::equals()
DbgDocBldr::key(key)
+ DbgDocBldr::equals()
+ value.refined_pretty_debug(PrettyDebugRefineKind::WithContext, source)
}),
b::space(),
DbgDocBldr::space(),
),
}
}
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
b::delimit(
DbgDocBldr::delimit(
"(",
self.refined_pretty_debug(PrettyDebugRefineKind::WithContext, source),
")",
@ -1573,11 +1597,11 @@ pub struct Flag {
impl PrettyDebugWithSource for Flag {
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
let prefix = match self.kind {
FlagKind::Longhand => b::description("--"),
FlagKind::Shorthand => b::description("-"),
FlagKind::Longhand => DbgDocBldr::description("--"),
FlagKind::Shorthand => DbgDocBldr::description("-"),
};
prefix + b::description(self.name.slice(source))
prefix + DbgDocBldr::description(self.name.slice(source))
}
}

View File

@ -1,6 +1,6 @@
use crate::value::Value;
use nu_errors::ShellError;
use nu_source::{b, DebugDocBuilder, PrettyDebug};
use nu_source::{DbgDocBldr, DebugDocBuilder, PrettyDebug};
use serde::{Deserialize, Serialize};
/// The inner set of actions for the command processor. Each denotes a way to change state in the processor without changing it directly from the command itself.
@ -34,19 +34,23 @@ impl PrettyDebug for CommandAction {
/// Get a command action ready to be pretty-printed
fn pretty(&self) -> DebugDocBuilder {
match self {
CommandAction::ChangePath(path) => b::typed("change path", b::description(path)),
CommandAction::Exit => b::description("exit"),
CommandAction::Error(_) => b::error("error"),
CommandAction::AutoConvert(_, extension) => {
b::typed("auto convert", b::description(extension))
CommandAction::ChangePath(path) => {
DbgDocBldr::typed("change path", DbgDocBldr::description(path))
}
CommandAction::EnterShell(s) => b::typed("enter shell", b::description(s)),
CommandAction::EnterValueShell(v) => b::typed("enter value shell", v.pretty()),
CommandAction::EnterHelpShell(v) => b::typed("enter help shell", v.pretty()),
CommandAction::AddPlugins(..) => b::description("add plugins"),
CommandAction::PreviousShell => b::description("previous shell"),
CommandAction::NextShell => b::description("next shell"),
CommandAction::LeaveShell => b::description("leave shell"),
CommandAction::Exit => DbgDocBldr::description("exit"),
CommandAction::Error(_) => DbgDocBldr::error("error"),
CommandAction::AutoConvert(_, extension) => {
DbgDocBldr::typed("auto convert", DbgDocBldr::description(extension))
}
CommandAction::EnterShell(s) => {
DbgDocBldr::typed("enter shell", DbgDocBldr::description(s))
}
CommandAction::EnterValueShell(v) => DbgDocBldr::typed("enter value shell", v.pretty()),
CommandAction::EnterHelpShell(v) => DbgDocBldr::typed("enter help shell", v.pretty()),
CommandAction::AddPlugins(..) => DbgDocBldr::description("add plugins"),
CommandAction::PreviousShell => DbgDocBldr::description("previous shell"),
CommandAction::NextShell => DbgDocBldr::description("next shell"),
CommandAction::LeaveShell => DbgDocBldr::description("leave shell"),
}
}
}
@ -66,9 +70,9 @@ impl PrettyDebug for ReturnSuccess {
/// Get a return success ready to be pretty-printed
fn pretty(&self) -> DebugDocBuilder {
match self {
ReturnSuccess::Value(value) => b::typed("value", value.pretty()),
ReturnSuccess::DebugValue(value) => b::typed("debug value", value.pretty()),
ReturnSuccess::Action(action) => b::typed("action", action.pretty()),
ReturnSuccess::Value(value) => DbgDocBldr::typed("value", value.pretty()),
ReturnSuccess::DebugValue(value) => DbgDocBldr::typed("debug value", value.pretty()),
ReturnSuccess::Action(action) => DbgDocBldr::typed("action", action.pretty()),
}
}
}

View File

@ -1,7 +1,7 @@
use crate::syntax_shape::SyntaxShape;
use crate::type_shape::Type;
use indexmap::IndexMap;
use nu_source::{b, DebugDocBuilder, PrettyDebug, PrettyDebugWithSource};
use nu_source::{DbgDocBldr, DebugDocBuilder, PrettyDebug, PrettyDebugWithSource};
use serde::{Deserialize, Serialize};
/// The types of named parameter that a command can have
@ -39,12 +39,17 @@ impl PrettyDebug for PositionalType {
fn pretty(&self) -> DebugDocBuilder {
match self {
PositionalType::Mandatory(string, shape) => {
b::description(string) + b::delimit("(", shape.pretty(), ")").into_kind().group()
DbgDocBldr::description(string)
+ DbgDocBldr::delimit("(", shape.pretty(), ")")
.into_kind()
.group()
}
PositionalType::Optional(string, shape) => {
b::description(string)
+ b::operator("?")
+ b::delimit("(", shape.pretty(), ")").into_kind().group()
DbgDocBldr::description(string)
+ DbgDocBldr::operator("?")
+ DbgDocBldr::delimit("(", shape.pretty(), ")")
.into_kind()
.group()
}
}
}
@ -165,16 +170,16 @@ impl Signature {
impl PrettyDebugWithSource for Signature {
/// Prepare a Signature for pretty-printing
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
b::typed(
DbgDocBldr::typed(
"signature",
b::description(&self.name)
+ b::preceded(
b::space(),
b::intersperse(
DbgDocBldr::description(&self.name)
+ DbgDocBldr::preceded(
DbgDocBldr::space(),
DbgDocBldr::intersperse(
self.positional
.iter()
.map(|(ty, _)| ty.pretty_debug(source)),
b::space(),
DbgDocBldr::space(),
),
),
)

View File

@ -1,4 +1,4 @@
use nu_source::{b, DebugDocBuilder, PrettyDebug};
use nu_source::{DbgDocBldr, DebugDocBuilder, PrettyDebug};
use serde::{Deserialize, Serialize};
/// The syntactic shapes that values must match to be passed into a command. You can think of this as the type-checking that occurs when you call a function.
@ -40,7 +40,7 @@ pub enum SyntaxShape {
impl PrettyDebug for SyntaxShape {
/// Prepare SyntaxShape for pretty-printing
fn pretty(&self) -> DebugDocBuilder {
b::kind(match self {
DbgDocBldr::kind(match self {
SyntaxShape::Any => "any",
SyntaxShape::String => "string",
SyntaxShape::FullColumnPath => "column path (with variable)",

View File

@ -10,7 +10,7 @@ use crate::value::range::RangeInclusion;
use crate::value::{UntaggedValue, Value};
use derive_new::new;
use indexmap::map::IndexMap;
use nu_source::{b, DebugDoc, DebugDocBuilder, PrettyDebug};
use nu_source::{DbgDocBldr, DebugDoc, DebugDocBuilder, PrettyDebug};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt::Debug;
@ -197,22 +197,22 @@ impl PrettyDebug for Type {
let (left, left_inclusion) = &range.from;
let (right, right_inclusion) = &range.to;
let left_bracket = b::delimiter(match left_inclusion {
let left_bracket = DbgDocBldr::delimiter(match left_inclusion {
RangeInclusion::Exclusive => "(",
RangeInclusion::Inclusive => "[",
});
let right_bracket = b::delimiter(match right_inclusion {
let right_bracket = DbgDocBldr::delimiter(match right_inclusion {
RangeInclusion::Exclusive => ")",
RangeInclusion::Inclusive => "]",
});
b::typed(
DbgDocBldr::typed(
"range",
(left_bracket
+ left.pretty()
+ b::operator(",")
+ b::space()
+ DbgDocBldr::operator(",")
+ DbgDocBldr::space()
+ right.pretty()
+ right_bracket)
.group(),
@ -229,20 +229,20 @@ impl PrettyDebug for Type {
Type::Duration => ty("duration"),
Type::FilePath => ty("path"),
Type::Binary => ty("binary"),
Type::Error => b::error("error"),
Type::BeginningOfStream => b::keyword("beginning-of-stream"),
Type::EndOfStream => b::keyword("end-of-stream"),
Type::Row(row) => (b::kind("row")
+ b::space()
+ b::intersperse(
Type::Error => DbgDocBldr::error("error"),
Type::BeginningOfStream => DbgDocBldr::keyword("beginning-of-stream"),
Type::EndOfStream => DbgDocBldr::keyword("end-of-stream"),
Type::Row(row) => (DbgDocBldr::kind("row")
+ DbgDocBldr::space()
+ DbgDocBldr::intersperse(
row.map.iter().map(|(key, ty)| {
(b::key(match key {
(DbgDocBldr::key(match key {
Column::String(string) => string.clone(),
Column::Value => "".to_string(),
}) + b::delimit("(", ty.pretty(), ")").into_kind())
}) + DbgDocBldr::delimit("(", ty.pretty(), ")").into_kind())
.nest()
}),
b::space(),
DbgDocBldr::space(),
)
.nest())
.nest(),
@ -254,34 +254,35 @@ impl PrettyDebug for Type {
group.add(item.to_doc(), i);
}
(b::kind("table") + b::space() + b::keyword("of")).group()
+ b::space()
(DbgDocBldr::kind("table") + DbgDocBldr::space() + DbgDocBldr::keyword("of"))
.group()
+ DbgDocBldr::space()
+ (if group.len() == 1 {
let (doc, _) = group.into_iter().collect::<Vec<_>>()[0].clone();
DebugDocBuilder::from_doc(doc)
} else {
b::intersperse(
DbgDocBldr::intersperse(
group.into_iter().map(|(doc, rows)| {
(b::intersperse(
(DbgDocBldr::intersperse(
rows.iter().map(|(from, to)| {
if from == to {
b::description(from)
DbgDocBldr::description(from)
} else {
(b::description(from)
+ b::space()
+ b::keyword("to")
+ b::space()
+ b::description(to))
(DbgDocBldr::description(from)
+ DbgDocBldr::space()
+ DbgDocBldr::keyword("to")
+ DbgDocBldr::space()
+ DbgDocBldr::description(to))
.group()
}
}),
b::description(", "),
) + b::description(":")
+ b::space()
DbgDocBldr::description(", "),
) + DbgDocBldr::description(":")
+ DbgDocBldr::space()
+ DebugDocBuilder::from_doc(doc))
.nest()
}),
b::space(),
DbgDocBldr::space(),
)
})
}
@ -300,16 +301,16 @@ struct DebugEntry<'a> {
impl<'a> PrettyDebug for DebugEntry<'a> {
/// Prepare debug entries for pretty-printing
fn pretty(&self) -> DebugDocBuilder {
b::key(match self.key {
DbgDocBldr::key(match self.key {
Column::String(string) => string.clone(),
Column::Value => "".to_string(),
}) + b::delimit("(", self.value.pretty(), ")").into_kind()
}) + DbgDocBldr::delimit("(", self.value.pretty(), ")").into_kind()
}
}
/// Helper to create a pretty-print for the type
fn ty(name: impl std::fmt::Display) -> DebugDocBuilder {
b::kind(format!("{}", name))
DbgDocBldr::kind(format!("{}", name))
}
pub trait GroupedValue: Debug + Clone {

View File

@ -1,8 +1,8 @@
use derive_new::new;
use getset::Getters;
use nu_source::{
b, span_for_spanned_list, DebugDocBuilder, HasFallibleSpan, PrettyDebug, Span, Spanned,
SpannedItem,
span_for_spanned_list, DbgDocBldr, DebugDocBuilder, HasFallibleSpan, PrettyDebug, Span,
Spanned, SpannedItem,
};
use num_bigint::BigInt;
use serde::{Deserialize, Serialize};
@ -38,8 +38,8 @@ impl PrettyDebug for &PathMember {
/// Gets the PathMember ready to be pretty-printed
fn pretty(&self) -> DebugDocBuilder {
match &self.unspanned {
UnspannedPathMember::String(string) => b::primitive(format!("{:?}", string)),
UnspannedPathMember::Int(int) => b::primitive(format!("{}", int)),
UnspannedPathMember::String(string) => DbgDocBldr::primitive(format!("{:?}", string)),
UnspannedPathMember::Int(int) => DbgDocBldr::primitive(format!("{}", int)),
}
}
}
@ -96,9 +96,11 @@ impl PrettyDebug for ColumnPath {
let members: Vec<DebugDocBuilder> =
self.members.iter().map(|member| member.pretty()).collect();
b::delimit(
DbgDocBldr::delimit(
"(",
b::description("path") + b::equals() + b::intersperse(members, b::space()),
DbgDocBldr::description("path")
+ DbgDocBldr::equals()
+ DbgDocBldr::intersperse(members, DbgDocBldr::space()),
")",
)
.nest()

View File

@ -1,7 +1,7 @@
use crate::type_name::PrettyType;
use crate::value::primitive::Primitive;
use crate::value::{UntaggedValue, Value};
use nu_source::{b, DebugDocBuilder, PrettyDebug};
use nu_source::{DbgDocBldr, DebugDocBuilder, PrettyDebug};
impl PrettyDebug for &Value {
/// Get a borrowed Value ready to be pretty-printed
@ -16,11 +16,14 @@ impl PrettyDebug for Value {
match &self.value {
UntaggedValue::Primitive(p) => p.pretty(),
UntaggedValue::Row(row) => row.pretty_builder().nest(1).group().into(),
UntaggedValue::Table(table) => {
b::delimit("[", b::intersperse(table, b::space()), "]").nest()
}
UntaggedValue::Error(_) => b::error("error"),
UntaggedValue::Block(_) => b::opaque("block"),
UntaggedValue::Table(table) => DbgDocBldr::delimit(
"[",
DbgDocBldr::intersperse(table, DbgDocBldr::space()),
"]",
)
.nest(),
UntaggedValue::Error(_) => DbgDocBldr::error("error"),
UntaggedValue::Block(_) => DbgDocBldr::opaque("block"),
}
}
}
@ -42,8 +45,8 @@ impl PrettyType for Primitive {
Primitive::Duration(_) => ty("duration"),
Primitive::FilePath(_) => ty("path"),
Primitive::Binary(_) => ty("binary"),
Primitive::BeginningOfStream => b::keyword("beginning-of-stream"),
Primitive::EndOfStream => b::keyword("end-of-stream"),
Primitive::BeginningOfStream => DbgDocBldr::keyword("beginning-of-stream"),
Primitive::EndOfStream => DbgDocBldr::keyword("end-of-stream"),
}
}
}
@ -52,19 +55,19 @@ impl PrettyDebug for Primitive {
/// Get a Primitive value ready to be pretty-printed
fn pretty(&self) -> DebugDocBuilder {
match self {
Primitive::Nothing => b::primitive("nothing"),
Primitive::Nothing => DbgDocBldr::primitive("nothing"),
Primitive::Int(int) => prim(format_args!("{}", int)),
Primitive::Decimal(decimal) => prim(format_args!("{}", decimal)),
Primitive::Range(range) => {
let (left, left_inclusion) = &range.from;
let (right, right_inclusion) = &range.to;
b::typed(
DbgDocBldr::typed(
"range",
(left_inclusion.debug_left_bracket()
+ left.pretty()
+ b::operator(",")
+ b::space()
+ DbgDocBldr::operator(",")
+ DbgDocBldr::space()
+ right.pretty()
+ right_inclusion.debug_right_bracket())
.group(),
@ -75,27 +78,28 @@ impl PrettyDebug for Primitive {
Primitive::ColumnPath(path) => path.pretty(),
Primitive::GlobPattern(pattern) => primitive_doc(pattern, "pattern"),
Primitive::Boolean(boolean) => match boolean {
true => b::primitive("$yes"),
false => b::primitive("$no"),
true => DbgDocBldr::primitive("$yes"),
false => DbgDocBldr::primitive("$no"),
},
Primitive::Date(date) => primitive_doc(date, "date"),
Primitive::Duration(duration) => primitive_doc(duration, "nanoseconds"),
Primitive::FilePath(path) => primitive_doc(path, "path"),
Primitive::Binary(_) => b::opaque("binary"),
Primitive::BeginningOfStream => b::keyword("beginning-of-stream"),
Primitive::EndOfStream => b::keyword("end-of-stream"),
Primitive::Binary(_) => DbgDocBldr::opaque("binary"),
Primitive::BeginningOfStream => DbgDocBldr::keyword("beginning-of-stream"),
Primitive::EndOfStream => DbgDocBldr::keyword("end-of-stream"),
}
}
}
fn prim(name: impl std::fmt::Debug) -> DebugDocBuilder {
b::primitive(format!("{:?}", name))
DbgDocBldr::primitive(format!("{:?}", name))
}
fn primitive_doc(name: impl std::fmt::Debug, ty: impl Into<String>) -> DebugDocBuilder {
b::primitive(format!("{:?}", name)) + b::delimit("(", b::kind(ty.into()), ")")
DbgDocBldr::primitive(format!("{:?}", name))
+ DbgDocBldr::delimit("(", DbgDocBldr::kind(ty.into()), ")")
}
fn ty(name: impl std::fmt::Debug) -> DebugDocBuilder {
b::kind(format!("{:?}", name))
DbgDocBldr::kind(format!("{:?}", name))
}

View File

@ -4,7 +4,7 @@ use crate::value::{UntaggedValue, Value};
use derive_new::new;
use getset::Getters;
use indexmap::IndexMap;
use nu_source::{b, DebugDocBuilder, PrettyDebug, Spanned, SpannedItem, Tag};
use nu_source::{DbgDocBldr, DebugDocBuilder, PrettyDebug, Spanned, SpannedItem, Tag};
use serde::{Deserialize, Serialize};
use std::cmp::{Ord, Ordering, PartialOrd};
use std::hash::{Hash, Hasher};
@ -78,20 +78,23 @@ struct DebugEntry<'a> {
impl<'a> PrettyDebug for DebugEntry<'a> {
/// Build the the information to pretty-print the DebugEntry
fn pretty(&self) -> DebugDocBuilder {
(b::key(self.key.to_string()) + b::equals() + self.value.pretty().into_value()).group()
(DbgDocBldr::key(self.key.to_string())
+ DbgDocBldr::equals()
+ self.value.pretty().into_value())
.group()
}
}
impl PrettyDebug for Dictionary {
/// Get a Dictionary ready to be pretty-printed
fn pretty(&self) -> DebugDocBuilder {
b::delimit(
DbgDocBldr::delimit(
"(",
b::intersperse(
DbgDocBldr::intersperse(
self.entries()
.iter()
.map(|(key, value)| DebugEntry::new(key, value)),
b::space(),
DbgDocBldr::space(),
),
")",
)

View File

@ -1,6 +1,6 @@
use crate::value::Primitive;
use derive_new::new;
use nu_source::{b, DebugDocBuilder, Spanned};
use nu_source::{DbgDocBldr, DebugDocBuilder, Spanned};
use serde::{Deserialize, Serialize};
/// The two types of ways to include a range end. Inclusive means to include the value (eg 1..3 inclusive would include the 3 value).
@ -14,7 +14,7 @@ pub enum RangeInclusion {
impl RangeInclusion {
/// Get a RangeInclusion left bracket ready for pretty printing
pub fn debug_left_bracket(self) -> DebugDocBuilder {
b::delimiter(match self {
DbgDocBldr::delimiter(match self {
RangeInclusion::Exclusive => "(",
RangeInclusion::Inclusive => "[",
})
@ -22,7 +22,7 @@ impl RangeInclusion {
/// Get a RangeInclusion right bracket ready for pretty printing
pub fn debug_right_bracket(self) -> DebugDocBuilder {
b::delimiter(match self {
DbgDocBldr::delimiter(match self {
RangeInclusion::Exclusive => ")",
RangeInclusion::Inclusive => "]",
})

View File

@ -8,8 +8,8 @@ pub use self::meta::{
IntoSpanned, Span, Spanned, SpannedItem, Tag, Tagged, TaggedItem,
};
pub use self::pretty::{
b, DebugDoc, DebugDocBuilder, PrettyDebug, PrettyDebugRefineKind, PrettyDebugWithSource,
ShellAnnotation,
DbgDocBldr, DebugDoc, DebugDocBuilder, PrettyDebug, PrettyDebugRefineKind,
PrettyDebugWithSource, ShellAnnotation,
};
pub use self::term_colored::TermColored;
pub use self::text::Text;

View File

@ -1,4 +1,4 @@
use crate::pretty::{b, DebugDocBuilder, PrettyDebugWithSource};
use crate::pretty::{DbgDocBldr, DebugDocBuilder, PrettyDebugWithSource};
use crate::text::Text;
use derive_new::new;
@ -738,7 +738,7 @@ where
impl PrettyDebugWithSource for Option<Span> {
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
match self {
None => b::description("no span"),
None => DbgDocBldr::description("no span"),
Some(span) => span.pretty_debug(source),
}
}
@ -752,9 +752,11 @@ impl HasFallibleSpan for Option<Span> {
impl PrettyDebugWithSource for Span {
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
b::typed(
DbgDocBldr::typed(
"span",
b::keyword("for") + b::space() + b::description(format!("{:?}", self.slice(source))),
DbgDocBldr::keyword("for")
+ DbgDocBldr::space()
+ DbgDocBldr::description(format!("{:?}", self.slice(source))),
)
}
}
@ -771,7 +773,7 @@ where
{
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
match self {
None => b::description("nothing"),
None => DbgDocBldr::description("nothing"),
Some(v) => v.pretty_debug(v.span.slice(source)),
}
}
@ -792,7 +794,7 @@ where
{
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
match self {
None => b::description("nothing"),
None => DbgDocBldr::description("nothing"),
Some(d) => d.pretty_debug(source),
}
}

View File

@ -92,7 +92,7 @@ pub type PrettyDebugDoc =
pub type PrettyDebugDocBuilder = pretty::DocBuilder<'static, pretty::BoxAllocator, ShellAnnotation>;
pub use self::DebugDocBuilder as b;
pub use self::DebugDocBuilder as DbgDocBldr;
#[derive(Clone, new)]
pub struct DebugDocBuilder {
@ -102,15 +102,15 @@ pub struct DebugDocBuilder {
impl PrettyDebug for bool {
fn pretty(&self) -> DebugDocBuilder {
match self {
true => b::primitive("true"),
false => b::primitive("false"),
true => DbgDocBldr::primitive("true"),
false => DbgDocBldr::primitive("false"),
}
}
}
impl PrettyDebug for () {
fn pretty(&self) -> DebugDocBuilder {
b::primitive("nothing")
DbgDocBldr::primitive("nothing")
}
}
@ -172,7 +172,7 @@ impl DebugDocBuilder {
}
pub fn typed(kind: &str, value: DebugDocBuilder) -> DebugDocBuilder {
b::kind(kind) + b::delimit("[", value.group(), "]")
DbgDocBldr::kind(kind) + DbgDocBldr::delimit("[", value.group(), "]")
}
pub fn subtyped(
@ -180,10 +180,12 @@ impl DebugDocBuilder {
subkind: impl std::fmt::Display,
value: DebugDocBuilder,
) -> DebugDocBuilder {
b::delimit(
DbgDocBldr::delimit(
"(",
(b::kind(kind) + b::delimit("[", b::kind(format!("{}", subkind)), "]")).group()
+ b::space()
(DbgDocBldr::kind(kind)
+ DbgDocBldr::delimit("[", DbgDocBldr::kind(format!("{}", subkind)), "]"))
.group()
+ DbgDocBldr::space()
+ value.group(),
")",
)
@ -237,7 +239,7 @@ impl DebugDocBuilder {
) -> DebugDocBuilder {
match builder {
None => DebugDocBuilder::blank(),
Some(b) => b::option(before) + b + b::option(after),
Some(b) => DbgDocBldr::option(before) + b + DbgDocBldr::option(after),
}
}
@ -398,7 +400,7 @@ impl<T: PrettyDebug> PrettyDebugWithSource for T {
impl<T: PrettyDebugWithSource, E> PrettyDebugWithSource for Result<T, E> {
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
match self {
Err(_) => b::error("error"),
Err(_) => DbgDocBldr::error("error"),
Ok(val) => val.pretty_debug(source),
}
}