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
160 changed files with 2975 additions and 3228 deletions

View File

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

View File

@ -47,15 +47,15 @@ impl Command for SchemaDb {
let sqlite_db = SQLiteDatabase::try_from_pipeline(input, span)?;
let conn = open_sqlite_db_connection(&sqlite_db, span)?;
let tables = sqlite_db.get_tables(&conn).map_err(|e| {
ShellError::GenericError(
"Error reading tables".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
})?;
let tables = sqlite_db
.get_tables(&conn)
.map_err(|e| ShellError::GenericError {
error: "Error reading tables".into(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
})?;
let mut tables_record = Record::new();
for table in tables {
@ -87,14 +87,12 @@ impl Command for SchemaDb {
}
fn open_sqlite_db_connection(db: &SQLiteDatabase, span: Span) -> Result<Connection, ShellError> {
db.open_connection().map_err(|e| {
ShellError::GenericError(
"Error opening file".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
db.open_connection().map_err(|e| ShellError::GenericError {
error: "Error opening file".into(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
})
}
@ -104,15 +102,15 @@ fn get_table_columns(
table: &DbTable,
span: Span,
) -> Result<Vec<Value>, ShellError> {
let columns = db.get_columns(conn, table).map_err(|e| {
ShellError::GenericError(
"Error getting database columns".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
})?;
let columns = db
.get_columns(conn, table)
.map_err(|e| ShellError::GenericError {
error: "Error getting database columns".into(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
})?;
// a record of column name = column value
let mut column_info = vec![];
@ -136,15 +134,15 @@ fn get_table_constraints(
table: &DbTable,
span: Span,
) -> Result<Vec<Value>, ShellError> {
let constraints = db.get_constraints(conn, table).map_err(|e| {
ShellError::GenericError(
"Error getting DB constraints".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
})?;
let constraints = db
.get_constraints(conn, table)
.map_err(|e| ShellError::GenericError {
error: "Error getting DB constraints".into(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
})?;
let mut constraint_info = vec![];
for constraint in constraints {
constraint_info.push(Value::record(
@ -167,15 +165,15 @@ fn get_table_foreign_keys(
table: &DbTable,
span: Span,
) -> Result<Vec<Value>, ShellError> {
let foreign_keys = db.get_foreign_keys(conn, table).map_err(|e| {
ShellError::GenericError(
"Error getting DB Foreign Keys".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
})?;
let foreign_keys = db
.get_foreign_keys(conn, table)
.map_err(|e| ShellError::GenericError {
error: "Error getting DB Foreign Keys".into(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
})?;
let mut foreign_key_info = vec![];
for fk in foreign_keys {
foreign_key_info.push(Value::record(
@ -197,15 +195,15 @@ fn get_table_indexes(
table: &DbTable,
span: Span,
) -> Result<Vec<Value>, ShellError> {
let indexes = db.get_indexes(conn, table).map_err(|e| {
ShellError::GenericError(
"Error getting DB Indexes".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
})?;
let indexes = db
.get_indexes(conn, table)
.map_err(|e| ShellError::GenericError {
error: "Error getting DB Indexes".into(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
})?;
let mut index_info = vec![];
for index in indexes {
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> {
let conn = open_sqlite_db(&self.path, call_span)?;
let stream = run_sql_query(conn, sql, self.ctrlc.clone()).map_err(|e| {
ShellError::GenericError(
"Failed to query SQLite database".into(),
e.to_string(),
Some(sql.span),
None,
Vec::new(),
)
})?;
let stream =
run_sql_query(conn, sql, self.ctrlc.clone()).map_err(|e| ShellError::GenericError {
error: "Failed to query SQLite database".into(),
msg: e.to_string(),
span: Some(sql.span),
help: None,
inner: vec![],
})?;
Ok(stream)
}
@ -119,14 +118,12 @@ impl SQLiteDatabase {
if self.path == PathBuf::from(MEMORY_DB) {
open_connection_in_memory_custom()
} else {
Connection::open(&self.path).map_err(|e| {
ShellError::GenericError(
"Failed to open SQLite database from open_connection".into(),
e.to_string(),
None,
None,
Vec::new(),
)
Connection::open(&self.path).map_err(|e| ShellError::GenericError {
error: "Failed to open SQLite database from open_connection".into(),
msg: e.to_string(),
span: None,
help: None,
inner: vec![],
})
}
}
@ -362,14 +359,12 @@ impl CustomValue for SQLiteDatabase {
fn to_base_value(&self, span: Span) -> Result<Value, ShellError> {
let db = open_sqlite_db(&self.path, span)?;
read_entire_sqlite_db(db, span, self.ctrlc.clone()).map_err(|e| {
ShellError::GenericError(
"Failed to read from SQLite database".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
read_entire_sqlite_db(db, span, self.ctrlc.clone()).map_err(|e| ShellError::GenericError {
error: "Failed to read from SQLite database".into(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
})
}
@ -386,13 +381,13 @@ impl CustomValue for SQLiteDatabase {
let db = open_sqlite_db(&self.path, span)?;
read_single_table(db, _column_name, span, self.ctrlc.clone()).map_err(|e| {
ShellError::GenericError(
"Failed to read from SQLite database".into(),
e.to_string(),
Some(span),
None,
Vec::new(),
)
ShellError::GenericError {
error: "Failed to read from SQLite database".into(),
msg: e.to_string(),
span: Some(span),
help: None,
inner: vec![],
}
})
}
@ -410,14 +405,12 @@ pub fn open_sqlite_db(path: &Path, call_span: Span) -> Result<Connection, ShellE
open_connection_in_memory_custom()
} else {
let path = path.to_string_lossy().to_string();
Connection::open(path).map_err(|e| {
ShellError::GenericError(
"Failed to open SQLite database".into(),
e.to_string(),
Some(call_span),
None,
Vec::new(),
)
Connection::open(path).map_err(|e| ShellError::GenericError {
error: "Failed to open SQLite database".into(),
msg: e.to_string(),
span: Some(call_span),
help: None,
inner: vec![],
})
}
}
@ -611,25 +604,21 @@ mod test {
pub fn open_connection_in_memory_custom() -> Result<Connection, ShellError> {
let flags = OpenFlags::default();
Connection::open_with_flags(MEMORY_DB, flags).map_err(|err| {
ShellError::GenericError(
"Failed to open SQLite custom connection in memory".into(),
err.to_string(),
Some(Span::test_data()),
None,
Vec::new(),
)
Connection::open_with_flags(MEMORY_DB, flags).map_err(|e| ShellError::GenericError {
error: "Failed to open SQLite custom connection in memory".into(),
msg: e.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})
}
pub fn open_connection_in_memory() -> Result<Connection, ShellError> {
Connection::open_in_memory().map_err(|err| {
ShellError::GenericError(
"Failed to open SQLite standard connection in memory".into(),
err.to_string(),
Some(Span::test_data()),
None,
Vec::new(),
)
Connection::open_in_memory().map_err(|e| ShellError::GenericError {
error: "Failed to open SQLite standard connection in memory".into(),
msg: e.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -158,13 +158,13 @@ impl Command for Glob {
};
if glob_pattern.item.is_empty() {
return Err(ShellError::GenericError(
"glob pattern must not be empty".to_string(),
"glob pattern is empty".to_string(),
Some(glob_pattern.span),
Some("add characters to the glob pattern".to_string()),
Vec::new(),
));
return Err(ShellError::GenericError {
error: "glob pattern must not be empty".into(),
msg: "glob pattern is empty".into(),
span: Some(glob_pattern.span),
help: Some("add characters to the glob pattern".into()),
inner: vec![],
});
}
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) {
Ok(p) => p.partition(),
Err(e) => {
return Err(ShellError::GenericError(
"error with glob pattern".to_string(),
format!("{e}"),
Some(glob_pattern.span),
None,
Vec::new(),
))
return Err(ShellError::GenericError {
error: "error with glob pattern".into(),
msg: format!("{e}"),
span: Some(glob_pattern.span),
help: None,
inner: vec![],
})
}
};
@ -195,13 +195,13 @@ impl Command for Glob {
std::path::PathBuf::new() // user should get empty list not an error
}
Err(e) => {
return Err(ShellError::GenericError(
"error in canonicalize".to_string(),
format!("{e}"),
Some(glob_pattern.span),
None,
Vec::new(),
))
return Err(ShellError::GenericError {
error: "error in canonicalize".into(),
msg: format!("{e}"),
span: Some(glob_pattern.span),
help: None,
inner: vec![],
})
}
};
@ -216,14 +216,12 @@ impl Command for Glob {
},
)
.not(np)
.map_err(|err| {
ShellError::GenericError(
"error with glob's not pattern".to_string(),
format!("{err}"),
Some(not_pattern_span),
None,
Vec::new(),
)
.map_err(|err| ShellError::GenericError {
error: "error with glob's not pattern".into(),
msg: format!("{err}"),
span: Some(not_pattern_span),
help: None,
inner: vec![],
})?
.flatten();
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))]
let error_msg = String::from("Permission denied");
return Err(ShellError::GenericError(
"Permission denied".to_string(),
error_msg,
Some(p_tag),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "Permission denied".into(),
msg: error_msg,
span: Some(p_tag),
help: None,
inner: vec![],
});
}
if is_empty_dir(&expanded) {
return Ok(Value::list(vec![], call_span).into_pipeline_data());
@ -168,13 +168,13 @@ impl Command for Ls {
let mut paths_peek = paths.peekable();
if paths_peek.peek().is_none() {
return Err(ShellError::GenericError(
format!("No matches found for {}", &path.display().to_string()),
"Pattern, file or folder not found".to_string(),
Some(p_tag),
Some("no matches found".to_string()),
Vec::new(),
));
return Err(ShellError::GenericError {
error: format!("No matches found for {}", &path.display().to_string()),
msg: "Pattern, file or folder not found".into(),
span: Some(p_tag),
help: Some("no matches found".into()),
inner: vec![],
});
}
let mut hidden_dirs = vec![];
@ -233,14 +233,12 @@ impl Command for Ls {
} else {
Some(path.to_string_lossy().to_string())
}
.ok_or_else(|| {
ShellError::GenericError(
format!("Invalid file name: {:}", path.to_string_lossy()),
"invalid file name".into(),
Some(call_span),
None,
Vec::new(),
)
.ok_or_else(|| ShellError::GenericError {
error: format!("Invalid file name: {:}", path.to_string_lossy()),
msg: "invalid file name".into(),
span: Some(call_span),
help: None,
inner: vec![],
});
match display_name {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -225,13 +225,13 @@ fn reject(
match members.first() {
Some(PathMember::Int { val, span, .. }) => {
if members.len() > 1 {
return Err(ShellError::GenericError(
"Reject only allows row numbers for rows".into(),
"extra after row number".into(),
Some(*span),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "Reject only allows row numbers for rows".into(),
msg: "extra after row number".into(),
span: Some(*span),
help: None,
inner: vec![],
});
}
if !unique_rows.contains(val) {
unique_rows.insert(*val);

View File

@ -215,13 +215,13 @@ fn select(
match members.first() {
Some(PathMember::Int { val, span, .. }) => {
if members.len() > 1 {
return Err(ShellError::GenericError(
"Select only allows row numbers for rows".into(),
"extra after row number".into(),
Some(*span),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "Select only allows row numbers for rows".into(),
msg: "extra after row number".into(),
span: Some(*span),
help: None,
inner: vec![],
});
}
unique_rows.insert(*val);
}

View File

@ -102,13 +102,13 @@ pub fn split_by(
Ok(split(splitter.as_ref(), input, name)?)
}
// This uses the same format as the 'requires a column name' error in sort_utils.rs
None => Err(ShellError::GenericError(
"expected name".into(),
"requires a column name for splitting".into(),
Some(name),
None,
Vec::new(),
)),
None => Err(ShellError::GenericError {
error: "expected name".into(),
msg: "requires a column name for splitting".into(),
span: Some(name),
help: None,
inner: vec![],
}),
}
}

View File

@ -196,33 +196,33 @@ pub fn transpose(
if let Ok(s) = x.as_string() {
headers.push(s.to_string());
} else {
return Err(ShellError::GenericError(
"Header row needs string headers".into(),
"used non-string headers".into(),
Some(name),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "Header row needs string headers".into(),
msg: "used non-string headers".into(),
span: Some(name),
help: None,
inner: vec![],
});
}
}
_ => {
return Err(ShellError::GenericError(
"Header row is incomplete and can't be used".into(),
"using incomplete header row".into(),
Some(name),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "Header row is incomplete and can't be used".into(),
msg: "using incomplete header row".into(),
span: Some(name),
help: None,
inner: vec![],
});
}
}
} else {
return Err(ShellError::GenericError(
"Header row is incomplete and can't be used".into(),
"using incomplete header row".into(),
Some(name),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "Header row is incomplete and can't be used".into(),
msg: "using incomplete header row".into(),
span: Some(name),
help: None,
inner: vec![],
});
}
}
} else {

View File

@ -117,13 +117,13 @@ fn validate(vec: &[Value], columns: &[String], span: Span) -> Result<(), ShellEr
if let Value::Record { val: record, .. } = &v {
if columns.is_empty() {
// This uses the same format as the 'requires a column name' error in split_by.rs
return Err(ShellError::GenericError(
"expected name".into(),
"requires a column name to filter table data".into(),
Some(span),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "expected name".into(),
msg: "requires a column name to filter table data".into(),
span: Some(span),
help: None,
inner: vec![],
});
}
if let Some(nonexistent) = nonexistent_column(columns, record.columns()) {

View File

@ -150,18 +150,18 @@ fn convert_string_to_value(string_input: String, span: Span) -> Result<Value, Sh
nu_json::Error::Syntax(_, row, col) => {
let label = x.to_string();
let label_span = convert_row_column_to_span(row, col, &string_input);
Err(ShellError::GenericError(
"Error while parsing JSON text".into(),
"error parsing JSON text".into(),
Some(span),
None,
vec![ShellError::OutsideSpannedLabeledError(
Err(ShellError::GenericError {
error: "Error while parsing JSON text".into(),
msg: "error parsing JSON text".into(),
span: Some(span),
help: None,
inner: vec![ShellError::OutsideSpannedLabeledError(
string_input,
"Error while parsing JSON text".into(),
label,
label_span,
)],
))
})
}
x => Err(ShellError::CantConvert {
to_type: format!("structured json data ({x})"),

View File

@ -60,32 +60,32 @@ impl Command for FromNuon {
if let Some(pipeline) = block.pipelines.get(1) {
if let Some(element) = pipeline.elements.first() {
return Err(ShellError::GenericError(
"error when loading nuon text".into(),
"could not load nuon text".into(),
Some(head),
None,
vec![ShellError::OutsideSpannedLabeledError(
return Err(ShellError::GenericError {
error: "error when loading nuon text".into(),
msg: "could not load nuon text".into(),
span: Some(head),
help: None,
inner: vec![ShellError::OutsideSpannedLabeledError(
string_input,
"error when loading".into(),
"excess values when loading".into(),
element.span(),
)],
));
});
} else {
return Err(ShellError::GenericError(
"error when loading nuon text".into(),
"could not load nuon text".into(),
Some(head),
None,
vec![ShellError::GenericError(
"error when loading".into(),
"excess values when loading".into(),
Some(head),
None,
Vec::new(),
)],
));
return Err(ShellError::GenericError {
error: "error when loading nuon text".into(),
msg: "could not load nuon text".into(),
span: Some(head),
help: None,
inner: vec![ShellError::GenericError {
error: "error when loading".into(),
msg: "excess values when loading".into(),
span: Some(head),
help: None,
inner: vec![],
}],
});
}
}
@ -100,18 +100,18 @@ impl Command for FromNuon {
let mut pipeline = block.pipelines.remove(0);
if let Some(expr) = pipeline.elements.get(1) {
return Err(ShellError::GenericError(
"error when loading nuon text".into(),
"could not load nuon text".into(),
Some(head),
None,
vec![ShellError::OutsideSpannedLabeledError(
return Err(ShellError::GenericError {
error: "error when loading nuon text".into(),
msg: "could not load nuon text".into(),
span: Some(head),
help: None,
inner: vec![ShellError::OutsideSpannedLabeledError(
string_input,
"error when loading".into(),
"detected a pipeline in nuon file".into(),
expr.span(),
)],
));
});
}
if pipeline.elements.is_empty() {
@ -140,31 +140,31 @@ impl Command for FromNuon {
};
if let Some(err) = working_set.parse_errors.first() {
return Err(ShellError::GenericError(
"error when parsing nuon text".into(),
"could not parse nuon text".into(),
Some(head),
None,
vec![ShellError::OutsideSpannedLabeledError(
return Err(ShellError::GenericError {
error: "error when parsing nuon text".into(),
msg: "could not parse nuon text".into(),
span: Some(head),
help: None,
inner: vec![ShellError::OutsideSpannedLabeledError(
string_input,
"error when parsing".into(),
err.to_string(),
err.span(),
)],
));
});
}
let result = convert_to_value(expr, head, &string_input);
match result {
Ok(result) => Ok(result.into_pipeline_data_with_metadata(metadata)),
Err(err) => Err(ShellError::GenericError(
"error when loading nuon text".into(),
"could not load nuon text".into(),
Some(head),
None,
vec![err],
)),
Err(err) => Err(ShellError::GenericError {
error: "error when loading nuon text".into(),
msg: "could not load nuon text".into(),
span: Some(head),
help: None,
inner: vec![err],
}),
}
}
}

View File

@ -155,13 +155,13 @@ used as the next argument to the closure, otherwise generation stops.
} else if k.eq_ignore_ascii_case("next") {
next = Some(v);
} else {
let error = ShellError::GenericError(
"Invalid block return".to_string(),
format!("Unexpected record key '{}'", k),
Some(span),
None,
Vec::new(),
);
let error = ShellError::GenericError {
error: "Invalid block return".into(),
msg: format!("Unexpected record key '{}'", k),
span: Some(span),
help: None,
inner: vec![],
};
err = Some(Value::error(error, block_span));
break;
}
@ -176,13 +176,13 @@ used as the next argument to the closure, otherwise generation stops.
// some other value -> error and stop
_ => {
let error = ShellError::GenericError(
"Invalid block return".to_string(),
format!("Expected record, found {}", value.get_type()),
Some(span),
None,
Vec::new(),
);
let error = ShellError::GenericError {
error: "Invalid block return".into(),
msg: format!("Expected record, found {}", value.get_type()),
span: Some(span),
help: None,
inner: vec![],
};
(Some(Value::error(error, block_span)), None)
}
@ -191,13 +191,13 @@ used as the next argument to the closure, otherwise generation stops.
Ok(other) => {
let val = other.into_value(block_span);
let error = ShellError::GenericError(
"Invalid block return".to_string(),
format!("Expected record, found {}", val.get_type()),
Some(val.span()),
None,
Vec::new(),
);
let error = ShellError::GenericError {
error: "Invalid block return".into(),
msg: format!("Expected record, found {}", val.get_type()),
span: Some(val.span()),
help: None,
inner: vec![],
};
(Some(Value::error(error, block_span)), None)
}

View File

@ -101,13 +101,13 @@ fn seq(
let contains_decimals = rest_nums_check.is_err();
if rest_nums.is_empty() {
return Err(ShellError::GenericError(
"seq requires some parameters".into(),
"needs parameter".into(),
Some(call.head),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "seq requires some parameters".into(),
msg: "needs parameter".into(),
span: Some(call.head),
help: None,
inner: vec![],
});
}
let rest_nums: Vec<f64> = rest_nums.iter().map(|n| n.item).collect();

View File

@ -82,23 +82,23 @@ fn seq_char(
let end: Spanned<String> = call.req(engine_state, stack, 1)?;
if !is_single_character(&start.item) {
return Err(ShellError::GenericError(
"seq char only accepts individual ASCII characters as parameters".into(),
"should be 1 character long".into(),
Some(start.span),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "seq char only accepts individual ASCII characters as parameters".into(),
msg: "should be 1 character long".into(),
span: Some(start.span),
help: None,
inner: vec![],
});
}
if !is_single_character(&end.item) {
return Err(ShellError::GenericError(
"seq char only accepts individual ASCII characters as parameters".into(),
"should be 1 character long".into(),
Some(end.span),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "seq char only accepts individual ASCII characters as parameters".into(),
msg: "should be 1 character long".into(),
span: Some(end.span),
help: None,
inner: vec![],
});
}
let start = start

View File

@ -194,26 +194,26 @@ pub fn run_seq_dates(
let mut step_size: i64 = increment.as_i64()?;
if step_size == 0 {
return Err(ShellError::GenericError(
"increment cannot be 0".to_string(),
"increment cannot be 0".to_string(),
Some(increment.span()),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "increment cannot be 0".into(),
msg: "increment cannot be 0".into(),
span: Some(increment.span()),
help: None,
inner: vec![],
});
}
let in_format = match input_format {
Some(i) => match i.as_string() {
Ok(v) => v,
Err(e) => {
return Err(ShellError::GenericError(
e.to_string(),
"".to_string(),
None,
Some("error with input_format as_string".to_string()),
Vec::new(),
));
return Err(ShellError::GenericError {
error: e.to_string(),
msg: "".into(),
span: None,
help: Some("error with input_format as_string".into()),
inner: vec![],
});
}
},
_ => "%Y-%m-%d".to_string(),
@ -223,13 +223,13 @@ pub fn run_seq_dates(
Some(i) => match i.as_string() {
Ok(v) => v,
Err(e) => {
return Err(ShellError::GenericError(
e.to_string(),
"".to_string(),
None,
Some("error with output_format as_string".to_string()),
Vec::new(),
));
return Err(ShellError::GenericError {
error: e.to_string(),
msg: "".into(),
span: None,
help: Some("error with output_format as_string".into()),
inner: vec![],
});
}
},
_ => "%Y-%m-%d".to_string(),
@ -239,13 +239,13 @@ pub fn run_seq_dates(
Some(d) => match parse_date_string(&d, &in_format) {
Ok(nd) => nd,
Err(e) => {
return Err(ShellError::GenericError(
e.to_string(),
"Failed to parse date".to_string(),
Some(call_span),
None,
Vec::new(),
))
return Err(ShellError::GenericError {
error: e.to_string(),
msg: "Failed to parse date".into(),
span: Some(call_span),
help: None,
inner: vec![],
})
}
},
_ => today,
@ -255,13 +255,13 @@ pub fn run_seq_dates(
Some(d) => match parse_date_string(&d, &in_format) {
Ok(nd) => nd,
Err(e) => {
return Err(ShellError::GenericError(
e.to_string(),
"Failed to parse date".to_string(),
Some(call_span),
None,
Vec::new(),
))
return Err(ShellError::GenericError {
error: e.to_string(),
msg: "Failed to parse date".into(),
span: Some(call_span),
help: None,
inner: vec![],
})
}
},
_ => today,
@ -282,13 +282,13 @@ pub fn run_seq_dates(
end_date = match start_date.checked_add_signed(Duration::days(days_to_output)) {
Some(date) => date,
None => {
return Err(ShellError::GenericError(
"int value too large".to_string(),
"int value too large".to_string(),
Some(call_span),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "int value too large".into(),
msg: "int value too large".into(),
span: Some(call_span),
help: None,
inner: vec![],
});
}
}
}
@ -304,13 +304,13 @@ pub fn run_seq_dates(
let mut next = start_date;
if is_out_of_range(next) {
return Err(ShellError::GenericError(
"date is out of range".to_string(),
"date is out of range".to_string(),
Some(call_span),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "date is out of range".into(),
msg: "date is out of range".into(),
span: Some(call_span),
help: None,
inner: vec![],
});
}
let mut ret = vec![];

View File

@ -207,13 +207,13 @@ pub fn highlight_search_string(
let regex = match Regex::new(&regex_string) {
Ok(regex) => regex,
Err(err) => {
return Err(ShellError::GenericError(
"Could not compile regex".into(),
err.to_string(),
Some(Span::test_data()),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "Could not compile regex".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
});
}
};
// strip haystack to remove existing ansi style
@ -245,13 +245,13 @@ pub fn highlight_search_string(
last_match_end = end;
}
Err(e) => {
return Err(ShellError::GenericError(
"Error with regular expression capture".into(),
e.to_string(),
None,
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "Error with regular expression capture".into(),
msg: e.to_string(),
span: None,
help: None,
inner: vec![],
});
}
}
}

View File

@ -403,26 +403,23 @@ fn transform_response_using_content_type(
resp: Response,
content_type: &str,
) -> Result<PipelineData, ShellError> {
let content_type = mime::Mime::from_str(content_type).map_err(|_| {
ShellError::GenericError(
format!("MIME type unknown: {content_type}"),
"".to_string(),
None,
Some("given unknown MIME type".to_string()),
Vec::new(),
)
})?;
let content_type =
mime::Mime::from_str(content_type).map_err(|_| ShellError::GenericError {
error: format!("MIME type unknown: {content_type}"),
msg: "".into(),
span: None,
help: Some("given unknown MIME type".into()),
inner: vec![],
})?;
let ext = match (content_type.type_(), content_type.subtype()) {
(mime::TEXT, mime::PLAIN) => {
let path_extension = url::Url::parse(requested_url)
.map_err(|_| {
ShellError::GenericError(
format!("Cannot parse URL: {requested_url}"),
"".to_string(),
None,
Some("cannot parse".to_string()),
Vec::new(),
)
.map_err(|_| ShellError::GenericError {
error: format!("Cannot parse URL: {requested_url}"),
msg: "".into(),
span: None,
help: Some("cannot parse".into()),
inner: vec![],
})?
.path_segments()
.and_then(|segments| segments.last())

View File

@ -85,13 +85,13 @@ fn action(input: &Value, _arg: &CellPathOnlyArgs, head: Span) -> Value {
match val {
Ok(val) => Value::string(val, head),
Err(e) => Value::error(
ShellError::GenericError(
"Failed to decode string".into(),
e.to_string(),
Some(input_span),
None,
Vec::new(),
),
ShellError::GenericError {
error: "Failed to decode string".into(),
msg: e.to_string(),
span: Some(input_span),
help: None,
inner: vec![],
},
head,
),
}

View File

@ -283,13 +283,13 @@ impl UrlComponents {
_ => {
nu_protocol::report_error_new(
engine_state,
&ShellError::GenericError(
format!("'{key}' is not a valid URL field"),
format!("remove '{key}' col from input record"),
Some(span),
None,
vec![],
),
&ShellError::GenericError {
error: format!("'{key}' is not a valid URL field"),
msg: format!("remove '{key}' col from input record"),
span: Some(span),
help: None,
inner: vec![],
},
);
Ok(self)
}

View File

@ -157,15 +157,15 @@ fn expand(path: &Path, span: Span, args: &Arguments) -> Value {
}
}
Err(_) => Value::error(
ShellError::GenericError(
"Could not expand path".into(),
"could not be expanded (path might not exist, non-final \
ShellError::GenericError {
error: "Could not expand path".into(),
msg: "could not be expanded (path might not exist, non-final \
component is not a directory, or other cause)"
.into(),
Some(span),
None,
Vec::new(),
),
span: Some(span),
help: None,
inner: vec![],
},
span,
),
}

View File

@ -732,13 +732,13 @@ Operating system commands:
None => Color::White.prefix().to_string(),
},
Err(err) => {
return Err(ShellError::GenericError(
"error parsing hex color".to_string(),
format!("{err}"),
Some(code.span()),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "error parsing hex color".into(),
msg: format!("{err}"),
span: Some(code.span()),
help: None,
inner: vec![],
});
}
}
} else {

View File

@ -90,14 +90,12 @@ There are 4 `key_type` variants:
terminal::enable_raw_mode()?;
let console_state = event_type_filter.enable_events()?;
loop {
let event = crossterm::event::read().map_err(|_| {
ShellError::GenericError(
"Error with user input".to_string(),
"".to_string(),
Some(head),
None,
Vec::new(),
)
let event = crossterm::event::read().map_err(|_| ShellError::GenericError {
error: "Error with user input".into(),
msg: "".into(),
span: Some(head),
help: None,
inner: vec![],
})?;
let event = parse_event(head, &event, &event_type_filter, add_raw);
if let Some(event) = event {

View File

@ -92,27 +92,23 @@ impl Command for Kill {
left_message: "force".to_string(),
left_span: call
.get_named_arg("force")
.ok_or_else(|| {
ShellError::GenericError(
"Flag error".into(),
"flag force not found".into(),
Some(call.head),
None,
Vec::new(),
)
.ok_or_else(|| ShellError::GenericError {
error: "Flag error".into(),
msg: "flag force not found".into(),
span: Some(call.head),
help: None,
inner: vec![],
})?
.span,
right_message: "signal".to_string(),
right_span: span(&[
call.get_named_arg("signal")
.ok_or_else(|| {
ShellError::GenericError(
"Flag error".into(),
"flag signal not found".into(),
Some(call.head),
None,
Vec::new(),
)
.ok_or_else(|| ShellError::GenericError {
error: "Flag error".into(),
msg: "flag signal not found".into(),
span: Some(call.head),
help: None,
inner: vec![],
})?
.span,
signal_span,
@ -138,36 +134,32 @@ impl Command for Kill {
.stderr(Stdio::null());
}
let output = cmd.output().map_err(|e| {
ShellError::GenericError(
"failed to execute shell command".into(),
e.to_string(),
Some(call.head),
None,
Vec::new(),
)
let output = cmd.output().map_err(|e| ShellError::GenericError {
error: "failed to execute shell command".into(),
msg: e.to_string(),
span: Some(call.head),
help: None,
inner: vec![],
})?;
if !quiet && !output.status.success() {
return Err(ShellError::GenericError(
"process didn't terminate successfully".into(),
String::from_utf8(output.stderr).unwrap_or_default(),
Some(call.head),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "process didn't terminate successfully".into(),
msg: String::from_utf8(output.stderr).unwrap_or_default(),
span: Some(call.head),
help: None,
inner: vec![],
});
}
let val = String::from(
String::from_utf8(output.stdout)
.map_err(|e| {
ShellError::GenericError(
"failed to convert output to string".into(),
e.to_string(),
Some(call.head),
None,
Vec::new(),
)
.map_err(|e| ShellError::GenericError {
error: "failed to convert output to string".into(),
msg: e.to_string(),
span: Some(call.head),
help: None,
inner: vec![],
})?
.trim_end(),
);

View File

@ -36,14 +36,14 @@ impl Command for Whoami {
) -> Result<PipelineData, ShellError> {
let output = match uu_whoami::whoami() {
Ok(username) => username.to_string_lossy().to_string(),
Err(err) => {
return Err(ShellError::GenericError(
"Failed to get username".into(),
err.to_string(),
Some(call.head),
None,
Vec::new(),
))
Err(e) => {
return Err(ShellError::GenericError {
error: "Failed to get username".into(),
msg: e.to_string(),
span: Some(call.head),
help: None,
inner: vec![],
})
}
};

View File

@ -69,13 +69,13 @@ pub fn sort(
Some(Value::Record { val: record, .. }) => {
if sort_columns.is_empty() {
// This uses the same format as the 'requires a column name' error in split_by.rs
return Err(ShellError::GenericError(
"expected name".into(),
"requires a column name to sort table data".into(),
Some(span),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "expected name".into(),
msg: "requires a column name to sort table data".into(),
span: Some(span),
help: None,
inner: vec![],
});
}
if let Some(nonexistent) = nonexistent_column(&sort_columns, record.columns()) {

View File

@ -128,15 +128,14 @@ fn process(
// dbg!(&create_stmt);
conn.execute(&create_stmt, []).map_err(|err| {
ShellError::GenericError(
"Failed to open SQLite connection in memory from create".into(),
err.to_string(),
Some(Span::test_data()),
None,
Vec::new(),
)
})?;
conn.execute(&create_stmt, [])
.map_err(|err| ShellError::GenericError {
error: "Failed to open SQLite connection in memory from create".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
None => {
return Err(ShellError::MissingParameter {

View File

@ -112,15 +112,14 @@ impl Command for StorDelete {
};
// dbg!(&sql_stmt);
conn.execute(&sql_stmt, []).map_err(|err| {
ShellError::GenericError(
"Failed to open SQLite connection in memory from delete".into(),
err.to_string(),
Some(Span::test_data()),
None,
Vec::new(),
)
})?;
conn.execute(&sql_stmt, [])
.map_err(|err| ShellError::GenericError {
error: "Failed to open SQLite connection in memory from delete".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
}
// dbg!(db.clone());

View File

@ -70,14 +70,12 @@ impl Command for StorExport {
// This uses vacuum. I'm not really sure if this is the best way to do this.
// I also added backup in the sqlitedatabase impl. If we have problems, we could switch to that.
db.export_in_memory_database_to_file(&conn, file_name)
.map_err(|err| {
ShellError::GenericError(
"Failed to open SQLite connection in memory from export".into(),
err.to_string(),
Some(Span::test_data()),
None,
Vec::new(),
)
.map_err(|err| ShellError::GenericError {
error: "Failed to open SQLite connection in memory from export".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
// dbg!(db.clone());

View File

@ -68,14 +68,12 @@ impl Command for StorImport {
if let Ok(mut conn) = db.open_connection() {
db.restore_database_from_file(&mut conn, file_name)
.map_err(|err| {
ShellError::GenericError(
"Failed to open SQLite connection in memory from import".into(),
err.to_string(),
Some(Span::test_data()),
None,
Vec::new(),
)
.map_err(|err| ShellError::GenericError {
error: "Failed to open SQLite connection in memory from import".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
// dbg!(db.clone());

View File

@ -119,15 +119,14 @@ impl Command for StorInsert {
// dbg!(&create_stmt);
conn.execute(&create_stmt, []).map_err(|err| {
ShellError::GenericError(
"Failed to open SQLite connection in memory from insert".into(),
err.to_string(),
Some(Span::test_data()),
None,
Vec::new(),
)
})?;
conn.execute(&create_stmt, [])
.map_err(|err| ShellError::GenericError {
error: "Failed to open SQLite connection in memory from insert".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
None => {
return Err(ShellError::MissingParameter {

View File

@ -49,15 +49,14 @@ impl Command for StorReset {
let db = Box::new(SQLiteDatabase::new(std::path::Path::new(MEMORY_DB), None));
if let Ok(conn) = db.open_connection() {
db.drop_all_tables(&conn).map_err(|err| {
ShellError::GenericError(
"Failed to open SQLite connection in memory from reset".into(),
err.to_string(),
Some(Span::test_data()),
None,
Vec::new(),
)
})?;
db.drop_all_tables(&conn)
.map_err(|err| ShellError::GenericError {
error: "Failed to open SQLite connection in memory from reset".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
// dbg!(db.clone());
Ok(Value::custom_value(db, span).into_pipeline_data())

View File

@ -131,15 +131,14 @@ impl Command for StorUpdate {
}
// dbg!(&update_stmt);
conn.execute(&update_stmt, []).map_err(|err| {
ShellError::GenericError(
"Failed to open SQLite connection in memory from update".into(),
err.to_string(),
Some(Span::test_data()),
None,
Vec::new(),
)
})?;
conn.execute(&update_stmt, [])
.map_err(|err| ShellError::GenericError {
error: "Failed to open SQLite connection in memory from update".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
None => {
return Err(ShellError::MissingParameter {

View File

@ -91,15 +91,15 @@ fn action(
"crypt" => GeneralPurpose::new(&alphabet::CRYPT, NO_PAD),
"mutf7" => GeneralPurpose::new(&alphabet::IMAP_MUTF7, NO_PAD),
not_valid => return Value::error (
ShellError::GenericError(
"value is not an accepted character set".to_string(),
format!(
ShellError::GenericError {
error: "value is not an accepted character set".into(),
msg: format!(
"{not_valid} is not a valid character-set.\nPlease use `help encode base64` to see a list of valid character sets."
),
Some(config_character_set.span),
None,
Vec::new(),
), config_character_set.span)
span: Some(config_character_set.span),
help: None,
inner: vec![],
}, config_character_set.span)
};
let value_span = input.span();
match input {
@ -110,15 +110,15 @@ fn action(
let mut enc_vec = vec![0; val.len() * 4 / 3 + 4];
let bytes_written = match base64_engine.encode_slice(val, &mut enc_vec) {
Ok(bytes_written) => bytes_written,
Err(err) => {
Err(e) => {
return Value::error(
ShellError::GenericError(
"Error encoding data".into(),
err.to_string(),
Some(value_span),
None,
Vec::new(),
),
ShellError::GenericError {
error: "Error encoding data".into(),
msg: e.to_string(),
span: Some(value_span),
help: None,
inner: vec![],
},
value_span,
)
}
@ -157,30 +157,32 @@ fn action(
match String::from_utf8(decoded_value) {
Ok(string_value) => Value::string(string_value, command_span),
Err(e) => Value::error(
ShellError::GenericError(
"base64 payload isn't a valid utf-8 sequence"
.to_owned(),
e.to_string(),
Some(value_span),
Some("consider using the `--binary` flag".to_owned()),
Vec::new(),
),
ShellError::GenericError {
error: "base64 payload isn't a valid utf-8 sequence"
.into(),
msg: e.to_string(),
span: Some(value_span),
help: Some(
"consider using the `--binary` flag".to_owned(),
),
inner: vec![],
},
value_span,
),
}
}
}
Err(_) => Value::error(
ShellError::GenericError(
"value could not be base64 decoded".to_string(),
format!(
ShellError::GenericError {
error: "value could not be base64 decoded".into(),
msg: format!(
"invalid base64 input for character set {}",
&config_character_set.item
),
Some(command_span),
None,
Vec::new(),
),
span: Some(command_span),
help: None,
inner: vec![],
},
command_span,
),
}

View File

@ -55,13 +55,13 @@ pub fn encode(
// This behaviour can be enabled with -i. Otherwise, it becomes an error.
if replacements && !ignore_errors {
// TODO: make GenericError accept two spans (including head)
Err(ShellError::GenericError(
"error while encoding string".into(),
format!("string contained characters not in {}", &encoding_name.item),
Some(s_span),
None,
vec![],
))
Err(ShellError::GenericError {
error: "error while encoding string".into(),
msg: format!("string contained characters not in {}", &encoding_name.item),
span: Some(s_span),
help: None,
inner: vec![],
})
} else {
Ok(Value::binary(result.into_owned(), head))
}
@ -75,15 +75,15 @@ fn parse_encoding(span: Span, label: &str) -> Result<&'static Encoding, ShellErr
label
};
match Encoding::for_label_no_replacement(label.as_bytes()) {
None => Err(ShellError::GenericError(
format!(
None => Err(ShellError::GenericError{
error: format!(
r#"{label} is not a valid encoding"#
),
"invalid encoding".into(),
Some(span),
Some("refer to https://docs.rs/encoding_rs/latest/encoding_rs/index.html#statics for a valid list of encodings".into()),
vec![],
)),
msg: "invalid encoding".into(),
span: Some(span),
help: Some("refer to https://docs.rs/encoding_rs/latest/encoding_rs/index.html#statics for a valid list of encodings".into()),
inner: vec![],
}),
Some(encoding) => Ok(encoding),
}
}

View File

@ -138,14 +138,12 @@ fn operate(
build_regex(&pattern_item, pattern_span)?
};
let regex_pattern = Regex::new(&item_to_parse).map_err(|err| {
ShellError::GenericError(
"Error with regular expression".into(),
err.to_string(),
Some(pattern_span),
None,
Vec::new(),
)
let regex_pattern = Regex::new(&item_to_parse).map_err(|e| ShellError::GenericError {
error: "Error with regular expression".into(),
msg: e.to_string(),
span: Some(pattern_span),
help: None,
inner: vec![],
})?;
let columns = column_names(&regex_pattern);
@ -164,13 +162,13 @@ fn operate(
let captures = match c {
Ok(c) => c,
Err(e) => {
return Err(ShellError::GenericError(
"Error with regular expression captures".into(),
e.to_string(),
None,
None,
Vec::new(),
))
return Err(ShellError::GenericError {
error: "Error with regular expression captures".into(),
msg: e.to_string(),
span: None,
help: None,
inner: vec![],
})
}
};
@ -430,13 +428,13 @@ fn stream_helper(
Ok(c) => c,
Err(e) => {
return Some(Value::error(
ShellError::GenericError(
"Error with regular expression captures".into(),
e.to_string(),
Some(span),
Some(e.to_string()),
Vec::new(),
),
ShellError::GenericError {
error: "Error with regular expression captures".into(),
msg: e.to_string(),
span: Some(span),
help: Some(e.to_string()),
inner: vec![],
},
span,
))
}

View File

@ -127,14 +127,12 @@ fn split_column(
let escaped = regex::escape(&separator.item);
Regex::new(&escaped)
}
.map_err(|err| {
ShellError::GenericError(
"Error with regular expression".into(),
err.to_string(),
Some(separator.span),
None,
Vec::new(),
)
.map_err(|e| ShellError::GenericError {
error: "Error with regular expression".into(),
msg: e.to_string(),
span: Some(separator.span),
help: None,
inner: vec![],
})?;
input.flat_map(

View File

@ -161,17 +161,15 @@ impl Matcher {
pub fn new(regex: bool, lhs: Value) -> Result<Self, ShellError> {
if regex {
Ok(Matcher::Regex(Regex::new(&lhs.as_string()?).map_err(
|err| {
ShellError::GenericError(
"Error with regular expression".into(),
err.to_string(),
match lhs {
Value::Error { .. } => None,
_ => Some(lhs.span()),
},
None,
Vec::new(),
)
|e| ShellError::GenericError {
error: "Error with regular expression".into(),
msg: e.to_string(),
span: match lhs {
Value::Error { .. } => None,
_ => Some(lhs.span()),
},
help: None,
inner: vec![],
},
)?))
} else {

View File

@ -129,14 +129,12 @@ fn split_row(
let escaped = regex::escape(&separator.item);
Regex::new(&escaped)
}
.map_err(|err| {
ShellError::GenericError(
"Error with regular expression".into(),
err.to_string(),
Some(separator.span),
None,
Vec::new(),
)
.map_err(|e| ShellError::GenericError {
error: "Error with regular expression".into(),
msg: e.to_string(),
span: Some(separator.span),
help: None,
inner: vec![],
})?;
let max_split: Option<usize> = call.get_flag(engine_state, stack, "number")?;
input.flat_map(

View File

@ -234,7 +234,7 @@ fn str_expand(contents: &str, span: Span, value_span: Span) -> Value {
},
Err(e) => match e {
bracoxide::ExpansionError::NumConversionFailed(s) => Value::error(
ShellError::GenericError("Number Conversion Failed".to_owned(), format!("Number conversion failed at {s}."), Some(value_span), Some("Expected number, found text. Range format is `{M..N}`, where M and N are numeric values representing the starting and ending limits.".to_owned()), vec![]),
ShellError::GenericError{error: "Number Conversion Failed".into(), msg: format!("Number conversion failed at {s}."), span: Some(value_span), help: Some("Expected number, found text. Range format is `{M..N}`, where M and N are numeric values representing the starting and ending limits.".into()), inner: vec![]},
span,
),
},
@ -243,17 +243,17 @@ fn str_expand(contents: &str, span: Span, value_span: Span) -> Value {
Err(e) => Value::error(
match e {
ParsingError::NoTokens => ShellError::PipelineEmpty { dst_span: value_span },
ParsingError::OBraExpected(s) => ShellError::GenericError("Opening Brace Expected".to_owned(), format!("Opening brace is expected at {s}."), Some(value_span), Some("In brace syntax, we use equal amount of opening (`{`) and closing (`}`). Please, take a look at the examples.".to_owned()), vec![]),
ParsingError::CBraExpected(s) => ShellError::GenericError("Closing Brace Expected".to_owned(), format!("Closing brace is expected at {s}."), Some(value_span), Some("In brace syntax, we use equal amount of opening (`{`) and closing (`}`). Please, see the examples.".to_owned()), vec![]),
ParsingError::RangeStartLimitExpected(s) => ShellError::GenericError("Range Start Expected".to_owned(), format!("Range start limit is missing, expected at {s}."), Some(value_span), Some("In brace syntax, Range is defined like `{X..Y}`, where X and Y are a number. X is the start, Y is the end. Please, inspect the examples for more information.".to_owned()), vec![]),
ParsingError::RangeEndLimitExpected(s) => ShellError::GenericError("Range Start Expected".to_owned(), format!("Range start limit is missing, expected at {s}."), Some(value_span), Some("In brace syntax, Range is defined like `{X..Y}`, where X and Y are a number. X is the start, Y is the end. Please see the examples, for more information.".to_owned()), vec![]),
ParsingError::ExpectedText(s) => ShellError::GenericError("Expected Text".to_owned(), format!("Expected text at {s}."), Some(value_span), Some("Texts are only allowed before opening brace (`{`), after closing brace (`}`), or inside `{}`. Please take a look at the examples.".to_owned()), vec![]),
ParsingError::InvalidCommaUsage(s) => ShellError::GenericError("Invalid Comma Usage".to_owned(), format!("Found comma at {s}. Commas are only valid inside collection (`{{X,Y}}`)."), Some(value_span), Some("To escape comma use backslash `\\,`.".to_owned()), vec![]),
ParsingError::RangeCantHaveText(s) => ShellError::GenericError("Range Can not Have Text".to_owned(), format!("Expecting, brace, number, or range operator, but found text at {s}."), Some(value_span), Some("Please use the format {M..N} for ranges in brace expansion, where M and N are numeric values representing the starting and ending limits of the sequence, respectively.".to_owned()), vec![]),
ParsingError::ExtraRangeOperator(s) => ShellError::GenericError("Extra Range Operator".to_owned(), format!("Found additional, range operator at {s}."), Some(value_span), Some("Please, use the format `{M..N}` where M and N are numeric values representing the starting and ending limits of the range.".to_owned()), vec![]),
ParsingError::ExtraCBra(s) => ShellError::GenericError("Extra Closing Brace".to_owned(), format!("Used extra closing brace at {s}."), Some(value_span), Some("To escape closing brace use backslash, e.g. `\\}`".to_owned()), vec![]),
ParsingError::ExtraOBra(s) => ShellError::GenericError("Extra Opening Brace".to_owned(), format!("Used extra opening brace at {s}."), Some(value_span), Some("To escape opening brace use backslash, e.g. `\\{`".to_owned()), vec![]),
ParsingError::NothingInBraces(s) => ShellError::GenericError("Nothing In Braces".to_owned(), format!("Nothing found inside braces at {s}."), Some(value_span), Some("Please provide valid content within the braces. Additionally, you can safely remove it, not needed.".to_owned()), vec![]),
ParsingError::OBraExpected(s) => ShellError::GenericError{ error: "Opening Brace Expected".into(), msg: format!("Opening brace is expected at {s}."), span: Some(value_span), help: Some("In brace syntax, we use equal amount of opening (`{`) and closing (`}`). Please, take a look at the examples.".into()), inner: vec![]},
ParsingError::CBraExpected(s) => ShellError::GenericError{ error: "Closing Brace Expected".into(), msg: format!("Closing brace is expected at {s}."), span: Some(value_span), help: Some("In brace syntax, we use equal amount of opening (`{`) and closing (`}`). Please, see the examples.".into()), inner: vec![]},
ParsingError::RangeStartLimitExpected(s) => ShellError::GenericError{error: "Range Start Expected".into(), msg: format!("Range start limit is missing, expected at {s}."), span: Some(value_span), help: Some("In brace syntax, Range is defined like `{X..Y}`, where X and Y are a number. X is the start, Y is the end. Please, inspect the examples for more information.".into()), inner: vec![]},
ParsingError::RangeEndLimitExpected(s) => ShellError::GenericError{ error: "Range Start Expected".into(), msg: format!("Range start limit is missing, expected at {s}."),span: Some(value_span), help: Some("In brace syntax, Range is defined like `{X..Y}`, where X and Y are a number. X is the start, Y is the end. Please see the examples, for more information.".into()), inner: vec![]},
ParsingError::ExpectedText(s) => ShellError::GenericError { error: "Expected Text".into(), msg: format!("Expected text at {s}."), span: Some(value_span), help: Some("Texts are only allowed before opening brace (`{`), after closing brace (`}`), or inside `{}`. Please take a look at the examples.".into()), inner: vec![] },
ParsingError::InvalidCommaUsage(s) => ShellError::GenericError { error: "Invalid Comma Usage".into(), msg: format!("Found comma at {s}. Commas are only valid inside collection (`{{X,Y}}`)."),span: Some(value_span), help: Some("To escape comma use backslash `\\,`.".into()), inner: vec![] },
ParsingError::RangeCantHaveText(s) => ShellError::GenericError { error: "Range Can not Have Text".into(), msg: format!("Expecting, brace, number, or range operator, but found text at {s}."), span: Some(value_span), help: Some("Please use the format {M..N} for ranges in brace expansion, where M and N are numeric values representing the starting and ending limits of the sequence, respectively.".into()), inner: vec![]},
ParsingError::ExtraRangeOperator(s) => ShellError::GenericError { error: "Extra Range Operator".into(), msg: format!("Found additional, range operator at {s}."), span: Some(value_span), help: Some("Please, use the format `{M..N}` where M and N are numeric values representing the starting and ending limits of the range.".into()), inner: vec![] },
ParsingError::ExtraCBra(s) => ShellError::GenericError { error: "Extra Closing Brace".into(), msg: format!("Used extra closing brace at {s}."), span: Some(value_span), help: Some("To escape closing brace use backslash, e.g. `\\}`".into()), inner: vec![] },
ParsingError::ExtraOBra(s) => ShellError::GenericError { error: "Extra Opening Brace".into(), msg: format!("Used extra opening brace at {s}."), span: Some(value_span), help: Some("To escape opening brace use backslash, e.g. `\\{`".into()), inner: vec![] },
ParsingError::NothingInBraces(s) => ShellError::GenericError { error: "Nothing In Braces".into(), msg: format!("Nothing found inside braces at {s}."), span: Some(value_span), help: Some("Please provide valid content within the braces. Additionally, you can safely remove it, not needed.".into()), inner: vec![] },
}
,
span,
@ -267,17 +267,17 @@ fn str_expand(contents: &str, span: Span, value_span: Span) -> Value {
),
TokenizationError::FormatNotSupported => Value::error(
ShellError::GenericError(
"Format Not Supported".to_owned(),
"Usage of only `{` or `}`. Brace Expansion syntax, needs to have equal amount of opening (`{`) and closing (`}`)".to_owned(),
Some(value_span),
Some("In brace expansion syntax, it is important to have an equal number of opening (`{`) and closing (`}`) braces. Please ensure that you provide a balanced pair of braces in your brace expansion pattern.".to_owned()),
vec![]
),
ShellError::GenericError {
error: "Format Not Supported".into(),
msg: "Usage of only `{` or `}`. Brace Expansion syntax, needs to have equal amount of opening (`{`) and closing (`}`)".into(),
span: Some(value_span),
help: Some("In brace expansion syntax, it is important to have an equal number of opening (`{`) and closing (`}`) braces. Please ensure that you provide a balanced pair of braces in your brace expansion pattern.".into()),
inner: vec![]
},
value_span,
),
TokenizationError::NoBraces => Value::error(
ShellError::GenericError("No Braces".to_owned(), "At least one `{}` brace expansion expected.".to_owned(), Some(value_span), Some("Please, examine the examples.".to_owned()), vec![]),
ShellError::GenericError { error: "No Braces".into(), msg: "At least one `{}` brace expansion expected.".into(), span: Some(value_span), help: Some("Please, examine the examples.".into()), inner: vec![] },
value_span,
)
},

View File

@ -88,13 +88,13 @@ impl Command for SubCommand {
let to_trim = match character.as_ref() {
Some(v) => {
if v.item.chars().count() > 1 {
return Err(ShellError::GenericError(
"Trim only works with single character".into(),
"needs single character".into(),
Some(v.span),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "Trim only works with single character".into(),
msg: "needs single character".into(),
span: Some(v.span),
help: None,
inner: vec![],
});
}
v.item.chars().next()
}

View File

@ -101,13 +101,13 @@ impl Command for Complete {
Ok(Value::record(record, call.head).into_pipeline_data())
}
_ => Err(ShellError::GenericError(
"Complete only works with external streams".to_string(),
"complete only works on external streams".to_string(),
Some(call.head),
None,
Vec::new(),
)),
_ => Err(ShellError::GenericError {
error: "Complete only works with external streams".into(),
msg: "complete only works on external streams".into(),
span: Some(call.head),
help: None,
inner: vec![],
}),
}
}

View File

@ -81,13 +81,13 @@ fn exec_impl(mut command: std::process::Command, span: Span) -> Result<PipelineD
let error = command.exec();
Err(ShellError::GenericError(
"Error on exec".into(),
error.to_string(),
Some(span),
None,
Vec::new(),
))
Err(ShellError::GenericError {
error: "Error on exec".into(),
msg: error.to_string(),
span: Some(span),
help: None,
inner: vec![],
})
}
#[cfg(windows)]

View File

@ -53,11 +53,13 @@ impl Command for NuCheck {
let mut working_set = StateWorkingSet::new(engine_state);
if is_all && is_module {
return Err(ShellError::GenericError(
"Detected command flags conflict".to_string(),
"You cannot have both `--all` and `--as-module` on the same command line, please refer to `nu-check --help` for more details".to_string(),
Some(call.head),
None, vec![]));
return Err(ShellError::GenericError {
error: "Detected command flags conflict".into(),
msg: "You cannot have both `--all` and `--as-module` on the same command line, please refer to `nu-check --help` for more details".into(),
span: Some(call.head),
help: None,
inner: vec![]
});
}
let span = input.span().unwrap_or(call.head);
@ -130,13 +132,13 @@ impl Command for NuCheck {
let ext: Vec<_> = path_str.rsplitn(2, '.').collect();
if ext[0] != "nu" {
return Err(ShellError::GenericError(
"Cannot parse input".to_string(),
"File extension must be the type of .nu".to_string(),
Some(call.head),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "Cannot parse input".into(),
msg: "File extension must be the type of .nu".into(),
span: Some(call.head),
help: None,
inner: vec![],
});
}
// Change currently parsed directory
@ -163,13 +165,13 @@ impl Command for NuCheck {
result
} else {
Err(ShellError::GenericError(
"Failed to execute command".to_string(),
"Please run 'nu-check --help' for more details".to_string(),
Some(call.head),
None,
Vec::new(),
))
Err(ShellError::GenericError {
error: "Failed to execute command".into(),
msg: "Please run 'nu-check --help' for more details".into(),
span: Some(call.head),
help: None,
inner: vec![],
})
}
}
}
@ -241,13 +243,13 @@ fn heuristic_parse(
Ok(v) => Ok(v),
Err(_) => {
if is_debug {
Err(ShellError::GenericError(
"Failed to parse content,tried both script and module".to_string(),
"syntax error".to_string(),
Some(span),
Some("Run `nu-check --help` for more details".to_string()),
Vec::new(),
))
Err(ShellError::GenericError {
error: "Failed to parse content,tried both script and module".into(),
msg: "syntax error".into(),
span: Some(span),
help: Some("Run `nu-check --help` for more details".into()),
inner: vec![],
})
} else {
Ok(PipelineData::Value(Value::bool(false, span), None))
}
@ -285,14 +287,14 @@ fn heuristic_parse_file(
Ok(v) => Ok(v),
Err(_) => {
if is_debug {
Err(ShellError::GenericError(
"Failed to parse content,tried both script and module"
.to_string(),
"syntax error".to_string(),
Some(call.head),
Some("Run `nu-check --help` for more details".to_string()),
Vec::new(),
))
Err(ShellError::GenericError {
error: "Failed to parse content,tried both script and module"
.into(),
msg: "syntax error".into(),
span: Some(call.head),
help: Some("Run `nu-check --help` for more details".into()),
inner: vec![],
})
} else {
Ok(PipelineData::Value(Value::bool(false, call.head), None))
}
@ -334,13 +336,13 @@ fn parse_module(
.first()
.expect("Unable to parse content as module")
);
Err(ShellError::GenericError(
"Failed to parse content".to_string(),
Err(ShellError::GenericError {
error: "Failed to parse content".into(),
msg,
Some(span),
Some("If the content is intended to be a script, please try to remove `--as-module` flag ".to_string()),
Vec::new(),
))
span: Some(span),
help: Some("If the content is intended to be a script, please try to remove `--as-module` flag ".into()),
inner: vec![],
})
} else {
Ok(PipelineData::Value(Value::bool(false, new_span), None))
}
@ -367,13 +369,13 @@ fn parse_script(
.expect("Unable to parse content")
);
if is_debug {
Err(ShellError::GenericError(
"Failed to parse content".to_string(),
Err(ShellError::GenericError {
error: "Failed to parse content".into(),
msg,
Some(span),
Some("If the content is intended to be a module, please consider flag of `--as-module` ".to_string()),
Vec::new(),
))
span: Some(span),
help: Some("If the content is intended to be a module, please consider flag of `--as-module` ".into()),
inner: vec![],
})
} else {
Ok(PipelineData::Value(Value::bool(false, span), None))
}

View File

@ -126,15 +126,16 @@ fn run_ps(engine_state: &EngineState, call: &Call) -> Result<PipelineData, Shell
not(target_os = "ios")
))]
{
let proc_stat = proc.curr_proc.stat().map_err(|e| {
ShellError::GenericError(
"Error getting process stat".into(),
e.to_string(),
Some(Span::unknown()),
None,
Vec::new(),
)
})?;
let proc_stat = proc
.curr_proc
.stat()
.map_err(|e| ShellError::GenericError {
error: "Error getting process stat".into(),
msg: e.to_string(),
span: Some(Span::unknown()),
help: None,
inner: vec![],
})?;
// If we can't get the start time, just use the current time
let proc_start = proc_stat
.starttime()

View File

@ -130,13 +130,13 @@ fn registry_query(
)
.into_pipeline_data())
}
Err(_) => Err(ShellError::GenericError(
"Unable to find registry key/value".to_string(),
format!("Registry value: {} was not found", value.item),
Some(value.span),
None,
Vec::new(),
)),
Err(_) => Err(ShellError::GenericError {
error: "Unable to find registry key/value".into(),
msg: format!("Registry value: {} was not found", value.item),
span: Some(value.span),
help: None,
inner: vec![],
}),
}
}
None => Ok(Value::nothing(call_span).into_pipeline_data()),
@ -153,13 +153,13 @@ fn get_reg_hive(call: &Call) -> Result<RegKey, ShellError> {
.filter(|flag| call.has_flag(flag))
.collect();
if flags.len() > 1 {
return Err(ShellError::GenericError(
"Only one registry key can be specified".into(),
"Only one registry key can be specified".into(),
Some(call.head),
None,
Vec::new(),
));
return Err(ShellError::GenericError {
error: "Only one registry key can be specified".into(),
msg: "Only one registry key can be specified".into(),
span: Some(call.head),
help: None,
inner: vec![],
});
}
let hive = flags.first().copied().unwrap_or("hkcu");
let hkey = match hive {

View File

@ -601,16 +601,16 @@ impl ExternalCommand {
}
process
} else {
return Err(ShellError::GenericError(
"Current directory not found".to_string(),
"did not find PWD environment variable".to_string(),
Some(span),
Some(concat!(
return Err(ShellError::GenericError{
error: "Current directory not found".into(),
msg: "did not find PWD environment variable".into(),
span: Some(span),
help: Some(concat!(
"The environment variable 'PWD' was not found. ",
"It is required to define the current directory when running an external command."
).to_string()),
Vec::new(),
));
).into()),
inner:Vec::new(),
});
};
process.envs(&self.env_vars);

View File

@ -143,24 +143,20 @@ pub fn icon_for_file(file_path: &Path, span: Span) -> Result<char, ShellError> {
} else if file_path.is_dir() {
let str = file_path
.file_name()
.ok_or_else(|| {
ShellError::GenericError(
"File name error".into(),
"Unable to get file name".into(),
Some(span),
None,
Vec::new(),
)
.ok_or_else(|| ShellError::GenericError {
error: "File name error".into(),
msg: "Unable to get file name".into(),
span: Some(span),
help: None,
inner: vec![],
})?
.to_str()
.ok_or_else(|| {
ShellError::GenericError(
"Unable to get str error".into(),
"Unable to convert to str file name".into(),
Some(span),
None,
Vec::new(),
)
.ok_or_else(|| ShellError::GenericError {
error: "Unable to get str error".into(),
msg: "Unable to convert to str file name".into(),
span: Some(span),
help: None,
inner: vec![],
})?;
Ok(match str {
"bin" => '\u{e5fc}', // 
@ -171,14 +167,12 @@ pub fn icon_for_file(file_path: &Path, span: Span) -> Result<char, ShellError> {
} else if let Some(icon) = extensions.icon_file(file_path) {
Ok(icon)
} else if let Some(ext) = file_path.extension().as_ref() {
let str = ext.to_str().ok_or_else(|| {
ShellError::GenericError(
"Unable to get str error".into(),
"Unable to convert to str file name".into(),
Some(span),
None,
Vec::new(),
)
let str = ext.to_str().ok_or_else(|| ShellError::GenericError {
error: "Unable to get str error".into(),
msg: "Unable to convert to str file name".into(),
span: Some(span),
help: None,
inner: vec![],
})?;
Ok(match str {
"a" => '\u{f17c}', // 