mirror of
https://github.com/nushell/nushell.git
synced 2025-04-27 22:58:20 +02:00
Add general refactorings (#3996)
This commit is contained in:
parent
ae9f4135c0
commit
51c74eebd0
@ -93,7 +93,7 @@ pub static RESET: &str = "\x1B[0m";
|
|||||||
|
|
||||||
impl Color {
|
impl Color {
|
||||||
fn write_foreground_code<W: AnyWrite + ?Sized>(&self, f: &mut W) -> Result<(), W::Error> {
|
fn write_foreground_code<W: AnyWrite + ?Sized>(&self, f: &mut W) -> Result<(), W::Error> {
|
||||||
match *self {
|
match self {
|
||||||
Color::Black => write!(f, "30"),
|
Color::Black => write!(f, "30"),
|
||||||
Color::Red => write!(f, "31"),
|
Color::Red => write!(f, "31"),
|
||||||
Color::Green => write!(f, "32"),
|
Color::Green => write!(f, "32"),
|
||||||
@ -103,8 +103,8 @@ impl Color {
|
|||||||
Color::Magenta => write!(f, "35"),
|
Color::Magenta => write!(f, "35"),
|
||||||
Color::Cyan => write!(f, "36"),
|
Color::Cyan => write!(f, "36"),
|
||||||
Color::White => write!(f, "37"),
|
Color::White => write!(f, "37"),
|
||||||
Color::Fixed(num) => write!(f, "38;5;{}", &num),
|
Color::Fixed(num) => write!(f, "38;5;{}", num),
|
||||||
Color::Rgb(r, g, b) => write!(f, "38;2;{};{};{}", &r, &g, &b),
|
Color::Rgb(r, g, b) => write!(f, "38;2;{};{};{}", r, g, b),
|
||||||
Color::DarkGray => write!(f, "90"),
|
Color::DarkGray => write!(f, "90"),
|
||||||
Color::LightRed => write!(f, "91"),
|
Color::LightRed => write!(f, "91"),
|
||||||
Color::LightGreen => write!(f, "92"),
|
Color::LightGreen => write!(f, "92"),
|
||||||
@ -118,7 +118,7 @@ impl Color {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn write_background_code<W: AnyWrite + ?Sized>(&self, f: &mut W) -> Result<(), W::Error> {
|
fn write_background_code<W: AnyWrite + ?Sized>(&self, f: &mut W) -> Result<(), W::Error> {
|
||||||
match *self {
|
match self {
|
||||||
Color::Black => write!(f, "40"),
|
Color::Black => write!(f, "40"),
|
||||||
Color::Red => write!(f, "41"),
|
Color::Red => write!(f, "41"),
|
||||||
Color::Green => write!(f, "42"),
|
Color::Green => write!(f, "42"),
|
||||||
@ -128,8 +128,8 @@ impl Color {
|
|||||||
Color::Magenta => write!(f, "45"),
|
Color::Magenta => write!(f, "45"),
|
||||||
Color::Cyan => write!(f, "46"),
|
Color::Cyan => write!(f, "46"),
|
||||||
Color::White => write!(f, "47"),
|
Color::White => write!(f, "47"),
|
||||||
Color::Fixed(num) => write!(f, "48;5;{}", &num),
|
Color::Fixed(num) => write!(f, "48;5;{}", num),
|
||||||
Color::Rgb(r, g, b) => write!(f, "48;2;{};{};{}", &r, &g, &b),
|
Color::Rgb(r, g, b) => write!(f, "48;2;{};{};{}", r, g, b),
|
||||||
Color::DarkGray => write!(f, "100"),
|
Color::DarkGray => write!(f, "100"),
|
||||||
Color::LightRed => write!(f, "101"),
|
Color::LightRed => write!(f, "101"),
|
||||||
Color::LightGreen => write!(f, "102"),
|
Color::LightGreen => write!(f, "102"),
|
||||||
|
@ -297,7 +297,7 @@ mod tests {
|
|||||||
fn no_control_codes_for_plain() {
|
fn no_control_codes_for_plain() {
|
||||||
let one = Style::default().paint("one");
|
let one = Style::default().paint("one");
|
||||||
let two = Style::default().paint("two");
|
let two = Style::default().paint("two");
|
||||||
let output = format!("{}", AnsiStrings(&[one, two]));
|
let output = AnsiStrings(&[one, two]).to_string();
|
||||||
assert_eq!(&*output, "onetwo");
|
assert_eq!(output, "onetwo");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -602,14 +602,14 @@ mod serde_json_tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn color_deserialization() {
|
fn color_deserialization() {
|
||||||
let colors = &[
|
let colors = [
|
||||||
Color::Red,
|
Color::Red,
|
||||||
Color::Blue,
|
Color::Blue,
|
||||||
Color::Rgb(123, 123, 123),
|
Color::Rgb(123, 123, 123),
|
||||||
Color::Fixed(255),
|
Color::Fixed(255),
|
||||||
];
|
];
|
||||||
|
|
||||||
for color in colors.iter() {
|
for color in colors {
|
||||||
let serialized = serde_json::to_string(&color).unwrap();
|
let serialized = serde_json::to_string(&color).unwrap();
|
||||||
let deserialized: Color = serde_json::from_str(&serialized).unwrap();
|
let deserialized: Color = serde_json::from_str(&serialized).unwrap();
|
||||||
|
|
||||||
|
@ -75,6 +75,6 @@ mod test {
|
|||||||
assert_eq!(unstyled_len(&a), 18);
|
assert_eq!(unstyled_len(&a), 18);
|
||||||
|
|
||||||
let l2 = [Black.paint("st"), Red.paint("-second"), White.paint("-t")];
|
let l2 = [Black.paint("st"), Red.paint("-second"), White.paint("-t")];
|
||||||
assert_eq!(sub_string(3, 11, &a).as_slice(), &l2);
|
assert_eq!(sub_string(3, 11, &a), l2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -508,14 +508,14 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn can_use_loglevels() -> Result<(), ShellError> {
|
fn can_use_loglevels() -> Result<(), ShellError> {
|
||||||
for level in &["error", "warn", "info", "debug", "trace"] {
|
for level in ["error", "warn", "info", "debug", "trace"] {
|
||||||
let ui = cli_app();
|
let ui = cli_app();
|
||||||
let args = format!("nu --loglevel={}", *level);
|
let args = format!("nu --loglevel={}", level);
|
||||||
ui.parse(&args)?;
|
ui.parse(&args)?;
|
||||||
assert_eq!(ui.loglevel().unwrap(), Ok(level.to_string()));
|
assert_eq!(ui.loglevel().unwrap(), Ok(level.to_string()));
|
||||||
|
|
||||||
let ui = cli_app();
|
let ui = cli_app();
|
||||||
let args = format!("nu -l {}", *level);
|
let args = format!("nu -l {}", level);
|
||||||
ui.parse(&args)?;
|
ui.parse(&args)?;
|
||||||
assert_eq!(ui.loglevel().unwrap(), Ok(level.to_string()));
|
assert_eq!(ui.loglevel().unwrap(), Ok(level.to_string()));
|
||||||
}
|
}
|
||||||
@ -541,11 +541,11 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn can_use_test_binaries() -> Result<(), ShellError> {
|
fn can_use_test_binaries() -> Result<(), ShellError> {
|
||||||
for binarie_name in &[
|
for binarie_name in [
|
||||||
"echo_env", "cococo", "iecho", "fail", "nonu", "chop", "repeater", "meow",
|
"echo_env", "cococo", "iecho", "fail", "nonu", "chop", "repeater", "meow",
|
||||||
] {
|
] {
|
||||||
let ui = cli_app();
|
let ui = cli_app();
|
||||||
let args = format!("nu --testbin={}", *binarie_name);
|
let args = format!("nu --testbin={}", binarie_name);
|
||||||
ui.parse(&args)?;
|
ui.parse(&args)?;
|
||||||
assert_eq!(ui.testbin().unwrap(), Ok(binarie_name.to_string()));
|
assert_eq!(ui.testbin().unwrap(), Ok(binarie_name.to_string()));
|
||||||
}
|
}
|
||||||
|
@ -44,7 +44,7 @@ impl Options {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn get(&self, key: &str) -> Option<Value> {
|
pub fn get(&self, key: &str) -> Option<Value> {
|
||||||
self.inner.borrow().get(key).map(Clone::clone)
|
self.inner.borrow().get(key).cloned()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn put(&self, key: &str, value: Value) {
|
pub fn put(&self, key: &str, value: Value) {
|
||||||
|
@ -67,48 +67,37 @@ impl OptionsParser for NuParser {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let value =
|
let value = value.map(|v| match k.as_ref() {
|
||||||
value
|
|
||||||
.map(|v| match k.as_ref() {
|
|
||||||
"testbin" => {
|
"testbin" => {
|
||||||
if let Ok(name) = v.as_string() {
|
if let Ok(name) = v.as_string() {
|
||||||
if testbins().iter().any(|n| name == *n) {
|
if testbins().iter().any(|n| name == *n) {
|
||||||
Some(v)
|
v
|
||||||
} else {
|
} else {
|
||||||
Some(
|
UntaggedValue::Error(ShellError::untagged_runtime_error(
|
||||||
UntaggedValue::Error(
|
|
||||||
ShellError::untagged_runtime_error(
|
|
||||||
format!("{} is not supported.", name),
|
format!("{} is not supported.", name),
|
||||||
),
|
))
|
||||||
)
|
.into_value(v.tag)
|
||||||
.into_value(v.tag),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Some(v)
|
v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"loglevel" => {
|
"loglevel" => {
|
||||||
if let Ok(name) = v.as_string() {
|
if let Ok(name) = v.as_string() {
|
||||||
if loglevels().iter().any(|n| name == *n) {
|
if loglevels().iter().any(|n| name == *n) {
|
||||||
Some(v)
|
v
|
||||||
} else {
|
} else {
|
||||||
Some(
|
UntaggedValue::Error(ShellError::untagged_runtime_error(
|
||||||
UntaggedValue::Error(
|
|
||||||
ShellError::untagged_runtime_error(
|
|
||||||
format!("{} is not supported.", name),
|
format!("{} is not supported.", name),
|
||||||
),
|
))
|
||||||
)
|
.into_value(v.tag)
|
||||||
.into_value(v.tag),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Some(v)
|
v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => Some(v),
|
_ => v,
|
||||||
})
|
});
|
||||||
.flatten();
|
|
||||||
|
|
||||||
if let Some(value) = value {
|
if let Some(value) = value {
|
||||||
options.put(k, value);
|
options.put(k, value);
|
||||||
|
@ -165,7 +165,10 @@ pub fn cli(
|
|||||||
// Store cmd duration in an env var
|
// Store cmd duration in an env var
|
||||||
context.scope.add_env_var(
|
context.scope.add_env_var(
|
||||||
"CMD_DURATION_MS",
|
"CMD_DURATION_MS",
|
||||||
format!("{}", startup_commands_start_time.elapsed().as_millis()),
|
startup_commands_start_time
|
||||||
|
.elapsed()
|
||||||
|
.as_millis()
|
||||||
|
.to_string(),
|
||||||
);
|
);
|
||||||
|
|
||||||
if options.perf {
|
if options.perf {
|
||||||
@ -353,7 +356,7 @@ pub fn cli(
|
|||||||
// Store cmd duration in an env var
|
// Store cmd duration in an env var
|
||||||
context.scope.add_env_var(
|
context.scope.add_env_var(
|
||||||
"CMD_DURATION_MS",
|
"CMD_DURATION_MS",
|
||||||
format!("{}", cmd_start_time.elapsed().as_millis()),
|
cmd_start_time.elapsed().as_millis().to_string(),
|
||||||
);
|
);
|
||||||
|
|
||||||
match line {
|
match line {
|
||||||
@ -397,8 +400,7 @@ pub fn cli(
|
|||||||
.lock()
|
.lock()
|
||||||
.global_config
|
.global_config
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|cfg| cfg.var("ctrlc_exit"))
|
.and_then(|cfg| cfg.var("ctrlc_exit"))
|
||||||
.flatten()
|
|
||||||
.map(|ctrl_c| ctrl_c.is_true())
|
.map(|ctrl_c| ctrl_c.is_true())
|
||||||
.unwrap_or(false); // default behavior is to allow CTRL-C spamming similar to other shells
|
.unwrap_or(false); // default behavior is to allow CTRL-C spamming similar to other shells
|
||||||
|
|
||||||
|
@ -461,7 +461,7 @@ pub(crate) fn load_keybindings(
|
|||||||
if let Ok(contents) = contents {
|
if let Ok(contents) = contents {
|
||||||
let keybindings: Keybindings = serde_yaml::from_str(&contents)?;
|
let keybindings: Keybindings = serde_yaml::from_str(&contents)?;
|
||||||
// eprintln!("{:#?}", keybindings);
|
// eprintln!("{:#?}", keybindings);
|
||||||
for keybinding in keybindings.into_iter() {
|
for keybinding in keybindings {
|
||||||
let (k, b) = convert_keybinding(keybinding);
|
let (k, b) = convert_keybinding(keybinding);
|
||||||
// eprintln!("{:?} {:?}", k, b);
|
// eprintln!("{:?} {:?}", k, b);
|
||||||
|
|
||||||
|
@ -509,7 +509,7 @@ fn spawn(
|
|||||||
Ok(stream.into_input_stream())
|
Ok(stream.into_input_stream())
|
||||||
}
|
}
|
||||||
Err(e) => Err(ShellError::labeled_error(
|
Err(e) => Err(ShellError::labeled_error(
|
||||||
format!("{}", e),
|
e.to_string(),
|
||||||
"failed to spawn",
|
"failed to spawn",
|
||||||
&command.name_tag,
|
&command.name_tag,
|
||||||
)),
|
)),
|
||||||
|
@ -159,7 +159,7 @@ pub fn action(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn format_int(int: i64) -> String {
|
fn format_int(int: i64) -> String {
|
||||||
format!("{}", int)
|
int.to_string()
|
||||||
|
|
||||||
// TODO once platform-specific dependencies are stable (see Cargo.toml)
|
// TODO once platform-specific dependencies are stable (see Cargo.toml)
|
||||||
// #[cfg(windows)]
|
// #[cfg(windows)]
|
||||||
@ -176,7 +176,7 @@ fn format_int(int: i64) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn format_bigint(int: &BigInt) -> String {
|
fn format_bigint(int: &BigInt) -> String {
|
||||||
format!("{}", int)
|
int.to_string()
|
||||||
|
|
||||||
// TODO once platform-specific dependencies are stable (see Cargo.toml)
|
// TODO once platform-specific dependencies are stable (see Cargo.toml)
|
||||||
// #[cfg(windows)]
|
// #[cfg(windows)]
|
||||||
@ -230,7 +230,7 @@ fn format_decimal(mut decimal: BigDecimal, digits: Option<u64>, group_digits: bo
|
|||||||
let format_default_loc = |int_part: BigInt| {
|
let format_default_loc = |int_part: BigInt| {
|
||||||
let loc = Locale::en;
|
let loc = Locale::en;
|
||||||
//TODO: when num_format is available for recent bigint, replace this with the locale-based format
|
//TODO: when num_format is available for recent bigint, replace this with the locale-based format
|
||||||
let (int_str, sep) = (format!("{}", int_part), String::from(loc.decimal()));
|
let (int_str, sep) = (int_part.to_string(), String::from(loc.decimal()));
|
||||||
|
|
||||||
format!("{}{}{}", int_str, sep, dec_str)
|
format!("{}{}{}", int_str, sep, dec_str)
|
||||||
};
|
};
|
||||||
|
@ -55,17 +55,18 @@ fn make_error(value: &Value) -> Option<ShellError> {
|
|||||||
{
|
{
|
||||||
let msg = dict.get_data_by_key("msg".spanned_unknown());
|
let msg = dict.get_data_by_key("msg".spanned_unknown());
|
||||||
|
|
||||||
let labels = dict
|
let labels =
|
||||||
.get_data_by_key("labels".spanned_unknown())
|
dict.get_data_by_key("labels".spanned_unknown())
|
||||||
.map(|table| match &table.value {
|
.and_then(|table| match &table.value {
|
||||||
UntaggedValue::Table(_) => table
|
UntaggedValue::Table(_) => table
|
||||||
.table_entries()
|
.table_entries()
|
||||||
.map(|value| value.as_string().ok())
|
.map(|value| value.as_string().ok())
|
||||||
.collect(),
|
.collect(),
|
||||||
UntaggedValue::Primitive(Primitive::String(label)) => Some(vec![label.to_string()]),
|
UntaggedValue::Primitive(Primitive::String(label)) => {
|
||||||
|
Some(vec![label.to_string()])
|
||||||
|
}
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
});
|
||||||
.flatten();
|
|
||||||
|
|
||||||
let _anchor = dict.get_data_by_key("tag".spanned_unknown());
|
let _anchor = dict.get_data_by_key("tag".spanned_unknown());
|
||||||
let span = dict.get_data_by_key("span".spanned_unknown());
|
let span = dict.get_data_by_key("span".spanned_unknown());
|
||||||
@ -74,7 +75,7 @@ fn make_error(value: &Value) -> Option<ShellError> {
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let msg = msg.map(|msg| msg.as_string().ok()).flatten();
|
let msg = msg.and_then(|msg| msg.as_string().ok());
|
||||||
|
|
||||||
if let Some(labels) = labels {
|
if let Some(labels) = labels {
|
||||||
if labels.is_empty() {
|
if labels.is_empty() {
|
||||||
|
@ -50,7 +50,7 @@ impl WholeStreamCommand for Find {
|
|||||||
|
|
||||||
fn row_contains(row: &Dictionary, search_terms: Vec<String>) -> bool {
|
fn row_contains(row: &Dictionary, search_terms: Vec<String>) -> bool {
|
||||||
for term in search_terms {
|
for term in search_terms {
|
||||||
for (k, v) in row.entries.iter() {
|
for (k, v) in &row.entries {
|
||||||
let key = k.to_string().trim().to_lowercase();
|
let key = k.to_string().trim().to_lowercase();
|
||||||
let value = v.convert_to_string().trim().to_lowercase();
|
let value = v.convert_to_string().trim().to_lowercase();
|
||||||
if key.contains(&term) || value.contains(&term) {
|
if key.contains(&term) || value.contains(&term) {
|
||||||
|
@ -302,7 +302,7 @@ pub fn signature_dict(signature: Signature, tag: impl Into<Tag>) -> Value {
|
|||||||
let tag = tag.into();
|
let tag = tag.into();
|
||||||
let mut sig = TaggedListBuilder::new(&tag);
|
let mut sig = TaggedListBuilder::new(&tag);
|
||||||
|
|
||||||
for arg in signature.positional.iter() {
|
for arg in &signature.positional {
|
||||||
let is_required = matches!(arg.0, PositionalType::Mandatory(_, _));
|
let is_required = matches!(arg.0, PositionalType::Mandatory(_, _));
|
||||||
|
|
||||||
sig.push_value(for_spec(arg.0.name(), "argument", is_required, &tag));
|
sig.push_value(for_spec(arg.0.name(), "argument", is_required, &tag));
|
||||||
@ -313,7 +313,7 @@ pub fn signature_dict(signature: Signature, tag: impl Into<Tag>) -> Value {
|
|||||||
sig.push_value(for_spec("rest", "argument", is_required, &tag));
|
sig.push_value(for_spec("rest", "argument", is_required, &tag));
|
||||||
}
|
}
|
||||||
|
|
||||||
for (name, ty) in signature.named.iter() {
|
for (name, ty) in &signature.named {
|
||||||
match ty.0 {
|
match ty.0 {
|
||||||
NamedType::Mandatory(_, _) => sig.push_value(for_spec(name, "flag", true, &tag)),
|
NamedType::Mandatory(_, _) => sig.push_value(for_spec(name, "flag", true, &tag)),
|
||||||
NamedType::Optional(_, _) => sig.push_value(for_spec(name, "flag", false, &tag)),
|
NamedType::Optional(_, _) => sig.push_value(for_spec(name, "flag", false, &tag)),
|
||||||
|
@ -100,14 +100,14 @@ fn if_command(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
context.scope.add_vars(&condition.captured.entries);
|
context.scope.add_vars(&condition.captured.entries);
|
||||||
|
|
||||||
//FIXME: should we use the scope that's brought in as well?
|
//FIXME: should we use the scope that's brought in as well?
|
||||||
let condition = evaluate_baseline_expr(cond, &*context);
|
let condition = evaluate_baseline_expr(cond, &context);
|
||||||
match condition {
|
match condition {
|
||||||
Ok(condition) => match condition.as_bool() {
|
Ok(condition) => match condition.as_bool() {
|
||||||
Ok(b) => {
|
Ok(b) => {
|
||||||
let result = if b {
|
let result = if b {
|
||||||
run_block(&then_case.block, &*context, input, external_redirection)
|
run_block(&then_case.block, &context, input, external_redirection)
|
||||||
} else {
|
} else {
|
||||||
run_block(&else_case.block, &*context, input, external_redirection)
|
run_block(&else_case.block, &context, input, external_redirection)
|
||||||
};
|
};
|
||||||
context.scope.exit_scope();
|
context.scope.exit_scope();
|
||||||
|
|
||||||
|
@ -56,7 +56,7 @@ fn tutor(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
let search: Option<String> = args.opt(0).unwrap_or(None);
|
let search: Option<String> = args.opt(0).unwrap_or(None);
|
||||||
let find: Option<String> = args.get_flag("find")?;
|
let find: Option<String> = args.get_flag("find")?;
|
||||||
|
|
||||||
let search_space = vec![
|
let search_space = [
|
||||||
(vec!["begin"], begin_tutor()),
|
(vec!["begin"], begin_tutor()),
|
||||||
(
|
(
|
||||||
vec!["table", "tables", "row", "rows", "column", "columns"],
|
vec!["table", "tables", "row", "rows", "column", "columns"],
|
||||||
@ -88,7 +88,7 @@ fn tutor(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
if let Some(find) = find {
|
if let Some(find) = find {
|
||||||
let mut results = vec![];
|
let mut results = vec![];
|
||||||
for search_group in search_space {
|
for search_group in search_space {
|
||||||
if search_group.1.contains(&find.as_str()) {
|
if search_group.1.contains(&find) {
|
||||||
results.push(search_group.0[0].to_string())
|
results.push(search_group.0[0].to_string())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -383,7 +383,7 @@ fn display(tag: Tag, scope: &Scope, help: &str) -> OutputStream {
|
|||||||
|
|
||||||
//TODO: support no-color mode
|
//TODO: support no-color mode
|
||||||
let colored_example = nu_engine::Painter::paint_string(item, scope, &palette);
|
let colored_example = nu_engine::Painter::paint_string(item, scope, &palette);
|
||||||
build.push_str(&format!("{}", colored_example));
|
build.push_str(&colored_example);
|
||||||
} else {
|
} else {
|
||||||
code_mode = true;
|
code_mode = true;
|
||||||
build.push_str(item);
|
build.push_str(item);
|
||||||
|
@ -245,7 +245,7 @@ fn perform_groupby_aggregation(
|
|||||||
None => &col[..],
|
None => &col[..],
|
||||||
};
|
};
|
||||||
|
|
||||||
res.rename(col.as_str(), new_col)
|
res.rename(&col, new_col)
|
||||||
.expect("Column is always there. Looping with known names");
|
.expect("Column is always there. Looping with known names");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -107,7 +107,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
let other: Value = args.req_named("other")?;
|
let other: Value = args.req_named("other")?;
|
||||||
let axis: Tagged<String> = args.req_named("axis")?;
|
let axis: Tagged<String> = args.req_named("axis")?;
|
||||||
|
|
||||||
let axis = Axis::try_from_str(axis.item.as_str(), &axis.tag.span)?;
|
let axis = Axis::try_from_str(&axis.item, &axis.tag.span)?;
|
||||||
|
|
||||||
let df_other = match other.value {
|
let df_other = match other.value {
|
||||||
UntaggedValue::DataFrame(df) => Ok(df),
|
UntaggedValue::DataFrame(df) => Ok(df),
|
||||||
|
@ -53,7 +53,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
|
|
||||||
let res = df
|
let res = df
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.column(column.item.as_ref())
|
.column(&column.item)
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, &column.tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &column.tag.span, None))?;
|
||||||
|
|
||||||
let df = NuDataFrame::try_from_series(vec![res.clone()], &tag.span)?;
|
let df = NuDataFrame::try_from_series(vec![res.clone()], &tag.span)?;
|
||||||
|
@ -195,7 +195,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
|
|
||||||
let name = format!("{} ({})", col.name(), col.dtype());
|
let name = format!("{} ({})", col.name(), col.dtype());
|
||||||
ChunkedArray::<Float64Type>::new_from_opt_slice(
|
ChunkedArray::<Float64Type>::new_from_opt_slice(
|
||||||
name.as_str(),
|
&name,
|
||||||
&[
|
&[
|
||||||
Some(count),
|
Some(count),
|
||||||
sum,
|
sum,
|
||||||
|
@ -72,7 +72,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
.expect("using name from list of names from dataframe")
|
.expect("using name from list of names from dataframe")
|
||||||
.dtype();
|
.dtype();
|
||||||
|
|
||||||
let dtype_str = format!("{}", dtype);
|
let dtype_str = dtype.to_string();
|
||||||
dtypes.push(Value {
|
dtypes.push(Value {
|
||||||
value: dtype_str.into(),
|
value: dtype_str.into(),
|
||||||
tag: Tag::default(),
|
tag: Tag::default(),
|
||||||
|
@ -177,7 +177,7 @@ fn check_column_datatypes<T: AsRef<str>>(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
for (l, r) in l_cols.iter().zip(r_cols.iter()) {
|
for (l, r) in l_cols.iter().zip(r_cols) {
|
||||||
let l_series = df_l
|
let l_series = df_l
|
||||||
.column(l.as_ref())
|
.column(l.as_ref())
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, l_col_span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, l_col_span, None))?;
|
||||||
|
@ -135,12 +135,12 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
.map_err(|e| parse_polars_error::<&str>(&e, &tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &tag.span, None))?;
|
||||||
|
|
||||||
if let Some(name) = &variable_name {
|
if let Some(name) = &variable_name {
|
||||||
res.rename("variable", name.item.as_str())
|
res.rename("variable", &name.item)
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, &name.tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &name.tag.span, None))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(name) = &value_name {
|
if let Some(name) = &value_name {
|
||||||
res.rename("value", name.item.as_str())
|
res.rename("value", &name.item)
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, &name.tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &name.tag.span, None))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -100,7 +100,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
|
|
||||||
let mut groupby = nu_groupby.to_groupby()?;
|
let mut groupby = nu_groupby.to_groupby()?;
|
||||||
|
|
||||||
let pivot = groupby.pivot(pivot_col.item.as_ref(), value_col.item.as_ref());
|
let pivot = groupby.pivot(&pivot_col.item, &value_col.item);
|
||||||
|
|
||||||
let res = match op {
|
let res = match op {
|
||||||
Operation::Mean => pivot.mean(),
|
Operation::Mean => pivot.mean(),
|
||||||
@ -120,7 +120,7 @@ fn check_pivot_column(
|
|||||||
col: &Tagged<String>,
|
col: &Tagged<String>,
|
||||||
) -> Result<(), ShellError> {
|
) -> Result<(), ShellError> {
|
||||||
let series = df
|
let series = df
|
||||||
.column(col.item.as_ref())
|
.column(&col.item)
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, &col.tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &col.tag.span, None))?;
|
||||||
|
|
||||||
match series.dtype() {
|
match series.dtype() {
|
||||||
@ -146,7 +146,7 @@ fn check_value_column(
|
|||||||
col: &Tagged<String>,
|
col: &Tagged<String>,
|
||||||
) -> Result<(), ShellError> {
|
) -> Result<(), ShellError> {
|
||||||
let series = df
|
let series = df
|
||||||
.column(col.item.as_ref())
|
.column(&col.item)
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, &col.tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &col.tag.span, None))?;
|
||||||
|
|
||||||
match series.dtype() {
|
match series.dtype() {
|
||||||
|
@ -61,7 +61,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
let (mut df, df_tag) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
let (mut df, df_tag) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
||||||
|
|
||||||
df.as_mut()
|
df.as_mut()
|
||||||
.rename(from.item.as_str(), to.item.as_str())
|
.rename(&from.item, &to.item)
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, &df_tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &df_tag.span, None))?;
|
||||||
|
|
||||||
Ok(OutputStream::one(df.into_value(tag)))
|
Ok(OutputStream::one(df.into_value(tag)))
|
||||||
|
@ -68,7 +68,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
let res = chunked
|
let res = chunked
|
||||||
.contains(pattern.as_str())
|
.contains(&pattern.item)
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, &tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &tag.span, None))?;
|
||||||
|
|
||||||
let df = NuDataFrame::try_from_series(vec![res.into_series()], &tag.span)?;
|
let df = NuDataFrame::try_from_series(vec![res.into_series()], &tag.span)?;
|
||||||
|
@ -99,7 +99,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let cum_type = CumType::from_str(cum_type.item.as_str(), &cum_type.tag.span)?;
|
let cum_type = CumType::from_str(&cum_type.item, &cum_type.tag.span)?;
|
||||||
let mut res = match cum_type {
|
let mut res = match cum_type {
|
||||||
CumType::Max => series.cum_max(reverse),
|
CumType::Max => series.cum_max(reverse),
|
||||||
CumType::Min => series.cum_min(reverse),
|
CumType::Min => series.cum_min(reverse),
|
||||||
|
@ -60,7 +60,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
|
|
||||||
let mut series = df.as_series(&df_tag.span)?;
|
let mut series = df.as_series(&df_tag.span)?;
|
||||||
|
|
||||||
series.rename(name.item.as_ref());
|
series.rename(&name.item);
|
||||||
|
|
||||||
let df = NuDataFrame::try_from_series(vec![series], &tag.span)?;
|
let df = NuDataFrame::try_from_series(vec![series], &tag.span)?;
|
||||||
Ok(OutputStream::one(df.into_value(df_tag)))
|
Ok(OutputStream::one(df.into_value(df_tag)))
|
||||||
|
@ -77,7 +77,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
let mut res = chunked
|
let mut res = chunked
|
||||||
.replace(pattern.as_str(), replace.as_str())
|
.replace(&pattern.item, &replace.item)
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, &tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &tag.span, None))?;
|
||||||
|
|
||||||
res.rename(series.name());
|
res.rename(series.name());
|
||||||
|
@ -77,7 +77,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
let mut res = chunked
|
let mut res = chunked
|
||||||
.replace_all(pattern.as_str(), replace.as_str())
|
.replace_all(&pattern.item, &replace.item)
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, &tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &tag.span, None))?;
|
||||||
|
|
||||||
res.rename(series.name());
|
res.rename(series.name());
|
||||||
|
@ -125,7 +125,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let roll_type = RollType::from_str(roll_type.item.as_str(), &roll_type.tag.span)?;
|
let roll_type = RollType::from_str(&roll_type.item, &roll_type.tag.span)?;
|
||||||
let res = match roll_type {
|
let res = match roll_type {
|
||||||
RollType::Max => series.rolling_max(
|
RollType::Max => series.rolling_max(
|
||||||
window_size.item as u32,
|
window_size.item as u32,
|
||||||
|
@ -61,7 +61,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
.date64()
|
.date64()
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, &df_tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &df_tag.span, None))?;
|
||||||
|
|
||||||
let res = casted.strftime(fmt.item.as_str()).into_series();
|
let res = casted.strftime(&fmt.item).into_series();
|
||||||
let df = NuDataFrame::try_from_series(vec![res], &tag.span)?;
|
let df = NuDataFrame::try_from_series(vec![res], &tag.span)?;
|
||||||
Ok(OutputStream::one(df.into_value(df_tag)))
|
Ok(OutputStream::one(df.into_value(df_tag)))
|
||||||
}
|
}
|
||||||
|
@ -64,14 +64,10 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
let delimiter: Option<Tagged<String>> = args.get_flag("delimiter")?;
|
let delimiter: Option<Tagged<String>> = args.get_flag("delimiter")?;
|
||||||
let no_header: bool = args.has_flag("no_header");
|
let no_header: bool = args.has_flag("no_header");
|
||||||
|
|
||||||
let (mut df, _) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
let (df, _) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
||||||
|
|
||||||
let mut file = File::create(&file_name.item).map_err(|e| {
|
let mut file = File::create(&file_name.item).map_err(|e| {
|
||||||
ShellError::labeled_error(
|
ShellError::labeled_error("Error with file name", e.to_string(), &file_name.tag.span)
|
||||||
"Error with file name",
|
|
||||||
format!("{}", e),
|
|
||||||
&file_name.tag.span,
|
|
||||||
)
|
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let writer = CsvWriter::new(&mut file);
|
let writer = CsvWriter::new(&mut file);
|
||||||
@ -103,7 +99,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
writer
|
writer
|
||||||
.finish(df.as_mut())
|
.finish(df.as_ref())
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, &file_name.tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &file_name.tag.span, None))?;
|
||||||
|
|
||||||
let tagged_value = Value {
|
let tagged_value = Value {
|
||||||
|
@ -48,18 +48,14 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
let tag = args.call_info.name_tag.clone();
|
let tag = args.call_info.name_tag.clone();
|
||||||
let file_name: Tagged<PathBuf> = args.req(0)?;
|
let file_name: Tagged<PathBuf> = args.req(0)?;
|
||||||
|
|
||||||
let (mut df, _) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
let (df, _) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
||||||
|
|
||||||
let file = File::create(&file_name.item).map_err(|e| {
|
let file = File::create(&file_name.item).map_err(|e| {
|
||||||
ShellError::labeled_error(
|
ShellError::labeled_error("Error with file name", e.to_string(), &file_name.tag.span)
|
||||||
"Error with file name",
|
|
||||||
format!("{}", e),
|
|
||||||
&file_name.tag.span,
|
|
||||||
)
|
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
ParquetWriter::new(file)
|
ParquetWriter::new(file)
|
||||||
.finish(df.as_mut())
|
.finish(df.as_ref())
|
||||||
.map_err(|e| parse_polars_error::<&str>(&e, &file_name.tag.span, None))?;
|
.map_err(|e| parse_polars_error::<&str>(&e, &file_name.tag.span, None))?;
|
||||||
|
|
||||||
let tagged_value = Value {
|
let tagged_value = Value {
|
||||||
|
@ -46,30 +46,32 @@ pub(crate) fn parse_polars_error<T: AsRef<str>>(
|
|||||||
span: &Span,
|
span: &Span,
|
||||||
secondary: Option<T>,
|
secondary: Option<T>,
|
||||||
) -> ShellError {
|
) -> ShellError {
|
||||||
let (msg, label) = match e {
|
let msg = match e {
|
||||||
PolarsError::PolarsArrowError(_) => ("PolarsArrow Error", format!("{}", e)),
|
PolarsError::PolarsArrowError(_) => "PolarsArrow Error",
|
||||||
PolarsError::ArrowError(_) => ("Arrow Error", format!("{}", e)),
|
PolarsError::ArrowError(_) => "Arrow Error",
|
||||||
PolarsError::InvalidOperation(_) => ("Invalid Operation", format!("{}", e)),
|
PolarsError::InvalidOperation(_) => "Invalid Operation",
|
||||||
PolarsError::DataTypeMisMatch(_) => ("Data Type Mismatch", format!("{}", e)),
|
PolarsError::DataTypeMisMatch(_) => "Data Type Mismatch",
|
||||||
PolarsError::NotFound(_) => ("Not Found", format!("{}", e)),
|
PolarsError::NotFound(_) => "Not Found",
|
||||||
PolarsError::ShapeMisMatch(_) => ("Shape Mismatch", format!("{}", e)),
|
PolarsError::ShapeMisMatch(_) => "Shape Mismatch",
|
||||||
PolarsError::Other(_) => ("Other", format!("{}", e)),
|
PolarsError::Other(_) => "Other",
|
||||||
PolarsError::OutOfBounds(_) => ("Out Of Bounds", format!("{}", e)),
|
PolarsError::OutOfBounds(_) => "Out Of Bounds",
|
||||||
PolarsError::NoSlice => ("No Slice", format!("{}", e)),
|
PolarsError::NoSlice => "No Slice",
|
||||||
PolarsError::NoData(_) => ("No Data", format!("{}", e)),
|
PolarsError::NoData(_) => "No Data",
|
||||||
PolarsError::ValueError(_) => ("Value Error", format!("{}", e)),
|
PolarsError::ValueError(_) => "Value Error",
|
||||||
PolarsError::MemoryNotAligned => ("Memory Not Aligned", format!("{}", e)),
|
PolarsError::MemoryNotAligned => "Memory Not Aligned",
|
||||||
PolarsError::ParquetError(_) => ("Parquet Error", format!("{}", e)),
|
PolarsError::ParquetError(_) => "Parquet Error",
|
||||||
PolarsError::RandError(_) => ("Rand Error", format!("{}", e)),
|
PolarsError::RandError(_) => "Rand Error",
|
||||||
PolarsError::HasNullValues(_) => ("Has Null Values", format!("{}", e)),
|
PolarsError::HasNullValues(_) => "Has Null Values",
|
||||||
PolarsError::UnknownSchema(_) => ("Unknown Schema", format!("{}", e)),
|
PolarsError::UnknownSchema(_) => "Unknown Schema",
|
||||||
PolarsError::Various(_) => ("Various", format!("{}", e)),
|
PolarsError::Various(_) => "Various",
|
||||||
PolarsError::Io(_) => ("Io Error", format!("{}", e)),
|
PolarsError::Io(_) => "Io Error",
|
||||||
PolarsError::Regex(_) => ("Regex Error", format!("{}", e)),
|
PolarsError::Regex(_) => "Regex Error",
|
||||||
PolarsError::Duplicate(_) => ("Duplicate Error", format!("{}", e)),
|
PolarsError::Duplicate(_) => "Duplicate Error",
|
||||||
PolarsError::ImplementationError => ("Implementation Error", format!("{}", e)),
|
PolarsError::ImplementationError => "Implementation Error",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let label = e.to_string();
|
||||||
|
|
||||||
match secondary {
|
match secondary {
|
||||||
None => ShellError::labeled_error(msg, label, span),
|
None => ShellError::labeled_error(msg, label, span),
|
||||||
Some(s) => ShellError::labeled_error_with_secondary(msg, label, span, s.as_ref(), span),
|
Some(s) => ShellError::labeled_error_with_secondary(msg, label, span, s.as_ref(), span),
|
||||||
|
@ -82,7 +82,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
|
|
||||||
let mut series = df.as_series(&value.tag.span)?;
|
let mut series = df.as_series(&value.tag.span)?;
|
||||||
|
|
||||||
let series = series.rename(name.item.as_ref()).clone();
|
let series = series.rename(&name.item).clone();
|
||||||
|
|
||||||
let (mut df, _) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
let (mut df, _) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
||||||
|
|
||||||
|
@ -61,7 +61,7 @@ impl WholeStreamCommand for AutoenvUntrust {
|
|||||||
let mut doc = String::new();
|
let mut doc = String::new();
|
||||||
file.read_to_string(&mut doc)?;
|
file.read_to_string(&mut doc)?;
|
||||||
|
|
||||||
let mut allowed: Trusted = toml::from_str(doc.as_str()).unwrap_or_else(|_| Trusted::new());
|
let mut allowed: Trusted = toml::from_str(&doc).unwrap_or_else(|_| Trusted::new());
|
||||||
|
|
||||||
let file_to_untrust = file_to_untrust.to_string_lossy().to_string();
|
let file_to_untrust = file_to_untrust.to_string_lossy().to_string();
|
||||||
|
|
||||||
|
@ -173,9 +173,9 @@ fn open(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
Ok(StringOrBinary::String(s)) => {
|
Ok(StringOrBinary::String(s)) => {
|
||||||
ReturnSuccess::value(UntaggedValue::string(s).into_value(file_tag))
|
ReturnSuccess::value(UntaggedValue::string(s).into_value(file_tag))
|
||||||
}
|
}
|
||||||
Ok(StringOrBinary::Binary(b)) => ReturnSuccess::value(
|
Ok(StringOrBinary::Binary(b)) => {
|
||||||
UntaggedValue::binary(b.into_iter().collect()).into_value(file_tag),
|
ReturnSuccess::value(UntaggedValue::binary(b).into_value(file_tag))
|
||||||
),
|
}
|
||||||
Err(se) => Err(se),
|
Err(se) => Err(se),
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
@ -241,7 +241,7 @@ fn string_from(input: &[Value]) -> String {
|
|||||||
|
|
||||||
if !input.is_empty() {
|
if !input.is_empty() {
|
||||||
let mut first = true;
|
let mut first = true;
|
||||||
for i in input.iter() {
|
for i in input {
|
||||||
if !first {
|
if !first {
|
||||||
save_data.push('\n');
|
save_data.push('\n');
|
||||||
} else {
|
} else {
|
||||||
|
@ -48,7 +48,7 @@ fn touch(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
let target: Tagged<PathBuf> = args.req(0)?;
|
let target: Tagged<PathBuf> = args.req(0)?;
|
||||||
let rest: Vec<Tagged<PathBuf>> = args.rest(1)?;
|
let rest: Vec<Tagged<PathBuf>> = args.rest(1)?;
|
||||||
|
|
||||||
for item in vec![target].into_iter().chain(rest.into_iter()) {
|
for item in vec![target].into_iter().chain(rest) {
|
||||||
match OpenOptions::new().write(true).create(true).open(&item) {
|
match OpenOptions::new().write(true).create(true).open(&item) {
|
||||||
Ok(_) => continue,
|
Ok(_) => continue,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
|
@ -45,7 +45,7 @@ impl WholeStreamCommand for Command {
|
|||||||
|
|
||||||
Ok(prepend
|
Ok(prepend
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.chain(args.input.into_iter().chain(vec![value]))
|
.chain(args.input.into_iter().chain([value]))
|
||||||
.into_output_stream())
|
.into_output_stream())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -96,7 +96,7 @@ pub fn process_row(
|
|||||||
|
|
||||||
let result = run_block(
|
let result = run_block(
|
||||||
&captured_block.block,
|
&captured_block.block,
|
||||||
&*context,
|
&context,
|
||||||
input_stream,
|
input_stream,
|
||||||
external_redirection,
|
external_redirection,
|
||||||
);
|
);
|
||||||
@ -127,7 +127,7 @@ fn each(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
Ok(args
|
Ok(args
|
||||||
.input
|
.input
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(move |input| {
|
.flat_map(move |input| {
|
||||||
let block = block.clone();
|
let block = block.clone();
|
||||||
let context = context.clone();
|
let context = context.clone();
|
||||||
let row = make_indexed_item(input.0, input.1);
|
let row = make_indexed_item(input.0, input.1);
|
||||||
@ -137,12 +137,11 @@ fn each(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
Err(e) => OutputStream::one(Value::error(e)),
|
Err(e) => OutputStream::one(Value::error(e)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.flatten()
|
|
||||||
.into_output_stream())
|
.into_output_stream())
|
||||||
} else {
|
} else {
|
||||||
Ok(args
|
Ok(args
|
||||||
.input
|
.input
|
||||||
.map(move |input| {
|
.flat_map(move |input| {
|
||||||
let block = block.clone();
|
let block = block.clone();
|
||||||
let context = context.clone();
|
let context = context.clone();
|
||||||
|
|
||||||
@ -151,7 +150,6 @@ fn each(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
Err(e) => OutputStream::one(Value::error(e)),
|
Err(e) => OutputStream::one(Value::error(e)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.flatten()
|
|
||||||
.into_output_stream())
|
.into_output_stream())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -64,7 +64,7 @@ impl WholeStreamCommand for EachWindow {
|
|||||||
Ok(args
|
Ok(args
|
||||||
.input
|
.input
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(move |(i, input)| {
|
.flat_map(move |(i, input)| {
|
||||||
// This would probably be more efficient if `last` was a VecDeque
|
// This would probably be more efficient if `last` was a VecDeque
|
||||||
// But we can't have that because it needs to be put into a Table
|
// But we can't have that because it needs to be put into a Table
|
||||||
window.remove(0);
|
window.remove(0);
|
||||||
@ -86,7 +86,6 @@ impl WholeStreamCommand for EachWindow {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
.flatten()
|
.flatten()
|
||||||
.flatten()
|
|
||||||
.map(Ok)
|
.map(Ok)
|
||||||
.into_input_stream())
|
.into_input_stream())
|
||||||
}
|
}
|
||||||
|
@ -140,7 +140,7 @@ fn process_row(
|
|||||||
|
|
||||||
let stream = run_block(
|
let stream = run_block(
|
||||||
&default_block.block,
|
&default_block.block,
|
||||||
&*context,
|
context,
|
||||||
input_stream,
|
input_stream,
|
||||||
ExternalRedirection::Stdout,
|
ExternalRedirection::Stdout,
|
||||||
);
|
);
|
||||||
|
@ -56,8 +56,7 @@ fn flatten(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
let input = args.input;
|
let input = args.input;
|
||||||
|
|
||||||
Ok(input
|
Ok(input
|
||||||
.map(move |item| flat_value(&columns, &item, &tag).into_iter())
|
.flat_map(move |item| flat_value(&columns, &item, &tag))
|
||||||
.flatten()
|
|
||||||
.into_action_stream())
|
.into_action_stream())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -96,7 +95,7 @@ fn flat_value(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (k, v) in mapa.into_iter() {
|
for (k, v) in mapa {
|
||||||
if out.contains_key(k) {
|
if out.contains_key(k) {
|
||||||
out.insert_value(format!("{}_{}", column, k), v.clone());
|
out.insert_value(format!("{}_{}", column, k), v.clone());
|
||||||
} else {
|
} else {
|
||||||
@ -159,7 +158,7 @@ fn flat_value(
|
|||||||
let mut expanded = vec![];
|
let mut expanded = vec![];
|
||||||
|
|
||||||
if let Some(TableInside::Entries(column, _, entries)) = a_table {
|
if let Some(TableInside::Entries(column, _, entries)) = a_table {
|
||||||
for entry in entries.into_iter() {
|
for entry in entries {
|
||||||
let mut base = out.clone();
|
let mut base = out.clone();
|
||||||
base.insert_value(column, entry.clone());
|
base.insert_value(column, entry.clone());
|
||||||
expanded.push(base.into_value());
|
expanded.push(base.into_value());
|
||||||
@ -170,7 +169,7 @@ fn flat_value(
|
|||||||
|
|
||||||
expanded
|
expanded
|
||||||
} else if item.is_table() {
|
} else if item.is_table() {
|
||||||
item.table_entries().map(Clone::clone).collect()
|
item.table_entries().cloned().collect()
|
||||||
} else {
|
} else {
|
||||||
vec![item.clone()]
|
vec![item.clone()]
|
||||||
}
|
}
|
||||||
|
@ -65,14 +65,12 @@ pub fn get(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
} else {
|
} else {
|
||||||
trace!("get {:?}", column_paths);
|
trace!("get {:?}", column_paths);
|
||||||
let output_stream = input
|
let output_stream = input
|
||||||
.map(move |item| {
|
.flat_map(move |item| {
|
||||||
column_paths
|
column_paths
|
||||||
.iter()
|
.iter()
|
||||||
.map(move |path| get_output(&item, path))
|
.flat_map(move |path| get_output(&item, path))
|
||||||
.flatten()
|
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
})
|
})
|
||||||
.flatten()
|
|
||||||
.into_action_stream();
|
.into_action_stream();
|
||||||
Ok(output_stream)
|
Ok(output_stream)
|
||||||
}
|
}
|
||||||
|
@ -140,7 +140,7 @@ pub fn group_by(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
let block = Arc::new(block_given);
|
let block = Arc::new(block_given);
|
||||||
let error_key = "error";
|
let error_key = "error";
|
||||||
|
|
||||||
for value in values.iter() {
|
for value in &values {
|
||||||
let run = block.clone();
|
let run = block.clone();
|
||||||
let context = context.clone();
|
let context = context.clone();
|
||||||
|
|
||||||
|
@ -80,7 +80,7 @@ fn process_row(
|
|||||||
|
|
||||||
let result = run_block(
|
let result = run_block(
|
||||||
&block.block,
|
&block.block,
|
||||||
&*context,
|
&context,
|
||||||
input_stream,
|
input_stream,
|
||||||
ExternalRedirection::Stdout,
|
ExternalRedirection::Stdout,
|
||||||
);
|
);
|
||||||
@ -162,7 +162,7 @@ fn insert(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
let column = Arc::new(column);
|
let column = Arc::new(column);
|
||||||
|
|
||||||
Ok(input
|
Ok(input
|
||||||
.map(move |input| {
|
.flat_map(move |input| {
|
||||||
let context = context.clone();
|
let context = context.clone();
|
||||||
let value = value.clone();
|
let value = value.clone();
|
||||||
let column = column.clone();
|
let column = column.clone();
|
||||||
@ -172,6 +172,5 @@ fn insert(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
Err(e) => ActionStream::one(Err(e)),
|
Err(e) => ActionStream::one(Err(e)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.flatten()
|
|
||||||
.into_action_stream())
|
.into_action_stream())
|
||||||
}
|
}
|
||||||
|
@ -74,7 +74,7 @@ impl WholeStreamCommand for SubCommand {
|
|||||||
ctx.scope.add_var(arg.name(), item.clone());
|
ctx.scope.add_var(arg.name(), item.clone());
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = evaluate_baseline_expr(&*condition, &*ctx);
|
let result = evaluate_baseline_expr(&condition, &ctx);
|
||||||
ctx.scope.exit_scope();
|
ctx.scope.exit_scope();
|
||||||
|
|
||||||
!matches!(result, Ok(ref v) if v.is_true())
|
!matches!(result, Ok(ref v) if v.is_true())
|
||||||
|
@ -76,7 +76,7 @@ impl WholeStreamCommand for SubCommand {
|
|||||||
}
|
}
|
||||||
trace!("ITEM = {:?}", item);
|
trace!("ITEM = {:?}", item);
|
||||||
|
|
||||||
let result = evaluate_baseline_expr(&*condition, &*ctx);
|
let result = evaluate_baseline_expr(&condition, &ctx);
|
||||||
ctx.scope.exit_scope();
|
ctx.scope.exit_scope();
|
||||||
trace!("RESULT = {:?}", result);
|
trace!("RESULT = {:?}", result);
|
||||||
|
|
||||||
|
@ -242,7 +242,7 @@ fn move_after(table: &Value, columns: &[String], from: &ColumnPath) -> Result<Va
|
|||||||
let mut insert = false;
|
let mut insert = false;
|
||||||
let mut inserted = false;
|
let mut inserted = false;
|
||||||
|
|
||||||
for name in columns_moved.into_iter() {
|
for name in columns_moved {
|
||||||
if let Some(name) = name {
|
if let Some(name) = name {
|
||||||
reordered_columns.push(Some(name.clone()));
|
reordered_columns.push(Some(name.clone()));
|
||||||
|
|
||||||
@ -291,7 +291,7 @@ fn move_before(table: &Value, columns: &[String], from: &ColumnPath) -> Result<V
|
|||||||
let mut reordered_columns = vec![];
|
let mut reordered_columns = vec![];
|
||||||
let mut inserted = false;
|
let mut inserted = false;
|
||||||
|
|
||||||
for name in columns_moved.into_iter() {
|
for name in columns_moved {
|
||||||
if let Some(name) = name {
|
if let Some(name) = name {
|
||||||
if !inserted && name == from {
|
if !inserted && name == from {
|
||||||
for column in columns {
|
for column in columns {
|
||||||
|
@ -163,7 +163,7 @@ fn reduce(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
|
|
||||||
context.scope.enter_scope();
|
context.scope.enter_scope();
|
||||||
context.scope.add_var("$acc", f);
|
context.scope.add_var("$acc", f);
|
||||||
let result = process_row(block, &*context, row);
|
let result = process_row(block, &context, row);
|
||||||
context.scope.exit_scope();
|
context.scope.exit_scope();
|
||||||
|
|
||||||
// we make sure that result is an indexed item
|
// we make sure that result is an indexed item
|
||||||
@ -201,7 +201,7 @@ fn reduce(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
|
|
||||||
context.scope.enter_scope();
|
context.scope.enter_scope();
|
||||||
context.scope.add_var("$acc", f);
|
context.scope.add_var("$acc", f);
|
||||||
let result = process_row(block, &*context, row);
|
let result = process_row(block, &context, row);
|
||||||
context.scope.exit_scope();
|
context.scope.exit_scope();
|
||||||
result
|
result
|
||||||
})?
|
})?
|
||||||
|
@ -59,14 +59,12 @@ pub fn roll(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
|
|
||||||
Ok(args
|
Ok(args
|
||||||
.input
|
.input
|
||||||
.map(move |value| {
|
.flat_map(move |value| {
|
||||||
let tag = value.tag();
|
let tag = value.tag();
|
||||||
|
|
||||||
roll_by(value, &options)
|
roll_by(value, &options)
|
||||||
.unwrap_or_else(|| vec![UntaggedValue::nothing().into_value(tag)])
|
.unwrap_or_else(|| vec![UntaggedValue::nothing().into_value(tag)])
|
||||||
.into_iter()
|
|
||||||
})
|
})
|
||||||
.flatten()
|
|
||||||
.into_output_stream())
|
.into_output_stream())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -84,8 +82,7 @@ fn roll_by(value: Value, options: &Arguments) -> Option<Vec<Value>> {
|
|||||||
let values_rotated = rotate(
|
let values_rotated = rotate(
|
||||||
value
|
value
|
||||||
.row_entries()
|
.row_entries()
|
||||||
.map(|(_, value)| value)
|
.map(|(_, value)| value.clone())
|
||||||
.map(Clone::clone)
|
|
||||||
.collect::<Vec<_>>(),
|
.collect::<Vec<_>>(),
|
||||||
&options.by,
|
&options.by,
|
||||||
direction,
|
direction,
|
||||||
@ -94,7 +91,7 @@ fn roll_by(value: Value, options: &Arguments) -> Option<Vec<Value>> {
|
|||||||
if let Some(ref values) = values_rotated {
|
if let Some(ref values) = values_rotated {
|
||||||
let mut out = TaggedDictBuilder::new(&tag);
|
let mut out = TaggedDictBuilder::new(&tag);
|
||||||
|
|
||||||
for (k, v) in columns.iter().zip(values.iter()) {
|
for (k, v) in columns.iter().zip(values) {
|
||||||
out.insert_value(k, v.clone());
|
out.insert_value(k, v.clone());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -104,7 +101,7 @@ fn roll_by(value: Value, options: &Arguments) -> Option<Vec<Value>> {
|
|||||||
None
|
None
|
||||||
} else if value.is_table() {
|
} else if value.is_table() {
|
||||||
rotate(
|
rotate(
|
||||||
value.table_entries().map(Clone::clone).collect(),
|
value.table_entries().cloned().collect(),
|
||||||
&options.by,
|
&options.by,
|
||||||
direction,
|
direction,
|
||||||
)
|
)
|
||||||
|
@ -76,7 +76,7 @@ impl WholeStreamCommand for SubCommand {
|
|||||||
}
|
}
|
||||||
trace!("ITEM = {:?}", item);
|
trace!("ITEM = {:?}", item);
|
||||||
|
|
||||||
let result = evaluate_baseline_expr(&*condition, &*ctx);
|
let result = evaluate_baseline_expr(&condition, &ctx);
|
||||||
ctx.scope.exit_scope();
|
ctx.scope.exit_scope();
|
||||||
trace!("RESULT = {:?}", result);
|
trace!("RESULT = {:?}", result);
|
||||||
|
|
||||||
|
@ -77,7 +77,7 @@ impl WholeStreamCommand for SubCommand {
|
|||||||
}
|
}
|
||||||
trace!("ITEM = {:?}", item);
|
trace!("ITEM = {:?}", item);
|
||||||
|
|
||||||
let result = evaluate_baseline_expr(&*condition, &*ctx);
|
let result = evaluate_baseline_expr(&condition, &ctx);
|
||||||
ctx.scope.exit_scope();
|
ctx.scope.exit_scope();
|
||||||
trace!("RESULT = {:?}", result);
|
trace!("RESULT = {:?}", result);
|
||||||
|
|
||||||
|
@ -118,7 +118,7 @@ fn sort_by(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
vec.reverse()
|
vec.reverse()
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok((vec.into_iter()).into_output_stream())
|
Ok(vec.into_iter().into_output_stream())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sort(
|
pub fn sort(
|
||||||
@ -137,7 +137,7 @@ pub fn sort(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
for sort_arg in keys.iter() {
|
for sort_arg in keys {
|
||||||
let match_test = &vec[0].get_data_by_key(sort_arg.borrow_spanned());
|
let match_test = &vec[0].get_data_by_key(sort_arg.borrow_spanned());
|
||||||
if match_test.is_none() {
|
if match_test.is_none() {
|
||||||
return Err(ShellError::labeled_error(
|
return Err(ShellError::labeled_error(
|
||||||
|
@ -66,7 +66,6 @@ fn process_row(
|
|||||||
field: Arc<ColumnPath>,
|
field: Arc<ColumnPath>,
|
||||||
tag: Arc<Tag>,
|
tag: Arc<Tag>,
|
||||||
) -> Result<ActionStream, ShellError> {
|
) -> Result<ActionStream, ShellError> {
|
||||||
let tag = &*tag;
|
|
||||||
let replacement = Arc::make_mut(&mut replacement);
|
let replacement = Arc::make_mut(&mut replacement);
|
||||||
|
|
||||||
Ok(match replacement {
|
Ok(match replacement {
|
||||||
@ -86,7 +85,7 @@ fn process_row(
|
|||||||
|
|
||||||
let result = run_block(
|
let result = run_block(
|
||||||
&captured_block.block,
|
&captured_block.block,
|
||||||
&*context,
|
&context,
|
||||||
input_stream,
|
input_stream,
|
||||||
ExternalRedirection::Stdout,
|
ExternalRedirection::Stdout,
|
||||||
);
|
);
|
||||||
@ -184,7 +183,7 @@ fn update(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
let field = Arc::new(field);
|
let field = Arc::new(field);
|
||||||
|
|
||||||
Ok(input
|
Ok(input
|
||||||
.map(move |input| {
|
.flat_map(move |input| {
|
||||||
let tag = name_tag.clone();
|
let tag = name_tag.clone();
|
||||||
let context = context.clone();
|
let context = context.clone();
|
||||||
let replacement = replacement.clone();
|
let replacement = replacement.clone();
|
||||||
@ -195,6 +194,5 @@ fn update(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
Err(e) => ActionStream::one(Err(e)),
|
Err(e) => ActionStream::one(Err(e)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.flatten()
|
|
||||||
.into_action_stream())
|
.into_action_stream())
|
||||||
}
|
}
|
||||||
|
@ -27,7 +27,7 @@ fn from_delimited_string_to_value(
|
|||||||
let mut rows = vec![];
|
let mut rows = vec![];
|
||||||
for row in reader.records() {
|
for row in reader.records() {
|
||||||
let mut tagged_row = TaggedDictBuilder::new(&tag);
|
let mut tagged_row = TaggedDictBuilder::new(&tag);
|
||||||
for (value, header) in row?.iter().zip(headers.iter()) {
|
for (value, header) in row?.iter().zip(&headers) {
|
||||||
if let Ok(i) = value.parse::<i64>() {
|
if let Ok(i) = value.parse::<i64>() {
|
||||||
tagged_row.insert_value(header, UntaggedValue::int(i).into_value(&tag))
|
tagged_row.insert_value(header, UntaggedValue::int(i).into_value(&tag))
|
||||||
} else if let Ok(f) = value.parse::<f64>() {
|
} else if let Ok(f) = value.parse::<f64>() {
|
||||||
|
@ -100,7 +100,7 @@ fn from_eml(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
dict.insert_untagged("To", headerfieldvalue_to_value(&tag, &to));
|
dict.insert_untagged("To", headerfieldvalue_to_value(&tag, &to));
|
||||||
}
|
}
|
||||||
|
|
||||||
for HeaderField { name, value } in eml.headers.iter() {
|
for HeaderField { name, value } in &eml.headers {
|
||||||
dict.insert_untagged(name, headerfieldvalue_to_value(&tag, value));
|
dict.insert_untagged(name, headerfieldvalue_to_value(&tag, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -75,7 +75,7 @@ fn convert_yaml_value_to_nu_value(
|
|||||||
serde_yaml::Value::Mapping(t) => {
|
serde_yaml::Value::Mapping(t) => {
|
||||||
let mut collected = TaggedDictBuilder::new(&tag);
|
let mut collected = TaggedDictBuilder::new(&tag);
|
||||||
|
|
||||||
for (k, v) in t.iter() {
|
for (k, v) in t {
|
||||||
// A ShellError that we re-use multiple times in the Mapping scenario
|
// A ShellError that we re-use multiple times in the Mapping scenario
|
||||||
let err_unexpected_map = ShellError::labeled_error(
|
let err_unexpected_map = ShellError::labeled_error(
|
||||||
format!("Unexpected YAML:\nKey: {:?}\nValue: {:?}", k, v),
|
format!("Unexpected YAML:\nKey: {:?}\nValue: {:?}", k, v),
|
||||||
@ -202,7 +202,7 @@ mod tests {
|
|||||||
expected: Ok(row!["value".to_owned() => string("{{ something }}")]),
|
expected: Ok(row!["value".to_owned() => string("{{ something }}")]),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
for tc in tt.into_iter() {
|
for tc in tt {
|
||||||
let actual = from_yaml_string_to_value(tc.input.to_owned(), Tag::default());
|
let actual = from_yaml_string_to_value(tc.input.to_owned(), Tag::default());
|
||||||
if actual.is_err() {
|
if actual.is_err() {
|
||||||
assert!(
|
assert!(
|
||||||
|
@ -20,7 +20,7 @@ fn from_value_to_delimited_string(
|
|||||||
let mut fields: VecDeque<String> = VecDeque::new();
|
let mut fields: VecDeque<String> = VecDeque::new();
|
||||||
let mut values: VecDeque<String> = VecDeque::new();
|
let mut values: VecDeque<String> = VecDeque::new();
|
||||||
|
|
||||||
for (k, v) in o.entries.iter() {
|
for (k, v) in &o.entries {
|
||||||
fields.push_back(k.clone());
|
fields.push_back(k.clone());
|
||||||
|
|
||||||
values.push_back(to_string_tagged_value(v)?);
|
values.push_back(to_string_tagged_value(v)?);
|
||||||
@ -130,12 +130,14 @@ pub fn clone_tagged_value(v: &Value) -> Value {
|
|||||||
// NOTE: could this be useful more widely and implemented on Value ?
|
// NOTE: could this be useful more widely and implemented on Value ?
|
||||||
fn to_string_tagged_value(v: &Value) -> Result<String, ShellError> {
|
fn to_string_tagged_value(v: &Value) -> Result<String, ShellError> {
|
||||||
match &v.value {
|
match &v.value {
|
||||||
UntaggedValue::Primitive(Primitive::String(_))
|
UntaggedValue::Primitive(
|
||||||
| UntaggedValue::Primitive(Primitive::Filesize(_))
|
Primitive::String(_)
|
||||||
| UntaggedValue::Primitive(Primitive::Boolean(_))
|
| Primitive::Filesize(_)
|
||||||
| UntaggedValue::Primitive(Primitive::Decimal(_))
|
| Primitive::Boolean(_)
|
||||||
| UntaggedValue::Primitive(Primitive::FilePath(_))
|
| Primitive::Decimal(_)
|
||||||
| UntaggedValue::Primitive(Primitive::Int(_)) => as_string(v),
|
| Primitive::FilePath(_)
|
||||||
|
| Primitive::Int(_),
|
||||||
|
) => as_string(v),
|
||||||
UntaggedValue::Primitive(Primitive::Date(d)) => Ok(d.to_string()),
|
UntaggedValue::Primitive(Primitive::Date(d)) => Ok(d.to_string()),
|
||||||
UntaggedValue::Primitive(Primitive::Nothing) => Ok(String::new()),
|
UntaggedValue::Primitive(Primitive::Nothing) => Ok(String::new()),
|
||||||
UntaggedValue::Table(_) => Ok(String::from("[Table]")),
|
UntaggedValue::Table(_) => Ok(String::from("[Table]")),
|
||||||
@ -153,7 +155,7 @@ fn merge_descriptors(values: &[Value]) -> Vec<Spanned<String>> {
|
|||||||
let mut seen: IndexSet<String> = indexset! {};
|
let mut seen: IndexSet<String> = indexset! {};
|
||||||
for value in values {
|
for value in values {
|
||||||
for desc in value.data_descriptors() {
|
for desc in value.data_descriptors() {
|
||||||
if !seen.contains(&desc[..]) {
|
if !seen.contains(&desc) {
|
||||||
seen.insert(desc.clone());
|
seen.insert(desc.clone());
|
||||||
ret.push(desc.spanned(value.tag.span));
|
ret.push(desc.spanned(value.tag.span));
|
||||||
}
|
}
|
||||||
|
@ -11,6 +11,7 @@ use serde::{Deserialize, Serialize};
|
|||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
|
use std::fmt::Write;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct HtmlThemes {
|
pub struct HtmlThemes {
|
||||||
@ -124,8 +125,8 @@ fn get_theme_from_asset_file(
|
|||||||
theme_tag: &Tag,
|
theme_tag: &Tag,
|
||||||
) -> Result<HashMap<&'static str, String>, ShellError> {
|
) -> Result<HashMap<&'static str, String>, ShellError> {
|
||||||
let theme_name = match theme {
|
let theme_name = match theme {
|
||||||
Some(s) => s.to_string(),
|
Some(s) => s.as_str(),
|
||||||
None => "default".to_string(), // There is no theme named "default" so this will be HtmlTheme::default(), which is "nu_default".
|
None => "default", // There is no theme named "default" so this will be HtmlTheme::default(), which is "nu_default".
|
||||||
};
|
};
|
||||||
|
|
||||||
// 228 themes come from
|
// 228 themes come from
|
||||||
@ -143,7 +144,7 @@ fn get_theme_from_asset_file(
|
|||||||
let th = asset
|
let th = asset
|
||||||
.themes
|
.themes
|
||||||
.iter()
|
.iter()
|
||||||
.find(|&n| n.name.to_lowercase() == *theme_name.to_lowercase().as_str()); // case insensitive search
|
.find(|&n| n.name.to_lowercase() == theme_name.to_lowercase()); // case insensitive search
|
||||||
|
|
||||||
// If no theme is found by the name provided, ensure we return the default theme
|
// If no theme is found by the name provided, ensure we return the default theme
|
||||||
let default_theme = HtmlTheme::default();
|
let default_theme = HtmlTheme::default();
|
||||||
@ -248,11 +249,7 @@ fn get_list_of_theme_names() -> Vec<String> {
|
|||||||
_ => HtmlThemes::default(),
|
_ => HtmlThemes::default(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let theme_names: Vec<String> = html_themes
|
let theme_names: Vec<String> = html_themes.themes.iter().map(|n| n.name.clone()).collect();
|
||||||
.themes
|
|
||||||
.iter()
|
|
||||||
.map(|n| n.name[..].to_string())
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
theme_names
|
theme_names
|
||||||
}
|
}
|
||||||
@ -278,8 +275,8 @@ fn to_html(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
let theme_names = get_list_of_theme_names();
|
let theme_names = get_list_of_theme_names();
|
||||||
|
|
||||||
// Put that list into the output string
|
// Put that list into the output string
|
||||||
for s in theme_names.iter() {
|
for s in &theme_names {
|
||||||
output_string.push_str(&format!("{}\n", s));
|
writeln!(&mut output_string, "{}", s).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
output_string.push_str("\nScreenshots of themes can be found here:\n");
|
output_string.push_str("\nScreenshots of themes can be found here:\n");
|
||||||
@ -304,7 +301,8 @@ fn to_html(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
|
|
||||||
// change the color of the page
|
// change the color of the page
|
||||||
if !partial {
|
if !partial {
|
||||||
output_string.push_str(&format!(
|
write!(
|
||||||
|
&mut output_string,
|
||||||
r"<html><style>body {{ background-color:{};color:{}; }}</style><body>",
|
r"<html><style>body {{ background-color:{};color:{}; }}</style><body>",
|
||||||
color_hm
|
color_hm
|
||||||
.get("background")
|
.get("background")
|
||||||
@ -312,9 +310,11 @@ fn to_html(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
color_hm
|
color_hm
|
||||||
.get("foreground")
|
.get("foreground")
|
||||||
.expect("Error getting foreground color")
|
.expect("Error getting foreground color")
|
||||||
));
|
)
|
||||||
|
.unwrap();
|
||||||
} else {
|
} else {
|
||||||
output_string.push_str(&format!(
|
write!(
|
||||||
|
&mut output_string,
|
||||||
"<div style=\"background-color:{};color:{};\">",
|
"<div style=\"background-color:{};color:{};\">",
|
||||||
color_hm
|
color_hm
|
||||||
.get("background")
|
.get("background")
|
||||||
@ -322,7 +322,8 @@ fn to_html(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
color_hm
|
color_hm
|
||||||
.get("foreground")
|
.get("foreground")
|
||||||
.expect("Error getting foreground color")
|
.expect("Error getting foreground color")
|
||||||
));
|
)
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
let inner_value = match input.len() {
|
let inner_value = match input.len() {
|
||||||
|
@ -134,7 +134,7 @@ pub fn value_to_json_value(v: &Value) -> Result<serde_json::Value, ShellError> {
|
|||||||
),
|
),
|
||||||
UntaggedValue::Row(o) => {
|
UntaggedValue::Row(o) => {
|
||||||
let mut m = serde_json::Map::new();
|
let mut m = serde_json::Map::new();
|
||||||
for (k, v) in o.entries.iter() {
|
for (k, v) in &o.entries {
|
||||||
m.insert(k.clone(), value_to_json_value(v)?);
|
m.insert(k.clone(), value_to_json_value(v)?);
|
||||||
}
|
}
|
||||||
serde_json::Value::Object(m)
|
serde_json::Value::Object(m)
|
||||||
@ -184,9 +184,7 @@ fn to_json(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
|
|
||||||
if let Ok(pretty_u64) = pretty_value.as_u64() {
|
if let Ok(pretty_u64) = pretty_value.as_u64() {
|
||||||
if let Ok(serde_json_value) =
|
if let Ok(serde_json_value) =
|
||||||
serde_json::from_str::<serde_json::Value>(
|
serde_json::from_str::<serde_json::Value>(&serde_json_string)
|
||||||
serde_json_string.as_str(),
|
|
||||||
)
|
|
||||||
{
|
{
|
||||||
let indentation_string = " ".repeat(pretty_u64 as usize);
|
let indentation_string = " ".repeat(pretty_u64 as usize);
|
||||||
let serde_formatter =
|
let serde_formatter =
|
||||||
|
@ -236,7 +236,7 @@ fn get_output_string(
|
|||||||
));
|
));
|
||||||
output_string.push(' ');
|
output_string.push(' ');
|
||||||
} else {
|
} else {
|
||||||
output_string.push_str(headers[i].as_str());
|
output_string.push_str(&headers[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
output_string.push('|');
|
output_string.push('|');
|
||||||
@ -275,7 +275,7 @@ fn get_output_string(
|
|||||||
output_string.push_str(&get_padded_string(row[i].clone(), column_widths[i], ' '));
|
output_string.push_str(&get_padded_string(row[i].clone(), column_widths[i], ' '));
|
||||||
output_string.push(' ');
|
output_string.push(' ');
|
||||||
} else {
|
} else {
|
||||||
output_string.push_str(row[i].as_str());
|
output_string.push_str(&row[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if !headers.is_empty() {
|
if !headers.is_empty() {
|
||||||
|
@ -83,7 +83,7 @@ fn helper(v: &Value) -> Result<toml::Value, ShellError> {
|
|||||||
}
|
}
|
||||||
UntaggedValue::Row(o) => {
|
UntaggedValue::Row(o) => {
|
||||||
let mut m = toml::map::Map::new();
|
let mut m = toml::map::Map::new();
|
||||||
for (k, v) in o.entries.iter() {
|
for (k, v) in &o.entries {
|
||||||
m.insert(k.clone(), helper(v)?);
|
m.insert(k.clone(), helper(v)?);
|
||||||
}
|
}
|
||||||
toml::Value::Table(m)
|
toml::Value::Table(m)
|
||||||
@ -97,7 +97,7 @@ pub fn value_to_toml_value(v: &Value) -> Result<toml::Value, ShellError> {
|
|||||||
match &v.value {
|
match &v.value {
|
||||||
UntaggedValue::Row(o) => {
|
UntaggedValue::Row(o) => {
|
||||||
let mut m = toml::map::Map::new();
|
let mut m = toml::map::Map::new();
|
||||||
for (k, v) in o.entries.iter() {
|
for (k, v) in &o.entries {
|
||||||
m.insert(k.clone(), helper(v)?);
|
m.insert(k.clone(), helper(v)?);
|
||||||
}
|
}
|
||||||
Ok(toml::Value::Table(m))
|
Ok(toml::Value::Table(m))
|
||||||
|
@ -37,7 +37,7 @@ pub fn add_attributes<'a>(
|
|||||||
element: &mut quick_xml::events::BytesStart<'a>,
|
element: &mut quick_xml::events::BytesStart<'a>,
|
||||||
attributes: &'a IndexMap<String, String>,
|
attributes: &'a IndexMap<String, String>,
|
||||||
) {
|
) {
|
||||||
for (k, v) in attributes.iter() {
|
for (k, v) in attributes {
|
||||||
element.push_attribute((k.as_str(), v.as_str()));
|
element.push_attribute((k.as_str(), v.as_str()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -47,7 +47,7 @@ pub fn get_attributes(row: &Value) -> Option<IndexMap<String, String>> {
|
|||||||
if let Some(v) = r.entries.get("attributes") {
|
if let Some(v) = r.entries.get("attributes") {
|
||||||
if let UntaggedValue::Row(a) = &v.value {
|
if let UntaggedValue::Row(a) = &v.value {
|
||||||
let mut h = IndexMap::new();
|
let mut h = IndexMap::new();
|
||||||
for (k, v) in a.entries.iter() {
|
for (k, v) in &a.entries {
|
||||||
h.insert(k.clone(), v.convert_to_string());
|
h.insert(k.clone(), v.convert_to_string());
|
||||||
}
|
}
|
||||||
return Some(h);
|
return Some(h);
|
||||||
@ -84,7 +84,7 @@ pub fn write_xml_events<W: Write>(
|
|||||||
) -> Result<(), ShellError> {
|
) -> Result<(), ShellError> {
|
||||||
match ¤t.value {
|
match ¤t.value {
|
||||||
UntaggedValue::Row(o) => {
|
UntaggedValue::Row(o) => {
|
||||||
for (k, v) in o.entries.iter() {
|
for (k, v) in &o.entries {
|
||||||
let mut e = BytesStart::owned(k.as_bytes(), k.len());
|
let mut e = BytesStart::owned(k.as_bytes(), k.len());
|
||||||
if !is_xml_row(v) {
|
if !is_xml_row(v) {
|
||||||
return Err(ShellError::labeled_error(
|
return Err(ShellError::labeled_error(
|
||||||
|
@ -65,7 +65,7 @@ pub fn value_to_yaml_value(v: &Value) -> Result<serde_yaml::Value, ShellError> {
|
|||||||
UntaggedValue::Primitive(Primitive::ColumnPath(path)) => {
|
UntaggedValue::Primitive(Primitive::ColumnPath(path)) => {
|
||||||
let mut out = vec![];
|
let mut out = vec![];
|
||||||
|
|
||||||
for member in path.iter() {
|
for member in path {
|
||||||
match &member.unspanned {
|
match &member.unspanned {
|
||||||
UnspannedPathMember::String(string) => {
|
UnspannedPathMember::String(string) => {
|
||||||
out.push(serde_yaml::Value::String(string.clone()))
|
out.push(serde_yaml::Value::String(string.clone()))
|
||||||
@ -104,7 +104,7 @@ pub fn value_to_yaml_value(v: &Value) -> Result<serde_yaml::Value, ShellError> {
|
|||||||
),
|
),
|
||||||
UntaggedValue::Row(o) => {
|
UntaggedValue::Row(o) => {
|
||||||
let mut m = serde_yaml::Mapping::new();
|
let mut m = serde_yaml::Mapping::new();
|
||||||
for (k, v) in o.entries.iter() {
|
for (k, v) in &o.entries {
|
||||||
m.insert(
|
m.insert(
|
||||||
serde_yaml::Value::String(k.clone()),
|
serde_yaml::Value::String(k.clone()),
|
||||||
value_to_yaml_value(v)?,
|
value_to_yaml_value(v)?,
|
||||||
|
@ -77,7 +77,7 @@ fn to_table(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
let tz = dt.offset();
|
let tz = dt.offset();
|
||||||
indexmap.insert(
|
indexmap.insert(
|
||||||
"timezone".to_string(),
|
"timezone".to_string(),
|
||||||
UntaggedValue::string(format!("{}", tz)).into_value(&tag),
|
UntaggedValue::string(tz.to_string()).into_value(&tag),
|
||||||
);
|
);
|
||||||
|
|
||||||
let value = UntaggedValue::Row(Dictionary::from(indexmap)).into_value(&tag);
|
let value = UntaggedValue::Row(Dictionary::from(indexmap)).into_value(&tag);
|
||||||
|
@ -90,7 +90,7 @@ pub fn process_row(
|
|||||||
|
|
||||||
let result = run_block(
|
let result = run_block(
|
||||||
&captured_block.block,
|
&captured_block.block,
|
||||||
&*context,
|
context,
|
||||||
input_stream,
|
input_stream,
|
||||||
external_redirection,
|
external_redirection,
|
||||||
);
|
);
|
||||||
@ -130,7 +130,7 @@ fn for_in(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
if numbered {
|
if numbered {
|
||||||
Ok(input
|
Ok(input
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(move |input| {
|
.flat_map(move |input| {
|
||||||
let row = make_indexed_item(input.0, input.1);
|
let row = make_indexed_item(input.0, input.1);
|
||||||
|
|
||||||
match process_row(&block, &context, row, &var_name, external_redirection) {
|
match process_row(&block, &context, row, &var_name, external_redirection) {
|
||||||
@ -138,11 +138,10 @@ fn for_in(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
Err(e) => OutputStream::one(Value::error(e)),
|
Err(e) => OutputStream::one(Value::error(e)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.flatten()
|
|
||||||
.into_output_stream())
|
.into_output_stream())
|
||||||
} else {
|
} else {
|
||||||
Ok(input
|
Ok(input
|
||||||
.map(move |input| {
|
.flat_map(move |input| {
|
||||||
let block = block.clone();
|
let block = block.clone();
|
||||||
|
|
||||||
match process_row(&block, &context, input, &var_name, external_redirection) {
|
match process_row(&block, &context, input, &var_name, external_redirection) {
|
||||||
@ -150,7 +149,6 @@ fn for_in(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
Err(e) => OutputStream::one(Value::error(e)),
|
Err(e) => OutputStream::one(Value::error(e)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.flatten()
|
|
||||||
.into_output_stream())
|
.into_output_stream())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -321,7 +321,7 @@ pub fn run_seq_dates(
|
|||||||
|
|
||||||
let mut ret_str = String::from("");
|
let mut ret_str = String::from("");
|
||||||
loop {
|
loop {
|
||||||
ret_str.push_str(&format!("{}", next.format(&out_format)));
|
ret_str.push_str(&next.format(&out_format).to_string());
|
||||||
// TODO: check this value is good
|
// TODO: check this value is good
|
||||||
next += Duration::days(step_size);
|
next += Duration::days(step_size);
|
||||||
|
|
||||||
|
@ -169,7 +169,7 @@ mod tests {
|
|||||||
// },
|
// },
|
||||||
];
|
];
|
||||||
let test_tag = Tag::unknown();
|
let test_tag = Tag::unknown();
|
||||||
for tc in tt.iter() {
|
for tc in &tt {
|
||||||
let tc: &TestCase = tc; // Just for type annotations
|
let tc: &TestCase = tc; // Just for type annotations
|
||||||
let math_functions: Vec<MathFunction> = vec![
|
let math_functions: Vec<MathFunction> = vec![
|
||||||
average, minimum, maximum, median, mode, stddev, summation, variance,
|
average, minimum, maximum, median, mode, stddev, summation, variance,
|
||||||
|
@ -45,7 +45,7 @@ pub fn mode(values: &[Value], name: &Tag) -> Result<Value, ShellError> {
|
|||||||
|
|
||||||
let mut max_freq = -1;
|
let mut max_freq = -1;
|
||||||
let mut modes = Vec::<Value>::new();
|
let mut modes = Vec::<Value>::new();
|
||||||
for (value, frequency) in frequency_map.iter() {
|
for (value, frequency) in &frequency_map {
|
||||||
match max_freq.cmp(frequency) {
|
match max_freq.cmp(frequency) {
|
||||||
Ordering::Less => {
|
Ordering::Less => {
|
||||||
max_freq = *frequency;
|
max_freq = *frequency;
|
||||||
|
@ -108,7 +108,7 @@ pub fn max(data: Vec<Value>) -> Result<Value, ShellError> {
|
|||||||
.value
|
.value
|
||||||
.clone();
|
.clone();
|
||||||
|
|
||||||
for value in data.iter() {
|
for value in &data {
|
||||||
if let Ok(greater_than) = compare_values(Operator::GreaterThan, &value.value, &biggest) {
|
if let Ok(greater_than) = compare_values(Operator::GreaterThan, &value.value, &biggest) {
|
||||||
if greater_than {
|
if greater_than {
|
||||||
biggest = value.value.clone();
|
biggest = value.value.clone();
|
||||||
@ -133,7 +133,7 @@ pub fn min(data: Vec<Value>) -> Result<Value, ShellError> {
|
|||||||
.value
|
.value
|
||||||
.clone();
|
.clone();
|
||||||
|
|
||||||
for value in data.iter() {
|
for value in &data {
|
||||||
if let Ok(greater_than) = compare_values(Operator::LessThan, &value.value, &smallest) {
|
if let Ok(greater_than) = compare_values(Operator::LessThan, &value.value, &smallest) {
|
||||||
if greater_than {
|
if greater_than {
|
||||||
smallest = value.value.clone();
|
smallest = value.value.clone();
|
||||||
|
@ -43,7 +43,7 @@ impl WholeStreamCommand for SubCommand {
|
|||||||
let mut column_values = IndexMap::new();
|
let mut column_values = IndexMap::new();
|
||||||
for value in values {
|
for value in values {
|
||||||
if let UntaggedValue::Row(row_dict) = &value.value {
|
if let UntaggedValue::Row(row_dict) = &value.value {
|
||||||
for (key, value) in row_dict.entries.iter() {
|
for (key, value) in &row_dict.entries {
|
||||||
column_values
|
column_values
|
||||||
.entry(key.clone())
|
.entry(key.clone())
|
||||||
.and_modify(|v: &mut Vec<Value>| v.push(value.clone()))
|
.and_modify(|v: &mut Vec<Value>| v.push(value.clone()))
|
||||||
|
@ -67,7 +67,7 @@ pub fn calculate(values: &[Value], name: &Tag, mf: MathFunction) -> Result<Value
|
|||||||
let mut column_values = IndexMap::new();
|
let mut column_values = IndexMap::new();
|
||||||
for value in values {
|
for value in values {
|
||||||
if let UntaggedValue::Row(row_dict) = &value.value {
|
if let UntaggedValue::Row(row_dict) = &value.value {
|
||||||
for (key, value) in row_dict.entries.iter() {
|
for (key, value) in &row_dict.entries {
|
||||||
column_values
|
column_values
|
||||||
.entry(key.clone())
|
.entry(key.clone())
|
||||||
.and_modify(|v: &mut Vec<Value>| v.push(value.clone()))
|
.and_modify(|v: &mut Vec<Value>| v.push(value.clone()))
|
||||||
|
@ -39,7 +39,7 @@ impl WholeStreamCommand for SubCommand {
|
|||||||
let mut column_values = IndexMap::new();
|
let mut column_values = IndexMap::new();
|
||||||
for value in values {
|
for value in values {
|
||||||
if let UntaggedValue::Row(row_dict) = &value.value {
|
if let UntaggedValue::Row(row_dict) = &value.value {
|
||||||
for (key, value) in row_dict.entries.iter() {
|
for (key, value) in &row_dict.entries {
|
||||||
column_values
|
column_values
|
||||||
.entry(key.clone())
|
.entry(key.clone())
|
||||||
.and_modify(|v: &mut Vec<Value>| v.push(value.clone()))
|
.and_modify(|v: &mut Vec<Value>| v.push(value.clone()))
|
||||||
|
@ -112,10 +112,7 @@ mod tests {
|
|||||||
|
|
||||||
fn only_examples() -> Vec<Command> {
|
fn only_examples() -> Vec<Command> {
|
||||||
let mut commands = full_tests();
|
let mut commands = full_tests();
|
||||||
commands.extend(vec![
|
commands.extend([whole_stream_command(Zip), whole_stream_command(Flatten)]);
|
||||||
whole_stream_command(Zip),
|
|
||||||
whole_stream_command(Flatten),
|
|
||||||
]);
|
|
||||||
commands
|
commands
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -519,7 +519,7 @@ pub fn value_to_json_value(v: &Value) -> Result<serde_json::Value, ShellError> {
|
|||||||
UntaggedValue::Primitive(Primitive::Binary(b)) => {
|
UntaggedValue::Primitive(Primitive::Binary(b)) => {
|
||||||
let mut output = vec![];
|
let mut output = vec![];
|
||||||
|
|
||||||
for item in b.iter() {
|
for item in b {
|
||||||
output.push(serde_json::Value::Number(
|
output.push(serde_json::Value::Number(
|
||||||
serde_json::Number::from_f64(*item as f64).ok_or_else(|| {
|
serde_json::Number::from_f64(*item as f64).ok_or_else(|| {
|
||||||
ShellError::labeled_error(
|
ShellError::labeled_error(
|
||||||
@ -534,7 +534,7 @@ pub fn value_to_json_value(v: &Value) -> Result<serde_json::Value, ShellError> {
|
|||||||
}
|
}
|
||||||
UntaggedValue::Row(o) => {
|
UntaggedValue::Row(o) => {
|
||||||
let mut m = serde_json::Map::new();
|
let mut m = serde_json::Map::new();
|
||||||
for (k, v) in o.entries.iter() {
|
for (k, v) in &o.entries {
|
||||||
m.insert(k.clone(), value_to_json_value(v)?);
|
m.insert(k.clone(), value_to_json_value(v)?);
|
||||||
}
|
}
|
||||||
serde_json::Value::Object(m)
|
serde_json::Value::Object(m)
|
||||||
|
@ -22,12 +22,12 @@ impl WholeStreamCommand for Clear {
|
|||||||
fn run(&self, _: CommandArgs) -> Result<InputStream, ShellError> {
|
fn run(&self, _: CommandArgs) -> Result<InputStream, ShellError> {
|
||||||
if cfg!(windows) {
|
if cfg!(windows) {
|
||||||
Command::new("cmd")
|
Command::new("cmd")
|
||||||
.args(&["/C", "cls"])
|
.args(["/C", "cls"])
|
||||||
.status()
|
.status()
|
||||||
.expect("failed to execute process");
|
.expect("failed to execute process");
|
||||||
} else if cfg!(unix) {
|
} else if cfg!(unix) {
|
||||||
Command::new("/bin/sh")
|
Command::new("/bin/sh")
|
||||||
.args(&["-c", "clear"])
|
.args(["-c", "clear"])
|
||||||
.status()
|
.status()
|
||||||
.expect("failed to execute process");
|
.expect("failed to execute process");
|
||||||
}
|
}
|
||||||
|
@ -51,7 +51,7 @@ pub fn clip(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
|
|
||||||
if !values.is_empty() {
|
if !values.is_empty() {
|
||||||
let mut first = true;
|
let mut first = true;
|
||||||
for i in values.iter() {
|
for i in &values {
|
||||||
if !first {
|
if !first {
|
||||||
new_copy_data.push('\n');
|
new_copy_data.push('\n');
|
||||||
} else {
|
} else {
|
||||||
|
@ -99,7 +99,7 @@ fn du(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
|
|
||||||
let exclude = args.exclude.map_or(Ok(None), move |x| {
|
let exclude = args.exclude.map_or(Ok(None), move |x| {
|
||||||
Pattern::new(&x.item)
|
Pattern::new(&x.item)
|
||||||
.map(Option::Some)
|
.map(Some)
|
||||||
.map_err(|e| ShellError::labeled_error(e.msg, "glob error", x.tag.clone()))
|
.map_err(|e| ShellError::labeled_error(e.msg, "glob error", x.tag.clone()))
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
@ -148,11 +148,10 @@ fn du(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
output.push(Ok(ReturnSuccess::Value(
|
output.push(Ok(ReturnSuccess::Value(
|
||||||
DirInfo::new(p, ¶ms, max_depth, ctrl_c.clone()).into(),
|
DirInfo::new(p, ¶ms, max_depth, ctrl_c.clone()).into(),
|
||||||
)));
|
)));
|
||||||
} else {
|
} else if let Ok(v) = FileInfo::new(p, deref, tag.clone()) {
|
||||||
for v in FileInfo::new(p, deref, tag.clone()).into_iter() {
|
|
||||||
output.push(Ok(ReturnSuccess::Value(v.into())));
|
output.push(Ok(ReturnSuccess::Value(v.into())));
|
||||||
}
|
}
|
||||||
}
|
|
||||||
output
|
output
|
||||||
}
|
}
|
||||||
Err(e) => vec![Err(e)],
|
Err(e) => vec![Err(e)],
|
||||||
|
@ -80,7 +80,7 @@ fn exec(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
|
|
||||||
Err(ShellError::labeled_error(
|
Err(ShellError::labeled_error(
|
||||||
"Error on exec",
|
"Error on exec",
|
||||||
format!("{}", err),
|
err.to_string(),
|
||||||
&name,
|
&name,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
@ -82,7 +82,7 @@ pub fn dice(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
UntaggedValue::int(thread_rng.gen_range(1..sides + 1)).into_value(tag.clone())
|
UntaggedValue::int(thread_rng.gen_range(1..sides + 1)).into_value(tag.clone())
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok((iter).into_output_stream())
|
Ok(iter.into_output_stream())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
@ -66,7 +66,7 @@ fn format_command(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
|
|
||||||
ctx.scope.enter_scope();
|
ctx.scope.enter_scope();
|
||||||
ctx.scope.add_var("$it", value.clone());
|
ctx.scope.add_var("$it", value.clone());
|
||||||
let result = evaluate_baseline_expr(&full_column_path.0, &*ctx);
|
let result = evaluate_baseline_expr(&full_column_path.0, &ctx);
|
||||||
ctx.scope.exit_scope();
|
ctx.scope.exit_scope();
|
||||||
|
|
||||||
if let Ok(c) = result {
|
if let Ok(c) = result {
|
||||||
|
@ -90,7 +90,7 @@ fn filesize(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
|
|
||||||
Ok(args
|
Ok(args
|
||||||
.input
|
.input
|
||||||
.map(move |input| {
|
.flat_map(move |input| {
|
||||||
let format = format.clone();
|
let format = format.clone();
|
||||||
let field = field.clone();
|
let field = field.clone();
|
||||||
|
|
||||||
@ -99,7 +99,6 @@ fn filesize(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
Err(e) => Err(e),
|
Err(e) => Err(e),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.flatten()
|
|
||||||
.map(Ok)
|
.map(Ok)
|
||||||
.into_input_stream())
|
.into_input_stream())
|
||||||
}
|
}
|
||||||
|
@ -91,7 +91,7 @@ fn lines(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
value: UntaggedValue::Primitive(Primitive::EndOfStream),
|
value: UntaggedValue::Primitive(Primitive::EndOfStream),
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
let st = (&*leftover_string).lock().clone();
|
let st = leftover_string.lock().clone();
|
||||||
if !st.is_empty() {
|
if !st.is_empty() {
|
||||||
Some(vec![ReturnSuccess::value(
|
Some(vec![ReturnSuccess::value(
|
||||||
UntaggedValue::string(st).into_untagged_value(),
|
UntaggedValue::string(st).into_untagged_value(),
|
||||||
|
@ -176,15 +176,14 @@ fn parse_regex_error(e: regex::Error, base_span: Span) -> ShellError {
|
|||||||
.map(|l| l.replace(':', ""))
|
.map(|l| l.replace(':', ""))
|
||||||
.expect("invalid regex pattern");
|
.expect("invalid regex pattern");
|
||||||
|
|
||||||
let span = lines.nth(1).map(|l| l.find('^')).flatten().map(|space| {
|
let span = lines.nth(1).and_then(|l| l.find('^')).map(|space| {
|
||||||
let start = base_span.start() + space - 3;
|
let start = base_span.start() + space - 3;
|
||||||
Span::for_char(start)
|
Span::for_char(start)
|
||||||
});
|
});
|
||||||
|
|
||||||
let msg = lines
|
let msg = lines
|
||||||
.next()
|
.next()
|
||||||
.map(|l| l.split(':').nth(1))
|
.and_then(|l| l.split(':').nth(1))
|
||||||
.flatten()
|
|
||||||
.map(|s| s.trim().to_string());
|
.map(|s| s.trim().to_string());
|
||||||
|
|
||||||
match (msg, span) {
|
match (msg, span) {
|
||||||
|
@ -69,14 +69,14 @@ fn split_column(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut dict = TaggedDictBuilder::new(&v.tag);
|
let mut dict = TaggedDictBuilder::new(&v.tag);
|
||||||
for (&k, v) in split_result.iter().zip(gen_columns.iter()) {
|
for (&k, v) in split_result.iter().zip(&gen_columns) {
|
||||||
dict.insert_untagged(v.clone(), Primitive::String(k.into()));
|
dict.insert_untagged(v.clone(), Primitive::String(k.into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
ReturnSuccess::value(dict.into_value())
|
ReturnSuccess::value(dict.into_value())
|
||||||
} else {
|
} else {
|
||||||
let mut dict = TaggedDictBuilder::new(&v.tag);
|
let mut dict = TaggedDictBuilder::new(&v.tag);
|
||||||
for (&k, v) in split_result.iter().zip(positional.iter()) {
|
for (&k, v) in split_result.iter().zip(&positional) {
|
||||||
dict.insert_untagged(
|
dict.insert_untagged(
|
||||||
v,
|
v,
|
||||||
UntaggedValue::Primitive(Primitive::String(k.into())),
|
UntaggedValue::Primitive(Primitive::String(k.into())),
|
||||||
|
@ -125,7 +125,7 @@ fn action(
|
|||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
let mut res = character.repeat(**length - s.chars().count());
|
let mut res = character.repeat(**length - s.chars().count());
|
||||||
res += s.as_ref();
|
res += s;
|
||||||
Ok(UntaggedValue::string(res).into_value(tag))
|
Ok(UntaggedValue::string(res).into_value(tag))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -125,7 +125,7 @@ fn action(
|
|||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
let mut res = s.to_string();
|
let mut res = s.to_string();
|
||||||
res += character.repeat(**length - s.chars().count()).as_str();
|
res += &character.repeat(**length - s.chars().count());
|
||||||
Ok(UntaggedValue::string(res).into_value(tag))
|
Ok(UntaggedValue::string(res).into_value(tag))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -343,7 +343,7 @@ mod tests {
|
|||||||
expectation("", (6, -6)),
|
expectation("", (6, -6)),
|
||||||
];
|
];
|
||||||
|
|
||||||
for expectation in cases.iter() {
|
for expectation in &cases {
|
||||||
let expected = expectation.expected;
|
let expected = expectation.expected;
|
||||||
let actual = action(&word, &expectation.options(), Tag::unknown()).unwrap();
|
let actual = action(&word, &expectation.options(), Tag::unknown()).unwrap();
|
||||||
|
|
||||||
|
@ -47,7 +47,7 @@ fn run_ps(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
|
|
||||||
let result: Vec<_> = sys.processes().iter().map(|x| *x.0).collect();
|
let result: Vec<_> = sys.processes().iter().map(|x| *x.0).collect();
|
||||||
|
|
||||||
for pid in result.into_iter() {
|
for pid in result {
|
||||||
if let Some(result) = sys.process(pid) {
|
if let Some(result) = sys.process(pid) {
|
||||||
let mut dict = TaggedDictBuilder::new(args.name_tag());
|
let mut dict = TaggedDictBuilder::new(args.name_tag());
|
||||||
dict.insert_untagged("pid", UntaggedValue::int(pid as i64));
|
dict.insert_untagged("pid", UntaggedValue::int(pid as i64));
|
||||||
|
@ -206,7 +206,7 @@ pub fn autoview(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||||||
> term_width)
|
> term_width)
|
||||||
{
|
{
|
||||||
let mut entries = vec![];
|
let mut entries = vec![];
|
||||||
for (key, value) in row.entries.iter() {
|
for (key, value) in &row.entries {
|
||||||
entries.push(vec![
|
entries.push(vec![
|
||||||
nu_table::StyledString::new(
|
nu_table::StyledString::new(
|
||||||
key.to_string(),
|
key.to_string(),
|
||||||
|
@ -61,7 +61,7 @@ pub fn test_examples(cmd: Command) -> Result<(), ShellError> {
|
|||||||
if let Some(expected) = &sample_pipeline.result {
|
if let Some(expected) = &sample_pipeline.result {
|
||||||
let result = evaluate_block(block, &mut ctx)?;
|
let result = evaluate_block(block, &mut ctx)?;
|
||||||
|
|
||||||
ctx.with_errors(|reasons| reasons.iter().cloned().take(1).next())
|
ctx.with_errors(|reasons| reasons.iter().cloned().next())
|
||||||
.map_or(Ok(()), Err)?;
|
.map_or(Ok(()), Err)?;
|
||||||
|
|
||||||
if expected.len() != result.len() {
|
if expected.len() != result.len() {
|
||||||
@ -75,7 +75,7 @@ pub fn test_examples(cmd: Command) -> Result<(), ShellError> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (e, a) in expected.iter().zip(result.iter()) {
|
for (e, a) in expected.iter().zip(&result) {
|
||||||
if !values_equal(e, a) {
|
if !values_equal(e, a) {
|
||||||
let row_errored = format!("expected: {:#?}\nactual: {:#?}", e, a);
|
let row_errored = format!("expected: {:#?}\nactual: {:#?}", e, a);
|
||||||
let failed_call = format!("command: {}\n", sample_pipeline.example);
|
let failed_call = format!("command: {}\n", sample_pipeline.example);
|
||||||
@ -140,7 +140,7 @@ pub fn test(cmd: impl WholeStreamCommand + 'static) -> Result<(), ShellError> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (e, a) in expected.iter().zip(result.iter()) {
|
for (e, a) in expected.iter().zip(&result) {
|
||||||
if !values_equal(e, a) {
|
if !values_equal(e, a) {
|
||||||
let row_errored = format!("expected: {:#?}\nactual: {:#?}", e, a);
|
let row_errored = format!("expected: {:#?}\nactual: {:#?}", e, a);
|
||||||
let failed_call = format!("command: {}\n", sample_pipeline.example);
|
let failed_call = format!("command: {}\n", sample_pipeline.example);
|
||||||
@ -275,10 +275,10 @@ pub fn test_anchors(cmd: Command) -> Result<(), ShellError> {
|
|||||||
if sample_pipeline.result.is_some() {
|
if sample_pipeline.result.is_some() {
|
||||||
let result = evaluate_block(block, &mut ctx)?;
|
let result = evaluate_block(block, &mut ctx)?;
|
||||||
|
|
||||||
ctx.with_errors(|reasons| reasons.iter().cloned().take(1).next())
|
ctx.with_errors(|reasons| reasons.iter().cloned().next())
|
||||||
.map_or(Ok(()), Err)?;
|
.map_or(Ok(()), Err)?;
|
||||||
|
|
||||||
for actual in result.iter() {
|
for actual in &result {
|
||||||
if !is_anchor_carried(actual, mock_path()) {
|
if !is_anchor_carried(actual, mock_path()) {
|
||||||
let failed_call = format!("command: {}\n", pipeline_with_anchor);
|
let failed_call = format!("command: {}\n", pipeline_with_anchor);
|
||||||
|
|
||||||
@ -351,10 +351,10 @@ fn values_equal(expected: &Value, actual: &Value) -> bool {
|
|||||||
|
|
||||||
e.entries
|
e.entries
|
||||||
.iter()
|
.iter()
|
||||||
.zip(a.entries.iter())
|
.zip(&a.entries)
|
||||||
.all(|((ek, ev), (ak, av))| ek == ak && values_equal(ev, av))
|
.all(|((ek, ev), (ak, av))| ek == ak && values_equal(ev, av))
|
||||||
}
|
}
|
||||||
(Table(e), Table(a)) => e.iter().zip(a.iter()).all(|(e, a)| values_equal(e, a)),
|
(Table(e), Table(a)) => e.iter().zip(a).all(|(e, a)| values_equal(e, a)),
|
||||||
(e, a) => unimplemented!("{} {}", e.type_name(), a.type_name()),
|
(e, a) => unimplemented!("{} {}", e.type_name(), a.type_name()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -38,7 +38,7 @@ impl WholeStreamCommand for Command {
|
|||||||
base_value = first.clone()
|
base_value = first.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
let stream = rest.into_iter().map(move |i| {
|
let stream = rest.into_iter().flat_map(move |i| {
|
||||||
let base_value = base_value.clone();
|
let base_value = base_value.clone();
|
||||||
match i.as_string() {
|
match i.as_string() {
|
||||||
Ok(s) => ActionStream::one(Ok(ReturnSuccess::Value(Value {
|
Ok(s) => ActionStream::one(Ok(ReturnSuccess::Value(Value {
|
||||||
@ -52,9 +52,9 @@ impl WholeStreamCommand for Command {
|
|||||||
} => {
|
} => {
|
||||||
if table.len() == 1 && table[0].is_table() {
|
if table.len() == 1 && table[0].is_table() {
|
||||||
let mut values: Vec<Value> =
|
let mut values: Vec<Value> =
|
||||||
table[0].table_entries().map(Clone::clone).collect();
|
table[0].table_entries().cloned().collect();
|
||||||
|
|
||||||
for v in values.iter_mut() {
|
for v in &mut values {
|
||||||
v.tag = base_value.tag();
|
v.tag = base_value.tag();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -81,6 +81,6 @@ impl WholeStreamCommand for Command {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok((stream).flatten().into_action_stream())
|
Ok(stream.into_action_stream())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -42,14 +42,14 @@ fn compute_sum_of_individual_row() -> Result<(), String> {
|
|||||||
("mem", 3032375296.),
|
("mem", 3032375296.),
|
||||||
("virtual", 102579965952.),
|
("virtual", 102579965952.),
|
||||||
];
|
];
|
||||||
for (column_name, expected_value) in answers_for_columns.iter() {
|
for (column_name, expected_value) in answers_for_columns {
|
||||||
let actual = nu!(
|
let actual = nu!(
|
||||||
cwd: "tests/fixtures/formats/",
|
cwd: "tests/fixtures/formats/",
|
||||||
format!("open sample-ps-output.json | select {} | math sum | get {}", column_name, column_name)
|
format!("open sample-ps-output.json | select {} | math sum | get {}", column_name, column_name)
|
||||||
);
|
);
|
||||||
let result =
|
let result =
|
||||||
f64::from_str(&actual.out).map_err(|_| String::from("Failed to parse float."))?;
|
f64::from_str(&actual.out).map_err(|_| String::from("Failed to parse float."))?;
|
||||||
assert_eq!(result, *expected_value);
|
assert_eq!(result, expected_value);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@ -63,14 +63,14 @@ fn compute_sum_of_table() -> Result<(), String> {
|
|||||||
("mem", 3032375296.),
|
("mem", 3032375296.),
|
||||||
("virtual", 102579965952.),
|
("virtual", 102579965952.),
|
||||||
];
|
];
|
||||||
for (column_name, expected_value) in answers_for_columns.iter() {
|
for (column_name, expected_value) in answers_for_columns {
|
||||||
let actual = nu!(
|
let actual = nu!(
|
||||||
cwd: "tests/fixtures/formats/",
|
cwd: "tests/fixtures/formats/",
|
||||||
format!("open sample-ps-output.json | select cpu mem virtual | math sum | get {}", column_name)
|
format!("open sample-ps-output.json | select cpu mem virtual | math sum | get {}", column_name)
|
||||||
);
|
);
|
||||||
let result =
|
let result =
|
||||||
f64::from_str(&actual.out).map_err(|_| String::from("Failed to parse float."))?;
|
f64::from_str(&actual.out).map_err(|_| String::from("Failed to parse float."))?;
|
||||||
assert_eq!(result, *expected_value);
|
assert_eq!(result, expected_value);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -25,7 +25,7 @@ where
|
|||||||
let path_executables = find_path_executables().unwrap_or_default();
|
let path_executables = find_path_executables().unwrap_or_default();
|
||||||
|
|
||||||
// TODO quote these, if necessary
|
// TODO quote these, if necessary
|
||||||
commands.extend(path_executables.into_iter());
|
commands.extend(path_executables);
|
||||||
|
|
||||||
let mut suggestions: Vec<_> = commands
|
let mut suggestions: Vec<_> = commands
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
@ -37,7 +37,7 @@ impl NuCompleter {
|
|||||||
.and_then(|cfg| cfg.get("line_editor").cloned())
|
.and_then(|cfg| cfg.get("line_editor").cloned())
|
||||||
.and_then(|le| {
|
.and_then(|le| {
|
||||||
le.row_entries()
|
le.row_entries()
|
||||||
.find(|(idx, _value)| idx.as_str() == "completion_match_method")
|
.find(|&(idx, _value)| idx == "completion_match_method")
|
||||||
.and_then(|(_idx, value)| value.as_string().ok())
|
.and_then(|(_idx, value)| value.as_string().ok())
|
||||||
})
|
})
|
||||||
.unwrap_or_else(String::new);
|
.unwrap_or_else(String::new);
|
||||||
|
@ -306,7 +306,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn get_signature(&self, name: &str) -> Option<nu_protocol::Signature> {
|
fn get_signature(&self, name: &str) -> Option<nu_protocol::Signature> {
|
||||||
self.0.iter().find(|v| v.name == name).map(Clone::clone)
|
self.0.iter().find(|v| v.name == name).cloned()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_alias(&self, _name: &str) -> Option<Vec<Spanned<String>>> {
|
fn get_alias(&self, _name: &str) -> Option<Vec<Spanned<String>>> {
|
||||||
|
@ -12,7 +12,7 @@ where
|
|||||||
fn complete(&self, ctx: &Context, partial: &str, matcher: &dyn Matcher) -> Vec<Suggestion> {
|
fn complete(&self, ctx: &Context, partial: &str, matcher: &dyn Matcher) -> Vec<Suggestion> {
|
||||||
if let Some(sig) = ctx.signature_registry().get(&self.cmd) {
|
if let Some(sig) = ctx.signature_registry().get(&self.cmd) {
|
||||||
let mut suggestions = Vec::new();
|
let mut suggestions = Vec::new();
|
||||||
for (name, (named_type, _desc)) in sig.named.iter() {
|
for (name, (named_type, _desc)) in &sig.named {
|
||||||
suggestions.push(format!("--{}", name));
|
suggestions.push(format!("--{}", name));
|
||||||
|
|
||||||
if let Some(c) = named_type.get_short() {
|
if let Some(c) = named_type.get_short() {
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user