use IntoValue and TryIntoValue more

This commit is contained in:
Tim 'Piepmatz' Hesse 2024-06-19 00:58:55 +02:00
parent a894e9c246
commit 52b8bb39fe
118 changed files with 415 additions and 331 deletions

View File

@ -8,7 +8,7 @@ use nu_parser::{flatten_pipeline_element, parse, FlatShape};
use nu_protocol::{
debugger::WithoutDebug,
engine::{Closure, EngineState, Stack, StateWorkingSet},
PipelineData, Span, Value,
PipelineData, Span, TryIntoValue, Value,
};
use reedline::{Completer as ReedlineCompleter, Suggestion};
use std::{str, sync::Arc};
@ -103,7 +103,7 @@ impl NuCompleter {
PipelineData::empty(),
);
match result.and_then(|data| data.into_value(span)) {
match result.and_then(|data| data.try_into_value(span)) {
Ok(value) => {
if let Value::List { vals, .. } = value {
let result =

View File

@ -7,7 +7,7 @@ use nu_protocol::{
ast::{Argument, Call, Expr, Expression},
debugger::WithoutDebug,
engine::{Stack, StateWorkingSet},
PipelineData, Span, Type, Value,
PipelineData, Span, TryIntoValue, Type, Value,
};
use nu_utils::IgnoreCaseExt;
use std::collections::HashMap;
@ -72,7 +72,7 @@ impl Completer for CustomCompletion {
// Parse result
let suggestions = result
.and_then(|data| data.into_value(span))
.and_then(|data| data.try_into_value(span))
.map(|value| match &value {
Value::Record { val, .. } => {
let completions = val

View File

@ -2,7 +2,7 @@ use nu_engine::eval_block;
use nu_protocol::{
debugger::WithoutDebug,
engine::{EngineState, Stack},
IntoPipelineData, Span, Value,
IntoPipelineData, Span, TryIntoValue, Value,
};
use reedline::{menu_functions::parse_selection_char, Completer, Suggestion};
use std::sync::Arc;
@ -59,7 +59,7 @@ impl Completer for NuMenuCompleter {
let res = eval_block::<WithoutDebug>(&self.engine_state, &mut self.stack, block, input);
if let Ok(values) = res.and_then(|data| data.into_value(self.span)) {
if let Ok(values) = res.and_then(|data| data.try_into_value(self.span)) {
convert_to_suggestions(values, line, pos, self.only_buffer_difference)
} else {
Vec::new()

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, ClosureEval, ClosureEvalOnce};
use nu_protocol::engine::Closure;
use nu_protocol::{engine::Closure, TryIntoValue};
#[derive(Clone)]
pub struct EachWhile;
@ -82,7 +82,7 @@ impl Command for EachWhile {
.map_while(move |value| {
match closure
.run_with_value(value)
.and_then(|data| data.into_value(head))
.and_then(|data| data.try_into_value(head))
{
Ok(value) => (!value.is_nothing()).then_some(value),
Err(_) => None,
@ -100,7 +100,7 @@ impl Command for EachWhile {
let value = value.ok()?;
match closure
.run_with_value(value)
.and_then(|data| data.into_value(span))
.and_then(|data| data.try_into_value(span))
{
Ok(value) => (!value.is_nothing()).then_some(value),
Err(_) => None,

View File

@ -1,5 +1,6 @@
use super::{vertical_rotate_value, VerticalDirection};
use nu_engine::command_prelude::*;
use nu_protocol::TryIntoValue;
#[derive(Clone)]
pub struct RollDown;
@ -56,7 +57,7 @@ impl Command for RollDown {
let by: Option<usize> = call.get_flag(engine_state, stack, "by")?;
let metadata = input.metadata();
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
let rotated_value = vertical_rotate_value(value, by, VerticalDirection::Down)?;
Ok(rotated_value.into_pipeline_data().set_metadata(metadata))

View File

@ -1,5 +1,6 @@
use super::{horizontal_rotate_value, HorizontalDirection};
use nu_engine::command_prelude::*;
use nu_protocol::TryIntoValue;
#[derive(Clone)]
pub struct RollLeft;
@ -94,7 +95,7 @@ impl Command for RollLeft {
let metadata = input.metadata();
let cells_only = call.has_flag(engine_state, stack, "cells-only")?;
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
let rotated_value =
horizontal_rotate_value(value, by, cells_only, &HorizontalDirection::Left)?;

View File

@ -1,5 +1,6 @@
use super::{horizontal_rotate_value, HorizontalDirection};
use nu_engine::command_prelude::*;
use nu_protocol::TryIntoValue;
#[derive(Clone)]
pub struct RollRight;
@ -94,7 +95,7 @@ impl Command for RollRight {
let metadata = input.metadata();
let cells_only = call.has_flag(engine_state, stack, "cells-only")?;
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
let rotated_value =
horizontal_rotate_value(value, by, cells_only, &HorizontalDirection::Right)?;

View File

@ -1,5 +1,6 @@
use super::{vertical_rotate_value, VerticalDirection};
use nu_engine::command_prelude::*;
use nu_protocol::TryIntoValue;
#[derive(Clone)]
pub struct RollUp;
@ -56,7 +57,7 @@ impl Command for RollUp {
let by: Option<usize> = call.get_flag(engine_state, stack, "by")?;
let metadata = input.metadata();
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
let rotated_value = vertical_rotate_value(value, by, VerticalDirection::Up)?;
Ok(rotated_value.into_pipeline_data().set_metadata(metadata))

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, ClosureEval};
use nu_protocol::{engine::Closure, PipelineIterator};
use nu_protocol::{engine::Closure, PipelineIterator, TryIntoValue};
use std::collections::HashSet;
#[derive(Clone)]
@ -152,7 +152,7 @@ impl Iterator for UpdateCellIterator {
fn eval_value(closure: &mut ClosureEval, span: Span, value: Value) -> Value {
closure
.run_with_value(value)
.and_then(|data| data.into_value(span))
.and_then(|data| data.try_into_value(span))
.unwrap_or_else(|err| Value::error(err, span))
}

View File

@ -1,5 +1,5 @@
use nu_engine::command_prelude::*;
use nu_protocol::{ast::PathMember, engine::StateWorkingSet, ListStream};
use nu_protocol::{ast::PathMember, engine::StateWorkingSet, ListStream, TryIntoValue};
#[derive(Clone)]
pub struct FormatPattern;
@ -38,7 +38,7 @@ impl Command for FormatPattern {
let mut working_set = StateWorkingSet::new(engine_state);
let specified_pattern: Result<Value, ShellError> = call.req(engine_state, stack, 0);
let input_val = input.into_value(call.head)?;
let input_val = input.try_into_value(call.head)?;
// add '$it' variable to support format like this: $it.column1.column2.
let it_id = working_set.add_variable(b"$it".to_vec(), call.head, Type::Any, false);
stack.add_var(it_id, input_val.clone());

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, get_eval_block, redirect_env};
use nu_protocol::{engine::Closure, DataSource, PipelineMetadata};
use nu_protocol::{engine::Closure, DataSource, PipelineMetadata, TryIntoValue};
#[derive(Clone)]
pub struct Collect;
@ -54,7 +54,7 @@ is particularly large, this can cause high memory usage."#
other => other,
};
let input = input.into_value(call.head)?;
let input = input.try_into_value(call.head)?;
let result;
if let Some(closure) = closure {

View File

@ -1,5 +1,5 @@
use nu_engine::command_prelude::*;
use nu_protocol::{engine::StateWorkingSet, ByteStreamSource, PipelineMetadata};
use nu_protocol::{engine::StateWorkingSet, ByteStreamSource, IntoValue, PipelineMetadata};
#[derive(Clone)]
pub struct Describe;
@ -195,7 +195,8 @@ fn run(
let subtype = if options.no_collect {
Value::string("any", head)
} else {
describe_value(stream.into_value(), head, engine_state)
let span = stream.span();
describe_value(stream.into_value(span), head, engine_state)
};
Value::record(
record! {
@ -209,7 +210,8 @@ fn run(
} else if options.no_collect {
Value::string("stream", head)
} else {
let value = stream.into_value();
let span = stream.span();
let value = stream.into_value(span);
let base_description = value.get_type().to_string();
Value::string(format!("{} (stream)", base_description), head)
}
@ -232,7 +234,7 @@ enum Description {
Record(Record),
}
impl Description {
impl IntoValue for Description {
fn into_value(self, span: Span) -> Value {
match self {
Description::String(ty) => Value::string(ty, span),

View File

@ -1,6 +1,6 @@
use nu_engine::{command_prelude::*, get_eval_block, get_eval_expression};
use nu_protocol::engine::CommandType;
use nu_protocol::ParseWarning;
use nu_protocol::{ParseWarning, TryIntoValue};
#[derive(Clone)]
pub struct For;
@ -193,7 +193,8 @@ impl Command for For {
x => {
stack.add_var(var_id, x);
eval_block(&engine_state, stack, block, PipelineData::empty())?.into_value(head)?;
eval_block(&engine_state, stack, block, PipelineData::empty())?
.try_into_value(head)?;
}
}
Ok(PipelineData::empty())

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, get_eval_block};
use nu_protocol::engine::CommandType;
use nu_protocol::{engine::CommandType, TryIntoValue};
#[derive(Clone)]
pub struct Let;
@ -62,7 +62,7 @@ impl Command for Let {
let eval_block = get_eval_block(engine_state);
let stack = &mut stack.start_capture();
let pipeline_data = eval_block(engine_state, stack, block, input)?;
let value = pipeline_data.into_value(call.head)?;
let value = pipeline_data.try_into_value(call.head)?;
// if given variable type is Glob, and our result is string
// then nushell need to convert from Value::String to Value::Glob

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, get_eval_block};
use nu_protocol::engine::CommandType;
use nu_protocol::{engine::CommandType, TryIntoValue};
#[derive(Clone)]
pub struct Mut;
@ -62,7 +62,7 @@ impl Command for Mut {
let eval_block = get_eval_block(engine_state);
let stack = &mut stack.start_capture();
let pipeline_data = eval_block(engine_state, stack, block, input)?;
let value = pipeline_data.into_value(call.head)?;
let value = pipeline_data.try_into_value(call.head)?;
// if given variable type is Glob, and our result is string
// then nushell need to convert from Value::String to Value::Glob

View File

@ -4,7 +4,7 @@ use nu_protocol::{
ast::Block,
debugger::WithoutDebug,
engine::{StateDelta, StateWorkingSet},
Range,
Range, TryIntoValue,
};
use std::{
sync::Arc,
@ -123,7 +123,7 @@ pub fn eval_block(
stack.add_env_var("PWD".to_string(), Value::test_string(cwd.to_string_lossy()));
nu_engine::eval_block::<WithoutDebug>(engine_state, &mut stack, &block, input)
.and_then(|data| data.into_value(Span::test_data()))
.and_then(|data| data.try_into_value(Span::test_data()))
.unwrap_or_else(|err| panic!("test eval error in `{}`: {:?}", "TODO", err))
}

View File

@ -4,7 +4,7 @@ use nu_engine::{env::get_config, ClosureEvalOnce};
use nu_protocol::{
cli_error::CliError,
engine::{Closure, EngineState, Stack, StateWorkingSet},
Span, Value,
Span, TryIntoValue, Value,
};
use std::{
collections::HashMap,
@ -59,7 +59,7 @@ impl<'a> StyleComputer<'a> {
let result = ClosureEvalOnce::new(self.engine_state, self.stack, closure.clone())
.debug(false)
.run_with_value(value.clone())
.and_then(|data| data.into_value(*span));
.and_then(|data| data.try_into_value(*span));
match result {
Ok(value) => {

View File

@ -1,5 +1,5 @@
use chrono::{DateTime, FixedOffset};
use nu_protocol::{ShellError, Span, Value};
use nu_protocol::{IntoValue, ShellError, Span, Value};
use std::hash::{Hash, Hasher};
/// A subset of [`Value`](crate::Value), which is hashable.
@ -112,18 +112,19 @@ impl HashableValue {
}),
}
}
}
/// Convert from self to nu's core data type `Value`.
pub fn into_value(self) -> Value {
impl IntoValue for HashableValue {
fn into_value(self, span: Span) -> Value {
match self {
HashableValue::Bool { val, span } => Value::bool(val, span),
HashableValue::Int { val, span } => Value::int(val, span),
HashableValue::Filesize { val, span } => Value::filesize(val, span),
HashableValue::Duration { val, span } => Value::duration(val, span),
HashableValue::Date { val, span } => Value::date(val, span),
HashableValue::Float { val, span } => Value::float(f64::from_ne_bytes(val), span),
HashableValue::String { val, span } => Value::string(val, span),
HashableValue::Binary { val, span } => Value::binary(val, span),
HashableValue::Bool { val, .. } => Value::bool(val, span),
HashableValue::Int { val, .. } => Value::int(val, span),
HashableValue::Filesize { val, .. } => Value::filesize(val, span),
HashableValue::Duration { val, .. } => Value::duration(val, span),
HashableValue::Date { val, .. } => Value::date(val, span),
HashableValue::Float { val, .. } => Value::float(f64::from_ne_bytes(val), span),
HashableValue::String { val, .. } => Value::string(val, span),
HashableValue::Binary { val, .. } => Value::binary(val, span),
}
}
}
@ -289,7 +290,7 @@ mod test {
assert_eq!(
HashableValue::from_value(val, Span::unknown())
.unwrap()
.into_value(),
.into_value(span),
expected_val
);
}

View File

@ -1,6 +1,7 @@
use super::hashable_value::HashableValue;
use itertools::Itertools;
use nu_engine::command_prelude::*;
use nu_protocol::TryIntoValue;
use std::collections::HashMap;
@ -121,7 +122,7 @@ impl Command for Histogram {
};
let span = call.head;
let data_as_value = input.into_value(span)?;
let data_as_value = input.try_into_value(span)?;
let value_span = data_as_value.span();
// `input` is not a list, here we can return an error.
run_histogram(
@ -248,7 +249,7 @@ fn histogram_impl(
count, // attach count first for easily sorting.
Value::record(
record! {
value_column_name => val.into_value(),
value_column_name => val.into_value(span),
"count" => Value::int(count, span),
"quantile" => Value::float(quantile, span),
"percentage" => Value::string(percentage, span),

View File

@ -1,6 +1,6 @@
use chrono::{DateTime, Datelike, FixedOffset, Timelike};
use nu_engine::command_prelude::*;
use nu_protocol::format_duration_as_timeperiod;
use nu_protocol::{format_duration_as_timeperiod, TryIntoValue};
#[derive(Clone)]
pub struct SubCommand;
@ -108,7 +108,7 @@ fn into_record(
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let input = input.into_value(call.head)?;
let input = input.try_into_value(call.head)?;
let input_type = input.get_type();
let span = input.span();
let res = match input {

View File

@ -2,7 +2,9 @@ use super::definitions::{
db_column::DbColumn, db_constraint::DbConstraint, db_foreignkey::DbForeignKey,
db_index::DbIndex, db_table::DbTable,
};
use nu_protocol::{CustomValue, PipelineData, Record, ShellError, Span, Spanned, Value};
use nu_protocol::{
CustomValue, IntoValue, PipelineData, Record, ShellError, Span, Spanned, TryIntoValue, Value,
};
use rusqlite::{
types::ValueRef, Connection, DatabaseName, Error as SqliteError, OpenFlags, Row, Statement,
ToSql,
@ -91,15 +93,10 @@ impl SQLiteDatabase {
}
pub fn try_from_pipeline(input: PipelineData, span: Span) -> Result<Self, ShellError> {
let value = input.into_value(span)?;
let value = input.try_into_value(span)?;
Self::try_from_value(value)
}
pub fn into_value(self, span: Span) -> Value {
let db = Box::new(self);
Value::custom(db, span)
}
pub fn query(
&self,
sql: &Spanned<String>,
@ -350,6 +347,13 @@ impl SQLiteDatabase {
}
}
impl IntoValue for SQLiteDatabase {
fn into_value(self, span: Span) -> Value {
let db = Box::new(self);
Value::custom(db, span)
}
}
impl CustomValue for SQLiteDatabase {
fn clone_value(&self, span: Span) -> Value {
let cloned = SQLiteDatabase {

View File

@ -1,5 +1,6 @@
use super::inspect_table;
use nu_engine::command_prelude::*;
use nu_protocol::TryIntoValue;
use terminal_size::{terminal_size, Height, Width};
#[derive(Clone)]
@ -29,7 +30,7 @@ impl Command for Inspect {
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let input_metadata = input.metadata();
let input_val = input.into_value(call.head)?;
let input_val = input.try_into_value(call.head)?;
if input_val.is_nothing() {
return Err(ShellError::PipelineEmpty {
dst_span: call.head,

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, ClosureEvalOnce};
use nu_protocol::{debugger::Profiler, engine::Closure};
use nu_protocol::{debugger::Profiler, engine::Closure, TryIntoValue};
#[derive(Clone)]
pub struct DebugProfile;
@ -125,7 +125,7 @@ confusing the id/parent_id hierarchy. The --expr flag is helpful for investigati
let pipeline_data = result?;
// Collect the output
let _ = pipeline_data.into_value(call.span());
let _ = pipeline_data.try_into_value(call.span());
Ok(engine_state
.deactivate_debugger()

View File

@ -1,4 +1,5 @@
use nu_engine::{command_prelude::*, get_eval_block, get_eval_expression_with_input};
use nu_protocol::TryIntoValue;
use std::time::Instant;
#[derive(Clone)]
@ -58,7 +59,7 @@ impl Command for TimeIt {
} else {
PipelineData::empty()
}
.into_value(call.head)?;
.try_into_value(call.head)?;
let end_time = Instant::now();

View File

@ -7,7 +7,7 @@ use nu_protocol::{
ast::{Expr, Expression},
byte_stream::copy_with_interrupt,
process::ChildPipe,
ByteStreamSource, DataSource, OutDest, PipelineMetadata,
ByteStreamSource, DataSource, OutDest, PipelineMetadata, TryIntoValue,
};
use std::{
fs::File,
@ -378,7 +378,7 @@ fn input_to_bytes(
input
};
value_to_bytes(input.into_value(span)?)
value_to_bytes(input.try_into_value(span)?)
}
/// Convert given data into content of file of specified extension if

View File

@ -129,7 +129,7 @@ with 'transpose' first."#
}
Some(Value::list(vals, span))
}
Ok(data) => Some(data.into_value(head).unwrap_or_else(|err| {
Ok(data) => Some(data.try_into_value(head).unwrap_or_else(|err| {
Value::error(chain_error_with_input(err, is_error, span), span)
})),
Err(ShellError::Continue { span }) => Some(Value::nothing(span)),
@ -160,7 +160,7 @@ with 'transpose' first."#
let is_error = value.is_error();
match closure
.run_with_value(value)
.and_then(|data| data.into_value(head))
.and_then(|data| data.try_into_value(head))
{
Ok(value) => Some(value),
Err(ShellError::Continue { span }) => Some(Value::nothing(span)),

View File

@ -1,6 +1,6 @@
use super::utils::chain_error_with_input;
use nu_engine::{command_prelude::*, ClosureEval, ClosureEvalOnce};
use nu_protocol::engine::Closure;
use nu_protocol::{engine::Closure, TryIntoValue};
#[derive(Clone)]
pub struct Filter;
@ -62,7 +62,7 @@ a variable. On the other hand, the "row condition" syntax is not supported."#
.filter_map(move |value| {
match closure
.run_with_value(value.clone())
.and_then(|data| data.into_value(head))
.and_then(|data| data.try_into_value(head))
{
Ok(cond) => cond.is_true().then_some(value),
Err(err) => {
@ -87,7 +87,7 @@ a variable. On the other hand, the "row condition" syntax is not supported."#
match closure
.run_with_value(value.clone())
.and_then(|data| data.into_value(head))
.and_then(|data| data.try_into_value(head))
{
Ok(cond) => cond.is_true().then_some(value),
Err(err) => {
@ -107,7 +107,7 @@ a variable. On the other hand, the "row condition" syntax is not supported."#
PipelineData::Value(value, ..) => {
let result = ClosureEvalOnce::new(engine_state, stack, closure)
.run_with_value(value.clone())
.and_then(|data| data.into_value(head));
.and_then(|data| data.try_into_value(head));
Ok(match result {
Ok(cond) => cond.is_true().then_some(value),

View File

@ -81,7 +81,7 @@ If multiple cell paths are given, this will produce a list of values."#
let paths = std::iter::once(cell_path).chain(rest);
let input = input.into_value(span)?;
let input = input.try_into_value(span)?;
for path in paths {
let val = input.clone().follow_cell_path(&path.members, !sensitive);

View File

@ -1,6 +1,6 @@
use indexmap::IndexMap;
use nu_engine::{command_prelude::*, ClosureEval};
use nu_protocol::engine::Closure;
use nu_protocol::{engine::Closure, TryIntoValue};
#[derive(Clone)]
pub struct GroupBy;
@ -207,7 +207,7 @@ fn group_closure(
for value in values {
let key = closure
.run_with_value(value.clone())?
.into_value(span)?
.try_into_value(span)?
.coerce_into_string()?;
groups.entry(key).or_default().push(value);

View File

@ -66,7 +66,7 @@ impl Command for Headers {
let config = engine_state.get_config();
let metadata = input.metadata();
let span = input.span().unwrap_or(call.head);
let value = input.into_value(span)?;
let value = input.try_into_value(span)?;
let Value::List { vals: table, .. } = value else {
return Err(ShellError::TypeMismatch {
err_message: "not a table".to_string(),

View File

@ -190,7 +190,7 @@ fn insert(
let value = value.unwrap_or(Value::nothing(head));
let new_value = ClosureEvalOnce::new(engine_state, stack, *val)
.run_with_value(value.clone())?
.into_value(head)?;
.try_into_value(head)?;
pre_elems.push(new_value);
if !end_of_stream {
@ -284,7 +284,9 @@ fn insert_value_by_closure(
value.clone()
};
let new_value = closure.run_with_value(value_at_path)?.into_value(span)?;
let new_value = closure
.run_with_value(value_at_path)?
.try_into_value(span)?;
value.insert_data_at_cell_path(cell_path, new_value, span)
}
@ -304,7 +306,9 @@ fn insert_single_value_by_closure(
value.clone()
};
let new_value = closure.run_with_value(value_at_path)?.into_value(span)?;
let new_value = closure
.run_with_value(value_at_path)?
.try_into_value(span)?;
value.insert_data_at_cell_path(cell_path, new_value, span)
}

View File

@ -56,7 +56,7 @@ impl Command for Items {
.add_arg(Value::string(col, span))
.add_arg(val)
.run_with_input(PipelineData::Empty)
.and_then(|data| data.into_value(head));
.and_then(|data| data.try_into_value(head));
match result {
Ok(value) => Some(value),

View File

@ -75,7 +75,7 @@ impl Command for Join {
let join_type = join_type(engine_state, stack, call)?;
// FIXME: we should handle ListStreams properly instead of collecting
let collected_input = input.into_value(span)?;
let collected_input = input.try_into_value(span)?;
match (&collected_input, &table_2, &l_on, &r_on) {
(

View File

@ -1,6 +1,6 @@
use super::utils::chain_error_with_input;
use nu_engine::{command_prelude::*, ClosureEvalOnce};
use nu_protocol::engine::Closure;
use nu_protocol::{engine::Closure, TryIntoValue};
use rayon::prelude::*;
#[derive(Clone)]
@ -146,7 +146,7 @@ impl Command for ParEach {
let value =
ClosureEvalOnce::new(engine_state, stack, closure.clone())
.run_with_value(value)
.and_then(|data| data.into_value(span))
.and_then(|data| data.try_into_value(span))
.unwrap_or_else(|err| {
Value::error(
chain_error_with_input(err, is_error, span),
@ -172,7 +172,7 @@ impl Command for ParEach {
let value =
ClosureEvalOnce::new(engine_state, stack, closure.clone())
.run_with_value(value)
.and_then(|data| data.into_value(span))
.and_then(|data| data.try_into_value(span))
.unwrap_or_else(|err| {
Value::error(
chain_error_with_input(err, is_error, span),
@ -203,7 +203,7 @@ impl Command for ParEach {
let is_error = value.is_error();
let value = ClosureEvalOnce::new(engine_state, stack, closure.clone())
.run_with_value(value)
.and_then(|data| data.into_value(head))
.and_then(|data| data.try_into_value(head))
.unwrap_or_else(|err| {
Value::error(chain_error_with_input(err, is_error, span), span)
});
@ -229,7 +229,7 @@ impl Command for ParEach {
let value =
ClosureEvalOnce::new(engine_state, stack, closure.clone())
.run_with_value(value)
.and_then(|data| data.into_value(head))
.and_then(|data| data.try_into_value(head))
.unwrap_or_else(|err| Value::error(err, head));
(index, value)

View File

@ -115,7 +115,7 @@ impl Command for Reduce {
.add_arg(value)
.add_arg(acc)
.run_with_input(PipelineData::Empty)?
.into_value(head)?;
.try_into_value(head)?;
}
Ok(acc.with_span(head).into_pipeline_data())

View File

@ -173,7 +173,7 @@ fn reject(
) -> Result<PipelineData, ShellError> {
let mut unique_rows: HashSet<usize> = HashSet::new();
let metadata = input.metadata();
let val = input.into_value(span)?;
let val = input.try_into_value(span)?;
let mut val = val;
let mut new_columns = vec![];
let mut new_rows = vec![];

View File

@ -85,7 +85,7 @@ impl Command for SkipUntil {
.skip_while(move |value| {
closure
.run_with_value(value.clone())
.and_then(|data| data.into_value(head))
.and_then(|data| data.try_into_value(head))
.map(|cond| cond.is_false())
.unwrap_or(false)
})

View File

@ -90,7 +90,7 @@ impl Command for SkipWhile {
.skip_while(move |value| {
closure
.run_with_value(value.clone())
.and_then(|data| data.into_value(head))
.and_then(|data| data.try_into_value(head))
.map(|cond| cond.is_true())
.unwrap_or(false)
})

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, ClosureEval};
use nu_protocol::engine::Closure;
use nu_protocol::{engine::Closure, TryIntoValue};
#[derive(Clone)]
pub struct TakeUntil;
@ -81,7 +81,7 @@ impl Command for TakeUntil {
.take_while(move |value| {
closure
.run_with_value(value.clone())
.and_then(|data| data.into_value(head))
.and_then(|data| data.try_into_value(head))
.map(|cond| cond.is_false())
.unwrap_or(false)
})

View File

@ -81,7 +81,7 @@ impl Command for TakeWhile {
.take_while(move |value| {
closure
.run_with_value(value.clone())
.and_then(|data| data.into_value(head))
.and_then(|data| data.try_into_value(head))
.map(|cond| cond.is_true())
.unwrap_or(false)
})

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, ClosureEval, ClosureEvalOnce};
use nu_protocol::ast::PathMember;
use nu_protocol::{ast::PathMember, TryIntoValue};
#[derive(Clone)]
pub struct Update;
@ -250,7 +250,7 @@ fn update_value_by_closure(
let new_value = closure
.add_arg(arg.clone())
.run_with_input(value_at_path.into_pipeline_data())?
.into_value(span)?;
.try_into_value(span)?;
value.update_data_at_cell_path(cell_path, new_value)
}
@ -273,7 +273,7 @@ fn update_single_value_by_closure(
let new_value = closure
.add_arg(arg.clone())
.run_with_input(value_at_path.into_pipeline_data())?
.into_value(span)?;
.try_into_value(span)?;
value.update_data_at_cell_path(cell_path, new_value)
}

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, ClosureEval, ClosureEvalOnce};
use nu_protocol::ast::PathMember;
use nu_protocol::{ast::PathMember, TryIntoValue};
#[derive(Clone)]
pub struct Upsert;
@ -218,7 +218,7 @@ fn upsert(
if let Value::Closure { val, .. } = replacement {
ClosureEvalOnce::new(engine_state, stack, *val)
.run_with_value(value)?
.into_value(head)?
.try_into_value(head)?
} else {
replacement
}
@ -314,7 +314,7 @@ fn upsert_value_by_closure(
let new_value = closure
.add_arg(arg)
.run_with_input(input)?
.into_value(span)?;
.try_into_value(span)?;
value.upsert_data_at_cell_path(cell_path, new_value)
}
@ -341,7 +341,7 @@ fn upsert_single_value_by_closure(
let new_value = closure
.add_arg(arg)
.run_with_input(input)?
.into_value(span)?;
.try_into_value(span)?;
value.upsert_data_at_cell_path(cell_path, new_value)
}

View File

@ -2,7 +2,7 @@ use nu_engine::{CallExt, ClosureEval};
use nu_protocol::{
ast::Call,
engine::{Closure, EngineState, Stack},
IntoPipelineData, PipelineData, ShellError, Span, Value,
IntoPipelineData, PipelineData, ShellError, Span, TryIntoValue, Value,
};
pub fn chain_error_with_input(
@ -36,7 +36,10 @@ pub fn boolean_fold(
break;
}
let pred = closure.run_with_value(value)?.into_value(head)?.is_true();
let pred = closure
.run_with_value(value)?
.try_into_value(head)?
.is_true();
if pred == accumulator {
return Ok(Value::bool(accumulator, head).into_pipeline_data());

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, ClosureEval};
use nu_protocol::engine::Closure;
use nu_protocol::{engine::Closure, TryIntoValue};
#[derive(Clone)]
pub struct Where;
@ -60,7 +60,7 @@ not supported."#
.filter_map(move |value| {
match closure
.run_with_value(value.clone())
.and_then(|data| data.into_value(head))
.and_then(|data| data.try_into_value(head))
{
Ok(cond) => cond.is_true().then_some(value),
Err(err) => Some(Value::error(err, head)),

View File

@ -1,4 +1,5 @@
use nu_engine::command_prelude::*;
use nu_protocol::TryIntoValue;
#[derive(Clone)]
pub struct Wrap;
@ -44,7 +45,7 @@ impl Command for Wrap {
.map(move |x| Value::record(record! { name.clone() => x }, span))
.into_pipeline_data_with_metadata(span, engine_state.ctrlc.clone(), metadata)),
PipelineData::ByteStream(stream, ..) => Ok(Value::record(
record! { name => stream.into_value()? },
record! { name => stream.try_into_value(span)? },
span,
)
.into_pipeline_data_with_metadata(metadata)),

View File

@ -1,7 +1,8 @@
use csv::WriterBuilder;
use nu_cmd_base::formats::to::delimited::merge_descriptors;
use nu_protocol::{
ByteStream, ByteStreamType, Config, PipelineData, ShellError, Span, Spanned, Value,
ByteStream, ByteStreamType, Config, PipelineData, ShellError, Span, Spanned, TryIntoValue,
Value,
};
use std::{iter, sync::Arc};
@ -110,7 +111,7 @@ pub fn to_delimited_data(
None => {
// The columns were not provided. We need to detect them, and in order to do so, we have
// to convert the input into a value first, so that we can find all of them
let value = input.into_value(span)?;
let value = input.try_into_value(span)?;
let columns = match &value {
Value::List { vals, .. } => merge_descriptors(vals),
Value::Record { val, .. } => val.columns().cloned().collect(),

View File

@ -1,5 +1,5 @@
use nu_engine::command_prelude::*;
use nu_protocol::ast::PathMember;
use nu_protocol::{ast::PathMember, TryIntoValue};
#[derive(Clone)]
pub struct ToJson;
@ -46,7 +46,7 @@ impl Command for ToJson {
let span = call.head;
// allow ranges to expand and turn into array
let input = input.try_expand_range()?;
let value = input.into_value(span)?;
let value = input.try_into_value(span)?;
let json_value = value_to_json_value(&value)?;
let json_result = if raw {

View File

@ -5,7 +5,7 @@ use std::io;
use byteorder::{BigEndian, WriteBytesExt};
use nu_engine::command_prelude::*;
use nu_protocol::{ast::PathMember, Spanned};
use nu_protocol::{ast::PathMember, Spanned, TryIntoValue};
use rmp::encode as mp;
/// Max recursion depth
@ -75,7 +75,7 @@ MessagePack: https://msgpack.org/
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let value_span = input.span().unwrap_or(call.head);
let value = input.into_value(value_span)?;
let value = input.try_into_value(value_span)?;
let mut out = vec![];
write_value(&mut out, &value, 0)?;

View File

@ -1,6 +1,7 @@
use std::io::Write;
use nu_engine::command_prelude::*;
use nu_protocol::TryIntoValue;
use super::msgpack::write_value;
@ -70,7 +71,7 @@ impl Command for ToMsgpackz {
.transpose()?;
let value_span = input.span().unwrap_or(call.head);
let value = input.into_value(value_span)?;
let value = input.try_into_value(value_span)?;
let mut out_buf = vec![];
let mut out = brotli::CompressorWriter::new(
&mut out_buf,

View File

@ -1,4 +1,5 @@
use nu_engine::command_prelude::*;
use nu_protocol::TryIntoValue;
#[derive(Clone)]
pub struct ToNuon;
@ -53,7 +54,7 @@ impl Command for ToNuon {
};
let span = call.head;
let value = input.into_value(span)?;
let value = input.try_into_value(span)?;
match nuon::to_nuon(&value, style, Some(span)) {
Ok(serde_nuon_string) => {

View File

@ -1,6 +1,6 @@
use chrono::{DateTime, Datelike, FixedOffset, Timelike};
use nu_engine::command_prelude::*;
use nu_protocol::ast::PathMember;
use nu_protocol::{ast::PathMember, TryIntoValue};
#[derive(Clone)]
pub struct ToToml;
@ -139,7 +139,7 @@ fn to_toml(
input: PipelineData,
span: Span,
) -> Result<PipelineData, ShellError> {
let value = input.into_value(span)?;
let value = input.try_into_value(span)?;
let toml_value = value_to_toml_value(engine_state, &value, span)?;
match toml_value {

View File

@ -2,6 +2,7 @@ use crate::formats::nu_xml_format::{COLUMN_ATTRS_NAME, COLUMN_CONTENT_NAME, COLU
use indexmap::IndexMap;
use nu_engine::command_prelude::*;
use nu_protocol::TryIntoValue;
use quick_xml::{
escape,
events::{BytesEnd, BytesStart, BytesText, Event},
@ -132,7 +133,7 @@ impl Job {
}
fn run(mut self, input: PipelineData, head: Span) -> Result<PipelineData, ShellError> {
let value = input.into_value(head)?;
let value = input.try_into_value(head)?;
self.write_xml_entry(value, true).and_then(|_| {
let b = self.writer.into_inner().into_inner();

View File

@ -1,5 +1,5 @@
use nu_engine::command_prelude::*;
use nu_protocol::ast::PathMember;
use nu_protocol::{ast::PathMember, TryIntoValue};
#[derive(Clone)]
pub struct ToYaml;
@ -95,7 +95,7 @@ pub fn value_to_yaml_value(v: &Value) -> Result<serde_yaml::Value, ShellError> {
}
fn to_yaml(input: PipelineData, head: Span) -> Result<PipelineData, ShellError> {
let value = input.into_value(head)?;
let value = input.try_into_value(head)?;
let yaml_value = value_to_yaml_value(&value)?;
match serde_yaml::to_string(&yaml_value) {

View File

@ -1,6 +1,6 @@
use itertools::unfold;
use nu_engine::{command_prelude::*, ClosureEval};
use nu_protocol::engine::Closure;
use nu_protocol::{engine::Closure, TryIntoValue};
#[derive(Clone)]
pub struct Generate;
@ -159,7 +159,7 @@ used as the next argument to the closure, otherwise generation stops.
Ok(other) => {
let error = other
.into_value(head)
.try_into_value(head)
.map(|val| ShellError::GenericError {
error: "Invalid block return".into(),
msg: format!("Expected record, found {}", val.get_type()),

View File

@ -1,5 +1,6 @@
use itertools::Itertools;
use nu_engine::command_prelude::*;
use nu_protocol::TryIntoValue;
#[derive(Clone)]
pub struct Tutor;
@ -416,7 +417,7 @@ fn display(help: &str, engine_state: &EngineState, stack: &mut Stack, span: Span
Value::string(item, Span::unknown()).into_pipeline_data(),
);
if let Ok(value) = result.and_then(|data| data.into_value(Span::unknown())) {
if let Ok(value) = result.and_then(|data| data.try_into_value(Span::unknown())) {
match value.coerce_into_string() {
Ok(s) => {
build.push_str(&s);

View File

@ -5,7 +5,7 @@ use base64::{
Engine,
};
use nu_engine::command_prelude::*;
use nu_protocol::ByteStream;
use nu_protocol::{ByteStream, TryIntoValue};
use std::{
collections::HashMap,
path::PathBuf,
@ -529,11 +529,11 @@ fn request_handle_response_content(
let response_status = resp.status();
let request_headers_value = headers_to_nu(&extract_request_headers(&request), span)
.and_then(|data| data.into_value(span))
.and_then(|data| data.try_into_value(span))
.unwrap_or(Value::nothing(span));
let response_headers_value = headers_to_nu(&extract_response_headers(&resp), span)
.and_then(|data| data.into_value(span))
.and_then(|data| data.try_into_value(span))
.unwrap_or(Value::nothing(span));
let headers = record! {
@ -541,7 +541,7 @@ fn request_handle_response_content(
"response" => response_headers_value,
};
let body = consume_response_body(resp)?.into_value(span)?;
let body = consume_response_body(resp)?.try_into_value(span)?;
let full_response = Value::record(
record! {

View File

@ -1,4 +1,5 @@
use nu_engine::command_prelude::*;
use nu_protocol::TryIntoValue;
use url::Url;
#[derive(Clone)]
@ -42,7 +43,7 @@ impl Command for SubCommand {
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
parse(input.into_value(call.head)?, call.head, engine_state)
parse(input.try_into_value(call.head)?, call.head, engine_state)
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,6 +1,6 @@
use super::PathSubcommandArguments;
use nu_engine::command_prelude::*;
use nu_protocol::engine::StateWorkingSet;
use nu_protocol::{engine::StateWorkingSet, IntoValue};
use std::path::{Path, PathBuf};
struct Arguments {
@ -171,10 +171,13 @@ fn run(call: &Call, args: &Arguments, input: PipelineData) -> Result<PipelineDat
match input {
PipelineData::Value(val, md) => Ok(PipelineData::Value(handle_value(val, args, head), md)),
PipelineData::ListStream(stream, ..) => Ok(PipelineData::Value(
handle_value(stream.into_value(), args, head),
metadata,
)),
PipelineData::ListStream(stream, ..) => {
let span = stream.span();
Ok(PipelineData::Value(
handle_value(stream.into_value(span), args, head),
metadata,
))
}
PipelineData::Empty { .. } => Err(ShellError::PipelineEmpty { dst_span: head }),
_ => Err(ShellError::UnsupportedInput {
msg: "Input value cannot be joined".to_string(),

View File

@ -3,6 +3,6 @@ pub use nu_protocol::{
ast::{Call, CellPath},
engine::{Command, EngineState, Stack, StateWorkingSet},
record, ByteStream, ByteStreamType, Category, ErrSpan, Example, IntoInterruptiblePipelineData,
IntoPipelineData, IntoSpanned, PipelineData, Record, ShellError, Signature, Span, Spanned,
SyntaxShape, Type, Value,
IntoPipelineData, IntoSpanned, IntoValue, PipelineData, Record, ShellError, Signature, Span,
Spanned, SyntaxShape, TryIntoValue, Type, Value,
};

View File

@ -4,7 +4,7 @@ use nu_protocol::{
debugger::WithoutDebug,
engine::{Command, EngineState, Stack, UNKNOWN_SPAN_ID},
record, Category, Example, IntoPipelineData, PipelineData, Signature, Span, SpanId,
SyntaxShape, Type, Value,
SyntaxShape, TryIntoValue, Type, Value,
};
use std::{collections::HashMap, fmt::Write};
@ -51,7 +51,7 @@ fn nu_highlight_string(code_string: &str, engine_state: &EngineState, stack: &mu
&Call::new(Span::unknown()),
Value::string(code_string, Span::unknown()).into_pipeline_data(),
) {
let result = output.into_value(Span::unknown());
let result = output.try_into_value(Span::unknown());
if let Ok(s) = result.and_then(Value::coerce_into_string) {
return s; // successfully highlighted string
}
@ -277,7 +277,7 @@ fn get_documentation(
Value::string(example.example, Span::unknown()).into_pipeline_data(),
) {
Ok(output) => {
let result = output.into_value(Span::unknown());
let result = output.try_into_value(Span::unknown());
match result.and_then(Value::coerce_into_string) {
Ok(s) => {
let _ = write!(long_desc, "\n > {s}\n");

View File

@ -3,7 +3,7 @@ use nu_path::canonicalize_with;
use nu_protocol::{
ast::{Call, Expr},
engine::{EngineState, Stack, StateWorkingSet},
Config, ShellError, Span, Value, VarId,
Config, ShellError, Span, TryIntoValue, Value, VarId,
};
use std::{
collections::HashMap,
@ -357,7 +357,7 @@ fn get_converted_value(
.debug(false)
.run_with_value(orig_val.clone())
})
.and_then(|data| data.into_value(orig_val.span()))
.and_then(|data| data.try_into_value(orig_val.span()))
.map_or_else(ConversionResult::ConversionError, ConversionResult::Ok)
} else {
ConversionResult::CellPathError

View File

@ -10,7 +10,7 @@ use nu_protocol::{
engine::{Closure, EngineState, Redirection, Stack},
eval_base::Eval,
ByteStreamSource, Config, FromValue, IntoPipelineData, OutDest, PipelineData, ShellError, Span,
Spanned, Type, Value, VarId, ENV_VARIABLE_ID,
Spanned, TryIntoValue, Type, Value, VarId, ENV_VARIABLE_ID,
};
use nu_utils::IgnoreCaseExt;
use std::{borrow::Cow, fs::OpenOptions, path::PathBuf};
@ -275,7 +275,7 @@ pub fn eval_expression_with_input<D: DebugContext>(
let stack = &mut stack.start_capture();
// FIXME: protect this collect with ctrl-c
input = eval_subexpression::<D>(engine_state, stack, block, input)?
.into_value(*span)?
.try_into_value(*span)?
.follow_cell_path(&full_cell_path.tail, false)?
.into_pipeline_data()
} else {
@ -704,7 +704,7 @@ impl Eval for EvalRuntime {
_: Span,
) -> Result<Value, ShellError> {
// FIXME: protect this collect with ctrl-c
eval_call::<D>(engine_state, stack, call, PipelineData::empty())?.into_value(call.head)
eval_call::<D>(engine_state, stack, call, PipelineData::empty())?.try_into_value(call.head)
}
fn eval_external_call(
@ -716,7 +716,7 @@ impl Eval for EvalRuntime {
) -> Result<Value, ShellError> {
let span = head.span(&engine_state);
// FIXME: protect this collect with ctrl-c
eval_external(engine_state, stack, head, args, PipelineData::empty())?.into_value(span)
eval_external(engine_state, stack, head, args, PipelineData::empty())?.try_into_value(span)
}
fn eval_subexpression<D: DebugContext>(
@ -727,7 +727,8 @@ impl Eval for EvalRuntime {
) -> Result<Value, ShellError> {
let block = engine_state.get_block(block_id);
// FIXME: protect this collect with ctrl-c
eval_subexpression::<D>(engine_state, stack, block, PipelineData::empty())?.into_value(span)
eval_subexpression::<D>(engine_state, stack, block, PipelineData::empty())?
.try_into_value(span)
}
fn regex_match(

View File

@ -1,7 +1,9 @@
use super::NuSpan;
use anyhow::Result;
use nu_engine::get_columns;
use nu_protocol::{record, ByteStream, ListStream, PipelineData, PipelineMetadata, Value};
use nu_protocol::{
record, ByteStream, ListStream, PipelineData, PipelineMetadata, TryIntoValue, Value,
};
use std::collections::HashMap;
pub fn collect_pipeline(input: PipelineData) -> Result<(Vec<String>, Vec<Vec<Value>>)> {
@ -63,8 +65,9 @@ fn collect_byte_stream(
}
},
Err(stream) => {
let span = stream.span();
let value = stream
.into_value()
.try_into_value(span)
.unwrap_or_else(|err| Value::error(err, span));
columns.push("".into());

View File

@ -3,7 +3,8 @@ use nu_engine::{get_eval_block_with_early_return, get_full_help, ClosureEvalOnce
use nu_protocol::{
ast::Call,
engine::{Closure, EngineState, Redirection, Stack},
Config, IntoSpanned, OutDest, PipelineData, PluginIdentity, ShellError, Span, Spanned, Value,
Config, IntoSpanned, OutDest, PipelineData, PluginIdentity, ShellError, Span, Spanned,
TryIntoValue, Value,
};
use std::{
borrow::Cow,
@ -108,7 +109,7 @@ impl<'a> PluginExecutionContext for PluginExecutionCommandContext<'a> {
Value::Closure { val, .. } => {
ClosureEvalOnce::new(&self.engine_state, &self.stack, *val)
.run_with_input(PipelineData::Empty)
.and_then(|data| data.into_value(span))
.and_then(|data| data.try_into_value(span))
.unwrap_or_else(|err| Value::error(err, self.call.head))
}
_ => value.clone(),

View File

@ -12,7 +12,7 @@ use nu_plugin_protocol::{
};
use nu_protocol::{
ast::Operator, CustomValue, IntoSpanned, PipelineData, PluginSignature, ShellError, Span,
Spanned, Value,
Spanned, TryIntoValue, Value,
};
use std::{
collections::{btree_map, BTreeMap},
@ -953,7 +953,7 @@ impl PluginInterface {
let call = PluginCall::CustomValueOp(value.map(|cv| cv.without_source()), op);
match self.plugin_call(call, None)? {
PluginCallResponse::PipelineData(out_data) => out_data.into_value(span),
PluginCallResponse::PipelineData(out_data) => out_data.try_into_value(span),
PluginCallResponse::Error(err) => Err(err.into()),
_ => Err(ShellError::PluginFailedToDecode {
msg: format!("Received unexpected response to custom value {op_name}() call"),

View File

@ -17,8 +17,8 @@ use nu_plugin_protocol::{
use nu_protocol::{
ast::{Math, Operator},
engine::Closure,
ByteStreamType, CustomValue, IntoInterruptiblePipelineData, IntoSpanned, PipelineData,
PluginSignature, ShellError, Span, Spanned, Value,
ByteStreamType, CustomValue, IntoInterruptiblePipelineData, IntoSpanned, IntoValue,
PipelineData, PluginSignature, ShellError, Span, Spanned, TryIntoValue, Value,
};
use serde::{Deserialize, Serialize};
use std::{
@ -1066,7 +1066,7 @@ fn interface_run() -> Result<(), ShellError> {
assert_eq!(
Value::test_int(number),
result.into_value(Span::test_data())?,
result.try_into_value(Span::test_data())?,
);
assert!(test.has_unconsumed_write());
Ok(())
@ -1115,7 +1115,7 @@ fn interface_prepare_pipeline_data_accepts_normal_values() -> Result<(), ShellEr
match interface.prepare_pipeline_data(PipelineData::Value(value.clone(), None), &state) {
Ok(data) => assert_eq!(
value.get_type(),
data.into_value(Span::test_data())?.get_type(),
data.try_into_value(Span::test_data())?.get_type(),
),
Err(err) => panic!("failed to accept {value:?}: {err}"),
}

View File

@ -2,7 +2,9 @@ use std::{cmp::Ordering, sync::Arc};
use nu_plugin_core::util::with_custom_values_in;
use nu_plugin_protocol::PluginCustomValue;
use nu_protocol::{ast::Operator, CustomValue, IntoSpanned, ShellError, Span, Spanned, Value};
use nu_protocol::{
ast::Operator, CustomValue, IntoSpanned, IntoValue, ShellError, Span, Spanned, Value,
};
use serde::Serialize;
use crate::{PluginInterface, PluginSource};
@ -27,11 +29,6 @@ impl PluginCustomValueWithSource {
PluginCustomValueWithSource { inner, source }
}
/// Create a [`Value`] containing this custom value.
pub fn into_value(self, span: Span) -> Value {
Value::custom(Box::new(self), span)
}
/// Which plugin the custom value came from. This provides a direct reference to be able to get
/// a plugin interface in order to make a call, when needed.
pub fn source(&self) -> &Arc<PluginSource> {
@ -133,6 +130,12 @@ impl PluginCustomValueWithSource {
}
}
impl IntoValue for PluginCustomValueWithSource {
fn into_value(self, span: Span) -> Value {
Value::custom(Box::new(self), span)
}
}
impl std::ops::Deref for PluginCustomValueWithSource {
type Target = PluginCustomValue;

View File

@ -1,6 +1,6 @@
use std::cmp::Ordering;
use nu_protocol::{ast::Operator, CustomValue, ShellError, Span, Value};
use nu_protocol::{ast::Operator, CustomValue, IntoValue, ShellError, Span, Value};
use nu_utils::SharedCow;
use serde::{Deserialize, Serialize};
@ -109,11 +109,6 @@ impl PluginCustomValue {
}))
}
/// Create a [`Value`] containing this custom value.
pub fn into_value(self, span: Span) -> Value {
Value::custom(Box::new(self), span)
}
/// The name of the type of the custom value as defined by the plugin (`type_name()`)
pub fn name(&self) -> &str {
&self.0.name
@ -219,3 +214,9 @@ impl PluginCustomValue {
})
}
}
impl IntoValue for PluginCustomValue {
fn into_value(self, span: Span) -> Value {
Value::custom(Box::new(self), span)
}
}

View File

@ -11,7 +11,7 @@ use nu_protocol::{
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
report_error_new, CustomValue, Example, IntoSpanned as _, LabeledError, PipelineData,
ShellError, Span, Value,
ShellError, Span, TryIntoValue, Value,
};
use crate::{diff::diff_by_line, fake_register::fake_register};
@ -230,7 +230,7 @@ impl PluginTest {
if let Some(expectation) = &example.result {
match self.eval(example.example) {
Ok(data) => {
let mut value = data.into_value(Span::test_data())?;
let mut value = data.try_into_value(Span::test_data())?;
// Set all of the spans in the value to test_data() to avoid unnecessary
// differences when printing

View File

@ -3,7 +3,8 @@ use std::cmp::Ordering;
use nu_plugin::{EngineInterface, EvaluatedCall, Plugin, SimplePluginCommand};
use nu_plugin_test_support::PluginTest;
use nu_protocol::{
CustomValue, Example, LabeledError, PipelineData, ShellError, Signature, Span, Type, Value,
CustomValue, Example, IntoValue, LabeledError, PipelineData, ShellError, Signature, Span,
TryIntoValue, Type, Value,
};
use serde::{Deserialize, Serialize};
@ -11,8 +12,8 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq)]
struct CustomU32(u32);
impl CustomU32 {
pub fn into_value(self, span: Span) -> Value {
impl IntoValue for CustomU32 {
fn into_value(self, span: Span) -> Value {
Value::custom(Box::new(self), span)
}
}
@ -143,7 +144,7 @@ fn test_into_int_from_u32() -> Result<(), ShellError> {
"into int from u32",
PipelineData::Value(CustomU32(42).into_value(Span::test_data()), None),
)?
.into_value(Span::test_data())?;
.try_into_value(Span::test_data())?;
assert_eq!(Value::test_int(42), result);
Ok(())
}

View File

@ -2,7 +2,7 @@
use nu_plugin::*;
use nu_plugin_test_support::PluginTest;
use nu_protocol::{Example, LabeledError, ShellError, Signature, Type, Value};
use nu_protocol::{Example, LabeledError, ShellError, Signature, TryIntoValue, Type, Value};
struct HelloPlugin;
struct Hello;
@ -80,7 +80,7 @@ fn test_requiring_nu_cmd_lang_commands() -> Result<(), ShellError> {
let result = PluginTest::new("hello", HelloPlugin.into())?
.eval("do { let greeting = hello; $greeting }")?
.into_value(Span::test_data())?;
.try_into_value(Span::test_data())?;
assert_eq!(Value::test_string("Hello, World!"), result);

View File

@ -2,7 +2,7 @@ use nu_plugin::*;
use nu_plugin_test_support::PluginTest;
use nu_protocol::{
Example, IntoInterruptiblePipelineData, LabeledError, PipelineData, ShellError, Signature,
Span, Type, Value,
Span, TryIntoValue, Type, Value,
};
struct LowercasePlugin;
@ -73,7 +73,7 @@ fn test_lowercase_using_eval_with() -> Result<(), ShellError> {
assert_eq!(
Value::test_list(vec![Value::test_string("hello world")]),
result.into_value(Span::test_data())?
result.try_into_value(Span::test_data())?
);
Ok(())

View File

@ -1,6 +1,6 @@
use nu_protocol::{
Example, IntoSpanned, LabeledError, PipelineData, PluginExample, PluginSignature, ShellError,
Signature, Value,
Signature, TryIntoValue, Value,
};
use crate::{EngineInterface, EvaluatedCall, Plugin};
@ -313,7 +313,7 @@ where
// Unwrap the PipelineData from input, consuming the potential stream, and pass it to the
// simpler signature in Plugin
let span = input.span().unwrap_or(call.head);
let input_value = input.into_value(span)?;
let input_value = input.try_into_value(span)?;
// Wrap the output in PipelineData::Value
<Self as SimplePluginCommand>::run(self, plugin, engine, call, &input_value)
.map(|value| PipelineData::Value(value, None))

View File

@ -12,7 +12,7 @@ use nu_plugin_protocol::{
};
use nu_protocol::{
engine::Closure, Config, LabeledError, PipelineData, PluginSignature, ShellError, Span,
Spanned, Value,
Spanned, TryIntoValue, Value,
};
use std::{
collections::{btree_map, BTreeMap, HashMap},
@ -850,7 +850,7 @@ impl EngineInterface {
let input = input.map_or_else(|| PipelineData::Empty, |v| PipelineData::Value(v, None));
let output = self.eval_closure_with_stream(closure, positional, input, true, false)?;
// Unwrap an error value
match output.into_value(closure.span)? {
match output.try_into_value(closure.span)? {
Value::Error { error, .. } => Err(*error),
value => Ok(value),
}

View File

@ -10,7 +10,7 @@ use nu_plugin_protocol::{
};
use nu_protocol::{
engine::Closure, ByteStreamType, Config, CustomValue, IntoInterruptiblePipelineData,
LabeledError, PipelineData, PluginSignature, ShellError, Span, Spanned, Value,
LabeledError, PipelineData, PluginSignature, ShellError, Span, Spanned, TryIntoValue, Value,
};
use std::{
collections::HashMap,
@ -1039,7 +1039,7 @@ fn interface_eval_closure_with_stream() -> Result<(), ShellError> {
true,
false,
)?
.into_value(Span::test_data())?;
.try_into_value(Span::test_data())?;
assert_eq!(Value::test_int(2), result);

View File

@ -3,7 +3,8 @@ use crate::{
debugger::{DebugContext, WithoutDebug},
engine::{EngineState, StateWorkingSet},
eval_base::Eval,
record, Config, HistoryFileFormat, PipelineData, Record, ShellError, Span, Value, VarId,
record, Config, HistoryFileFormat, PipelineData, Record, ShellError, Span, TryIntoValue, Value,
VarId,
};
use nu_system::os_info::{get_kernel_version, get_os_arch, get_os_family, get_os_name};
use std::{
@ -349,7 +350,7 @@ impl Eval for EvalConst {
) -> Result<Value, ShellError> {
// TODO: Allow debugging const eval
// TODO: eval.rs uses call.head for the span rather than expr.span
eval_const_call(working_set, call, PipelineData::empty())?.into_value(span)
eval_const_call(working_set, call, PipelineData::empty())?.try_into_value(span)
}
fn eval_external_call(
@ -371,7 +372,8 @@ impl Eval for EvalConst {
) -> Result<Value, ShellError> {
// TODO: Allow debugging const eval
let block = working_set.get_block(block_id);
eval_const_subexpression(working_set, block, PipelineData::empty(), span)?.into_value(span)
eval_const_subexpression(working_set, block, PipelineData::empty(), span)?
.try_into_value(span)
}
fn regex_match(

View File

@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use crate::{
process::{ChildPipe, ChildProcess, ExitStatus},
ErrSpan, IntoSpanned, OutDest, PipelineData, ShellError, Span, Type, Value,
ErrSpan, IntoSpanned, OutDest, PipelineData, ShellError, Span, TryIntoValue, Type, Value,
};
#[cfg(unix)]
use std::os::fd::OwnedFd;
@ -166,9 +166,10 @@ impl From<ByteStreamType> for Type {
/// Additionally, there are few methods to collect a [`Bytestream`] into memory:
/// - [`into_bytes`](ByteStream::into_bytes): collects all bytes into a [`Vec<u8>`].
/// - [`into_string`](ByteStream::into_string): collects all bytes into a [`String`], erroring if utf-8 decoding failed.
/// - [`into_value`](ByteStream::into_value): collects all bytes into a value typed appropriately
/// for the [type](.type_()) of this stream. If the type is [`Unknown`](ByteStreamType::Unknown),
/// it will produce a string value if the data is valid UTF-8, or a binary value otherwise.
/// - [`try_into_value`](ByteStream::try_into_value): collects all bytes into a value typed
/// appropriately for the [type](.type_()) of this stream.
/// If the type is [`Unknown`](ByteStreamType::Unknown), it will produce a string value if the
/// data is valid UTF-8, or a binary value otherwise.
///
/// There are also a few other methods to consume all the data of a [`Bytestream`]:
/// - [`drain`](ByteStream::drain): consumes all bytes and outputs nothing.
@ -512,37 +513,10 @@ impl ByteStream {
}
}
/// Collect all the bytes of the [`ByteStream`] into a [`Value`].
///
/// If this is a `String` stream, the stream is decoded to UTF-8. If the stream came from an
/// external process or file, the trailing new line (`\n` or `\r\n`), if any, is removed from
/// the [`String`] prior to being returned.
///
/// If this is a `Binary` stream, a [`Value::Binary`] is returned with any trailing new lines
/// preserved.
///
/// If this is an `Unknown` stream, the behavior depends on whether the stream parses as valid
/// UTF-8 or not. If it does, this is uses the `String` behavior; if not, it uses the `Binary`
/// behavior.
#[deprecated = "use `TryIntoValue::try_into_value` instead"]
pub fn into_value(self) -> Result<Value, ShellError> {
let span = self.span;
let trim = self.stream.is_external();
let value = match self.type_ {
// If the type is specified, then the stream should always become that type:
ByteStreamType::Binary => Value::binary(self.into_bytes()?, span),
ByteStreamType::String => Value::string(self.into_string()?, span),
// If the type is not specified, then it just depends on whether it parses or not:
ByteStreamType::Unknown => match String::from_utf8(self.into_bytes()?) {
Ok(mut str) => {
if trim {
trim_end_newline(&mut str);
}
Value::string(str, span)
}
Err(err) => Value::binary(err.into_bytes(), span),
},
};
Ok(value)
let span = self.span();
Self::try_into_value(self, span)
}
/// Consume and drop all bytes of the [`ByteStream`].
@ -686,6 +660,41 @@ impl ByteStream {
}
}
impl TryIntoValue for ByteStream {
/// Collect all the bytes of the [`ByteStream`] into a [`Value`].
///
/// If this is a `String` stream, the stream is decoded to UTF-8. If the stream came from an
/// external process or file, the trailing new line (`\n` or `\r\n`), if any, is removed from
/// the [`String`] prior to being returned.
///
/// If this is a `Binary` stream, a [`Value::Binary`] is returned with any trailing new lines
/// preserved.
///
/// If this is an `Unknown` stream, the behavior depends on whether the stream parses as valid
/// UTF-8 or not. If it does, this is uses the `String` behavior; if not, it uses the `Binary`
/// behavior.
fn try_into_value(self, _: Span) -> Result<Value, ShellError> {
let span = self.span;
let trim = self.stream.is_external();
let value = match self.type_ {
// If the type is specified, then the stream should always become that type:
ByteStreamType::Binary => Value::binary(self.into_bytes()?, span),
ByteStreamType::String => Value::string(self.into_string()?, span),
// If the type is not specified, then it just depends on whether it parses or not:
ByteStreamType::Unknown => match String::from_utf8(self.into_bytes()?) {
Ok(mut str) => {
if trim {
trim_end_newline(&mut str);
}
Value::string(str, span)
}
Err(err) => Value::binary(err.into_bytes(), span),
},
};
Ok(value)
}
}
impl From<ByteStream> for PipelineData {
fn from(stream: ByteStream) -> Self {
Self::ByteStream(stream, None)

View File

@ -1,4 +1,4 @@
use crate::{Config, PipelineData, ShellError, Span, Value};
use crate::{Config, IntoValue, PipelineData, ShellError, Span, Value};
use std::{
fmt::Debug,
sync::{atomic::AtomicBool, Arc},
@ -48,11 +48,6 @@ impl ListStream {
.join(separator)
}
/// Collect the values of a [`ListStream`] into a list [`Value`].
pub fn into_value(self) -> Value {
Value::list(self.stream.collect(), self.span)
}
/// Consume all values in the stream, returning an error if any of the values is a `Value::Error`.
pub fn drain(self) -> Result<(), ShellError> {
for next in self {
@ -98,6 +93,13 @@ impl Debug for ListStream {
}
}
impl IntoValue for ListStream {
/// Collect the values of a [`ListStream`] into a list [`Value`].
fn into_value(self, _: Span) -> Value {
Value::list(self.stream.collect(), self.span)
}
}
impl IntoIterator for ListStream {
type Item = Value;

View File

@ -2,8 +2,8 @@ use crate::{
ast::{Call, PathMember},
engine::{EngineState, Stack},
process::{ChildPipe, ChildProcess, ExitStatus},
ByteStream, ByteStreamType, Config, ErrSpan, ListStream, OutDest, PipelineMetadata, Range,
ShellError, Span, Type, Value,
ByteStream, ByteStreamType, Config, ErrSpan, IntoValue, ListStream, OutDest, PipelineMetadata,
Range, ShellError, Span, TryIntoValue, Type, Value,
};
use nu_utils::{stderr_write_all_and_flush, stdout_write_all_and_flush};
use std::{
@ -117,13 +117,9 @@ impl PipelineData {
}
}
#[deprecated = "use `TryIntoValue::try_into_value` instead"]
pub fn into_value(self, span: Span) -> Result<Value, ShellError> {
match self {
PipelineData::Empty => Ok(Value::nothing(span)),
PipelineData::Value(value, ..) => Ok(value.with_span(span)),
PipelineData::ListStream(stream, ..) => Ok(stream.into_value()),
PipelineData::ByteStream(stream, ..) => stream.into_value(),
}
Self::try_into_value(self, span)
}
/// Writes all values or redirects all output to the current [`OutDest`]s in `stack`.
@ -333,7 +329,8 @@ impl PipelineData {
Ok(PipelineData::ListStream(stream.map(f), metadata))
}
PipelineData::ByteStream(stream, metadata) => {
Ok(f(stream.into_value()?).into_pipeline_data_with_metadata(metadata))
let span = stream.span();
Ok(f(stream.try_into_value(span)?).into_pipeline_data_with_metadata(metadata))
}
}
}
@ -612,6 +609,17 @@ impl PipelineData {
}
}
impl TryIntoValue for PipelineData {
fn try_into_value(self, span: Span) -> Result<Value, ShellError> {
match self {
PipelineData::Empty => Ok(Value::nothing(span)),
PipelineData::Value(value, ..) => Ok(value.with_span(span)),
PipelineData::ListStream(stream, ..) => Ok(stream.into_value(span)),
PipelineData::ByteStream(stream, ..) => stream.try_into_value(span),
}
}
}
enum PipelineIteratorInner {
Empty,
Value(Value),

View File

@ -1,4 +1,4 @@
use nu_protocol::{IntoPipelineData, Span, Value};
use nu_protocol::{IntoPipelineData, Span, TryIntoValue, Value};
#[test]
fn test_convert_pipeline_data_to_value() {
@ -9,7 +9,7 @@ fn test_convert_pipeline_data_to_value() {
// Test that conversion into Value is correct
let new_span = Span::new(5, 6);
let converted_value = pipeline_data.into_value(new_span);
let converted_value = pipeline_data.try_into_value(new_span);
assert_eq!(converted_value, Ok(Value::int(value_val, new_span)));
}

View File

@ -1,4 +1,4 @@
use nu_protocol::{ast, CustomValue, ShellError, Span, Value};
use nu_protocol::{ast, CustomValue, IntoValue, ShellError, Span, Value};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
@ -14,10 +14,6 @@ impl CoolCustomValue {
}
}
pub fn into_value(self, span: Span) -> Value {
Value::custom(Box::new(self), span)
}
pub fn try_from_value(value: &Value) -> Result<Self, ShellError> {
let span = value.span();
match value {
@ -43,6 +39,12 @@ impl CoolCustomValue {
}
}
impl IntoValue for CoolCustomValue {
fn into_value(self, span: Span) -> Value {
Value::custom(Box::new(self), span)
}
}
#[typetag::serde]
impl CustomValue for CoolCustomValue {
fn clone_value(&self, span: Span) -> Value {

View File

@ -1,6 +1,6 @@
use crate::{cool_custom_value::CoolCustomValue, CustomValuePlugin};
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{Category, Example, LabeledError, Signature, Span, Value};
use nu_protocol::{Category, Example, IntoValue, LabeledError, Signature, Span, Value};
pub struct Generate;

View File

@ -1,6 +1,8 @@
use crate::{second_custom_value::SecondCustomValue, CustomValuePlugin};
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{Category, Example, LabeledError, Signature, Span, SyntaxShape, Value};
use nu_protocol::{
Category, Example, IntoValue, LabeledError, Signature, Span, SyntaxShape, Value,
};
pub struct Generate2;

View File

@ -1,12 +1,12 @@
use nu_protocol::{CustomValue, LabeledError, ShellError, Span, Value};
use nu_protocol::{CustomValue, IntoValue, LabeledError, ShellError, Span, Value};
use serde::{Deserialize, Serialize};
/// References a stored handle within the plugin
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HandleCustomValue(pub u64);
impl HandleCustomValue {
pub fn into_value(self, span: Span) -> Value {
impl IntoValue for HandleCustomValue {
fn into_value(self, span: Span) -> Value {
Value::custom(Box::new(self), span)
}
}

View File

@ -1,6 +1,6 @@
use std::cmp::Ordering;
use nu_protocol::{CustomValue, ShellError, Span, Value};
use nu_protocol::{CustomValue, IntoValue, ShellError, Span, Value};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
@ -15,10 +15,6 @@ impl SecondCustomValue {
}
}
pub fn into_value(self, span: Span) -> Value {
Value::custom(Box::new(self), span)
}
pub fn try_from_value(value: &Value) -> Result<Self, ShellError> {
let span = value.span();
match value {
@ -41,6 +37,12 @@ impl SecondCustomValue {
}
}
impl IntoValue for SecondCustomValue {
fn into_value(self, span: Span) -> Value {
Value::custom(Box::new(self), span)
}
}
#[typetag::serde]
impl CustomValue for SecondCustomValue {
fn clone_value(&self, span: nu_protocol::Span) -> Value {

View File

@ -2,7 +2,7 @@ use crate::{
cool_custom_value::CoolCustomValue, second_custom_value::SecondCustomValue, CustomValuePlugin,
};
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{Category, Example, LabeledError, ShellError, Signature, Span, Value};
use nu_protocol::{Category, Example, IntoValue, LabeledError, ShellError, Signature, Span, Value};
pub struct Update;

View File

@ -1,7 +1,7 @@
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type,
Value,
Category, Example, IntoValue, LabeledError, PipelineData, ShellError, Signature, Span,
SyntaxShape, Type, Value,
};
use polars::{prelude::NamedFrom, series::Series};
use uuid::Uuid;

View File

@ -8,7 +8,7 @@ use super::super::values::NuDataFrame;
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
record, Category, Example, LabeledError, PipelineData, ShellError, Signature, Span,
SyntaxShape, Type, Value,
SyntaxShape, TryIntoValue, Type, Value,
};
use polars::prelude::*;
@ -91,7 +91,7 @@ impl PluginCommand for CastDF {
call: &EvaluatedCall,
input: PipelineData,
) -> Result<PipelineData, LabeledError> {
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
match PolarsPluginObject::try_from_value(plugin, &value)? {
PolarsPluginObject::NuLazyFrame(lazy) => {
let (dtype, column_nm) = df_args(call)?;

View File

@ -1,7 +1,7 @@
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type,
Value,
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape,
TryIntoValue, Type, Value,
};
use polars::prelude::LazyFrame;
@ -84,7 +84,7 @@ impl PluginCommand for FilterWith {
call: &EvaluatedCall,
input: PipelineData,
) -> Result<PipelineData, LabeledError> {
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
match PolarsPluginObject::try_from_value(plugin, &value)? {
PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df),
PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy),

View File

@ -6,8 +6,8 @@ use crate::{
use super::super::values::{NuDataFrame, NuExpression};
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type,
Value,
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape,
TryIntoValue, Type, Value,
};
#[derive(Clone)]
@ -97,7 +97,7 @@ impl PluginCommand for FirstDF {
call: &EvaluatedCall,
input: PipelineData,
) -> Result<PipelineData, LabeledError> {
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
if NuDataFrame::can_downcast(&value) || NuLazyFrame::can_downcast(&value) {
let df = NuDataFrame::try_from_value_coerce(plugin, &value, call.head)?;
command(plugin, engine, call, df).map_err(|e| e.into())

View File

@ -6,8 +6,8 @@ use crate::{
use super::super::values::{utils::DEFAULT_ROWS, NuDataFrame, NuExpression};
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type,
Value,
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape,
TryIntoValue, Type, Value,
};
#[derive(Clone)]
@ -72,7 +72,7 @@ impl PluginCommand for LastDF {
call: &EvaluatedCall,
input: PipelineData,
) -> Result<PipelineData, LabeledError> {
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
if NuDataFrame::can_downcast(&value) || NuLazyFrame::can_downcast(&value) {
let df = NuDataFrame::try_from_value_coerce(plugin, &value, call.head)?;
command(plugin, engine, call, df).map_err(|e| e.into())

View File

@ -1,7 +1,7 @@
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type,
Value,
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape,
TryIntoValue, Type, Value,
};
use crate::{
@ -120,7 +120,7 @@ impl PluginCommand for RenameDF {
call: &EvaluatedCall,
input: PipelineData,
) -> Result<PipelineData, LabeledError> {
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
match PolarsPluginObject::try_from_value(plugin, &value).map_err(LabeledError::from)? {
PolarsPluginObject::NuDataFrame(df) => {
command_eager(plugin, engine, call, df).map_err(LabeledError::from)

View File

@ -1,7 +1,7 @@
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
record, Category, Example, LabeledError, PipelineData, ShellError, Signature, Span,
SyntaxShape, Type, Value,
SyntaxShape, TryIntoValue, Type, Value,
};
use crate::{
@ -90,7 +90,7 @@ impl PluginCommand for ToNu {
call: &EvaluatedCall,
input: PipelineData,
) -> Result<PipelineData, LabeledError> {
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
if NuDataFrame::can_downcast(&value) || NuLazyFrame::can_downcast(&value) {
dataframe_command(plugin, call, value)
} else {

View File

@ -6,8 +6,8 @@ use crate::{
};
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type,
Value,
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape,
TryIntoValue, Type, Value,
};
#[derive(Clone)]
@ -113,7 +113,7 @@ impl PluginCommand for WithColumn {
call: &EvaluatedCall,
input: PipelineData,
) -> Result<PipelineData, LabeledError> {
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
match PolarsPluginObject::try_from_value(plugin, &value)? {
PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df),
PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy),

View File

@ -5,7 +5,9 @@ use crate::dataframe::values::{Column, NuDataFrame, NuExpression, NuLazyFrame};
use crate::values::CustomValueSupport;
use crate::PolarsPlugin;
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{Category, Example, LabeledError, PipelineData, Signature, Span, Type, Value};
use nu_protocol::{
Category, Example, LabeledError, PipelineData, Signature, Span, TryIntoValue, Type, Value,
};
// The structs defined in this file are structs that form part of other commands
// since they share a similar name
@ -158,7 +160,7 @@ macro_rules! lazy_expr_command {
call: &EvaluatedCall,
input: PipelineData,
) -> Result<PipelineData, LabeledError> {
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
if NuDataFrame::can_downcast(&value) || NuLazyFrame::can_downcast(&value) {
let lazy = NuLazyFrame::try_from_value_coerce(plugin, &value)
.map_err(LabeledError::from)?;
@ -228,7 +230,7 @@ macro_rules! lazy_expr_command {
call: &EvaluatedCall,
input: PipelineData,
) -> Result<PipelineData, LabeledError> {
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
if NuDataFrame::can_downcast(&value) || NuLazyFrame::can_downcast(&value) {
let lazy = NuLazyFrame::try_from_value_coerce(plugin, &value)
.map_err(LabeledError::from)?;

View File

@ -5,8 +5,8 @@ use crate::{
};
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type,
Value,
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape,
TryIntoValue, Type, Value,
};
use polars::prelude::{is_in, lit, DataType, IntoSeries};
@ -114,7 +114,7 @@ impl PluginCommand for ExprIsIn {
call: &EvaluatedCall,
input: PipelineData,
) -> Result<PipelineData, LabeledError> {
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
match PolarsPluginObject::try_from_value(plugin, &value)? {
PolarsPluginObject::NuDataFrame(df) => command_df(plugin, engine, call, df),
PolarsPluginObject::NuLazyFrame(lazy) => {

View File

@ -5,7 +5,8 @@ use crate::{
};
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, Type, Value,
Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, TryIntoValue,
Type, Value,
};
#[derive(Clone)]
@ -99,7 +100,7 @@ impl PluginCommand for ExprOtherwise {
let otherwise_predicate: Value = call.req(0)?;
let otherwise_predicate = NuExpression::try_from_value(plugin, &otherwise_predicate)?;
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
let complete: NuExpression = match NuWhen::try_from_value(plugin, &value)?.when_type {
NuWhenType::Then(then) => then.otherwise(otherwise_predicate.into_polars()).into(),
NuWhenType::ChainedThen(chained_when) => chained_when

View File

@ -5,7 +5,8 @@ use crate::{
};
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, Type, Value,
Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, TryIntoValue,
Type, Value,
};
use polars::prelude::when;
@ -111,7 +112,7 @@ impl PluginCommand for ExprWhen {
let then_predicate: Value = call.req(1)?;
let then_predicate = NuExpression::try_from_value(plugin, &then_predicate)?;
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
let when_then: NuWhen = match value {
Value::Nothing { .. } => when(when_predicate.into_polars())
.then(then_predicate.into_polars())

View File

@ -5,7 +5,9 @@ use crate::{
};
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{Category, Example, LabeledError, PipelineData, Signature, Span, Type, Value};
use nu_protocol::{
Category, Example, LabeledError, PipelineData, Signature, Span, TryIntoValue, Type, Value,
};
#[derive(Clone)]
pub struct LazyCollect;
@ -61,7 +63,7 @@ impl PluginCommand for LazyCollect {
call: &EvaluatedCall,
input: PipelineData,
) -> Result<PipelineData, LabeledError> {
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
match PolarsPluginObject::try_from_value(plugin, &value)? {
PolarsPluginObject::NuLazyFrame(lazy) => {
let mut eager = lazy.collect(call.head)?;

View File

@ -4,8 +4,8 @@ use crate::PolarsPlugin;
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type,
Value,
Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape,
TryIntoValue, Type, Value,
};
#[derive(Clone)]
@ -116,7 +116,7 @@ pub(crate) fn explode(
call: &EvaluatedCall,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let value = input.into_value(call.head)?;
let value = input.try_into_value(call.head)?;
match PolarsPluginObject::try_from_value(plugin, &value)? {
PolarsPluginObject::NuDataFrame(df) => {
let lazy = df.lazy();

Some files were not shown because too many files have changed in this diff Show More