Convert Shellerror::GenericError to named fields (#11230)

# Description

Replace `.to_string()` used in `GenericError` with `.into()` as
`.into()` seems more popular

Replace `Vec::new()` used in `GenericError` with `vec![]` as `vec![]`
seems more popular

(There are so, so many)
This commit is contained in:
Eric Hodel 2023-12-06 15:40:03 -08:00 committed by GitHub
parent b03f1efac4
commit a95a4505ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
160 changed files with 2975 additions and 3228 deletions

View File

@ -45,13 +45,13 @@ impl Command for KeybindingsListen {
Ok(v) => Ok(v.into_pipeline_data()), Ok(v) => Ok(v.into_pipeline_data()),
Err(e) => { Err(e) => {
terminal::disable_raw_mode()?; terminal::disable_raw_mode()?;
Err(ShellError::GenericError( Err(ShellError::GenericError {
"Error with input".to_string(), error: "Error with input".into(),
"".to_string(), msg: "".into(),
None, span: None,
Some(e.to_string()), help: Some(e.to_string()),
Vec::new(), inner: vec![],
)) })
} }
} }
} }

View File

@ -773,23 +773,21 @@ pub fn get_command_finished_marker(stack: &Stack, engine_state: &EngineState) ->
} }
fn run_ansi_sequence(seq: &str) -> Result<(), ShellError> { fn run_ansi_sequence(seq: &str) -> Result<(), ShellError> {
io::stdout().write_all(seq.as_bytes()).map_err(|e| { io::stdout()
ShellError::GenericError( .write_all(seq.as_bytes())
"Error writing ansi sequence".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error writing ansi sequence".into(),
Some(Span::unknown()), msg: e.to_string(),
None, span: Some(Span::unknown()),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
io::stdout().flush().map_err(|e| { io::stdout().flush().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error flushing stdio".into(),
"Error flushing stdio".into(), msg: e.to_string(),
e.to_string(), span: Some(Span::unknown()),
Some(Span::unknown()), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
} }

View File

@ -43,13 +43,13 @@ fn gather_env_vars(
let working_set = StateWorkingSet::new(engine_state); let working_set = StateWorkingSet::new(engine_state);
report_error( report_error(
&working_set, &working_set,
&ShellError::GenericError( &ShellError::GenericError {
format!("Environment variable was not captured: {env_str}"), error: format!("Environment variable was not captured: {env_str}"),
"".to_string(), msg: "".into(),
None, span: None,
Some(msg.into()), help: Some(msg.into()),
Vec::new(), inner: vec![],
), },
); );
} }
@ -75,15 +75,15 @@ fn gather_env_vars(
let working_set = StateWorkingSet::new(engine_state); let working_set = StateWorkingSet::new(engine_state);
report_error( report_error(
&working_set, &working_set,
&ShellError::GenericError( &ShellError::GenericError {
"Current directory is not a valid utf-8 path".to_string(), error: "Current directory is not a valid utf-8 path".into(),
"".to_string(), msg: "".into(),
None, span: None,
Some(format!( help: Some(format!(
"Retrieving current directory failed: {init_cwd:?} not a valid utf-8 path" "Retrieving current directory failed: {init_cwd:?} not a valid utf-8 path"
)), )),
Vec::new(), inner: vec![],
), },
); );
} }
} }

View File

@ -72,22 +72,22 @@ fn get_editor_commandline(
let params = editor_cmd.collect::<Result<_, ShellError>>()?; let params = editor_cmd.collect::<Result<_, ShellError>>()?;
Ok((editor, params)) Ok((editor, params))
} }
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Editor executable is missing".into(), error: "Editor executable is missing".into(),
"Set the first element to an executable".into(), msg: "Set the first element to an executable".into(),
Some(value.span()), span: Some(value.span()),
Some(HELP_MSG.into()), help: Some(HELP_MSG.into()),
vec![], inner: vec![],
)), }),
} }
} }
Value::String { .. } | Value::List { .. } => Err(ShellError::GenericError( Value::String { .. } | Value::List { .. } => Err(ShellError::GenericError {
format!("{var_name} should be a non-empty string or list<String>"), error: format!("{var_name} should be a non-empty string or list<String>"),
"Specify an executable here".into(), msg: "Specify an executable here".into(),
Some(value.span()), span: Some(value.span()),
Some(HELP_MSG.into()), help: Some(HELP_MSG.into()),
vec![], inner: vec![],
)), }),
x => Err(ShellError::CantConvert { x => Err(ShellError::CantConvert {
to_type: "string or list<string>".into(), to_type: "string or list<string>".into(),
from_type: x.get_type().to_string(), from_type: x.get_type().to_string(),
@ -114,13 +114,14 @@ pub fn get_editor(
} else if let Some(value) = env_vars.get("VISUAL") { } else if let Some(value) = env_vars.get("VISUAL") {
get_editor_commandline(value, "$env.VISUAL") get_editor_commandline(value, "$env.VISUAL")
} else { } else {
Err(ShellError::GenericError( Err(ShellError::GenericError {
"No editor configured".into(), error: "No editor configured".into(),
"Please specify one via `$env.config.buffer_editor` or `$env.EDITOR`/`$env.VISUAL`" msg:
.into(), "Please specify one via `$env.config.buffer_editor` or `$env.EDITOR`/`$env.VISUAL`"
Some(span), .into(),
Some(HELP_MSG.into()), span: Some(span),
vec![], help: Some(HELP_MSG.into()),
)) inner: vec![],
})
} }
} }

View File

@ -69,25 +69,23 @@ fn command(
let new_df = col_string let new_df = col_string
.first() .first()
.ok_or_else(|| { .ok_or_else(|| ShellError::GenericError {
ShellError::GenericError( error: "Empty names list".into(),
"Empty names list".into(), msg: "No column names were found".into(),
"No column names were found".into(), span: Some(col_span),
Some(col_span), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
.and_then(|col| { .and_then(|col| {
df.as_ref().drop(&col.item).map_err(|e| { df.as_ref()
ShellError::GenericError( .drop(&col.item)
"Error dropping column".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error dropping column".into(),
Some(col.span), msg: e.to_string(),
None, span: Some(col.span),
Vec::new(), help: None,
) inner: vec![],
}) })
})?; })?;
// If there are more columns in the drop selection list, these // If there are more columns in the drop selection list, these
@ -96,15 +94,15 @@ fn command(
.iter() .iter()
.skip(1) .skip(1)
.try_fold(new_df, |new_df, col| { .try_fold(new_df, |new_df, col| {
new_df.drop(&col.item).map_err(|e| { new_df
ShellError::GenericError( .drop(&col.item)
"Error dropping column".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error dropping column".into(),
Some(col.span), msg: e.to_string(),
None, span: Some(col.span),
Vec::new(), help: None,
) inner: vec![],
}) })
}) })
.map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None)) .map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None))
} }

View File

@ -100,14 +100,12 @@ fn command(
df.as_ref() df.as_ref()
.unique(subset_slice, keep_strategy, None) .unique(subset_slice, keep_strategy, None)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error dropping duplicates".into(),
"Error dropping duplicates".into(), msg: e.to_string(),
e.to_string(), span: Some(col_span),
Some(col_span), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
.map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None)) .map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None))
} }

View File

@ -115,14 +115,12 @@ fn command(
df.as_ref() df.as_ref()
.drop_nulls(subset_slice) .drop_nulls(subset_slice)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error dropping nulls".into(),
"Error dropping nulls".into(), msg: e.to_string(),
e.to_string(), span: Some(col_span),
Some(col_span), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
.map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None)) .map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None))
} }

View File

@ -88,14 +88,12 @@ fn command(
df.as_ref() df.as_ref()
.to_dummies(None, drop_first) .to_dummies(None, drop_first)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error calculating dummies".into(),
"Error calculating dummies".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: Some("The only allowed column types for dummies are String or Int".into()),
Some("The only allowed column types for dummies are String or Int".into()), inner: vec![],
Vec::new(),
)
}) })
.map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None)) .map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None))
} }

View File

@ -105,26 +105,22 @@ fn command_eager(
)) ))
} else { } else {
let mask = NuDataFrame::try_from_value(mask_value)?.as_series(mask_span)?; let mask = NuDataFrame::try_from_value(mask_value)?.as_series(mask_span)?;
let mask = mask.bool().map_err(|e| { let mask = mask.bool().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to bool".into(),
"Error casting to bool".into(), msg: e.to_string(),
e.to_string(), span: Some(mask_span),
Some(mask_span), help: Some("Perhaps you want to use a series with booleans as mask".into()),
Some("Perhaps you want to use a series with booleans as mask".into()), inner: vec![],
Vec::new(),
)
})?; })?;
df.as_ref() df.as_ref()
.filter(mask) .filter(mask)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error filtering dataframe".into(),
"Error filtering dataframe".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: Some("The only allowed column types for dummies are String or Int".into()),
Some("The only allowed column types for dummies are String or Int".into()), inner: vec![],
Vec::new(),
)
}) })
.map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None)) .map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None))
} }

View File

@ -70,14 +70,12 @@ fn command(
df.as_ref() df.as_ref()
.select(col_string) .select(col_string)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error selecting columns".into(),
"Error selecting columns".into(), msg: e.to_string(),
e.to_string(), span: Some(col_span),
Some(col_span), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
.map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None)) .map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None))
} }

View File

