mirror of
https://github.com/nushell/nushell.git
synced 2025-08-09 06:25:43 +02:00
Refactor I/O Errors (#14927)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx
you can also mention related issues, PRs or discussions!
-->
# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.
Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
As mentioned in #10698, we have too many `ShellError` variants, with
some even overlapping in meaning. This PR simplifies and improves I/O
error handling by restructuring `ShellError` related to I/O issues.
Previously, `ShellError::IOError` only contained a message string,
making it convenient but overly generic. It was widely used without
providing spans (#4323).
This PR introduces a new `ShellError::Io` variant that consolidates
multiple I/O-related errors (except for `ShellError::NetworkFailure`,
which remains distinct for now). The new `ShellError::Io` variant
replaces the following:
- `FileNotFound`
- `FileNotFoundCustom`
- `IOInterrupted`
- `IOError`
- `IOErrorSpanned`
- `NotADirectory`
- `DirectoryNotFound`
- `MoveNotPossible`
- `CreateNotPossible`
- `ChangeAccessTimeNotPossible`
- `ChangeModifiedTimeNotPossible`
- `RemoveNotPossible`
- `ReadingFile`
## The `IoError`
`IoError` includes the following fields:
1. **`kind`**: Extends `std::io::ErrorKind` to specify the type of I/O
error without needing new `ShellError` variants. This aligns with the
approach used in `std::io::Error`. This adds a second dimension to error
reporting by combining the `kind` field with `ShellError` variants,
making it easier to describe errors in more detail. As proposed by
@kubouch in [#design-discussion on
Discord](https://discord.com/channels/601130461678272522/615329862395101194/1323699197165178930),
this helps reduce the number of `ShellError` variants. In the error
report, the `kind` field is displayed as the "source" of the error,
e.g., "I/O error," followed by the specific kind of I/O error.
2. **`span`**: A non-optional field to encourage providing spans for
better error reporting (#4323).
3. **`path`**: Optional `PathBuf` to give context about the file or
directory involved in the error (#7695). If provided, it’s shown as a
help entry in error reports.
4. **`additional_context`**: Allows adding custom messages when the
span, kind, and path are insufficient. This is rendered in the error
report at the labeled span.
5. **`location`**: Sometimes, I/O errors occur in the engine itself and
are not caused directly by user input. In such cases, if we don’t have a
span and must set it to `Span::unknown()`, we need another way to
reference the error. For this, the `location` field uses the new
`Location` struct, which records the Rust file and line number where the
error occurred. This ensures that we at least know the Rust code
location that failed, helping with debugging. To make this work, a new
`location!` macro was added, which retrieves `file!`, `line!`, and
`column!` values accurately. If `Location::new` is used directly, it
issues a warning to remind developers to use the macro instead, ensuring
consistent and correct usage.
### Constructor Behavior
`IoError` provides five constructor methods:
- `new` and `new_with_additional_context`: Used for errors caused by
user input and require a valid (non-unknown) span to ensure precise
error reporting.
- `new_internal` and `new_internal_with_path`: Used for internal errors
where a span is not available. These methods require additional context
and the `Location` struct to pinpoint the source of the error in the
engine code.
- `factory`: Returns a closure that maps an `std::io::Error` to an
`IoError`. This is useful for handling multiple I/O errors that share
the same span and path, streamlining error handling in such cases.
## New Report Look
This is simulation how the I/O errors look like (the `open crates` is
simulated to show how internal errors are referenced now):

## `Span::test_data()`
To enable better testing, `Span::test_data()` now returns a value
distinct from `Span::unknown()`. Both `Span::test_data()` and
`Span::unknown()` refer to invalid source code, but having a separate
value for test data helps identify issues during testing while keeping
spans unique.
## Cursed Sneaky Error Transfers
I removed the conversions between `std::io::Error` and `ShellError` as
they often removed important information and were used too broadly to
handle I/O errors. This also removed the problematic implementation
found here:
7ea4895513/crates/nu-protocol/src/errors/shell_error.rs (L1534-L1583)
which hid some downcasting from I/O errors and made it hard to trace
where `ShellError` was converted into `std::io::Error`. To address this,
I introduced a new struct called `ShellErrorBridge`, which explicitly
defines this transfer behavior. With `ShellErrorBridge`, we can now
easily grep the codebase to locate and manage such conversions.
## Miscellaneous
- Removed the OS error added in #14640, as it’s no longer needed.
- Improved error messages in `glob_from` (#14679).
- Trying to open a directory with `open` caused a permissions denied
error (it's just what the OS provides). I added a `is_dir` check to
provide a better error in that case.
# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
- Error outputs now include more detailed information and are formatted
differently, including updated error codes.
- The structure of `ShellError` has changed, requiring plugin authors
and embedders to update their implementations.
# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.
Make sure you've run and fixed any issues with these commands:
- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library
> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->
I updated tests to account for the new I/O error structure and
formatting changes.
# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
This PR closes #7695 and closes #14892 and partially addresses #4323 and
#10698.
---------
Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
This commit is contained in:
@ -1,4 +1,7 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use nu_engine::command_prelude::*;
|
||||
use nu_protocol::shell_error::{self, io::IoError};
|
||||
use nu_utils::filesystem::{have_permission, PermissionResult};
|
||||
|
||||
#[derive(Clone)]
|
||||
@ -77,25 +80,39 @@ impl Command for Cd {
|
||||
if physical {
|
||||
if let Ok(path) = nu_path::canonicalize_with(path_no_whitespace, &cwd) {
|
||||
if !path.is_dir() {
|
||||
return Err(ShellError::NotADirectory { span: v.span });
|
||||
return Err(shell_error::io::IoError::new(
|
||||
shell_error::io::ErrorKind::NotADirectory,
|
||||
v.span,
|
||||
None,
|
||||
)
|
||||
.into());
|
||||
};
|
||||
path
|
||||
} else {
|
||||
return Err(ShellError::DirectoryNotFound {
|
||||
dir: path_no_whitespace.to_string(),
|
||||
span: v.span,
|
||||
});
|
||||
return Err(shell_error::io::IoError::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
v.span,
|
||||
PathBuf::from(path_no_whitespace),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
} else {
|
||||
let path = nu_path::expand_path_with(path_no_whitespace, &cwd, true);
|
||||
if !path.exists() {
|
||||
return Err(ShellError::DirectoryNotFound {
|
||||
dir: path_no_whitespace.to_string(),
|
||||
span: v.span,
|
||||
});
|
||||
return Err(shell_error::io::IoError::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
v.span,
|
||||
PathBuf::from(path_no_whitespace),
|
||||
)
|
||||
.into());
|
||||
};
|
||||
if !path.is_dir() {
|
||||
return Err(ShellError::NotADirectory { span: v.span });
|
||||
return Err(shell_error::io::IoError::new(
|
||||
shell_error::io::ErrorKind::NotADirectory,
|
||||
v.span,
|
||||
path,
|
||||
)
|
||||
.into());
|
||||
};
|
||||
path
|
||||
}
|
||||
@ -117,13 +134,9 @@ impl Command for Cd {
|
||||
stack.set_cwd(path)?;
|
||||
Ok(PipelineData::empty())
|
||||
}
|
||||
PermissionResult::PermissionDenied(reason) => Err(ShellError::IOError {
|
||||
msg: format!(
|
||||
"Cannot change directory to {}: {}",
|
||||
path.to_string_lossy(),
|
||||
reason
|
||||
),
|
||||
}),
|
||||
PermissionResult::PermissionDenied(_) => {
|
||||
Err(IoError::new(std::io::ErrorKind::PermissionDenied, call.head, path).into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -5,7 +5,7 @@ use nu_engine::glob_from;
|
||||
use nu_engine::{command_prelude::*, env::current_dir};
|
||||
use nu_glob::MatchOptions;
|
||||
use nu_path::{expand_path_with, expand_to_real_path};
|
||||
use nu_protocol::{DataSource, NuGlob, PipelineMetadata, Signals};
|
||||
use nu_protocol::{shell_error::io::IoError, DataSource, NuGlob, PipelineMetadata, Signals};
|
||||
use pathdiff::diff_paths;
|
||||
use rayon::prelude::*;
|
||||
#[cfg(unix)]
|
||||
@ -254,10 +254,12 @@ fn ls_for_one_pattern(
|
||||
if let Some(path) = pattern_arg {
|
||||
// it makes no sense to list an empty string.
|
||||
if path.item.as_ref().is_empty() {
|
||||
return Err(ShellError::FileNotFoundCustom {
|
||||
msg: "empty string('') directory or file does not exist".to_string(),
|
||||
span: path.span,
|
||||
});
|
||||
return Err(ShellError::Io(IoError::new_with_additional_context(
|
||||
std::io::ErrorKind::NotFound,
|
||||
path.span,
|
||||
PathBuf::from(path.item.to_string()),
|
||||
"empty string('') directory or file does not exist",
|
||||
)));
|
||||
}
|
||||
match path.item {
|
||||
NuGlob::DoNotExpand(p) => Some(Spanned {
|
||||
@ -283,10 +285,7 @@ fn ls_for_one_pattern(
|
||||
nu_path::expand_path_with(pat.item.as_ref(), &cwd, pat.item.is_expand());
|
||||
// Avoid checking and pushing "*" to the path when directory (do not show contents) flag is true
|
||||
if !directory && tmp_expanded.is_dir() {
|
||||
if read_dir(&tmp_expanded, p_tag, use_threads)?
|
||||
.next()
|
||||
.is_none()
|
||||
{
|
||||
if read_dir(tmp_expanded, p_tag, use_threads)?.next().is_none() {
|
||||
return Ok(Value::test_nothing().into_pipeline_data());
|
||||
}
|
||||
just_read_dir = !(pat.item.is_expand() && nu_glob::is_glob(pat.item.as_ref()));
|
||||
@ -305,7 +304,7 @@ fn ls_for_one_pattern(
|
||||
// Avoid pushing "*" to the default path when directory (do not show contents) flag is true
|
||||
if directory {
|
||||
(NuGlob::Expand(".".to_string()), false)
|
||||
} else if read_dir(&cwd, p_tag, use_threads)?.next().is_none() {
|
||||
} else if read_dir(cwd.clone(), p_tag, use_threads)?.next().is_none() {
|
||||
return Ok(Value::test_nothing().into_pipeline_data());
|
||||
} else {
|
||||
(NuGlob::Expand("*".to_string()), false)
|
||||
@ -318,7 +317,7 @@ fn ls_for_one_pattern(
|
||||
let path = pattern_arg.into_spanned(p_tag);
|
||||
let (prefix, paths) = if just_read_dir {
|
||||
let expanded = nu_path::expand_path_with(path.item.as_ref(), &cwd, path.item.is_expand());
|
||||
let paths = read_dir(&expanded, p_tag, use_threads)?;
|
||||
let paths = read_dir(expanded.clone(), p_tag, use_threads)?;
|
||||
// just need to read the directory, so prefix is path itself.
|
||||
(Some(expanded), paths)
|
||||
} else {
|
||||
@ -350,7 +349,16 @@ fn ls_for_one_pattern(
|
||||
let signals_clone = signals.clone();
|
||||
|
||||
let pool = if use_threads {
|
||||
let count = std::thread::available_parallelism()?.get();
|
||||
let count = std::thread::available_parallelism()
|
||||
.map_err(|err| {
|
||||
IoError::new_with_additional_context(
|
||||
err.kind(),
|
||||
call_span,
|
||||
None,
|
||||
"Could not get available parallelism",
|
||||
)
|
||||
})?
|
||||
.get();
|
||||
create_pool(count)?
|
||||
} else {
|
||||
create_pool(1)?
|
||||
@ -910,14 +918,12 @@ mod windows_helper {
|
||||
&mut find_data,
|
||||
) {
|
||||
Ok(_) => Ok(find_data),
|
||||
Err(e) => Err(ShellError::ReadingFile {
|
||||
msg: format!(
|
||||
"Could not read metadata for '{}':\n '{}'",
|
||||
filename.to_string_lossy(),
|
||||
e
|
||||
),
|
||||
Err(e) => Err(ShellError::Io(IoError::new_with_additional_context(
|
||||
std::io::ErrorKind::Other,
|
||||
span,
|
||||
}),
|
||||
PathBuf::from(filename),
|
||||
format!("Could not read metadata: {e}"),
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -950,28 +956,17 @@ mod windows_helper {
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn read_dir(
|
||||
f: &Path,
|
||||
f: PathBuf,
|
||||
span: Span,
|
||||
use_threads: bool,
|
||||
) -> Result<Box<dyn Iterator<Item = Result<PathBuf, ShellError>> + Send>, ShellError> {
|
||||
let items = f
|
||||
.read_dir()
|
||||
.map_err(|error| {
|
||||
if error.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
return ShellError::GenericError {
|
||||
error: "Permission denied".into(),
|
||||
msg: "The permissions may not allow access for this user".into(),
|
||||
span: Some(span),
|
||||
help: None,
|
||||
inner: vec![],
|
||||
};
|
||||
}
|
||||
|
||||
error.into()
|
||||
})?
|
||||
.map(|d| {
|
||||
.map_err(|err| IoError::new(err.kind(), span, f.clone()))?
|
||||
.map(move |d| {
|
||||
d.map(|r| r.path())
|
||||
.map_err(|e| ShellError::IOError { msg: e.to_string() })
|
||||
.map_err(|err| IoError::new(err.kind(), span, f.clone()))
|
||||
.map_err(ShellError::from)
|
||||
});
|
||||
if !use_threads {
|
||||
let mut collected = items.collect::<Vec<_>>();
|
||||
|
@ -106,14 +106,10 @@ impl Command for Mktemp {
|
||||
};
|
||||
|
||||
let res = match uu_mktemp::mktemp(&options) {
|
||||
Ok(res) => {
|
||||
res.into_os_string()
|
||||
.into_string()
|
||||
.map_err(|e| ShellError::IOErrorSpanned {
|
||||
msg: e.to_string_lossy().to_string(),
|
||||
span,
|
||||
})?
|
||||
}
|
||||
Ok(res) => res
|
||||
.into_os_string()
|
||||
.into_string()
|
||||
.map_err(|_| ShellError::NonUtf8 { span })?,
|
||||
Err(e) => {
|
||||
return Err(ShellError::GenericError {
|
||||
error: format!("{}", e),
|
||||
|
@ -1,7 +1,11 @@
|
||||
#[allow(deprecated)]
|
||||
use nu_engine::{command_prelude::*, current_dir, get_eval_block};
|
||||
use nu_protocol::{ast, DataSource, NuGlob, PipelineMetadata};
|
||||
use std::path::Path;
|
||||
use nu_protocol::{
|
||||
ast,
|
||||
shell_error::{self, io::IoError},
|
||||
DataSource, NuGlob, PipelineMetadata,
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[cfg(feature = "sqlite")]
|
||||
use crate::database::SQLiteDatabase;
|
||||
@ -87,25 +91,10 @@ impl Command for Open {
|
||||
|
||||
for path in nu_engine::glob_from(&path, &cwd, call_span, None)
|
||||
.map_err(|err| match err {
|
||||
ShellError::DirectoryNotFound { span, .. } => ShellError::FileNotFound {
|
||||
file: path.item.to_string(),
|
||||
span,
|
||||
},
|
||||
// that particular error in `nu_engine::glob_from` doesn't have a span attached
|
||||
// to it, so let's add it
|
||||
ShellError::GenericError {
|
||||
error,
|
||||
msg,
|
||||
span: _,
|
||||
help,
|
||||
inner,
|
||||
} if error.as_str() == "Permission denied" => ShellError::GenericError {
|
||||
error,
|
||||
msg,
|
||||
span: Some(arg_span),
|
||||
help,
|
||||
inner,
|
||||
},
|
||||
ShellError::Io(mut err) => {
|
||||
err.span = arg_span;
|
||||
err.into()
|
||||
}
|
||||
_ => err,
|
||||
})?
|
||||
.1
|
||||
@ -114,24 +103,26 @@ impl Command for Open {
|
||||
let path = Path::new(&path);
|
||||
|
||||
if permission_denied(path) {
|
||||
let err = IoError::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
arg_span,
|
||||
PathBuf::from(path),
|
||||
);
|
||||
|
||||
#[cfg(unix)]
|
||||
let error_msg = match path.metadata() {
|
||||
Ok(md) => format!(
|
||||
"The permissions of {:o} does not allow access for this user",
|
||||
md.permissions().mode() & 0o0777
|
||||
),
|
||||
Err(e) => e.to_string(),
|
||||
let err = {
|
||||
let mut err = err;
|
||||
err.additional_context = Some(match path.metadata() {
|
||||
Ok(md) => format!(
|
||||
"The permissions of {:o} does not allow access for this user",
|
||||
md.permissions().mode() & 0o0777
|
||||
),
|
||||
Err(e) => e.to_string(),
|
||||
});
|
||||
err
|
||||
};
|
||||
|
||||
#[cfg(not(unix))]
|
||||
let error_msg = String::from("Permission denied");
|
||||
return Err(ShellError::GenericError {
|
||||
error: "Permission denied".into(),
|
||||
msg: error_msg,
|
||||
span: Some(arg_span),
|
||||
help: None,
|
||||
inner: vec![],
|
||||
});
|
||||
return Err(err.into());
|
||||
} else {
|
||||
#[cfg(feature = "sqlite")]
|
||||
if !raw {
|
||||
@ -147,18 +138,18 @@ impl Command for Open {
|
||||
}
|
||||
}
|
||||
|
||||
let file = match std::fs::File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(err) => {
|
||||
return Err(ShellError::GenericError {
|
||||
error: "Permission denied".into(),
|
||||
msg: err.to_string(),
|
||||
span: Some(arg_span),
|
||||
help: None,
|
||||
inner: vec![],
|
||||
});
|
||||
}
|
||||
};
|
||||
if path.is_dir() {
|
||||
// At least under windows this check ensures that we don't get a
|
||||
// permission denied error on directories
|
||||
return Err(ShellError::Io(IoError::new(
|
||||
shell_error::io::ErrorKind::IsADirectory,
|
||||
arg_span,
|
||||
PathBuf::from(path),
|
||||
)));
|
||||
}
|
||||
|
||||
let file = std::fs::File::open(path)
|
||||
.map_err(|err| IoError::new(err.kind(), arg_span, PathBuf::from(path)))?;
|
||||
|
||||
// No content_type by default - Is added later if no converter is found
|
||||
let stream = PipelineData::ByteStream(
|
||||
|
@ -3,7 +3,11 @@ use super::util::try_interaction;
|
||||
use nu_engine::{command_prelude::*, env::current_dir};
|
||||
use nu_glob::MatchOptions;
|
||||
use nu_path::expand_path_with;
|
||||
use nu_protocol::{report_shell_error, NuGlob};
|
||||
use nu_protocol::{
|
||||
report_shell_error,
|
||||
shell_error::{self, io::IoError},
|
||||
NuGlob,
|
||||
};
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::prelude::FileTypeExt;
|
||||
use std::{
|
||||
@ -299,9 +303,17 @@ fn rm(
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// glob_from may canonicalize path and return `DirectoryNotFound`
|
||||
// glob_from may canonicalize path and return an error when a directory is not found
|
||||
// nushell should suppress the error if `--force` is used.
|
||||
if !(force && matches!(e, ShellError::DirectoryNotFound { .. })) {
|
||||
if !(force
|
||||
&& matches!(
|
||||
e,
|
||||
ShellError::Io(IoError {
|
||||
kind: shell_error::io::ErrorKind::Std(std::io::ErrorKind::NotFound),
|
||||
..
|
||||
})
|
||||
))
|
||||
{
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
@ -413,8 +425,7 @@ fn rm(
|
||||
};
|
||||
|
||||
if let Err(e) = result {
|
||||
let msg = format!("Could not delete {:}: {e:}", f.to_string_lossy());
|
||||
Err(ShellError::RemoveNotPossible { msg, span })
|
||||
Err(ShellError::Io(IoError::new(e.kind(), span, f)))
|
||||
} else if verbose {
|
||||
let msg = if interactive && !confirmed {
|
||||
"not deleted"
|
||||
|
@ -4,8 +4,8 @@ use nu_engine::get_eval_block;
|
||||
use nu_engine::{command_prelude::*, current_dir};
|
||||
use nu_path::expand_path_with;
|
||||
use nu_protocol::{
|
||||
ast, byte_stream::copy_with_signals, process::ChildPipe, ByteStreamSource, DataSource, OutDest,
|
||||
PipelineMetadata, Signals,
|
||||
ast, byte_stream::copy_with_signals, process::ChildPipe, shell_error::io::IoError,
|
||||
ByteStreamSource, DataSource, OutDest, PipelineMetadata, Signals,
|
||||
};
|
||||
use std::{
|
||||
fs::File,
|
||||
@ -86,6 +86,7 @@ impl Command for Save {
|
||||
span: arg.span,
|
||||
});
|
||||
|
||||
let from_io_error = IoError::factory(span, path.item.as_path());
|
||||
match input {
|
||||
PipelineData::ByteStream(stream, metadata) => {
|
||||
check_saving_to_source_file(metadata.as_ref(), &path, stderr_path.as_ref())?;
|
||||
@ -129,7 +130,7 @@ impl Command for Save {
|
||||
io::copy(&mut tee, &mut io::stderr())
|
||||
}
|
||||
}
|
||||
.err_span(span)?;
|
||||
.map_err(|err| IoError::new(err.kind(), span, None))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@ -153,7 +154,7 @@ impl Command for Save {
|
||||
)
|
||||
})
|
||||
.transpose()
|
||||
.err_span(span)?;
|
||||
.map_err(&from_io_error)?;
|
||||
|
||||
let res = match stdout {
|
||||
ChildPipe::Pipe(pipe) => {
|
||||
@ -203,15 +204,10 @@ impl Command for Save {
|
||||
let (mut file, _) = get_files(&path, stderr_path.as_ref(), append, force)?;
|
||||
for val in ls {
|
||||
file.write_all(&value_to_bytes(val)?)
|
||||
.map_err(|err| ShellError::IOError {
|
||||
msg: err.to_string(),
|
||||
})?;
|
||||
file.write_all("\n".as_bytes())
|
||||
.map_err(|err| ShellError::IOError {
|
||||
msg: err.to_string(),
|
||||
})?;
|
||||
.map_err(&from_io_error)?;
|
||||
file.write_all("\n".as_bytes()).map_err(&from_io_error)?;
|
||||
}
|
||||
file.flush()?;
|
||||
file.flush().map_err(&from_io_error)?;
|
||||
|
||||
Ok(PipelineData::empty())
|
||||
}
|
||||
@ -232,11 +228,8 @@ impl Command for Save {
|
||||
// Only open file after successful conversion
|
||||
let (mut file, _) = get_files(&path, stderr_path.as_ref(), append, force)?;
|
||||
|
||||
file.write_all(&bytes).map_err(|err| ShellError::IOError {
|
||||
msg: err.to_string(),
|
||||
})?;
|
||||
|
||||
file.flush()?;
|
||||
file.write_all(&bytes).map_err(&from_io_error)?;
|
||||
file.flush().map_err(&from_io_error)?;
|
||||
|
||||
Ok(PipelineData::empty())
|
||||
}
|
||||
@ -420,33 +413,27 @@ fn prepare_path(
|
||||
}
|
||||
|
||||
fn open_file(path: &Path, span: Span, append: bool) -> Result<File, ShellError> {
|
||||
let file = match (append, path.exists()) {
|
||||
(true, true) => std::fs::OpenOptions::new().append(true).open(path),
|
||||
let file: Result<File, nu_protocol::shell_error::io::ErrorKind> = match (append, path.exists())
|
||||
{
|
||||
(true, true) => std::fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(path)
|
||||
.map_err(|err| err.kind().into()),
|
||||
_ => {
|
||||
// This is a temporary solution until `std::fs::File::create` is fixed on Windows (rust-lang/rust#134893)
|
||||
// A TOCTOU problem exists here, which may cause wrong error message to be shown
|
||||
#[cfg(target_os = "windows")]
|
||||
if path.is_dir() {
|
||||
// It should be `io::ErrorKind::IsADirectory` but it's not available in stable yet (1.83)
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"Is a directory (os error 21)",
|
||||
))
|
||||
Err(nu_protocol::shell_error::io::ErrorKind::IsADirectory)
|
||||
} else {
|
||||
std::fs::File::create(path)
|
||||
std::fs::File::create(path).map_err(|err| err.kind().into())
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
std::fs::File::create(path)
|
||||
std::fs::File::create(path).map_err(|err| err.kind().into())
|
||||
}
|
||||
};
|
||||
|
||||
file.map_err(|e| ShellError::GenericError {
|
||||
error: format!("Problem with [{}], Permission denied", path.display()),
|
||||
msg: e.to_string(),
|
||||
span: Some(span),
|
||||
help: None,
|
||||
inner: vec![],
|
||||
})
|
||||
file.map_err(|err_kind| ShellError::Io(IoError::new(err_kind, span, PathBuf::from(path))))
|
||||
}
|
||||
|
||||
/// Get output file and optional stderr file
|
||||
@ -493,6 +480,9 @@ fn stream_to_file(
|
||||
span: Span,
|
||||
progress: bool,
|
||||
) -> Result<(), ShellError> {
|
||||
// TODO: maybe we can get a path in here
|
||||
let from_io_error = IoError::factory(span, None);
|
||||
|
||||
// https://github.com/nushell/nushell/pull/9377 contains the reason for not using `BufWriter`
|
||||
if progress {
|
||||
let mut bytes_processed = 0;
|
||||
@ -512,7 +502,7 @@ fn stream_to_file(
|
||||
match reader.fill_buf() {
|
||||
Ok(&[]) => break Ok(()),
|
||||
Ok(buf) => {
|
||||
file.write_all(buf).err_span(span)?;
|
||||
file.write_all(buf).map_err(&from_io_error)?;
|
||||
let len = buf.len();
|
||||
reader.consume(len);
|
||||
bytes_processed += len as u64;
|
||||
@ -530,9 +520,9 @@ fn stream_to_file(
|
||||
if let Err(err) = res {
|
||||
let _ = file.flush();
|
||||
bar.abandoned_msg("# Error while saving #".to_owned());
|
||||
Err(err.into_spanned(span).into())
|
||||
Err(from_io_error(err).into())
|
||||
} else {
|
||||
file.flush().err_span(span)?;
|
||||
file.flush().map_err(&from_io_error)?;
|
||||
Ok(())
|
||||
}
|
||||
} else {
|
||||
|
@ -1,6 +1,6 @@
|
||||
#[allow(deprecated)]
|
||||
use nu_engine::{command_prelude::*, current_dir};
|
||||
use nu_protocol::NuGlob;
|
||||
use nu_protocol::{shell_error::io::IoError, NuGlob};
|
||||
use std::path::PathBuf;
|
||||
use uu_cp::{BackupMode, CopyMode, UpdateMode};
|
||||
|
||||
@ -197,10 +197,11 @@ impl Command for UCp {
|
||||
.map(|f| f.1)?
|
||||
.collect();
|
||||
if exp_files.is_empty() {
|
||||
return Err(ShellError::FileNotFound {
|
||||
file: p.item.to_string(),
|
||||
span: p.span,
|
||||
});
|
||||
return Err(ShellError::Io(IoError::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
p.span,
|
||||
PathBuf::from(p.item.to_string()),
|
||||
)));
|
||||
};
|
||||
let mut app_vals: Vec<PathBuf> = Vec::new();
|
||||
for v in exp_files {
|
||||
|
@ -1,7 +1,7 @@
|
||||
#[allow(deprecated)]
|
||||
use nu_engine::{command_prelude::*, current_dir};
|
||||
use nu_path::expand_path_with;
|
||||
use nu_protocol::NuGlob;
|
||||
use nu_protocol::{shell_error::io::IoError, NuGlob};
|
||||
use std::{ffi::OsString, path::PathBuf};
|
||||
use uu_mv::{BackupMode, UpdateMode};
|
||||
|
||||
@ -138,10 +138,11 @@ impl Command for UMv {
|
||||
.map(|f| f.1)?
|
||||
.collect();
|
||||
if exp_files.is_empty() {
|
||||
return Err(ShellError::FileNotFound {
|
||||
file: p.item.to_string(),
|
||||
span: p.span,
|
||||
});
|
||||
return Err(ShellError::Io(IoError::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
p.span,
|
||||
PathBuf::from(p.item.to_string()),
|
||||
)));
|
||||
};
|
||||
let mut app_vals: Vec<PathBuf> = Vec::new();
|
||||
for v in exp_files {
|
||||
|
@ -3,8 +3,8 @@ use filetime::FileTime;
|
||||
use nu_engine::command_prelude::*;
|
||||
use nu_glob::{glob, is_glob};
|
||||
use nu_path::expand_path_with;
|
||||
use nu_protocol::NuGlob;
|
||||
use std::{io::ErrorKind, path::PathBuf};
|
||||
use nu_protocol::{shell_error::io::IoError, NuGlob};
|
||||
use std::path::PathBuf;
|
||||
use uu_touch::{error::TouchError, ChangeTimes, InputFile, Options, Source};
|
||||
|
||||
#[derive(Clone)]
|
||||
@ -225,20 +225,12 @@ impl Command for UTouch {
|
||||
},
|
||||
TouchError::ReferenceFileInaccessible(reference_path, io_err) => {
|
||||
let span = reference_span.expect("touch should've been given a reference file");
|
||||
if io_err.kind() == ErrorKind::NotFound {
|
||||
ShellError::FileNotFound {
|
||||
span,
|
||||
file: reference_path.display().to_string(),
|
||||
}
|
||||
} else {
|
||||
ShellError::GenericError {
|
||||
error: io_err.to_string(),
|
||||
msg: format!("Failed to read metadata of {}", reference_path.display()),
|
||||
span: Some(span),
|
||||
help: None,
|
||||
inner: Vec::new(),
|
||||
}
|
||||
}
|
||||
ShellError::Io(IoError::new_with_additional_context(
|
||||
io_err.kind(),
|
||||
span,
|
||||
reference_path,
|
||||
"failed to read metadata",
|
||||
))
|
||||
}
|
||||
_ => ShellError::GenericError {
|
||||
error: err.to_string(),
|
||||
|
@ -9,6 +9,7 @@ use nu_engine::{command_prelude::*, ClosureEval};
|
||||
use nu_protocol::{
|
||||
engine::{Closure, StateWorkingSet},
|
||||
format_shell_error,
|
||||
shell_error::io::IoError,
|
||||
};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
@ -83,11 +84,12 @@ impl Command for Watch {
|
||||
|
||||
let path = match nu_path::canonicalize_with(path_no_whitespace, cwd) {
|
||||
Ok(p) => p,
|
||||
Err(_) => {
|
||||
return Err(ShellError::DirectoryNotFound {
|
||||
dir: path_no_whitespace.to_string(),
|
||||
span: path_arg.span,
|
||||
})
|
||||
Err(err) => {
|
||||
return Err(ShellError::Io(IoError::new(
|
||||
err.kind(),
|
||||
path_arg.span,
|
||||
PathBuf::from(path_no_whitespace),
|
||||
)))
|
||||
}
|
||||
};
|
||||
|
||||
@ -151,14 +153,22 @@ impl Command for Watch {
|
||||
let mut debouncer = match new_debouncer(debounce_duration, None, tx) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
return Err(ShellError::IOError {
|
||||
msg: format!("Failed to create watcher: {e}"),
|
||||
})
|
||||
return Err(ShellError::GenericError {
|
||||
error: "Failed to create watcher".to_string(),
|
||||
msg: e.to_string(),
|
||||
span: Some(call.head),
|
||||
help: None,
|
||||
inner: vec![],
|
||||
});
|
||||
}
|
||||
};
|
||||
if let Err(e) = debouncer.watcher().watch(&path, recursive_mode) {
|
||||
return Err(ShellError::IOError {
|
||||
msg: format!("Failed to create watcher: {e}"),
|
||||
return Err(ShellError::GenericError {
|
||||
error: "Failed to create watcher".to_string(),
|
||||
msg: e.to_string(),
|
||||
span: Some(call.head),
|
||||
help: None,
|
||||
inner: vec![],
|
||||
});
|
||||
}
|
||||
// need to cache to make sure that rename event works.
|
||||
@ -249,13 +259,21 @@ impl Command for Watch {
|
||||
}
|
||||
}
|
||||
Ok(Err(_)) => {
|
||||
return Err(ShellError::IOError {
|
||||
return Err(ShellError::GenericError {
|
||||
error: "Receiving events failed".to_string(),
|
||||
msg: "Unexpected errors when receiving events".into(),
|
||||
})
|
||||
span: None,
|
||||
help: None,
|
||||
inner: vec![],
|
||||
});
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => {
|
||||
return Err(ShellError::IOError {
|
||||
return Err(ShellError::GenericError {
|
||||
error: "Disconnected".to_string(),
|
||||
msg: "Unexpected disconnect from file watcher".into(),
|
||||
span: None,
|
||||
help: None,
|
||||
inner: vec![],
|
||||
});
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
|
Reference in New Issue
Block a user