@ -152,38 +152,34 @@ fn command(
let mut res = df let mut res = df
.as_ref() .as_ref()
.melt(&id_col_string, &val_col_string) .melt(&id_col_string, &val_col_string)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error calculating melt".into(),
"Error calculating melt".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
if let Some(name) = &variable_name { if let Some(name) = &variable_name {
res.rename("variable", &name.item).map_err(|e| { res.rename("variable", &name.item)
ShellError::GenericError( .map_err(|e| ShellError::GenericError {
"Error renaming column".into(), error: "Error renaming column".into(),
e.to_string(), msg: e.to_string(),
Some(name.span), span: Some(name.span),
None, help: None,
Vec::new(), inner: vec![],
) })?;
})?;
} }
if let Some(name) = &value_name { if let Some(name) = &value_name {
res.rename("value", &name.item).map_err(|e| { res.rename("value", &name.item)
ShellError::GenericError( .map_err(|e| ShellError::GenericError {
"Error renaming column".into(), error: "Error renaming column".into(),
e.to_string(), msg: e.to_string(),
Some(name.span), span: Some(name.span),
None, help: None,
Vec::new(), inner: vec![],
) })?;
})?;
} }
Ok(PipelineData::Value( Ok(PipelineData::Value(
@ -198,50 +194,50 @@ fn check_column_datatypes<T: AsRef<str>>(
col_span: Span, col_span: Span,
) -> Result<(), ShellError> { ) -> Result<(), ShellError> {
if cols.is_empty() { if cols.is_empty() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Merge error".into(), error: "Merge error".into(),
"empty column list".into(), msg: "empty column list".into(),
Some(col_span), span: Some(col_span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
// Checking if they are same type // Checking if they are same type
if cols.len() > 1 { if cols.len() > 1 {
for w in cols.windows(2) { for w in cols.windows(2) {
let l_series = df.column(w[0].as_ref()).map_err(|e| { let l_series = df
ShellError::GenericError( .column(w[0].as_ref())
"Error selecting columns".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error selecting columns".into(),
Some(col_span), msg: e.to_string(),
None, span: Some(col_span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
let r_series = df.column(w[1].as_ref()).map_err(|e| { let r_series = df
ShellError::GenericError( .column(w[1].as_ref())
"Error selecting columns".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error selecting columns".into(),
Some(col_span), msg: e.to_string(),
None, span: Some(col_span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
if l_series.dtype() != r_series.dtype() { if l_series.dtype() != r_series.dtype() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Merge error".into(), error: "Merge error".into(),
"found different column types in list".into(), msg: "found different column types in list".into(),
Some(col_span), span: Some(col_span),
Some(format!( help: Some(format!(
"datatypes {} and {} are incompatible", "datatypes {} and {} are incompatible",
l_series.dtype(), l_series.dtype(),
r_series.dtype() r_series.dtype()
)), )),
Vec::new(), inner: vec![],
)); });
} }
} }
} }

View File

@ -154,14 +154,12 @@ fn from_parquet(
}; };
let df: NuLazyFrame = LazyFrame::scan_parquet(file, args) let df: NuLazyFrame = LazyFrame::scan_parquet(file, args)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Parquet reader error".into(),
"Parquet reader error".into(), msg: format!("{e:?}"),
format!("{e:?}"), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into(); .into();
@ -170,14 +168,12 @@ fn from_parquet(
let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?; let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?;
let columns: Option<Vec<String>> = call.get_flag(engine_state, stack, "columns")?; let columns: Option<Vec<String>> = call.get_flag(engine_state, stack, "columns")?;
let r = File::open(&file.item).map_err(|e| { let r = File::open(&file.item).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error opening file".into(),
"Error opening file".into(), msg: e.to_string(),
e.to_string(), span: Some(file.span),
Some(file.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let reader = ParquetReader::new(r); let reader = ParquetReader::new(r);
@ -188,14 +184,12 @@ fn from_parquet(
let df: NuDataFrame = reader let df: NuDataFrame = reader
.finish() .finish()
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Parquet reader error".into(),
"Parquet reader error".into(), msg: format!("{e:?}"),
format!("{e:?}"), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into(); .into();
@ -211,14 +205,12 @@ fn from_avro(
let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?; let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?;
let columns: Option<Vec<String>> = call.get_flag(engine_state, stack, "columns")?; let columns: Option<Vec<String>> = call.get_flag(engine_state, stack, "columns")?;
let r = File::open(&file.item).map_err(|e| { let r = File::open(&file.item).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error opening file".into(),
"Error opening file".into(), msg: e.to_string(),
e.to_string(), span: Some(file.span),
Some(file.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let reader = AvroReader::new(r); let reader = AvroReader::new(r);
@ -229,14 +221,12 @@ fn from_avro(
let df: NuDataFrame = reader let df: NuDataFrame = reader
.finish() .finish()
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Avro reader error".into(),
"Avro reader error".into(), msg: format!("{e:?}"),
format!("{e:?}"), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into(); .into();
@ -259,14 +249,12 @@ fn from_ipc(
}; };
let df: NuLazyFrame = LazyFrame::scan_ipc(file, args) let df: NuLazyFrame = LazyFrame::scan_ipc(file, args)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "IPC reader error".into(),
"IPC reader error".into(), msg: format!("{e:?}"),
format!("{e:?}"), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into(); .into();
@ -275,14 +263,12 @@ fn from_ipc(
let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?; let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?;
let columns: Option<Vec<String>> = call.get_flag(engine_state, stack, "columns")?; let columns: Option<Vec<String>> = call.get_flag(engine_state, stack, "columns")?;
let r = File::open(&file.item).map_err(|e| { let r = File::open(&file.item).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error opening file".into(),
"Error opening file".into(), msg: e.to_string(),
e.to_string(), span: Some(file.span),
Some(file.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let reader = IpcReader::new(r); let reader = IpcReader::new(r);
@ -293,14 +279,12 @@ fn from_ipc(
let df: NuDataFrame = reader let df: NuDataFrame = reader
.finish() .finish()
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "IPC reader error".into(),
"IPC reader error".into(), msg: format!("{e:?}"),
format!("{e:?}"), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into(); .into();
@ -314,14 +298,12 @@ fn from_json(
call: &Call, call: &Call,
) -> Result<Value, ShellError> { ) -> Result<Value, ShellError> {
let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?; let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?;
let file = File::open(&file.item).map_err(|e| { let file = File::open(&file.item).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error opening file".into(),
"Error opening file".into(), msg: e.to_string(),
e.to_string(), span: Some(file.span),
Some(file.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let buf_reader = BufReader::new(file); let buf_reader = BufReader::new(file);
@ -329,14 +311,12 @@ fn from_json(
let df: NuDataFrame = reader let df: NuDataFrame = reader
.finish() .finish()
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Json reader error".into(),
"Json reader error".into(), msg: format!("{e:?}"),
format!("{e:?}"), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into(); .into();
@ -350,14 +330,12 @@ fn from_jsonl(
) -> Result<Value, ShellError> { ) -> Result<Value, ShellError> {
let infer_schema: Option<usize> = call.get_flag(engine_state, stack, "infer-schema")?; let infer_schema: Option<usize> = call.get_flag(engine_state, stack, "infer-schema")?;
let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?; let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?;
let file = File::open(&file.item).map_err(|e| { let file = File::open(&file.item).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error opening file".into(),
"Error opening file".into(), msg: e.to_string(),
e.to_string(), span: Some(file.span),
Some(file.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let buf_reader = BufReader::new(file); let buf_reader = BufReader::new(file);
@ -367,14 +345,12 @@ fn from_jsonl(
let df: NuDataFrame = reader let df: NuDataFrame = reader
.finish() .finish()
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Json lines reader error".into(),
"Json lines reader error".into(), msg: format!("{e:?}"),
format!("{e:?}"), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into(); .into();
@ -400,13 +376,13 @@ fn from_csv(
None => csv_reader, None => csv_reader,
Some(d) => { Some(d) => {
if d.item.len() != 1 { if d.item.len() != 1 {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Incorrect delimiter".into(), error: "Incorrect delimiter".into(),
"Delimiter has to be one character".into(), msg: "Delimiter has to be one character".into(),
Some(d.span), span: Some(d.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} else { } else {
let delimiter = match d.item.chars().next() { let delimiter = match d.item.chars().next() {
Some(d) => d as u8, Some(d) => d as u8,
@ -431,14 +407,12 @@ fn from_csv(
let df: NuLazyFrame = csv_reader let df: NuLazyFrame = csv_reader
.finish() .finish()
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Parquet reader error".into(),
"Parquet reader error".into(), msg: format!("{e:?}"),
format!("{e:?}"), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into(); .into();
@ -446,14 +420,12 @@ fn from_csv(
} else { } else {
let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?; let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?;
let csv_reader = CsvReader::from_path(&file.item) let csv_reader = CsvReader::from_path(&file.item)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error creating CSV reader".into(),
"Error creating CSV reader".into(), msg: e.to_string(),
e.to_string(), span: Some(file.span),
Some(file.span), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.with_encoding(CsvEncoding::LossyUtf8); .with_encoding(CsvEncoding::LossyUtf8);
@ -461,13 +433,13 @@ fn from_csv(
None => csv_reader, None => csv_reader,
Some(d) => { Some(d) => {
if d.item.len() != 1 { if d.item.len() != 1 {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Incorrect delimiter".into(), error: "Incorrect delimiter".into(),
"Delimiter has to be one character".into(), msg: "Delimiter has to be one character".into(),
Some(d.span), span: Some(d.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} else { } else {
let delimiter = match d.item.chars().next() { let delimiter = match d.item.chars().next() {
Some(d) => d as u8, Some(d) => d as u8,
@ -497,14 +469,12 @@ fn from_csv(
let df: NuDataFrame = csv_reader let df: NuDataFrame = csv_reader
.finish() .finish()
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Parquet reader error".into(),
"Parquet reader error".into(), msg: format!("{e:?}"),
format!("{e:?}"), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into(); .into();

View File

@ -76,15 +76,15 @@ fn command(
let mut ctx = SQLContext::new(); let mut ctx = SQLContext::new();
ctx.register("df", &df.df); ctx.register("df", &df.df);
let df_sql = ctx.execute(&sql_query).map_err(|e| { let df_sql = ctx
ShellError::GenericError( .execute(&sql_query)
"Dataframe Error".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Dataframe Error".into(),
Some(call.head), msg: e.to_string(),
None, span: Some(call.head),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
let lazy = NuLazyFrame::new(false, df_sql); let lazy = NuLazyFrame::new(false, df_sql);
let eager = lazy.collect(call.head)?; let eager = lazy.collect(call.head)?;

View File

@ -130,15 +130,15 @@ fn command_eager(
let new_names = extract_strings(new_names)?; let new_names = extract_strings(new_names)?;
for (from, to) in columns.iter().zip(new_names.iter()) { for (from, to) in columns.iter().zip(new_names.iter()) {
df.as_mut().rename(from, to).map_err(|e| { df.as_mut()
ShellError::GenericError( .rename(from, to)
"Error renaming".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error renaming".into(),
Some(call.head), msg: e.to_string(),
None, span: Some(call.head),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
} }
Ok(PipelineData::Value(df.into_value(call.head), None)) Ok(PipelineData::Value(df.into_value(call.head), None))

View File

@ -97,41 +97,37 @@ fn command(
(Some(rows), None) => df (Some(rows), None) => df
.as_ref() .as_ref()
.sample_n(&Series::new("s", &[rows.item]), replace, shuffle, seed) .sample_n(&Series::new("s", &[rows.item]), replace, shuffle, seed)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error creating sample".into(),
"Error creating sample".into(), msg: e.to_string(),
e.to_string(), span: Some(rows.span),
Some(rows.span), help: None,
None, inner: vec![],
Vec::new(),
)
}), }),
(None, Some(frac)) => df (None, Some(frac)) => df
.as_ref() .as_ref()
.sample_frac(&Series::new("frac", &[frac.item]), replace, shuffle, seed) .sample_frac(&Series::new("frac", &[frac.item]), replace, shuffle, seed)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error creating sample".into(),
"Error creating sample".into(), msg: e.to_string(),
e.to_string(), span: Some(frac.span),
Some(frac.span), help: None,
None, inner: vec![],
Vec::new(),
)
}), }),
(Some(_), Some(_)) => Err(ShellError::GenericError( (Some(_), Some(_)) => Err(ShellError::GenericError {
"Incompatible flags".into(), error: "Incompatible flags".into(),
"Only one selection criterion allowed".into(), msg: "Only one selection criterion allowed".into(),
Some(call.head), span: Some(call.head),
None, help: None,
Vec::new(), inner: vec![],
)), }),
(None, None) => Err(ShellError::GenericError( (None, None) => Err(ShellError::GenericError {
"No selection".into(), error: "No selection".into(),
"No selection criterion was found".into(), msg: "No selection criterion was found".into(),
Some(call.head), span: Some(call.head),
Some("Perhaps you want to use the flag -n or -f".into()), help: Some("Perhaps you want to use the flag -n or -f".into()),
Vec::new(), inner: vec![],
)), }),
} }
.map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None)) .map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None))
} }

View File

@ -127,23 +127,23 @@ fn command(
if (&0.0..=&1.0).contains(&val) { if (&0.0..=&1.0).contains(&val) {
Ok(*val) Ok(*val)
} else { } else {
Err(ShellError::GenericError( Err(ShellError::GenericError {
"Incorrect value for quantile".to_string(), error: "Incorrect value for quantile".into(),
"value should be between 0 and 1".to_string(), msg: "value should be between 0 and 1".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
} }
Value::Error { error, .. } => Err(*error.clone()), Value::Error { error, .. } => Err(*error.clone()),
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Incorrect value for quantile".to_string(), error: "Incorrect value for quantile".into(),
"value should be a float".to_string(), msg: "value should be a float".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
}) })
.collect::<Result<Vec<f64>, ShellError>>() .collect::<Result<Vec<f64>, ShellError>>()
@ -250,14 +250,12 @@ fn command(
let res = head.chain(tail).collect::<Vec<Series>>(); let res = head.chain(tail).collect::<Vec<Series>>();
DataFrame::new(res) DataFrame::new(res)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Dataframe Error".into(),
"Dataframe Error".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
.map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None)) .map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None))
} }

View File

@ -97,47 +97,41 @@ fn command(
let index = NuDataFrame::try_from_value(index_value)?.as_series(index_span)?; let index = NuDataFrame::try_from_value(index_value)?.as_series(index_span)?;
let casted = match index.dtype() { let casted = match index.dtype() {
DataType::UInt32 | DataType::UInt64 | DataType::Int32 | DataType::Int64 => { DataType::UInt32 | DataType::UInt64 | DataType::Int32 | DataType::Int64 => index
index.cast(&DataType::UInt32).map_err(|e| { .cast(&DataType::UInt32)
ShellError::GenericError( .map_err(|e| ShellError::GenericError {
"Error casting index list".into(), error: "Error casting index list".into(),
e.to_string(), msg: e.to_string(),
Some(index_span), span: Some(index_span),
None, help: None,
Vec::new(), inner: vec![],
) }),
}) _ => Err(ShellError::GenericError {
} error: "Incorrect type".into(),
_ => Err(ShellError::GenericError( msg: "Series with incorrect type".into(),
"Incorrect type".into(), span: Some(call.head),
"Series with incorrect type".into(), help: Some("Consider using a Series with type int type".into()),
Some(call.head), inner: vec![],
Some("Consider using a Series with type int type".into()), }),
Vec::new(),
)),
}?; }?;
let indices = casted.u32().map_err(|e| { let indices = casted.u32().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting index list".into(),
"Error casting index list".into(), msg: e.to_string(),
e.to_string(), span: Some(index_span),
Some(index_span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
NuDataFrame::try_from_pipeline(input, call.head).and_then(|df| { NuDataFrame::try_from_pipeline(input, call.head).and_then(|df| {
df.as_ref() df.as_ref()
.take(indices) .take(indices)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error taking values".into(),
"Error taking values".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
.map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None)) .map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None))
}) })

View File

@ -58,25 +58,23 @@ fn command(
let mut df = NuDataFrame::try_from_pipeline(input, call.head)?; let mut df = NuDataFrame::try_from_pipeline(input, call.head)?;
let mut file = File::create(&file_name.item).map_err(|e| { let mut file = File::create(&file_name.item).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error with file name".into(),
"Error with file name".into(), msg: e.to_string(),
e.to_string(), span: Some(file_name.span),
Some(file_name.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
IpcWriter::new(&mut file).finish(df.as_mut()).map_err(|e| { IpcWriter::new(&mut file)
ShellError::GenericError( .finish(df.as_mut())
"Error saving file".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error saving file".into(),
Some(file_name.span), msg: e.to_string(),
None, span: Some(file_name.span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
let file_value = Value::string(format!("saved {:?}", &file_name.item), file_name.span); let file_value = Value::string(format!("saved {:?}", &file_name.item), file_name.span);

View File

@ -85,27 +85,23 @@ fn command(
let mut df = NuDataFrame::try_from_pipeline(input, call.head)?; let mut df = NuDataFrame::try_from_pipeline(input, call.head)?;
let file = File::create(&file_name.item).map_err(|e| { let file = File::create(&file_name.item).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error with file name".into(),
"Error with file name".into(), msg: e.to_string(),
e.to_string(), span: Some(file_name.span),
Some(file_name.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
AvroWriter::new(file) AvroWriter::new(file)
.with_compression(compression) .with_compression(compression)
.finish(df.as_mut()) .finish(df.as_mut())
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error saving file".into(),
"Error saving file".into(), msg: e.to_string(),
e.to_string(), span: Some(file_name.span),
Some(file_name.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let file_value = Value::string(format!("saved {:?}", &file_name.item), file_name.span); let file_value = Value::string(format!("saved {:?}", &file_name.item), file_name.span);

View File

@ -74,14 +74,12 @@ fn command(
let mut df = NuDataFrame::try_from_pipeline(input, call.head)?; let mut df = NuDataFrame::try_from_pipeline(input, call.head)?;
let mut file = File::create(&file_name.item).map_err(|e| { let mut file = File::create(&file_name.item).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error with file name".into(),
"Error with file name".into(), msg: e.to_string(),
e.to_string(), span: Some(file_name.span),
Some(file_name.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let writer = CsvWriter::new(&mut file); let writer = CsvWriter::new(&mut file);
@ -96,13 +94,13 @@ fn command(
None => writer, None => writer,
Some(d) => { Some(d) => {
if d.item.len() != 1 { if d.item.len() != 1 {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Incorrect delimiter".into(), error: "Incorrect delimiter".into(),
"Delimiter has to be one char".into(), msg: "Delimiter has to be one char".into(),
Some(d.span), span: Some(d.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} else { } else {
let delimiter = match d.item.chars().next() { let delimiter = match d.item.chars().next() {
Some(d) => d as u8, Some(d) => d as u8,
@ -114,15 +112,15 @@ fn command(
} }
}; };
writer.finish(df.as_mut()).map_err(|e| { writer
ShellError::GenericError( .finish(df.as_mut())
"Error writing to file".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error writing to file".into(),
Some(file_name.span), msg: e.to_string(),
None, span: Some(file_name.span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
let file_value = Value::string(format!("saved {:?}", &file_name.item), file_name.span); let file_value = Value::string(format!("saved {:?}", &file_name.item), file_name.span);

View File

@ -58,27 +58,23 @@ fn command(
let mut df = NuDataFrame::try_from_pipeline(input, call.head)?; let mut df = NuDataFrame::try_from_pipeline(input, call.head)?;
let file = File::create(&file_name.item).map_err(|e| { let file = File::create(&file_name.item).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error with file name".into(),
"Error with file name".into(), msg: e.to_string(),
e.to_string(), span: Some(file_name.span),
Some(file_name.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let buf_writer = BufWriter::new(file); let buf_writer = BufWriter::new(file);
JsonWriter::new(buf_writer) JsonWriter::new(buf_writer)
.finish(df.as_mut()) .finish(df.as_mut())
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error saving file".into(),
"Error saving file".into(), msg: e.to_string(),
e.to_string(), span: Some(file_name.span),
Some(file_name.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let file_value = Value::string(format!("saved {:?}", &file_name.item), file_name.span); let file_value = Value::string(format!("saved {:?}", &file_name.item), file_name.span);

View File

@ -58,25 +58,23 @@ fn command(
let mut df = NuDataFrame::try_from_pipeline(input, call.head)?; let mut df = NuDataFrame::try_from_pipeline(input, call.head)?;
let file = File::create(&file_name.item).map_err(|e| { let file = File::create(&file_name.item).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error with file name".into(),
"Error with file name".into(), msg: e.to_string(),
e.to_string(), span: Some(file_name.span),
Some(file_name.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
ParquetWriter::new(file).finish(df.as_mut()).map_err(|e| { ParquetWriter::new(file)
ShellError::GenericError( .finish(df.as_mut())
"Error saving file".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error saving file".into(),
Some(file_name.span), msg: e.to_string(),
None, span: Some(file_name.span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
let file_value = Value::string(format!("saved {:?}", &file_name.item), file_name.span); let file_value = Value::string(format!("saved {:?}", &file_name.item), file_name.span);

View File

@ -151,14 +151,12 @@ fn command_eager(
df.as_mut() df.as_mut()
.with_column(series) .with_column(series)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error adding column to dataframe".into(),
"Error adding column to dataframe".into(), msg: e.to_string(),
e.to_string(), span: Some(column_span),
Some(column_span), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
.map(|df| { .map(|df| {
PipelineData::Value( PipelineData::Value(

View File

@ -125,13 +125,13 @@ impl Command for LazyAggregate {
let dtype = schema.get(name.as_str()); let dtype = schema.get(name.as_str());
if matches!(dtype, Some(DataType::Object(..))) { if matches!(dtype, Some(DataType::Object(..))) {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Object type column not supported for aggregation".into(), error: "Object type column not supported for aggregation".into(),
format!("Column '{name}' is type Object"), msg: format!("Column '{name}' is type Object"),
Some(call.head), span: Some(call.head),
Some("Aggregations cannot be performed on Object type columns. Use dtype command to check column types".into()), help: Some("Aggregations cannot be performed on Object type columns. Use dtype command to check column types".into()),
Vec::new(), inner: vec![],
)); });
} }
} }
} }

View File

@ -67,14 +67,12 @@ impl Command for LazyFetch {
let eager: NuDataFrame = lazy let eager: NuDataFrame = lazy
.into_polars() .into_polars()
.fetch(rows as usize) .fetch(rows as usize)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error fetching rows".into(),
"Error fetching rows".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into(); .into();

View File

@ -118,13 +118,13 @@ impl Command for LazySortBy {
.get_flag::<Value>(engine_state, stack, "reverse")? .get_flag::<Value>(engine_state, stack, "reverse")?
.expect("already checked and it exists") .expect("already checked and it exists")
.span(); .span();
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Incorrect list size".into(), error: "Incorrect list size".into(),
"Size doesn't match expression list".into(), msg: "Size doesn't match expression list".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} else { } else {
list list
} }

View File

@ -78,14 +78,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let bool = series.bool().map_err(|_| { let bool = series.bool().map_err(|_| ShellError::GenericError {
ShellError::GenericError( error: "Error converting to bool".into(),
"Error converting to bool".into(), msg: "all-false only works with series of type bool".into(),
"all-false only works with series of type bool".into(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let value = Value::bool(!bool.any(), call.head); let value = Value::bool(!bool.any(), call.head);

View File

@ -78,14 +78,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let bool = series.bool().map_err(|_| { let bool = series.bool().map_err(|_| ShellError::GenericError {
ShellError::GenericError( error: "Error converting to bool".into(),
"Error converting to bool".into(), msg: "all-false only works with series of type bool".into(),
"all-false only works with series of type bool".into(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let value = Value::bool(bool.all(), call.head); let value = Value::bool(bool.all(), call.head);

View File

@ -22,13 +22,13 @@ impl CumType {
"min" => Ok(Self::Min), "min" => Ok(Self::Min),
"max" => Ok(Self::Max), "max" => Ok(Self::Max),
"sum" => Ok(Self::Sum), "sum" => Ok(Self::Sum),
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Wrong operation".into(), error: "Wrong operation".into(),
"Operation not valid for cumulative".into(), msg: "Operation not valid for cumulative".into(),
Some(span), span: Some(span),
Some("Allowed values: max, min, sum".into()), help: Some("Allowed values: max, min, sum".into()),
Vec::new(), inner: vec![],
)), }),
} }
} }
@ -109,13 +109,13 @@ fn command(
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
if let DataType::Object(_) = series.dtype() { if let DataType::Object(_) = series.dtype() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Found object series".into(), error: "Found object series".into(),
"Series of type object cannot be used for cumulative operation".into(), msg: "Series of type object cannot be used for cumulative operation".into(),
Some(call.head), span: Some(call.head),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
let cum_type = CumType::from_str(&cum_type.item, cum_type.span)?; let cum_type = CumType::from_str(&cum_type.item, cum_type.span)?;
@ -124,14 +124,12 @@ fn command(
CumType::Min => cum_min(&series, reverse), CumType::Min => cum_min(&series, reverse),
CumType::Sum => cum_sum(&series, reverse), CumType::Sum => cum_sum(&series, reverse),
} }
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error creating cumulative".into(),
"Error creating cumulative".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let name = format!("{}_{}", series.name(), cum_type.to_str()); let name = format!("{}_{}", series.name(), cum_type.to_str());

View File

@ -68,14 +68,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.utf8().map_err(|e| { let casted = series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to string".into(),
"Error casting to string".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = if not_exact { let res = if not_exact {
@ -85,14 +83,12 @@ fn command(
}; };
let mut res = res let mut res = res
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error creating datetime".into(),
"Error creating datetime".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into_series(); .into_series();

View File

@ -132,14 +132,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.utf8().map_err(|e| { let casted = series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to string".into(),
"Error casting to string".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = if not_exact { let res = if not_exact {
@ -162,14 +160,12 @@ fn command(
}; };
let mut res = res let mut res = res
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error creating datetime".into(),
"Error creating datetime".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into_series(); .into_series();

View File

@ -65,14 +65,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.datetime().map_err(|e| { let casted = series.datetime().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to datetime type".into(),
"Error casting to datetime type".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = casted.day().into_series(); let res = casted.day().into_series();

View File

@ -65,14 +65,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.datetime().map_err(|e| { let casted = series.datetime().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to datetime type".into(),
"Error casting to datetime type".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = casted.hour().into_series(); let res = casted.hour().into_series();

View File

@ -65,14 +65,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.datetime().map_err(|e| { let casted = series.datetime().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to datetime type".into(),
"Error casting to datetime type".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = casted.minute().into_series(); let res = casted.minute().into_series();

View File

@ -65,14 +65,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.datetime().map_err(|e| { let casted = series.datetime().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to datetime type".into(),
"Error casting to datetime type".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = casted.month().into_series(); let res = casted.month().into_series();

View File

@ -65,14 +65,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.datetime().map_err(|e| { let casted = series.datetime().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to datetime type".into(),
"Error casting to datetime type".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = casted.nanosecond().into_series(); let res = casted.nanosecond().into_series();

View File

@ -65,14 +65,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.datetime().map_err(|e| { let casted = series.datetime().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to datetime type".into(),
"Error casting to datetime type".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = casted.ordinal().into_series(); let res = casted.ordinal().into_series();

View File

@ -65,14 +65,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.datetime().map_err(|e| { let casted = series.datetime().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to datetime type".into(),
"Error casting to datetime type".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = casted.second().into_series(); let res = casted.second().into_series();

View File

@ -65,14 +65,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.datetime().map_err(|e| { let casted = series.datetime().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to datetime type".into(),
"Error casting to datetime type".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = casted.week().into_series(); let res = casted.week().into_series();

View File

@ -65,14 +65,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.datetime().map_err(|e| { let casted = series.datetime().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to datetime type".into(),
"Error casting to datetime type".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = casted.weekday().into_series(); let res = casted.weekday().into_series();

View File

@ -65,14 +65,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.datetime().map_err(|e| { let casted = series.datetime().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to datetime type".into(),
"Error casting to datetime type".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = casted.year().into_series(); let res = casted.year().into_series();

View File

@ -67,13 +67,13 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let columns = df.as_ref().get_column_names(); let columns = df.as_ref().get_column_names();
if columns.len() > 1 { if columns.len() > 1 {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Error using as series".into(), error: "Error using as series".into(),
"dataframe has more than one column".into(), msg: "dataframe has more than one column".into(),
Some(call.head), span: Some(call.head),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
match columns.first() { match columns.first() {
@ -85,14 +85,12 @@ fn command(
.lazy() .lazy()
.select(&[expression]) .select(&[expression])
.collect() .collect()
.map_err(|err| { .map_err(|err| ShellError::GenericError {
ShellError::GenericError( error: "Error creating index column".into(),
"Error creating index column".into(), msg: err.to_string(),
err.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let value = NuDataFrame::dataframe_into_value(res, call.head); let value = NuDataFrame::dataframe_into_value(res, call.head);

View File

@ -69,14 +69,12 @@ fn command(
let mut res = df let mut res = df
.as_series(call.head)? .as_series(call.head)?
.arg_unique() .arg_unique()
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error extracting unique values".into(),
"Error extracting unique values".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into_series(); .into_series();
res.rename("arg_unique"); res.rename("arg_unique");

View File

@ -86,36 +86,33 @@ fn command(
let indices = NuDataFrame::try_from_value(indices_value)?.as_series(indices_span)?; let indices = NuDataFrame::try_from_value(indices_value)?.as_series(indices_span)?;
let casted = match indices.dtype() { let casted = match indices.dtype() {
DataType::UInt32 | DataType::UInt64 | DataType::Int32 | DataType::Int64 => { DataType::UInt32 | DataType::UInt64 | DataType::Int32 | DataType::Int64 => indices
indices.as_ref().cast(&DataType::UInt32).map_err(|e| { .as_ref()
ShellError::GenericError( .cast(&DataType::UInt32)
"Error casting indices".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error casting indices".into(),
Some(indices_span), msg: e.to_string(),
None, span: Some(indices_span),
Vec::new(), help: None,
) inner: vec![],
}) }),
} _ => Err(ShellError::GenericError {
_ => Err(ShellError::GenericError( error: "Incorrect type".into(),
"Incorrect type".into(), msg: "Series with incorrect type".into(),
"Series with incorrect type".into(), span: Some(indices_span),
Some(indices_span), help: Some("Consider using a Series with type int type".into()),
Some("Consider using a Series with type int type".into()), inner: vec![],
Vec::new(), }),
)),
}?; }?;
let indices = casted let indices = casted
.u32() .u32()
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting indices".into(),
"Error casting indices".into(), msg: e.to_string(),
e.to_string(), span: Some(indices_span),
Some(indices_span), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into_iter() .into_iter()
.flatten(); .flatten();
@ -124,92 +121,85 @@ fn command(
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let span = value.span(); let span = value.span();
let res = match value { let res =
Value::Int { val, .. } => { match value {
let chunked = series.i64().map_err(|e| { Value::Int { val, .. } => {
ShellError::GenericError( let chunked = series.i64().map_err(|e| ShellError::GenericError {
"Error casting to i64".into(), error: "Error casting to i64".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)
})?;
let res = chunked.set_at_idx(indices, Some(val)).map_err(|e| {
ShellError::GenericError(
"Error setting value".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
})?;
NuDataFrame::try_from_series(vec![res.into_series()], call.head)
}
Value::Float { val, .. } => {
let chunked = series.f64().map_err(|e| {
ShellError::GenericError(
"Error casting to f64".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
})?;
let res = chunked.set_at_idx(indices, Some(val)).map_err(|e| {
ShellError::GenericError(
"Error setting value".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
})?;
NuDataFrame::try_from_series(vec![res.into_series()], call.head)
}
Value::String { val, .. } => {
let chunked = series.utf8().map_err(|e| {
ShellError::GenericError(
"Error casting to string".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
})?;
let res = chunked
.set_at_idx(indices, Some(val.as_ref()))
.map_err(|e| {
ShellError::GenericError(
"Error setting value".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
})?; })?;
let mut res = res.into_series(); let res = chunked.set_at_idx(indices, Some(val)).map_err(|e| {
res.rename("string"); ShellError::GenericError {
error: "Error setting value".into(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
}
})?;
NuDataFrame::try_from_series(vec![res.into_series()], call.head) NuDataFrame::try_from_series(vec![res.into_series()], call.head)
} }
_ => Err(ShellError::GenericError( Value::Float { val, .. } => {
"Incorrect value type".into(), let chunked = series.f64().map_err(|e| ShellError::GenericError {
format!( error: "Error casting to f64".into(),
"this value cannot be set in a series of type '{}'", msg: e.to_string(),
series.dtype() span: Some(span),
), help: None,
Some(span), inner: vec![],
None, })?;
Vec::new(),
)), let res = chunked.set_at_idx(indices, Some(val)).map_err(|e| {
}; ShellError::GenericError {
error: "Error setting value".into(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
}
})?;
NuDataFrame::try_from_series(vec![res.into_series()], call.head)
}
Value::String { val, .. } => {
let chunked = series.utf8().map_err(|e| ShellError::GenericError {
error: "Error casting to string".into(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
})?;
let res = chunked
.set_at_idx(indices, Some(val.as_ref()))
.map_err(|e| ShellError::GenericError {
error: "Error setting value".into(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
})?;
let mut res = res.into_series();
res.rename("string");
NuDataFrame::try_from_series(vec![res.into_series()], call.head)
}
_ => Err(ShellError::GenericError {
error: "Incorrect value type".into(),
msg: format!(
"this value cannot be set in a series of type '{}'",
series.dtype()
),
span: Some(span),
help: None,
inner: vec![],
}),
};
res.map(|df| PipelineData::Value(NuDataFrame::into_value(df, call.head), None)) res.map(|df| PipelineData::Value(NuDataFrame::into_value(df, call.head), None))
} }

View File

@ -94,14 +94,12 @@ fn command(
let mut res = df let mut res = df
.as_ref() .as_ref()
.is_duplicated() .is_duplicated()
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error finding duplicates".into(),
"Error finding duplicates".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into_series(); .into_series();

View File

@ -79,14 +79,12 @@ fn command(
let other = other_df.as_series(other_span)?; let other = other_df.as_series(other_span)?;
let mut res = is_in(&df, &other) let mut res = is_in(&df, &other)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error finding in other".into(),
"Error finding in other".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into_series(); .into_series();

View File

@ -93,14 +93,12 @@ fn command(
let mut res = df let mut res = df
.as_ref() .as_ref()
.is_unique() .is_unique()
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error finding unique values".into(),
"Error finding unique values".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into_series(); .into_series();

View File

@ -68,14 +68,12 @@ fn command(
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let bool = series.bool().map_err(|e| { let bool = series.bool().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error inverting mask".into(),
"Error inverting mask".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = bool.not(); let res = bool.not();

View File

@ -85,22 +85,20 @@ fn command(
let mask = NuDataFrame::try_from_value(mask_value)?.as_series(mask_span)?; let mask = NuDataFrame::try_from_value(mask_value)?.as_series(mask_span)?;
let bool_mask = match mask.dtype() { let bool_mask = match mask.dtype() {
DataType::Boolean => mask.bool().map_err(|e| { DataType::Boolean => mask.bool().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to bool".into(),
"Error casting to bool".into(), msg: e.to_string(),
e.to_string(), span: Some(mask_span),
Some(mask_span), help: None,
None, inner: vec![],
Vec::new(), }),
) _ => Err(ShellError::GenericError {
error: "Incorrect type".into(),
msg: "can only use bool series as mask".into(),
span: Some(mask_span),
help: None,
inner: vec![],
}), }),
_ => Err(ShellError::GenericError(
"Incorrect type".into(),
"can only use bool series as mask".into(),
Some(mask_span),
None,
Vec::new(),
)),
}?; }?;
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
@ -108,70 +106,64 @@ fn command(
let span = value.span(); let span = value.span();
let res = match value { let res = match value {
Value::Int { val, .. } => { Value::Int { val, .. } => {
let chunked = series.i64().map_err(|e| { let chunked = series.i64().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to i64".into(),
"Error casting to i64".into(), msg: e.to_string(),
e.to_string(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = chunked.set(bool_mask, Some(val)).map_err(|e| { let res = chunked
ShellError::GenericError( .set(bool_mask, Some(val))
"Error setting value".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error setting value".into(),
Some(span), msg: e.to_string(),
None, span: Some(span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
NuDataFrame::try_from_series(vec![res.into_series()], call.head) NuDataFrame::try_from_series(vec![res.into_series()], call.head)
} }
Value::Float { val, .. } => { Value::Float { val, .. } => {
let chunked = series.f64().map_err(|e| { let chunked = series.f64().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to f64".into(),
"Error casting to f64".into(), msg: e.to_string(),
e.to_string(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = chunked.set(bool_mask, Some(val)).map_err(|e| { let res = chunked
ShellError::GenericError( .set(bool_mask, Some(val))
"Error setting value".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error setting value".into(),
Some(span), msg: e.to_string(),
None, span: Some(span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
NuDataFrame::try_from_series(vec![res.into_series()], call.head) NuDataFrame::try_from_series(vec![res.into_series()], call.head)
} }
Value::String { val, .. } => { Value::String { val, .. } => {
let chunked = series.utf8().map_err(|e| { let chunked = series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to string".into(),
"Error casting to string".into(), msg: e.to_string(),
e.to_string(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = chunked.set(bool_mask, Some(val.as_ref())).map_err(|e| { let res = chunked.set(bool_mask, Some(val.as_ref())).map_err(|e| {
ShellError::GenericError( ShellError::GenericError {
"Error setting value".into(), error: "Error setting value".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
) }
})?; })?;
let mut res = res.into_series(); let mut res = res.into_series();
@ -179,16 +171,16 @@ fn command(
NuDataFrame::try_from_series(vec![res.into_series()], call.head) NuDataFrame::try_from_series(vec![res.into_series()], call.head)
} }
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Incorrect value type".into(), error: "Incorrect value type".into(),
format!( msg: format!(
"this value cannot be set in a series of type '{}'", "this value cannot be set in a series of type '{}'",
series.dtype() series.dtype()
), ),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
}; };
res.map(|df| PipelineData::Value(NuDataFrame::into_value(df, call.head), None)) res.map(|df| PipelineData::Value(NuDataFrame::into_value(df, call.head), None))

View File

@ -83,15 +83,16 @@ fn command(
call: &Call, call: &Call,
df: NuDataFrame, df: NuDataFrame,
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let res = df.as_series(call.head)?.n_unique().map_err(|e| { let res = df
ShellError::GenericError( .as_series(call.head)?
"Error counting unique values".into(), .n_unique()
e.to_string(), .map_err(|e| ShellError::GenericError {
Some(call.head), error: "Error counting unique values".into(),
None, msg: e.to_string(),
Vec::new(), span: Some(call.head),
) help: None,
})?; inner: vec![],
})?;
let value = Value::int(res as i64, call.head); let value = Value::int(res as i64, call.head);

View File

@ -23,13 +23,13 @@ impl RollType {
"max" => Ok(Self::Max), "max" => Ok(Self::Max),
"sum" => Ok(Self::Sum), "sum" => Ok(Self::Sum),
"mean" => Ok(Self::Mean), "mean" => Ok(Self::Mean),
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Wrong operation".into(), error: "Wrong operation".into(),
"Operation not valid for cumulative".into(), msg: "Operation not valid for cumulative".into(),
Some(span), span: Some(span),
Some("Allowed values: min, max, sum, mean".into()), help: Some("Allowed values: min, max, sum, mean".into()),
Vec::new(), inner: vec![],
)), }),
} }
} }
@ -129,13 +129,13 @@ fn command(
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
if let DataType::Object(_) = series.dtype() { if let DataType::Object(_) = series.dtype() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Found object series".into(), error: "Found object series".into(),
"Series of type object cannot be used for rolling operation".into(), msg: "Series of type object cannot be used for rolling operation".into(),
Some(call.head), span: Some(call.head),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
let roll_type = RollType::from_str(&roll_type.item, roll_type.span)?; let roll_type = RollType::from_str(&roll_type.item, roll_type.span)?;
@ -158,14 +158,12 @@ fn command(
RollType::Mean => series.rolling_mean(rolling_opts), RollType::Mean => series.rolling_mean(rolling_opts),
}; };
let mut res = res.map_err(|e| { let mut res = res.map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error calculating rolling values".into(),
"Error calculating rolling values".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let name = format!("{}_{}", series.name(), roll_type.to_str()); let name = format!("{}_{}", series.name(), roll_type.to_str());

View File

@ -78,25 +78,21 @@ fn command(
let other_df = NuDataFrame::try_from_value(other)?; let other_df = NuDataFrame::try_from_value(other)?;
let other_series = other_df.as_series(other_span)?; let other_series = other_df.as_series(other_span)?;
let other_chunked = other_series.utf8().map_err(|e| { let other_chunked = other_series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "The concatenate only with string columns".into(),
"The concatenate only with string columns".into(), msg: e.to_string(),
e.to_string(), span: Some(other_span),
Some(other_span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let chunked = series.utf8().map_err(|e| { let chunked = series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "The concatenate only with string columns".into(),
"The concatenate only with string columns".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let mut res = chunked.concat(other_chunked); let mut res = chunked.concat(other_chunked);

View File

@ -74,25 +74,23 @@ fn command(
let pattern: String = call.req(engine_state, stack, 0)?; let pattern: String = call.req(engine_state, stack, 0)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let chunked = series.utf8().map_err(|e| { let chunked = series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "The contains command only with string columns".into(),
"The contains command only with string columns".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let res = chunked.contains(&pattern, false).map_err(|e| { let res = chunked
ShellError::GenericError( .contains(&pattern, false)
"Error searching in series".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error searching in series".into(),
Some(call.head), msg: e.to_string(),
None, span: Some(call.head),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
NuDataFrame::try_from_series(vec![res.into_series()], call.head) NuDataFrame::try_from_series(vec![res.into_series()], call.head)
.map(|df| PipelineData::Value(NuDataFrame::into_value(df, call.head), None)) .map(|df| PipelineData::Value(NuDataFrame::into_value(df, call.head), None))

View File

@ -86,25 +86,23 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let chunked = series.utf8().map_err(|e| { let chunked = series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error conversion to string".into(),
"Error conversion to string".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let mut res = chunked.replace(&pattern, &replace).map_err(|e| { let mut res = chunked
ShellError::GenericError( .replace(&pattern, &replace)
"Error finding pattern other".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error finding pattern other".into(),
Some(call.head), msg: e.to_string(),
None, span: Some(call.head),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
res.rename(series.name()); res.rename(series.name());

View File

@ -86,25 +86,24 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let chunked = series.utf8().map_err(|e| { let chunked = series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error conversion to string".into(),
"Error conversion to string".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let mut res = chunked.replace_all(&pattern, &replace).map_err(|e| { let mut res =
ShellError::GenericError( chunked
"Error finding pattern other".into(), .replace_all(&pattern, &replace)
e.to_string(), .map_err(|e| ShellError::GenericError {
Some(call.head), error: "Error finding pattern other".into(),
None, msg: e.to_string(),
Vec::new(), span: Some(call.head),
) help: None,
})?; inner: vec![],
})?;
res.rename(series.name()); res.rename(series.name());

View File

@ -63,14 +63,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let chunked = series.utf8().map_err(|e| { let chunked = series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to string".into(),
"Error casting to string".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: Some("The str-lengths command can only be used with string columns".into()),
Some("The str-lengths command can only be used with string columns".into()), inner: vec![],
Vec::new(),
)
})?; })?;
let res = chunked.as_ref().str_len_bytes().into_series(); let res = chunked.as_ref().str_len_bytes().into_series();

View File

@ -75,14 +75,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let chunked = series.utf8().map_err(|e| { let chunked = series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to string".into(),
"Error casting to string".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: Some("The str-slice command can only be used with string columns".into()),
Some("The str-slice command can only be used with string columns".into()), inner: vec![],
Vec::new(),
)
})?; })?;
let mut res = chunked.str_slice(start, length); let mut res = chunked.str_slice(start, length);

View File

@ -72,26 +72,22 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.datetime().map_err(|e| { let casted = series.datetime().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to date".into(),
"Error casting to date".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: Some("The str-slice command can only be used with string columns".into()),
Some("The str-slice command can only be used with string columns".into()), inner: vec![],
Vec::new(),
)
})?; })?;
let res = casted let res = casted
.strftime(&fmt) .strftime(&fmt)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error formatting datetime".into(),
"Error formatting datetime".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into_series(); .into_series();

View File

@ -67,14 +67,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.utf8().map_err(|e| { let casted = series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to string".into(),
"Error casting to string".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: Some("The str-slice command can only be used with string columns".into()),
Some("The str-slice command can only be used with string columns".into()), inner: vec![],
Vec::new(),
)
})?; })?;
let mut res = casted.to_lowercase(); let mut res = casted.to_lowercase();

View File

@ -71,14 +71,12 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let casted = series.utf8().map_err(|e| { let casted = series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting to string".into(),
"Error casting to string".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: Some("The str-slice command can only be used with string columns".into()),
Some("The str-slice command can only be used with string columns".into()), inner: vec![],
Vec::new(),
)
})?; })?;
let mut res = casted.to_uppercase(); let mut res = casted.to_uppercase();

View File

@ -96,14 +96,12 @@ fn command_eager(
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let res = series.unique().map_err(|e| { let res = series.unique().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error calculating unique values".into(),
"Error calculating unique values".into(), msg: e.to_string(),
e.to_string(), span: Some(call.head),
Some(call.head), help: Some("The str-slice command can only be used with string columns".into()),
Some("The str-slice command can only be used with string columns".into()), inner: vec![],
Vec::new(),
)
})?; })?;
NuDataFrame::try_from_series(vec![res.into_series()], call.head) NuDataFrame::try_from_series(vec![res.into_series()], call.head)

View File

@ -70,15 +70,15 @@ fn command(
let df = NuDataFrame::try_from_pipeline(input, call.head)?; let df = NuDataFrame::try_from_pipeline(input, call.head)?;
let series = df.as_series(call.head)?; let series = df.as_series(call.head)?;
let res = series.value_counts(false, false).map_err(|e| { let res = series
ShellError::GenericError( .value_counts(false, false)
"Error calculating value counts values".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error calculating value counts values".into(),
Some(call.head), msg: e.to_string(),
Some("The str-slice command can only be used with string columns".into()), span: Some(call.head),
Vec::new(), help: Some("The str-slice command can only be used with string columns".into()),
) inner: vec![],
})?; })?;
Ok(PipelineData::Value( Ok(PipelineData::Value(
NuDataFrame::dataframe_into_value(res, call.head), NuDataFrame::dataframe_into_value(res, call.head),

View File

@ -68,13 +68,13 @@ pub(super) fn compute_between_series(
res.rename(&name); res.rename(&name);
NuDataFrame::series_to_value(res, operation_span) NuDataFrame::series_to_value(res, operation_span)
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Division error".into(), error: "Division error".into(),
e.to_string(), msg: e.to_string(),
Some(right.span()), span: Some(right.span()),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
Operator::Comparison(Comparison::Equal) => { Operator::Comparison(Comparison::Equal) => {
@ -119,13 +119,13 @@ pub(super) fn compute_between_series(
res.rename(&name); res.rename(&name);
NuDataFrame::series_to_value(res, operation_span) NuDataFrame::series_to_value(res, operation_span)
} }
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Incompatible types".into(), error: "Incompatible types".into(),
"unable to cast to boolean".into(), msg: "unable to cast to boolean".into(),
Some(right.span()), span: Some(right.span()),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
_ => Err(ShellError::IncompatibleParametersSingle { _ => Err(ShellError::IncompatibleParametersSingle {
@ -148,13 +148,13 @@ pub(super) fn compute_between_series(
res.rename(&name); res.rename(&name);
NuDataFrame::series_to_value(res, operation_span) NuDataFrame::series_to_value(res, operation_span)
} }
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Incompatible types".into(), error: "Incompatible types".into(),
"unable to cast to boolean".into(), msg: "unable to cast to boolean".into(),
Some(right.span()), span: Some(right.span()),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
_ => Err(ShellError::IncompatibleParametersSingle { _ => Err(ShellError::IncompatibleParametersSingle {
@ -186,14 +186,12 @@ where
F: Fn(&'s Series, &'s Series) -> Result<ChunkedArray<BooleanType>, PolarsError>, F: Fn(&'s Series, &'s Series) -> Result<ChunkedArray<BooleanType>, PolarsError>,
{ {
let mut res = f(lhs, rhs) let mut res = f(lhs, rhs)
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Equality error".into(),
"Equality error".into(), msg: e.to_string(),
e.to_string(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.into_series(); .into_series();
@ -458,29 +456,29 @@ where
let casted = series.i64(); let casted = series.i64();
compute_casted_i64(casted, val, f, span) compute_casted_i64(casted, val, f, span)
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Unable to cast to i64".into(), error: "Unable to cast to i64".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
DataType::Int64 => { DataType::Int64 => {
let casted = series.i64(); let casted = series.i64();
compute_casted_i64(casted, val, f, span) compute_casted_i64(casted, val, f, span)
} }
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Incorrect type".into(), error: "Incorrect type".into(),
format!( msg: format!(
"Series of type {} can not be used for operations with an i64 value", "Series of type {} can not be used for operations with an i64 value",
series.dtype() series.dtype()
), ),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
@ -499,13 +497,13 @@ where
let res = res.into_series(); let res = res.into_series();
NuDataFrame::series_to_value(res, span) NuDataFrame::series_to_value(res, span)
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Unable to cast to i64".into(), error: "Unable to cast to i64".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
@ -522,29 +520,29 @@ where
let casted = series.f64(); let casted = series.f64();
compute_casted_f64(casted, val, f, span) compute_casted_f64(casted, val, f, span)
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Unable to cast to f64".into(), error: "Unable to cast to f64".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
DataType::Float64 => { DataType::Float64 => {
let casted = series.f64(); let casted = series.f64();
compute_casted_f64(casted, val, f, span) compute_casted_f64(casted, val, f, span)
} }
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Incorrect type".into(), error: "Incorrect type".into(),
format!( msg: format!(
"Series of type {} can not be used for operations with a float value", "Series of type {} can not be used for operations with a float value",
series.dtype() series.dtype()
), ),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
@ -563,13 +561,13 @@ where
let res = res.into_series(); let res = res.into_series();
NuDataFrame::series_to_value(res, span) NuDataFrame::series_to_value(res, span)
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Unable to cast to f64".into(), error: "Unable to cast to f64".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
@ -586,13 +584,13 @@ where
let casted = series.i64(); let casted = series.i64();
compare_casted_i64(casted, val, f, span) compare_casted_i64(casted, val, f, span)
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Unable to cast to f64".into(), error: "Unable to cast to f64".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
DataType::Date => { DataType::Date => {
@ -607,29 +605,29 @@ where
.expect("already checked for casting"); .expect("already checked for casting");
compare_casted_i64(Ok(&casted), val, f, span) compare_casted_i64(Ok(&casted), val, f, span)
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Unable to cast to f64".into(), error: "Unable to cast to f64".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
DataType::Int64 => { DataType::Int64 => {
let casted = series.i64(); let casted = series.i64();
compare_casted_i64(casted, val, f, span) compare_casted_i64(casted, val, f, span)
} }
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Incorrect type".into(), error: "Incorrect type".into(),
format!( msg: format!(
"Series of type {} can not be used for operations with an i64 value", "Series of type {} can not be used for operations with an i64 value",
series.dtype() series.dtype()
), ),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
@ -648,13 +646,13 @@ where
let res = res.into_series(); let res = res.into_series();
NuDataFrame::series_to_value(res, span) NuDataFrame::series_to_value(res, span)
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Unable to cast to i64".into(), error: "Unable to cast to i64".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
@ -671,29 +669,29 @@ where
let casted = series.f64(); let casted = series.f64();
compare_casted_f64(casted, val, f, span) compare_casted_f64(casted, val, f, span)
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Unable to cast to i64".into(), error: "Unable to cast to i64".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
DataType::Float64 => { DataType::Float64 => {
let casted = series.f64(); let casted = series.f64();
compare_casted_f64(casted, val, f, span) compare_casted_f64(casted, val, f, span)
} }
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Incorrect type".into(), error: "Incorrect type".into(),
format!( msg: format!(
"Series of type {} can not be used for operations with a float value", "Series of type {} can not be used for operations with a float value",
series.dtype() series.dtype()
), ),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
@ -712,13 +710,13 @@ where
let res = res.into_series(); let res = res.into_series();
NuDataFrame::series_to_value(res, span) NuDataFrame::series_to_value(res, span)
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Unable to cast to f64".into(), error: "Unable to cast to f64".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
@ -733,22 +731,22 @@ fn contains_series_pat(series: &Series, pat: &str, span: Span) -> Result<Value,
let res = res.into_series(); let res = res.into_series();
NuDataFrame::series_to_value(res, span) NuDataFrame::series_to_value(res, span)
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Error using contains".into(), error: "Error using contains".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Unable to cast to string".into(), error: "Unable to cast to string".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
@ -761,12 +759,12 @@ fn add_string_to_series(series: &Series, pat: &str, span: Span) -> Result<Value,
NuDataFrame::series_to_value(res, span) NuDataFrame::series_to_value(res, span)
} }
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Unable to cast to string".into(), error: "Unable to cast to string".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }

View File

@ -287,14 +287,12 @@ pub fn from_parsed_columns(column_values: ColumnMap) -> Result<NuDataFrame, Shel
DataFrame::new(df_series) DataFrame::new(df_series)
.map(|df| NuDataFrame::new(false, df)) .map(|df| NuDataFrame::new(false, df))
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error creating dataframe".into(),
"Error creating dataframe".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
}) })
} }
@ -314,16 +312,14 @@ fn input_type_list_to_series(
list_type: &InputType, list_type: &InputType,
values: &[Value], values: &[Value],
) -> Result<Series, ShellError> { ) -> Result<Series, ShellError> {
let inconsistent_error = |_| { let inconsistent_error = |_| ShellError::GenericError {
ShellError::GenericError( error: format!(
format!( "column {name} contains a list with inconsistent types: Expecting: {list_type:?}"
"column {name} contains a list with inconsistent types: Expecting: {list_type:?}" ),
), msg: "".into(),
"".to_string(), span: None,
None, help: None,
None, inner: vec![],
Vec::new(),
)
}; };
match *list_type { match *list_type {
// list of boolean values // list of boolean values
@ -423,14 +419,12 @@ fn input_type_list_to_series(
builder builder
.append_series(&dt_chunked.into_series()) .append_series(&dt_chunked.into_series())
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error appending to series".into(),
"Error appending to series".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})? })?
} }
let res = builder.finish(); let res = builder.finish();
@ -463,14 +457,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::UInt8 => { DataType::UInt8 => {
let casted = series.u8().map_err(|e| { let casted = series.u8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to u8".into(),
"Error casting column to u8".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -488,14 +480,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::UInt16 => { DataType::UInt16 => {
let casted = series.u16().map_err(|e| { let casted = series.u16().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to u16".into(),
"Error casting column to u16".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -513,14 +503,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::UInt32 => { DataType::UInt32 => {
let casted = series.u32().map_err(|e| { let casted = series.u32().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to u32".into(),
"Error casting column to u32".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -538,14 +526,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::UInt64 => { DataType::UInt64 => {
let casted = series.u64().map_err(|e| { let casted = series.u64().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to u64".into(),
"Error casting column to u64".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -563,14 +549,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::Int8 => { DataType::Int8 => {
let casted = series.i8().map_err(|e| { let casted = series.i8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to i8".into(),
"Error casting column to i8".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -588,14 +572,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::Int16 => { DataType::Int16 => {
let casted = series.i16().map_err(|e| { let casted = series.i16().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to i16".into(),
"Error casting column to i16".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -613,14 +595,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::Int32 => { DataType::Int32 => {
let casted = series.i32().map_err(|e| { let casted = series.i32().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to i32".into(),
"Error casting column to i32".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -638,14 +618,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::Int64 => { DataType::Int64 => {
let casted = series.i64().map_err(|e| { let casted = series.i64().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to i64".into(),
"Error casting column to i64".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -663,14 +641,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::Float32 => { DataType::Float32 => {
let casted = series.f32().map_err(|e| { let casted = series.f32().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to f32".into(),
"Error casting column to f32".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -688,14 +664,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::Float64 => { DataType::Float64 => {
let casted = series.f64().map_err(|e| { let casted = series.f64().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to f64".into(),
"Error casting column to f64".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -713,14 +687,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::Boolean => { DataType::Boolean => {
let casted = series.bool().map_err(|e| { let casted = series.bool().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to bool".into(),
"Error casting column to bool".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -738,14 +710,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::Utf8 => { DataType::Utf8 => {
let casted = series.utf8().map_err(|e| { let casted = series.utf8().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to string".into(),
"Error casting column to string".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -768,13 +738,13 @@ fn series_to_values(
.downcast_ref::<ChunkedArray<ObjectType<DataFrameValue>>>(); .downcast_ref::<ChunkedArray<ObjectType<DataFrameValue>>>();
match casted { match casted {
None => Err(ShellError::GenericError( None => Err(ShellError::GenericError {
"Error casting object from series".into(), error: "Error casting object from series".into(),
"".to_string(), msg: "".into(),
None, span: None,
Some(format!("Object not supported for conversion: {x}")), help: Some(format!("Object not supported for conversion: {x}")),
Vec::new(), inner: vec![],
)), }),
Some(ca) => { Some(ca) => {
let it = ca.into_iter(); let it = ca.into_iter();
let values = if let (Some(size), Some(from_row)) = (maybe_size, maybe_from_row) let values = if let (Some(size), Some(from_row)) = (maybe_size, maybe_from_row)
@ -796,13 +766,13 @@ fn series_to_values(
DataType::List(x) => { DataType::List(x) => {
let casted = series.as_any().downcast_ref::<ChunkedArray<ListType>>(); let casted = series.as_any().downcast_ref::<ChunkedArray<ListType>>();
match casted { match casted {
None => Err(ShellError::GenericError( None => Err(ShellError::GenericError {
"Error casting list from series".into(), error: "Error casting list from series".into(),
"".to_string(), msg: "".into(),
None, span: None,
Some(format!("List not supported for conversion: {x}")), help: Some(format!("List not supported for conversion: {x}")),
Vec::new(), inner: vec![],
)), }),
Some(ca) => { Some(ca) => {
let it = ca.into_iter(); let it = ca.into_iter();
let values: Vec<Value> = let values: Vec<Value> =
@ -831,14 +801,12 @@ fn series_to_values(
} }
} }
DataType::Date => { DataType::Date => {
let casted = series.date().map_err(|e| { let casted = series.date().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to date".into(),
"Error casting column to date".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -894,14 +862,12 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::Datetime(time_unit, _) => { DataType::Datetime(time_unit, _) => {
let casted = series.datetime().map_err(|e| { let casted = series.datetime().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error casting column to datetime".into(),
"Error casting column to datetime".into(), msg: "".into(),
"".to_string(), span: None,
None, help: Some(e.to_string()),
Some(e.to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
let it = casted.into_iter(); let it = casted.into_iter();
@ -962,15 +928,16 @@ fn series_to_values(
Ok(values) Ok(values)
} }
DataType::Time => { DataType::Time => {
let casted = series.timestamp(TimeUnit::Nanoseconds).map_err(|e| { let casted =
ShellError::GenericError( series
"Error casting column to time".into(), .timestamp(TimeUnit::Nanoseconds)
"".to_string(), .map_err(|e| ShellError::GenericError {
None, error: "Error casting column to time".into(),
Some(e.to_string()), msg: "".into(),
Vec::new(), span: None,
) help: Some(e.to_string()),
})?; inner: vec![],
})?;
let it = casted.into_iter(); let it = casted.into_iter();
let values = if let (Some(size), Some(from_row)) = (maybe_size, maybe_from_row) { let values = if let (Some(size), Some(from_row)) = (maybe_size, maybe_from_row) {
@ -986,13 +953,13 @@ fn series_to_values(
Ok(values) Ok(values)
} }
e => Err(ShellError::GenericError( e => Err(ShellError::GenericError {
"Error creating Dataframe".into(), error: "Error creating Dataframe".into(),
"".to_string(), msg: "".to_string(),
None, span: None,
Some(format!("Value not supported in nushell: {e}")), help: Some(format!("Value not supported in nushell: {e}")),
Vec::new(), inner: vec![],
)), }),
} }
} }

View File

@ -131,13 +131,13 @@ impl NuDataFrame {
pub fn series_to_value(series: Series, span: Span) -> Result<Value, ShellError> { pub fn series_to_value(series: Series, span: Span) -> Result<Value, ShellError> {
match DataFrame::new(vec![series]) { match DataFrame::new(vec![series]) {
Ok(dataframe) => Ok(NuDataFrame::dataframe_into_value(dataframe, span)), Ok(dataframe) => Ok(NuDataFrame::dataframe_into_value(dataframe, span)),
Err(e) => Err(ShellError::GenericError( Err(e) => Err(ShellError::GenericError {
"Error creating dataframe".into(), error: "Error creating dataframe".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }
@ -174,14 +174,12 @@ impl NuDataFrame {
} }
pub fn try_from_series(columns: Vec<Series>, span: Span) -> Result<Self, ShellError> { pub fn try_from_series(columns: Vec<Series>, span: Span) -> Result<Self, ShellError> {
let dataframe = DataFrame::new(columns).map_err(|e| { let dataframe = DataFrame::new(columns).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error creating dataframe".into(),
"Error creating dataframe".into(), msg: format!("Unable to create DataFrame: {e}"),
format!("Unable to create DataFrame: {e}"), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
Ok(Self::new(false, dataframe)) Ok(Self::new(false, dataframe))
@ -301,14 +299,12 @@ impl NuDataFrame {
} }
})?; })?;
let df = DataFrame::new(vec![s.clone()]).map_err(|e| { let df = DataFrame::new(vec![s.clone()]).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error creating dataframe".into(),
"Error creating dataframe".into(), msg: e.to_string(),
e.to_string(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
Ok(Self { Ok(Self {
@ -323,13 +319,13 @@ impl NuDataFrame {
pub fn as_series(&self, span: Span) -> Result<Series, ShellError> { pub fn as_series(&self, span: Span) -> Result<Series, ShellError> {
if !self.is_series() { if !self.is_series() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Error using as series".into(), error: "Error using as series".into(),
"dataframe has more than one column".into(), msg: "dataframe has more than one column".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
let series = self let series = self

View File

@ -135,14 +135,12 @@ impl NuDataFrame {
}) })
.collect::<Vec<Series>>(); .collect::<Vec<Series>>();
let df_new = DataFrame::new(new_cols).map_err(|e| { let df_new = DataFrame::new(new_cols).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error creating dataframe".into(),
"Error creating dataframe".into(), msg: e.to_string(),
e.to_string(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
Ok(NuDataFrame::new(false, df_new)) Ok(NuDataFrame::new(false, df_new))
@ -183,26 +181,24 @@ impl NuDataFrame {
match res { match res {
Ok(s) => Ok(s.clone()), Ok(s) => Ok(s.clone()),
Err(e) => Err({ Err(e) => Err({
ShellError::GenericError( ShellError::GenericError {
"Error appending dataframe".into(), error: "Error appending dataframe".into(),
format!("Unable to append: {e}"), msg: format!("Unable to append: {e}"),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
) }
}), }),
} }
}) })
.collect::<Result<Vec<Series>, ShellError>>()?; .collect::<Result<Vec<Series>, ShellError>>()?;
let df_new = DataFrame::new(new_cols).map_err(|e| { let df_new = DataFrame::new(new_cols).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error appending dataframe".into(),
"Error appending dataframe".into(), msg: format!("Unable to append dataframes: {e}"),
format!("Unable to append dataframes: {e}"), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
Ok(NuDataFrame::new(false, df_new)) Ok(NuDataFrame::new(false, df_new))

View File

@ -104,14 +104,12 @@ impl NuLazyFrame {
self.lazy self.lazy
.expect("No empty lazy for collect") .expect("No empty lazy for collect")
.collect() .collect()
.map_err(|e| { .map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error collecting lazy frame".into(),
"Error collecting lazy frame".to_string(), msg: e.to_string(),
e.to_string(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
.map(|df| NuDataFrame { .map(|df| NuDataFrame {
df, df,

View File

@ -12,14 +12,12 @@ pub(crate) fn convert_columns(
// First column span // First column span
let mut col_span = columns let mut col_span = columns
.first() .first()
.ok_or_else(|| { .ok_or_else(|| ShellError::GenericError {
ShellError::GenericError( error: "Empty column list".into(),
"Empty column list".into(), msg: "Empty list found for command".into(),
"Empty list found for command".into(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
.map(|v| v.span())?; .map(|v| v.span())?;
@ -32,13 +30,13 @@ pub(crate) fn convert_columns(
col_span = span_join(&[col_span, span]); col_span = span_join(&[col_span, span]);
Ok(Spanned { item: val, span }) Ok(Spanned { item: val, span })
} }
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Incorrect column format".into(), error: "Incorrect column format".into(),
"Only string as column name".into(), msg: "Only string as column name".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
}) })
.collect::<Result<Vec<Spanned<String>>, _>>()?; .collect::<Result<Vec<Spanned<String>>, _>>()?;
@ -55,14 +53,12 @@ pub(crate) fn convert_columns_string(
// First column span // First column span
let mut col_span = columns let mut col_span = columns
.first() .first()
.ok_or_else(|| { .ok_or_else(|| ShellError::GenericError {
ShellError::GenericError( error: "Empty column list".into(),
"Empty column list".into(), msg: "Empty list found for command".into(),
"Empty list found for command".into(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
.map(|v| v.span())?; .map(|v| v.span())?;
@ -75,13 +71,13 @@ pub(crate) fn convert_columns_string(
col_span = span_join(&[col_span, span]); col_span = span_join(&[col_span, span]);
Ok(val) Ok(val)
} }
_ => Err(ShellError::GenericError( _ => Err(ShellError::GenericError {
"Incorrect column format".into(), error: "Incorrect column format".into(),
"Only string as column name".into(), msg: "Only string as column name".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
}) })
.collect::<Result<Vec<String>, _>>()?; .collect::<Result<Vec<String>, _>>()?;

View File

@ -108,15 +108,15 @@ where
match rotate_result { match rotate_result {
Ok(val) => Value::int(val, span), Ok(val) => Value::int(val, span),
Err(_) => Value::error( Err(_) => Value::error(
ShellError::GenericError( ShellError::GenericError {
"Rotate left result beyond the range of 64 bit signed number".to_string(), error: "Rotate left result beyond the range of 64 bit signed number".into(),
format!( msg: format!(
"{val} of the specified number of bytes rotate left {bits} bits exceed limit" "{val} of the specified number of bytes rotate left {bits} bits exceed limit"
), ),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
), },
span, span,
), ),
} }

View File

@ -112,15 +112,15 @@ where
match rotate_result { match rotate_result {
Ok(val) => Value::int(val, span), Ok(val) => Value::int(val, span),
Err(_) => Value::error( Err(_) => Value::error(
ShellError::GenericError( ShellError::GenericError {
"Rotate right result beyond the range of 64 bit signed number".to_string(), error: "Rotate right result beyond the range of 64 bit signed number".into(),
format!( msg: format!(
"{val} of the specified number of bytes rotate right {bits} bits exceed limit" "{val} of the specified number of bytes rotate right {bits} bits exceed limit"
), ),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
), },
span, span,
), ),
} }

View File

@ -120,27 +120,27 @@ where
match shift_result { match shift_result {
Ok(val) => Value::int( val, span ), Ok(val) => Value::int( val, span ),
Err(_) => Value::error( Err(_) => Value::error(
ShellError::GenericError( ShellError::GenericError {
"Shift left result beyond the range of 64 bit signed number".to_string(), error:"Shift left result beyond the range of 64 bit signed number".into(),
format!( msg: format!(
"{val} of the specified number of bytes shift left {bits} bits exceed limit" "{val} of the specified number of bytes shift left {bits} bits exceed limit"
), ),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
), },
span, span,
), ),
} }
} }
None => Value::error( None => Value::error(
ShellError::GenericError( ShellError::GenericError {
"Shift left failed".to_string(), error: "Shift left failed".into(),
format!("{val} shift left {bits} bits failed, you may shift too many bits"), msg: format!("{val} shift left {bits} bits failed, you may shift too many bits"),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
), },
span, span,
), ),
} }

View File

@ -110,27 +110,27 @@ where
match shift_result { match shift_result {
Ok(val) => Value::int( val, span ), Ok(val) => Value::int( val, span ),
Err(_) => Value::error( Err(_) => Value::error(
ShellError::GenericError( ShellError::GenericError {
"Shift right result beyond the range of 64 bit signed number".to_string(), error: "Shift right result beyond the range of 64 bit signed number".into(),
format!( msg: format!(
"{val} of the specified number of bytes shift right {bits} bits exceed limit" "{val} of the specified number of bytes shift right {bits} bits exceed limit"
), ),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
), },
span, span,
), ),
} }
} }
None => Value::error( None => Value::error(
ShellError::GenericError( ShellError::GenericError {
"Shift right failed".to_string(), error: "Shift right failed".into(),
format!("{val} shift right {bits} bits failed, you may shift too many bits"), msg: format!("{val} shift right {bits} bits failed, you may shift too many bits"),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
), },
span, span,
), ),
} }

View File

@ -304,13 +304,13 @@ fn to_html(
let color_hm = match color_hm { let color_hm = match color_hm {
Ok(c) => c, Ok(c) => c,
_ => { _ => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Error finding theme name".to_string(), error: "Error finding theme name".into(),
"Error finding theme name".to_string(), msg: "Error finding theme name".into(),
Some(theme_span), span: Some(theme_span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
}; };

View File

@ -121,22 +121,22 @@ fn action(
ActionType::Decode => match hex_decode(val.as_ref()) { ActionType::Decode => match hex_decode(val.as_ref()) {
Ok(decoded_value) => Value::binary(decoded_value, command_span), Ok(decoded_value) => Value::binary(decoded_value, command_span),
Err(HexDecodingError::InvalidLength(len)) => Value::error(ShellError::GenericError( Err(HexDecodingError::InvalidLength(len)) => Value::error(ShellError::GenericError {
"value could not be hex decoded".to_string(), error: "value could not be hex decoded".into(),
format!("invalid hex input length: {len}. The length should be even"), msg: format!("invalid hex input length: {len}. The length should be even"),
Some(command_span), span: Some(command_span),
None, help: None,
Vec::new(), inner: vec![],
), },
command_span, command_span,
), ),
Err(HexDecodingError::InvalidDigit(index, digit)) => Value::error(ShellError::GenericError( Err(HexDecodingError::InvalidDigit(index, digit)) => Value::error(ShellError::GenericError {
"value could not be hex decoded".to_string(), error: "value could not be hex decoded".into(),
format!("invalid hex digit: '{digit}' at index {index}. Only 0-9, A-F, a-f are allowed in hex encoding"), msg: format!("invalid hex digit: '{digit}' at index {index}. Only 0-9, A-F, a-f are allowed in hex encoding"),
Some(command_span), span: Some(command_span),
None, help: None,
Vec::new(), inner: vec![],
), },
command_span, command_span,
), ),
}, },

View File

@ -61,13 +61,13 @@ impl Command for ErrorMake {
description: "Create a simple custom error", description: "Create a simple custom error",
example: r#"error make {msg: "my custom error message"}"#, example: r#"error make {msg: "my custom error message"}"#,
result: Some(Value::error( result: Some(Value::error(
ShellError::GenericError( ShellError::GenericError {
"my custom error message".to_string(), error: "my custom error message".into(),
"".to_string(), msg: "".into(),
None, span: None,
None, help: None,
Vec::new(), inner: vec![],
), },
Span::unknown(), Span::unknown(),
)), )),
}, },
@ -87,13 +87,13 @@ impl Command for ErrorMake {
help: "A help string, suggesting a fix to the user" # optional help: "A help string, suggesting a fix to the user" # optional
}"#, }"#,
result: Some(Value::error( result: Some(Value::error(
ShellError::GenericError( ShellError::GenericError {
"my custom error message".to_string(), error: "my custom error message".into(),
"my custom label text".to_string(), msg: "my custom label text".into(),
Some(Span::new(123, 456)), span: Some(Span::new(123, 456)),
Some("A help string, suggesting a fix to the user".to_string()), help: Some("A help string, suggesting a fix to the user".into()),
Vec::new(), inner: vec![],
), },
Span::unknown(), Span::unknown(),
)), )),
}, },
@ -122,35 +122,35 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
let value = match value { let value = match value {
Value::Record { val, .. } => val, Value::Record { val, .. } => val,
_ => { _ => {
return ShellError::GenericError( return ShellError::GenericError {
"Creating error value not supported.".into(), error: "Creating error value not supported.".into(),
"unsupported error format, must be a record".into(), msg: "unsupported error format, must be a record".into(),
throw_span, span: throw_span,
None, help: None,
Vec::new(), inner: vec![],
) }
} }
}; };
let msg = match value.get("msg") { let msg = match value.get("msg") {
Some(Value::String { val, .. }) => val.clone(), Some(Value::String { val, .. }) => val.clone(),
Some(_) => { Some(_) => {
return ShellError::GenericError( return ShellError::GenericError {
UNABLE_TO_PARSE.into(), error: UNABLE_TO_PARSE.into(),
"`$.msg` has wrong type, must be string".into(), msg: "`$.msg` has wrong type, must be string".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
) }
} }
None => { None => {
return ShellError::GenericError( return ShellError::GenericError {
UNABLE_TO_PARSE.into(), error: UNABLE_TO_PARSE.into(),
"missing required member `$.msg`".into(), msg: "missing required member `$.msg`".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
) }
} }
}; };
@ -162,72 +162,80 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
let (label, label_span) = match value.get("label") { let (label, label_span) = match value.get("label") {
Some(value @ Value::Record { val, .. }) => (val, value.span()), Some(value @ Value::Record { val, .. }) => (val, value.span()),
Some(_) => { Some(_) => {
return ShellError::GenericError( return ShellError::GenericError {
UNABLE_TO_PARSE.into(), error: UNABLE_TO_PARSE.into(),
"`$.label` has wrong type, must be a record".into(), msg: "`$.label` has wrong type, must be a record".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
) }
} }
// correct return: no label // correct return: no label
None => { None => {
return ShellError::GenericError( return ShellError::GenericError {
msg, error: msg,
"originates from here".to_string(), msg: "originates from here".into(),
throw_span, span: throw_span,
help, help,
Vec::new(), inner: vec![],
) }
} }
}; };
// remove after a few versions // remove after a few versions
if label.get("start").is_some() || label.get("end").is_some() { if label.get("start").is_some() || label.get("end").is_some() {
return ShellError::GenericError( return ShellError::GenericError {
UNABLE_TO_PARSE.into(), error: UNABLE_TO_PARSE.into(),
"`start` and `end` are deprecated".into(), msg: "`start` and `end` are deprecated".into(),
Some(span), span: Some(span),
Some("Use `$.label.span` instead".into()), help: Some("Use `$.label.span` instead".into()),
Vec::new(), inner: vec![],
); };
} }
let text = match label.get("text") { let text = match label.get("text") {
Some(Value::String { val, .. }) => val.clone(), Some(Value::String { val, .. }) => val.clone(),
Some(_) => { Some(_) => {
return ShellError::GenericError( return ShellError::GenericError {
UNABLE_TO_PARSE.into(), error: UNABLE_TO_PARSE.into(),
"`$.label.text` has wrong type, must be string".into(), msg: "`$.label.text` has wrong type, must be string".into(),
Some(label_span), span: Some(label_span),
None, help: None,
Vec::new(), inner: vec![],
) }
} }
None => { None => {
return ShellError::GenericError( return ShellError::GenericError {
UNABLE_TO_PARSE.into(), error: UNABLE_TO_PARSE.into(),
"missing required member `$.label.text`".into(), msg: "missing required member `$.label.text`".into(),
Some(label_span), span: Some(label_span),
None, help: None,
Vec::new(), inner: vec![],
) }
} }
}; };
let (span, span_span) = match label.get("span") { let (span, span_span) = match label.get("span") {
Some(value @ Value::Record { val, .. }) => (val, value.span()), Some(value @ Value::Record { val, .. }) => (val, value.span()),
Some(value) => { Some(value) => {
return ShellError::GenericError( return ShellError::GenericError {
UNABLE_TO_PARSE.into(), error: UNABLE_TO_PARSE.into(),
"`$.label.span` has wrong type, must be record".into(), msg: "`$.label.span` has wrong type, must be record".into(),
Some(value.span()), span: Some(value.span()),
None, help: None,
Vec::new(), inner: vec![],
) }
} }
// correct return: label, no span // correct return: label, no span
None => return ShellError::GenericError(msg, text, throw_span, help, Vec::new()), None => {
return ShellError::GenericError {
error: msg,
msg: text,
span: throw_span,
help,
inner: vec![],
}
}
}; };
let span_start = match get_span_sides(span, span_span, "start") { let span_start = match get_span_sides(span, span_span, "start") {
@ -240,41 +248,41 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
}; };
if span_start > span_end { if span_start > span_end {
return ShellError::GenericError( return ShellError::GenericError {
"invalid error format.".into(), error: "invalid error format.".into(),
"`$.label.start` should be smaller than `$.label.end`".into(), msg: "`$.label.start` should be smaller than `$.label.end`".into(),
Some(label_span), span: Some(label_span),
Some(format!("{} > {}", span_start, span_end)), help: Some(format!("{} > {}", span_start, span_end)),
Vec::new(), inner: vec![],
); };
} }
// correct return: everything present // correct return: everything present
ShellError::GenericError( ShellError::GenericError {
msg, error: msg,
text, msg: text,
Some(Span::new(span_start as usize, span_end as usize)), span: Some(Span::new(span_start as usize, span_end as usize)),
help, help,
Vec::new(), inner: vec![],
) }
} }
fn get_span_sides(span: &Record, span_span: Span, side: &str) -> Result<i64, ShellError> { fn get_span_sides(span: &Record, span_span: Span, side: &str) -> Result<i64, ShellError> {
match span.get(side) { match span.get(side) {
Some(Value::Int { val, .. }) => Ok(*val), Some(Value::Int { val, .. }) => Ok(*val),
Some(_) => Err(ShellError::GenericError( Some(_) => Err(ShellError::GenericError {
UNABLE_TO_PARSE.into(), error: UNABLE_TO_PARSE.into(),
format!("`$.span.{side}` must be int"), msg: format!("`$.span.{side}` must be int"),
Some(span_span), span: Some(span_span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
None => Err(ShellError::GenericError( None => Err(ShellError::GenericError {
UNABLE_TO_PARSE.into(), error: UNABLE_TO_PARSE.into(),
format!("`$.span.{side}` must be present, if span is specified."), msg: format!("`$.span.{side}` must be present, if span is specified."),
Some(span_span), span: Some(span_span),
None, help: None,
Vec::new(), inner: vec![],
)), }),
} }
} }

View File

@ -58,13 +58,13 @@ This command is a parser keyword. For details, check:
.. ..
}) = call.get_parser_info("import_pattern") }) = call.get_parser_info("import_pattern")
else { else {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Unexpected import".into(), error: "Unexpected import".into(),
"import pattern not supported".into(), msg: "import pattern not supported".into(),
Some(call.head), span: Some(call.head),
None, help: None,
Vec::new(), inner: vec![],
)); });
}; };
if let Some(module_id) = import_pattern.head.id { if let Some(module_id) = import_pattern.head.id {
@ -131,16 +131,16 @@ This command is a parser keyword. For details, check:
redirect_env(engine_state, caller_stack, &callee_stack); redirect_env(engine_state, caller_stack, &callee_stack);
} }
} else { } else {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
format!( error: format!(
"Could not import from '{}'", "Could not import from '{}'",
String::from_utf8_lossy(&import_pattern.head.name) String::from_utf8_lossy(&import_pattern.head.name)
), ),
"module does not exist".to_string(), msg: "module does not exist".to_string(),
Some(import_pattern.head.span), span: Some(import_pattern.head.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
Ok(PipelineData::empty()) Ok(PipelineData::empty())

View File

@ -155,25 +155,23 @@ fn action(
format!("CREATE TABLE IF NOT EXISTS [{table_name}] ({table_columns_creation})"); format!("CREATE TABLE IF NOT EXISTS [{table_name}] ({table_columns_creation})");
// prepare the string as a sqlite statement // prepare the string as a sqlite statement
let mut stmt = conn.prepare(&create_statement).map_err(|e| { let mut stmt =
ShellError::GenericError( conn.prepare(&create_statement)
"Failed to prepare SQLite statement".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Failed to prepare SQLite statement".into(),
Some(file.span), msg: e.to_string(),
None, span: Some(file.span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
// execute the statement // execute the statement
stmt.execute([]).map_err(|e| { stmt.execute([]).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Failed to execute SQLite statement".into(),
"Failed to execute SQLite statement".into(), msg: e.to_string(),
e.to_string(), span: Some(file.span),
Some(file.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
// use normal sql to create the table // use normal sql to create the table
@ -187,25 +185,23 @@ fn action(
let insert_statement = format!("INSERT INTO [{table_name}] VALUES {table_values}"); let insert_statement = format!("INSERT INTO [{table_name}] VALUES {table_values}");
// prepare the string as a sqlite statement // prepare the string as a sqlite statement
let mut stmt = conn.prepare(&insert_statement).map_err(|e| { let mut stmt =
ShellError::GenericError( conn.prepare(&insert_statement)
"Failed to prepare SQLite statement".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Failed to prepare SQLite statement".into(),
Some(file.span), msg: e.to_string(),
None, span: Some(file.span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
// execute the statement // execute the statement
stmt.execute([]).map_err(|e| { stmt.execute([]).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Failed to execute SQLite statement".into(),
"Failed to execute SQLite statement".into(), msg: e.to_string(),
e.to_string(), span: Some(file.span),
Some(file.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
// and we're done // and we're done

View File

@ -47,15 +47,15 @@ impl Command for SchemaDb {
let sqlite_db = SQLiteDatabase::try_from_pipeline(input, span)?; let sqlite_db = SQLiteDatabase::try_from_pipeline(input, span)?;
let conn = open_sqlite_db_connection(&sqlite_db, span)?; let conn = open_sqlite_db_connection(&sqlite_db, span)?;
let tables = sqlite_db.get_tables(&conn).map_err(|e| { let tables = sqlite_db
ShellError::GenericError( .get_tables(&conn)
"Error reading tables".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error reading tables".into(),
Some(span), msg: e.to_string(),
None, span: Some(span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
let mut tables_record = Record::new(); let mut tables_record = Record::new();
for table in tables { for table in tables {
@ -87,14 +87,12 @@ impl Command for SchemaDb {
} }
fn open_sqlite_db_connection(db: &SQLiteDatabase, span: Span) -> Result<Connection, ShellError> { fn open_sqlite_db_connection(db: &SQLiteDatabase, span: Span) -> Result<Connection, ShellError> {
db.open_connection().map_err(|e| { db.open_connection().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error opening file".into(),
"Error opening file".into(), msg: e.to_string(),
e.to_string(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
} }
@ -104,15 +102,15 @@ fn get_table_columns(
table: &DbTable, table: &DbTable,
span: Span, span: Span,
) -> Result<Vec<Value>, ShellError> { ) -> Result<Vec<Value>, ShellError> {
let columns = db.get_columns(conn, table).map_err(|e| { let columns = db
ShellError::GenericError( .get_columns(conn, table)
"Error getting database columns".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error getting database columns".into(),
Some(span), msg: e.to_string(),
None, span: Some(span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
// a record of column name = column value // a record of column name = column value
let mut column_info = vec![]; let mut column_info = vec![];
@ -136,15 +134,15 @@ fn get_table_constraints(
table: &DbTable, table: &DbTable,
span: Span, span: Span,
) -> Result<Vec<Value>, ShellError> { ) -> Result<Vec<Value>, ShellError> {
let constraints = db.get_constraints(conn, table).map_err(|e| { let constraints = db
ShellError::GenericError( .get_constraints(conn, table)
"Error getting DB constraints".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error getting DB constraints".into(),
Some(span), msg: e.to_string(),
None, span: Some(span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
let mut constraint_info = vec![]; let mut constraint_info = vec![];
for constraint in constraints { for constraint in constraints {
constraint_info.push(Value::record( constraint_info.push(Value::record(
@ -167,15 +165,15 @@ fn get_table_foreign_keys(
table: &DbTable, table: &DbTable,
span: Span, span: Span,
) -> Result<Vec<Value>, ShellError> { ) -> Result<Vec<Value>, ShellError> {
let foreign_keys = db.get_foreign_keys(conn, table).map_err(|e| { let foreign_keys = db
ShellError::GenericError( .get_foreign_keys(conn, table)
"Error getting DB Foreign Keys".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error getting DB Foreign Keys".into(),
Some(span), msg: e.to_string(),
None, span: Some(span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
let mut foreign_key_info = vec![]; let mut foreign_key_info = vec![];
for fk in foreign_keys { for fk in foreign_keys {
foreign_key_info.push(Value::record( foreign_key_info.push(Value::record(
@ -197,15 +195,15 @@ fn get_table_indexes(
table: &DbTable, table: &DbTable,
span: Span, span: Span,
) -> Result<Vec<Value>, ShellError> { ) -> Result<Vec<Value>, ShellError> {
let indexes = db.get_indexes(conn, table).map_err(|e| { let indexes = db
ShellError::GenericError( .get_indexes(conn, table)
"Error getting DB Indexes".into(), .map_err(|e| ShellError::GenericError {
e.to_string(), error: "Error getting DB Indexes".into(),
Some(span), msg: e.to_string(),
None, span: Some(span),
Vec::new(), help: None,
) inner: vec![],
})?; })?;
let mut index_info = vec![]; let mut index_info = vec![];
for index in indexes { for index in indexes {
index_info.push(Value::record( index_info.push(Value::record(

View File

@ -102,15 +102,14 @@ impl SQLiteDatabase {
pub fn query(&self, sql: &Spanned<String>, call_span: Span) -> Result<Value, ShellError> { pub fn query(&self, sql: &Spanned<String>, call_span: Span) -> Result<Value, ShellError> {
let conn = open_sqlite_db(&self.path, call_span)?; let conn = open_sqlite_db(&self.path, call_span)?;
let stream = run_sql_query(conn, sql, self.ctrlc.clone()).map_err(|e| { let stream =
ShellError::GenericError( run_sql_query(conn, sql, self.ctrlc.clone()).map_err(|e| ShellError::GenericError {
"Failed to query SQLite database".into(), error: "Failed to query SQLite database".into(),
e.to_string(), msg: e.to_string(),
Some(sql.span), span: Some(sql.span),
None, help: None,
Vec::new(), inner: vec![],
) })?;
})?;
Ok(stream) Ok(stream)
} }
@ -119,14 +118,12 @@ impl SQLiteDatabase {
if self.path == PathBuf::from(MEMORY_DB) { if self.path == PathBuf::from(MEMORY_DB) {
open_connection_in_memory_custom() open_connection_in_memory_custom()
} else { } else {
Connection::open(&self.path).map_err(|e| { Connection::open(&self.path).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Failed to open SQLite database from open_connection".into(),
"Failed to open SQLite database from open_connection".into(), msg: e.to_string(),
e.to_string(), span: None,
None, help: None,
None, inner: vec![],
Vec::new(),
)
}) })
} }
} }
@ -362,14 +359,12 @@ impl CustomValue for SQLiteDatabase {
fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { fn to_base_value(&self, span: Span) -> Result<Value, ShellError> {
let db = open_sqlite_db(&self.path, span)?; let db = open_sqlite_db(&self.path, span)?;
read_entire_sqlite_db(db, span, self.ctrlc.clone()).map_err(|e| { read_entire_sqlite_db(db, span, self.ctrlc.clone()).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Failed to read from SQLite database".into(),
"Failed to read from SQLite database".into(), msg: e.to_string(),
e.to_string(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
} }
@ -386,13 +381,13 @@ impl CustomValue for SQLiteDatabase {
let db = open_sqlite_db(&self.path, span)?; let db = open_sqlite_db(&self.path, span)?;
read_single_table(db, _column_name, span, self.ctrlc.clone()).map_err(|e| { read_single_table(db, _column_name, span, self.ctrlc.clone()).map_err(|e| {
ShellError::GenericError( ShellError::GenericError {
"Failed to read from SQLite database".into(), error: "Failed to read from SQLite database".into(),
e.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
) }
}) })
} }
@ -410,14 +405,12 @@ pub fn open_sqlite_db(path: &Path, call_span: Span) -> Result<Connection, ShellE
open_connection_in_memory_custom() open_connection_in_memory_custom()
} else { } else {
let path = path.to_string_lossy().to_string(); let path = path.to_string_lossy().to_string();
Connection::open(path).map_err(|e| { Connection::open(path).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Failed to open SQLite database".into(),
"Failed to open SQLite database".into(), msg: e.to_string(),
e.to_string(), span: Some(call_span),
Some(call_span), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
} }
} }
@ -611,25 +604,21 @@ mod test {
pub fn open_connection_in_memory_custom() -> Result<Connection, ShellError> { pub fn open_connection_in_memory_custom() -> Result<Connection, ShellError> {
let flags = OpenFlags::default(); let flags = OpenFlags::default();
Connection::open_with_flags(MEMORY_DB, flags).map_err(|err| { Connection::open_with_flags(MEMORY_DB, flags).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Failed to open SQLite custom connection in memory".into(),
"Failed to open SQLite custom connection in memory".into(), msg: e.to_string(),
err.to_string(), span: Some(Span::test_data()),
Some(Span::test_data()), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
} }
pub fn open_connection_in_memory() -> Result<Connection, ShellError> { pub fn open_connection_in_memory() -> Result<Connection, ShellError> {
Connection::open_in_memory().map_err(|err| { Connection::open_in_memory().map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Failed to open SQLite standard connection in memory".into(),
"Failed to open SQLite standard connection in memory".into(), msg: e.to_string(),
err.to_string(), span: Some(Span::test_data()),
Some(Span::test_data()), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
} }

View File

@ -85,22 +85,22 @@ impl Command for ViewSource {
final_contents.push_str(&String::from_utf8_lossy(contents)); final_contents.push_str(&String::from_utf8_lossy(contents));
Ok(Value::string(final_contents, call.head).into_pipeline_data()) Ok(Value::string(final_contents, call.head).into_pipeline_data())
} else { } else {
Err(ShellError::GenericError( Err(ShellError::GenericError {
"Cannot view value".to_string(), error: "Cannot view value".to_string(),
"the command does not have a viewable block".to_string(), msg: "the command does not have a viewable block".to_string(),
Some(arg_span), span: Some(arg_span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
} else { } else {
Err(ShellError::GenericError( Err(ShellError::GenericError {
"Cannot view value".to_string(), error: "Cannot view value".to_string(),
"the command does not have a viewable block".to_string(), msg: "the command does not have a viewable block".to_string(),
Some(arg_span), span: Some(arg_span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
} else if let Some(module_id) = engine_state.find_module(val.as_bytes(), &[]) { } else if let Some(module_id) = engine_state.find_module(val.as_bytes(), &[]) {
// arg is a module // arg is a module
@ -110,22 +110,22 @@ impl Command for ViewSource {
Ok(Value::string(String::from_utf8_lossy(contents), call.head) Ok(Value::string(String::from_utf8_lossy(contents), call.head)
.into_pipeline_data()) .into_pipeline_data())
} else { } else {
Err(ShellError::GenericError( Err(ShellError::GenericError {
"Cannot view value".to_string(), error: "Cannot view value".to_string(),
"the module does not have a viewable block".to_string(), msg: "the module does not have a viewable block".to_string(),
Some(arg_span), span: Some(arg_span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
} else { } else {
Err(ShellError::GenericError( Err(ShellError::GenericError {
"Cannot view value".to_string(), error: "Cannot view value".to_string(),
"this name does not correspond to a viewable value".to_string(), msg: "this name does not correspond to a viewable value".to_string(),
Some(arg_span), span: Some(arg_span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
} }
value => { value => {
@ -140,13 +140,13 @@ impl Command for ViewSource {
Ok(Value::string("<internal command>", call.head).into_pipeline_data()) Ok(Value::string("<internal command>", call.head).into_pipeline_data())
} }
} else { } else {
Err(ShellError::GenericError( Err(ShellError::GenericError {
"Cannot view value".to_string(), error: "Cannot view value".to_string(),
"this value cannot be viewed".to_string(), msg: "this value cannot be viewed".to_string(),
Some(arg_span), span: Some(arg_span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
} }
} }

View File

@ -48,13 +48,13 @@ impl Command for ViewSpan {
.into_pipeline_data(), .into_pipeline_data(),
) )
} else { } else {
Err(ShellError::GenericError( Err(ShellError::GenericError {
"Cannot view span".to_string(), error: "Cannot view span".to_string(),
"this start and end does not correspond to a viewable value".to_string(), msg: "this start and end does not correspond to a viewable value".to_string(),
Some(call.head), span: Some(call.head),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
} }

View File

@ -68,13 +68,13 @@ impl Command for ConfigEnv {
let nu_config = match engine_state.get_config_path("env-path") { let nu_config = match engine_state.get_config_path("env-path") {
Some(path) => path.clone(), Some(path) => path.clone(),
None => { None => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Could not find $nu.env-path".to_string(), error: "Could not find $nu.env-path".into(),
"Could not find $nu.env-path".to_string(), msg: "Could not find $nu.env-path".into(),
None, span: None,
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
}; };

View File

@ -72,13 +72,13 @@ impl Command for ConfigNu {
let nu_config = match engine_state.get_config_path("config-path") { let nu_config = match engine_state.get_config_path("config-path") {
Some(path) => path.clone(), Some(path) => path.clone(),
None => { None => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Could not find $nu.config-path".to_string(), error: "Could not find $nu.config-path".into(),
"Could not find $nu.config-path".to_string(), msg: "Could not find $nu.config-path".into(),
None, span: None,
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
}; };

View File

@ -51,13 +51,13 @@ impl Command for ConfigReset {
let mut config_path = match nu_path::config_dir() { let mut config_path = match nu_path::config_dir() {
Some(path) => path, Some(path) => path,
None => { None => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Could not find config path".to_string(), error: "Could not find config path".into(),
"Could not find config path".to_string(), msg: "Could not find config path".into(),
None, span: None,
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
}; };
config_path.push("nushell"); config_path.push("nushell");

View File

@ -100,13 +100,13 @@ impl Command for Cp {
let sources: Vec<_> = match arg_glob(&src, &current_dir_path) { let sources: Vec<_> = match arg_glob(&src, &current_dir_path) {
Ok(files) => files.collect(), Ok(files) => files.collect(),
Err(e) => { Err(e) => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
e.to_string(), error: e.to_string(),
"invalid pattern".to_string(), msg: "invalid pattern".into(),
Some(src.span), span: Some(src.span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
}; };
@ -115,25 +115,25 @@ impl Command for Cp {
} }
if sources.len() > 1 && !destination.is_dir() { if sources.len() > 1 && !destination.is_dir() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Destination must be a directory when copying multiple files".into(), error: "Destination must be a directory when copying multiple files".into(),
"is not a directory".into(), msg: "is not a directory".into(),
Some(dst.span), span: Some(dst.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
let any_source_is_dir = sources.iter().any(|f| matches!(f, Ok(f) if f.is_dir())); let any_source_is_dir = sources.iter().any(|f| matches!(f, Ok(f) if f.is_dir()));
if any_source_is_dir && !recursive { if any_source_is_dir && !recursive {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Directories must be copied using \"--recursive\"".into(), error: "Directories must be copied using \"--recursive\"".into(),
"resolves to a directory (not copied)".into(), msg: "resolves to a directory (not copied)".into(),
Some(src.span), span: Some(src.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
let mut result = Vec::new(); let mut result = Vec::new();
@ -170,15 +170,15 @@ impl Command for Cp {
} }
let res = if src == dst { let res = if src == dst {
let message = format!("src and dst identical: {:?} (not copied)", src); let msg = format!("src and dst identical: {:?} (not copied)", src);
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Copy aborted".into(), error: "Copy aborted".into(),
message, msg,
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} else if interactive && dst.exists() { } else if interactive && dst.exists() {
if progress { if progress {
interactive_copy( interactive_copy(
@ -210,25 +210,23 @@ impl Command for Cp {
match entry.file_name() { match entry.file_name() {
Some(name) => destination.join(name), Some(name) => destination.join(name),
None => { None => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Copy aborted. Not a valid path".into(), error: "Copy aborted. Not a valid path".into(),
"not a valid path".into(), msg: "not a valid path".into(),
Some(dst.span), span: Some(dst.span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
} }
}; };
std::fs::create_dir_all(&destination).map_err(|e| { std::fs::create_dir_all(&destination).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: e.to_string(),
e.to_string(), msg: e.to_string(),
e.to_string(), span: Some(dst.span),
Some(dst.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
let not_follow_symlink = call.has_flag("no-symlink"); let not_follow_symlink = call.has_flag("no-symlink");
@ -271,14 +269,12 @@ impl Command for Cp {
} }
if s.is_dir() && !d.exists() { if s.is_dir() && !d.exists() {
std::fs::create_dir_all(&d).map_err(|e| { std::fs::create_dir_all(&d).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: e.to_string(),
e.to_string(), msg: e.to_string(),
e.to_string(), span: Some(dst.span),
Some(dst.span), help: None,
None, inner: vec![],
Vec::new(),
)
})?; })?;
} }
if s.is_symlink() && not_follow_symlink { if s.is_symlink() && not_follow_symlink {
@ -374,7 +370,13 @@ fn interactive_copy(
); );
if let Err(e) = interaction { if let Err(e) = interaction {
Value::error( Value::error(
ShellError::GenericError(e.to_string(), e.to_string(), Some(span), None, Vec::new()), ShellError::GenericError {
error: e.to_string(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
},
span, span,
) )
} else if !confirmed { } else if !confirmed {
@ -506,15 +508,15 @@ fn copy_symlink(
let target_path = read_link(src.as_path()); let target_path = read_link(src.as_path());
let target_path = match target_path { let target_path = match target_path {
Ok(p) => p, Ok(p) => p,
Err(err) => { Err(e) => {
return Value::error( return Value::error(
ShellError::GenericError( ShellError::GenericError {
err.to_string(), error: e.to_string(),
err.to_string(), msg: e.to_string(),
Some(span), span: Some(span),
None, help: None,
vec![], inner: vec![],
), },
span, span,
) )
} }
@ -542,7 +544,13 @@ fn copy_symlink(
Value::string(msg, span) Value::string(msg, span)
} }
Err(e) => Value::error( Err(e) => Value::error(
ShellError::GenericError(e.to_string(), e.to_string(), Some(span), None, vec![]), ShellError::GenericError {
error: e.to_string(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
},
span, span,
), ),
} }

View File

@ -158,13 +158,13 @@ impl Command for Glob {
}; };
if glob_pattern.item.is_empty() { if glob_pattern.item.is_empty() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"glob pattern must not be empty".to_string(), error: "glob pattern must not be empty".into(),
"glob pattern is empty".to_string(), msg: "glob pattern is empty".into(),
Some(glob_pattern.span), span: Some(glob_pattern.span),
Some("add characters to the glob pattern".to_string()), help: Some("add characters to the glob pattern".into()),
Vec::new(), inner: vec![],
)); });
} }
let folder_depth = if let Some(depth) = depth { let folder_depth = if let Some(depth) = depth {
@ -176,13 +176,13 @@ impl Command for Glob {
let (prefix, glob) = match WaxGlob::new(&glob_pattern.item) { let (prefix, glob) = match WaxGlob::new(&glob_pattern.item) {
Ok(p) => p.partition(), Ok(p) => p.partition(),
Err(e) => { Err(e) => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"error with glob pattern".to_string(), error: "error with glob pattern".into(),
format!("{e}"), msg: format!("{e}"),
Some(glob_pattern.span), span: Some(glob_pattern.span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
}; };
@ -195,13 +195,13 @@ impl Command for Glob {
std::path::PathBuf::new() // user should get empty list not an error std::path::PathBuf::new() // user should get empty list not an error
} }
Err(e) => { Err(e) => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"error in canonicalize".to_string(), error: "error in canonicalize".into(),
format!("{e}"), msg: format!("{e}"),
Some(glob_pattern.span), span: Some(glob_pattern.span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
}; };
@ -216,14 +216,12 @@ impl Command for Glob {
}, },
) )
.not(np) .not(np)
.map_err(|err| { .map_err(|err| ShellError::GenericError {
ShellError::GenericError( error: "error with glob's not pattern".into(),
"error with glob's not pattern".to_string(), msg: format!("{err}"),
format!("{err}"), span: Some(not_pattern_span),
Some(not_pattern_span), help: None,
None, inner: vec![],
Vec::new(),
)
})? })?
.flatten(); .flatten();
let result = glob_to_value(ctrlc, glob_results, no_dirs, no_files, no_symlinks, span)?; let result = glob_to_value(ctrlc, glob_results, no_dirs, no_files, no_symlinks, span)?;

View File

@ -120,13 +120,13 @@ impl Command for Ls {
); );
#[cfg(not(unix))] #[cfg(not(unix))]
let error_msg = String::from("Permission denied"); let error_msg = String::from("Permission denied");
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Permission denied".to_string(), error: "Permission denied".into(),
error_msg, msg: error_msg,
Some(p_tag), span: Some(p_tag),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
if is_empty_dir(&expanded) { if is_empty_dir(&expanded) {
return Ok(Value::list(vec![], call_span).into_pipeline_data()); return Ok(Value::list(vec![], call_span).into_pipeline_data());
@ -168,13 +168,13 @@ impl Command for Ls {
let mut paths_peek = paths.peekable(); let mut paths_peek = paths.peekable();
if paths_peek.peek().is_none() { if paths_peek.peek().is_none() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
format!("No matches found for {}", &path.display().to_string()), error: format!("No matches found for {}", &path.display().to_string()),
"Pattern, file or folder not found".to_string(), msg: "Pattern, file or folder not found".into(),
Some(p_tag), span: Some(p_tag),
Some("no matches found".to_string()), help: Some("no matches found".into()),
Vec::new(), inner: vec![],
)); });
} }
let mut hidden_dirs = vec![]; let mut hidden_dirs = vec![];
@ -233,14 +233,12 @@ impl Command for Ls {
} else { } else {
Some(path.to_string_lossy().to_string()) Some(path.to_string_lossy().to_string())
} }
.ok_or_else(|| { .ok_or_else(|| ShellError::GenericError {
ShellError::GenericError( error: format!("Invalid file name: {:}", path.to_string_lossy()),
format!("Invalid file name: {:}", path.to_string_lossy()), msg: "invalid file name".into(),
"invalid file name".into(), span: Some(call_span),
Some(call_span), help: None,
None, inner: vec![],
Vec::new(),
)
}); });
match display_name { match display_name {

View File

@ -119,13 +119,13 @@ impl Command for Mktemp {
})? })?
} }
Err(e) => { Err(e) => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
format!("{}", e), error: format!("{}", e),
format!("{}", e), msg: format!("{}", e),
None, span: None,
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
}; };
Ok(PipelineData::Value(Value::string(res, span), None)) Ok(PipelineData::Value(Value::string(res, span), None))

View File

@ -96,31 +96,31 @@ impl Command for Mv {
// it's an error. // it's an error.
if destination.exists() && !force && !destination.is_dir() && !source.is_dir() { if destination.exists() && !force && !destination.is_dir() && !source.is_dir() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Destination file already exists".into(), error: "Destination file already exists".into(),
// These messages all use to_string_lossy() because // These messages all use to_string_lossy() because
// showing the full path reduces misinterpretation of the message. // showing the full path reduces misinterpretation of the message.
// Also, this is preferable to {:?} because that renders Windows paths incorrectly. // Also, this is preferable to {:?} because that renders Windows paths incorrectly.
format!( msg: format!(
"Destination file '{}' already exists", "Destination file '{}' already exists",
destination.to_string_lossy() destination.to_string_lossy()
), ),
Some(spanned_destination.span), span: Some(spanned_destination.span),
Some("you can use -f, --force to force overwriting the destination".into()), help: Some("you can use -f, --force to force overwriting the destination".into()),
Vec::new(), inner: vec![],
)); });
} }
if (destination.exists() && !destination.is_dir() && sources.len() > 1) if (destination.exists() && !destination.is_dir() && sources.len() > 1)
|| (!destination.exists() && sources.len() > 1) || (!destination.exists() && sources.len() > 1)
{ {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Can only move multiple sources if destination is a directory".into(), error: "Can only move multiple sources if destination is a directory".into(),
"destination must be a directory when moving multiple sources".into(), msg: "destination must be a directory when moving multiple sources".into(),
Some(spanned_destination.span), span: Some(spanned_destination.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
// This is the case where you move a directory A to the interior of directory B, but directory B // This is the case where you move a directory A to the interior of directory B, but directory B
@ -129,17 +129,17 @@ impl Command for Mv {
if let Some(name) = source.file_name() { if let Some(name) = source.file_name() {
let dst = destination.join(name); let dst = destination.join(name);
if dst.is_dir() { if dst.is_dir() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
format!( error: format!(
"Can't move '{}' to '{}'", "Can't move '{}' to '{}'",
source.to_string_lossy(), source.to_string_lossy(),
dst.to_string_lossy() dst.to_string_lossy()
), ),
format!("Directory '{}' is not empty", destination.to_string_lossy()), msg: format!("Directory '{}' is not empty", destination.to_string_lossy()),
Some(spanned_destination.span), span: Some(spanned_destination.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
} }
} }
@ -149,16 +149,16 @@ impl Command for Mv {
.find(|f| matches!(f, Ok(f) if destination.starts_with(f))); .find(|f| matches!(f, Ok(f) if destination.starts_with(f)));
if destination.exists() && destination.is_dir() && sources.len() == 1 { if destination.exists() && destination.is_dir() && sources.len() == 1 {
if let Some(Ok(filename)) = some_if_source_is_destination { if let Some(Ok(filename)) = some_if_source_is_destination {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
format!( error: format!(
"Not possible to move '{}' to itself", "Not possible to move '{}' to itself",
filename.to_string_lossy() filename.to_string_lossy()
), ),
"cannot move to itself".into(), msg: "cannot move to itself".into(),
Some(spanned_destination.span), span: Some(spanned_destination.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
} }
@ -291,13 +291,13 @@ fn move_file(
format!("mv: overwrite '{}'? ", to.to_string_lossy()), format!("mv: overwrite '{}'? ", to.to_string_lossy()),
); );
if let Err(e) = interaction { if let Err(e) = interaction {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
format!("Error during interaction: {e:}"), error: format!("Error during interaction: {e:}"),
"could not move".into(), msg: "could not move".into(),
None, span: None,
None, help: None,
Vec::new(), inner: vec![],
)); });
} else if !confirmed { } else if !confirmed {
return Ok(false); return Ok(false);
} }
@ -341,13 +341,13 @@ fn move_item(from: &Path, from_span: Span, to: &Path) -> Result<(), ShellError>
} }
_ => e.to_string(), _ => e.to_string(),
}; };
Err(ShellError::GenericError( Err(ShellError::GenericError {
format!("Could not move {from:?} to {to:?}. Error Kind: {error_kind}"), error: format!("Could not move {from:?} to {to:?}. Error Kind: {error_kind}"),
"could not move".into(), msg: "could not move".into(),
Some(from_span), span: Some(from_span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
} }
}) })

View File

@ -125,13 +125,13 @@ impl Command for Open {
#[cfg(not(unix))] #[cfg(not(unix))]
let error_msg = String::from("Permission denied"); let error_msg = String::from("Permission denied");
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Permission denied".into(), error: "Permission denied".into(),
error_msg, msg: error_msg,
Some(arg_span), span: Some(arg_span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} else { } else {
#[cfg(feature = "sqlite")] #[cfg(feature = "sqlite")]
if !raw { if !raw {
@ -146,13 +146,13 @@ impl Command for Open {
let file = match std::fs::File::open(path) { let file = match std::fs::File::open(path) {
Ok(file) => file, Ok(file) => file,
Err(err) => { Err(err) => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Permission denied".into(), error: "Permission denied".into(),
err.to_string(), msg: err.to_string(),
Some(arg_span), span: Some(arg_span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
}; };
@ -200,13 +200,13 @@ impl Command for Open {
decl.run(engine_state, stack, &Call::new(call_span), file_contents) decl.run(engine_state, stack, &Call::new(call_span), file_contents)
}; };
output.push(command_output.map_err(|inner| { output.push(command_output.map_err(|inner| {
ShellError::GenericError( ShellError::GenericError{
format!("Error while parsing as {ext}"), error: format!("Error while parsing as {ext}"),
format!("Could not parse '{}' with `from {}`", path.display(), ext), msg: format!("Could not parse '{}' with `from {}`", path.display(), ext),
Some(arg_span), span: Some(arg_span),
Some(format!("Check out `help from {}` or `help from` for more options or open raw data with `open --raw '{}'`", ext, path.display())), help: Some(format!("Check out `help from {}` or `help from` for more options or open raw data with `open --raw '{}'`", ext, path.display())),
vec![inner], inner: vec![inner],
) }
})?); })?);
} }
None => output.push(file_contents), None => output.push(file_contents),

View File

@ -173,47 +173,47 @@ fn rm(
if !TRASH_SUPPORTED { if !TRASH_SUPPORTED {
if rm_always_trash { if rm_always_trash {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Cannot execute `rm`; the current configuration specifies \ error: "Cannot execute `rm`; the current configuration specifies \
`always_trash = true`, but the current nu executable was not \ `always_trash = true`, but the current nu executable was not \
built with feature `trash_support`." built with feature `trash_support`."
.into(), .into(),
"trash required to be true but not supported".into(), msg: "trash required to be true but not supported".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} else if trash { } else if trash {
return Err(ShellError::GenericError( return Err(ShellError::GenericError{
"Cannot execute `rm` with option `--trash`; feature `trash-support` not enabled or on an unsupported platform" error: "Cannot execute `rm` with option `--trash`; feature `trash-support` not enabled or on an unsupported platform"
.into(), .into(),
"this option is only available if nu is built with the `trash-support` feature and the platform supports trash" msg: "this option is only available if nu is built with the `trash-support` feature and the platform supports trash"
.into(), .into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
} }
if targets.is_empty() { if targets.is_empty() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"rm requires target paths".into(), error: "rm requires target paths".into(),
"needs parameter".into(), msg: "needs parameter".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
if unique_argument_check.is_some() && !(interactive_once || interactive) { if unique_argument_check.is_some() && !(interactive_once || interactive) {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"You are trying to remove your home dir".into(), error: "You are trying to remove your home dir".into(),
"If you really want to remove your home dir, please use -I or -i".into(), msg: "If you really want to remove your home dir, please use -I or -i".into(),
unique_argument_check, span: unique_argument_check,
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
let targets_span = Span::new( let targets_span = Span::new(
@ -236,13 +236,13 @@ fn rm(
if currentdir_path.to_string_lossy() == target.item if currentdir_path.to_string_lossy() == target.item
|| currentdir_path.starts_with(format!("{}{}", target.item, std::path::MAIN_SEPARATOR)) || currentdir_path.starts_with(format!("{}{}", target.item, std::path::MAIN_SEPARATOR))
{ {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Cannot remove any parent directory".into(), error: "Cannot remove any parent directory".into(),
"cannot remove any parent directory".into(), msg: "cannot remove any parent directory".into(),
Some(target.span), span: Some(target.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
let path = currentdir_path.join(&target.item); let path = currentdir_path.join(&target.item);
@ -268,13 +268,13 @@ fn rm(
.or_insert_with(|| target.span); .or_insert_with(|| target.span);
} }
Err(e) => { Err(e) => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
format!("Could not remove {:}", path.to_string_lossy()), error: format!("Could not remove {:}", path.to_string_lossy()),
e.to_string(), msg: e.to_string(),
Some(target.span), span: Some(target.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
} }
} }
@ -285,25 +285,25 @@ fn rm(
} }
} }
Err(e) => { Err(e) => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
e.to_string(), error: e.to_string(),
e.to_string(), msg: e.to_string(),
Some(target.span), span: Some(target.span),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
}; };
} }
if all_targets.is_empty() && !force { if all_targets.is_empty() && !force {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"File(s) not found".into(), error: "File(s) not found".into(),
"File(s) not found".into(), msg: "File(s) not found".into(),
Some(targets_span), span: Some(targets_span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
if interactive_once { if interactive_once {
@ -312,13 +312,13 @@ fn rm(
format!("rm: remove {} files? ", all_targets.len()), format!("rm: remove {} files? ", all_targets.len()),
); );
if let Err(e) = interaction { if let Err(e) = interaction {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
format!("Error during interaction: {e:}"), error: format!("Error during interaction: {e:}"),
"could not move".into(), msg: "could not move".into(),
None, span: None,
None, help: None,
Vec::new(), inner: vec![],
)); });
} else if !confirmed { } else if !confirmed {
return Ok(PipelineData::Empty); return Ok(PipelineData::Empty);
} }
@ -406,28 +406,28 @@ fn rm(
Value::nothing(span) Value::nothing(span)
} }
} else { } else {
let msg = format!("Cannot remove {:}. try --recursive", f.to_string_lossy()); let error = format!("Cannot remove {:}. try --recursive", f.to_string_lossy());
Value::error( Value::error(
ShellError::GenericError( ShellError::GenericError {
msg, error,
"cannot remove non-empty directory".into(), msg: "cannot remove non-empty directory".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
), },
span, span,
) )
} }
} else { } else {
let msg = format!("no such file or directory: {:}", f.to_string_lossy()); let error = format!("no such file or directory: {:}", f.to_string_lossy());
Value::error( Value::error(
ShellError::GenericError( ShellError::GenericError {
msg, error,
"no such file or directory".into(), msg: "no such file or directory".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
), },
span, span,
) )
} }

View File

@ -323,16 +323,16 @@ fn prepare_path(
let path = &path.item; let path = &path.item;
if !(force || append) && path.exists() { if !(force || append) && path.exists() {
Err(ShellError::GenericError( Err(ShellError::GenericError {
"Destination file already exists".into(), error: "Destination file already exists".into(),
format!( msg: format!(
"Destination file '{}' already exists", "Destination file '{}' already exists",
path.to_string_lossy() path.to_string_lossy()
), ),
Some(span), span: Some(span),
Some("you can use -f, --force to force overwriting the destination".into()), help: Some("you can use -f, --force to force overwriting the destination".into()),
Vec::new(), inner: vec![],
)) })
} else { } else {
Ok((path, span)) Ok((path, span))
} }
@ -347,14 +347,12 @@ fn open_file(path: &Path, span: Span, append: bool) -> Result<File, ShellError>
_ => std::fs::File::create(path), _ => std::fs::File::create(path),
}; };
file.map_err(|err| { file.map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Permission denied".into(),
"Permission denied".into(), msg: e.to_string(),
err.to_string(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
}) })
} }
@ -380,13 +378,13 @@ fn get_files(
let stderr_file = stderr_path_and_span let stderr_file = stderr_path_and_span
.map(|(stderr_path, stderr_path_span)| { .map(|(stderr_path, stderr_path_span)| {
if path == stderr_path { if path == stderr_path {
Err(ShellError::GenericError( Err(ShellError::GenericError {
"input and stderr input to same file".to_string(), error: "input and stderr input to same file".into(),
"can't save both input and stderr input to the same file".to_string(), msg: "can't save both input and stderr input to the same file".into(),
Some(stderr_path_span), span: Some(stderr_path_span),
Some("you should use `o+e> file` instead".to_string()), help: Some("you should use `o+e> file` instead".into()),
vec![], inner: vec![],
)) })
} else { } else {
open_file(stderr_path, stderr_path_span, append || err_append) open_file(stderr_path, stderr_path_span, append || err_append)
} }

View File

@ -52,14 +52,12 @@ impl Command for Start {
if file_path.exists() { if file_path.exists() {
open_path(path_no_whitespace, engine_state, stack, path.span)?; open_path(path_no_whitespace, engine_state, stack, path.span)?;
} else if file_path.starts_with("https://") || file_path.starts_with("http://") { } else if file_path.starts_with("https://") || file_path.starts_with("http://") {
let url = url::Url::parse(&path.item).map_err(|_| { let url = url::Url::parse(&path.item).map_err(|_| ShellError::GenericError {
ShellError::GenericError( error: format!("Cannot parse url: {}", &path.item),
format!("Cannot parse url: {}", &path.item), msg: "".to_string(),
"".to_string(), span: Some(path.span),
Some(path.span), help: Some("cannot parse".to_string()),
Some("cannot parse".to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
open_path(url.as_str(), engine_state, stack, path.span)?; open_path(url.as_str(), engine_state, stack, path.span)?;
} else { } else {
@ -73,14 +71,12 @@ impl Command for Start {
let path_with_prefix = Path::new("https://").join(&path.item); let path_with_prefix = Path::new("https://").join(&path.item);
let common_domains = ["com", "net", "org", "edu", "sh"]; let common_domains = ["com", "net", "org", "edu", "sh"];
if let Some(url) = path_with_prefix.to_str() { if let Some(url) = path_with_prefix.to_str() {
let url = url::Url::parse(url).map_err(|_| { let url = url::Url::parse(url).map_err(|_| ShellError::GenericError {
ShellError::GenericError( error: format!("Cannot parse url: {}", &path.item),
format!("Cannot parse url: {}", &path.item), msg: "".into(),
"".to_string(), span: Some(path.span),
Some(path.span), help: Some("cannot parse".into()),
Some("cannot parse".to_string()), inner: vec![],
Vec::new(),
)
})?; })?;
if let Some(domain) = url.host() { if let Some(domain) = url.host() {
let domain = domain.to_string(); let domain = domain.to_string();
@ -91,13 +87,13 @@ impl Command for Start {
} }
} }
} }
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
format!("Cannot find file or url: {}", &path.item), error: format!("Cannot find file or url: {}", &path.item),
"".to_string(), msg: "".into(),
Some(path.span), span: Some(path.span),
Some("Use prefix https:// to disambiguate URLs from files".to_string()), help: Some("Use prefix https:// to disambiguate URLs from files".into()),
Vec::new(), inner: vec![],
)); });
} }
}; };
} }

View File

@ -135,34 +135,34 @@ impl Command for UCp {
}) })
.collect(); .collect();
if paths.is_empty() { if paths.is_empty() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Missing file operand".into(), error: "Missing file operand".into(),
"Missing file operand".into(), msg: "Missing file operand".into(),
Some(call.head), span: Some(call.head),
Some("Please provide source and destination paths".into()), help: Some("Please provide source and destination paths".into()),
Vec::new(), inner: vec![],
)); });
} }
if paths.len() == 1 { if paths.len() == 1 {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Missing destination path".into(), error: "Missing destination path".into(),
format!("Missing destination path operand after {}", paths[0].item), msg: format!("Missing destination path operand after {}", paths[0].item),
Some(paths[0].span), span: Some(paths[0].span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
let target = paths.pop().expect("Should not be reached?"); let target = paths.pop().expect("Should not be reached?");
let target_path = PathBuf::from(&target.item); let target_path = PathBuf::from(&target.item);
if target.item.ends_with(PATH_SEPARATOR) && !target_path.is_dir() { if target.item.ends_with(PATH_SEPARATOR) && !target_path.is_dir() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"is not a directory".into(), error: "is not a directory".into(),
"is not a directory".into(), msg: "is not a directory".into(),
Some(target.span), span: Some(target.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
}; };
// paths now contains the sources // paths now contains the sources
@ -180,13 +180,15 @@ impl Command for UCp {
match v { match v {
Ok(path) => { Ok(path) => {
if !recursive && path.is_dir() { if !recursive && path.is_dir() {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"could_not_copy_directory".into(), error: "could_not_copy_directory".into(),
"resolves to a directory (not copied)".into(), msg: "resolves to a directory (not copied)".into(),
Some(p.span), span: Some(p.span),
Some("Directories must be copied using \"--recursive\"".into()), help: Some(
Vec::new(), "Directories must be copied using \"--recursive\"".into(),
)); ),
inner: vec![],
});
}; };
app_vals.push(path) app_vals.push(path)
} }
@ -240,13 +242,13 @@ impl Command for UCp {
// code should still be EXIT_ERR as does GNU cp // code should still be EXIT_ERR as does GNU cp
uu_cp::Error::NotAllFilesCopied => {} uu_cp::Error::NotAllFilesCopied => {}
_ => { _ => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
format!("{}", error), error: format!("{}", error),
format!("{}", error), msg: format!("{}", error),
None, span: None,
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
}; };
// TODO: What should we do in place of set_exit_code? // TODO: What should we do in place of set_exit_code?

View File

@ -68,13 +68,13 @@ impl Command for UMkdir {
for dir in directories { for dir in directories {
if let Err(error) = mkdir(&dir, IS_RECURSIVE, DEFAULT_MODE, is_verbose) { if let Err(error) = mkdir(&dir, IS_RECURSIVE, DEFAULT_MODE, is_verbose) {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
format!("{}", error), error: format!("{}", error),
format!("{}", error), msg: format!("{}", error),
None, span: None,
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
} }

View File

@ -262,13 +262,13 @@ fn group_closure(
let collection: Vec<Value> = s.into_iter().collect(); let collection: Vec<Value> = s.into_iter().collect();
if collection.len() > 1 { if collection.len() > 1 {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"expected one value from the block".into(), error: "expected one value from the block".into(),
"requires a table with one value for grouping".into(), msg: "requires a table with one value for grouping".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
let value = match collection.first() { let value = match collection.first() {

View File

@ -159,14 +159,12 @@ fn extract_headers(
.iter() .iter()
.map(|value| extract_headers(value, config)) .map(|value| extract_headers(value, config))
.next() .next()
.ok_or_else(|| { .ok_or_else(|| ShellError::GenericError {
ShellError::GenericError( error: "Found empty list".into(),
"Found empty list".to_string(), msg: "unable to extract headers".into(),
"unable to extract headers".to_string(), span: Some(span),
Some(span), help: None,
None, inner: vec![],
Vec::new(),
)
})?, })?,
_ => Err(ShellError::TypeMismatch { _ => Err(ShellError::TypeMismatch {
err_message: "record".to_string(), err_message: "record".to_string(),

View File

@ -129,22 +129,22 @@ impl Command for Move {
span: v.span(), span: v.span(),
}, },
(Some(_), Some(_)) => { (Some(_), Some(_)) => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Cannot move columns".to_string(), error: "Cannot move columns".into(),
"Use either --after, or --before, not both".to_string(), msg: "Use either --after, or --before, not both".into(),
Some(call.head), span: Some(call.head),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
(None, None) => { (None, None) => {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Cannot move columns".to_string(), error: "Cannot move columns".into(),
"Missing --after or --before flag".to_string(), msg: "Missing --after or --before flag".into(),
Some(call.head), span: Some(call.head),
None, help: None,
Vec::new(), inner: vec![],
)) })
} }
}; };
@ -198,24 +198,24 @@ fn move_record_columns(
match &before_or_after.item { match &before_or_after.item {
BeforeOrAfter::After(after) => { BeforeOrAfter::After(after) => {
if !record.contains(after) { if !record.contains(after) {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Cannot move columns".to_string(), error: "Cannot move columns".into(),
"column does not exist".to_string(), msg: "column does not exist".into(),
Some(before_or_after.span), span: Some(before_or_after.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
} }
BeforeOrAfter::Before(before) => { BeforeOrAfter::Before(before) => {
if !record.contains(before) { if !record.contains(before) {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Cannot move columns".to_string(), error: "Cannot move columns".into(),
"column does not exist".to_string(), msg: "column does not exist".into(),
Some(before_or_after.span), span: Some(before_or_after.span),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
} }
} }
@ -227,13 +227,13 @@ fn move_record_columns(
if let Some(idx) = record.index_of(&column_str) { if let Some(idx) = record.index_of(&column_str) {
column_idx.push(idx); column_idx.push(idx);
} else { } else {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Cannot move columns".to_string(), error: "Cannot move columns".into(),
"column does not exist".to_string(), msg: "column does not exist".into(),
Some(column.span()), span: Some(column.span()),
None, help: None,
Vec::new(), inner: vec![],
)); });
} }
} }

View File

@ -107,14 +107,12 @@ impl Command for ParEach {
.num_threads(num_threads) .num_threads(num_threads)
.build() .build()
{ {
Err(e) => Err(e).map_err(|e| { Err(e) => Err(e).map_err(|e| ShellError::GenericError {
ShellError::GenericError( error: "Error creating thread pool".into(),
"Error creating thread pool".into(), msg: e.to_string(),
e.to_string(), span: Some(Span::unknown()),
Some(Span::unknown()), help: None,
None, inner: vec![],
Vec::new(),
)
}), }),
Ok(pool) => Ok(pool), Ok(pool) => Ok(pool),
} }

View File

@ -117,13 +117,13 @@ impl Command for Reduce {
} else if let Some(val) = input_iter.next() { } else if let Some(val) = input_iter.next() {
val val
} else { } else {
return Err(ShellError::GenericError( return Err(ShellError::GenericError {
"Expected input".to_string(), error: "Expected input".into(),
"needs input".to_string(), msg: "needs input".into(),
Some(span), span: Some(span),
None, help: None,
Vec::new(), inner: vec![],
)); });
}; };
let mut acc = start_val; let mut acc = start_val;

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