Skip to content

Refactor I/O Errors - #14927

Merged
fdncred merged 60 commits into
nushell:mainfrom
cptpiepmatz:consolidate-io-errors
Jan 28, 2025
Merged

fdncred merged 60 commits into
nushell:mainfrom
cptpiepmatz:consolidate-io-errors

Conversation

@cptpiepmatz

@cptpiepmatz cptpiepmatz commented Jan 27, 2025 •

Copy link
Copy Markdown
Member

Description

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, 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 (Deprecate error types without spans #4323).
  3. path: Optional PathBuf to give context about the file or directory involved in the error (Provide more context to OS errors #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):
Screenshot 2025-01-25 190426

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:

impl From<io::Error> for ShellError {
fn from(error: io::Error) -> ShellError {
if error.kind() == io::ErrorKind::Other {
match error.into_inner() {
Some(err) => match err.downcast() {
Ok(err) => *err,
Err(err) => Self::IOError {
msg: err.to_string(),
},
},
None => Self::IOError {
msg: "unknown error".into(),
},
}
} else {
Self::IOError {
msg: error.to_string(),
}
}
}
}
impl From<Spanned<io::Error>> for ShellError {
fn from(error: Spanned<io::Error>) -> Self {
let Spanned { item: error, span } = error;
match error.kind() {
io::ErrorKind::Other => match error.into_inner() {
Some(err) => match err.downcast() {
Ok(err) => *err,
Err(err) => Self::IOErrorSpanned {
msg: err.to_string(),
span,
},
},
None => Self::IOErrorSpanned {
msg: "unknown error".into(),
span,
},
},
io::ErrorKind::TimedOut => Self::NetworkFailure {
msg: error.to_string(),
span,
},
_ => Self::IOErrorSpanned {
msg: error.to_string(),
span,
},
}
}
}

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

User-Facing 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

I updated tests to account for the new I/O error structure and formatting changes.

After Submitting

This PR closes #7695 and closes #14892 and partially addresses #4323 and #10698.

@cptpiepmatz

Copy link
Copy Markdown
Member Author

I'm open to changing the exact display format of the file reference but not everything is easily done using miette while also providing a convenient API to inspect the raw Rust error type.

The format with filename:line:column worked great for me in VSCode, you can just Ctrl+Click on it and jump to the exact location.

@fdncred

fdncred commented Jan 28, 2025

Copy link
Copy Markdown
Contributor

We are 1 week before the next release. I'm hoping we'll be able to land this but I'm not sure there is time. We shall see.

@kubouch

kubouch commented Jan 28, 2025

Copy link
Copy Markdown
Contributor

I'm not opposed to landing this and dogfood for 1 week.

@132ikl

132ikl commented Jan 28, 2025

Copy link
Copy Markdown
Member

Looks great! I was a little concerned about how often we would be showing code locations in errors, but after looking through all the usages of the internal errors they seem to all make sense. I did find two cases I think we can improve:

  • We can avoid an internal error when canonicalizing globs:
diff --git a/crates/nu-engine/src/glob_from.rs b/crates/nu-engine/src/glob_from.rs
index bf4801ba1..1120499b4 100644
--- a/crates/nu-engine/src/glob_from.rs
+++ b/crates/nu-engine/src/glob_from.rs
@@ -27,6 +27,7 @@ pub fn glob_from(
     ShellError,
 > {
     let no_glob_for_pattern = matches!(pattern.item, NuGlob::DoNotExpand(_));
+    let pattern_span = pattern.span;
     let (prefix, pattern) = if nu_glob::is_glob(pattern.item.as_ref()) {
         // Pattern contains glob, split it
         let mut p = PathBuf::new();
@@ -79,13 +80,7 @@ pub fn glob_from(
                 }
                 Ok(p) => p,
                 Err(err) => {
-                    return Err(IoError::new_internal_with_path(
-                        err.kind(),
-                        "Could not canonicalize path",
-                        nu_protocol::location!(),
-                        path,
-                    )
-                    .into())
+                    return Err(IoError::new(err.kind(), pattern_span, path).into());
                 }
             };
             (path.parent().map(|parent| parent.to_path_buf()), path)

Before:

ls foo
# => Error: nu::shell::io::not_found
# => 
# =>   × I/O error
# =>   ╰─▶   × Entity not found
# => 
# =>    ╭────
# =>  1 │ crates/nu-engine/src/glob_from.rs:85:25
# =>    · ───────────────────┬───────────────────
# =>    ·                    ╰── Could not canonicalize path
# =>    ╰────
# =>   help: The error occurred at '/home/rose/src/nushell/foo'

After:

ls foo
# => Error: nu::shell::io::not_found
# => 
# =>   × I/O error
# =>   ╰─▶   × Entity not found
# => 
# =>    ╭─[entry #6:1:4]
# =>  1 │ ls foo
# =>    ·    ───
# =>    ╰────
# =>   help: The error occurred at '/home/rose/src/nushell/foo'

If you would be able to fix those, I'm good with landing this.

@cptpiepmatz

Copy link
Copy Markdown
Member Author

@132ikl I updated that 👍🏻

I worked through most of the code via deprecation warnings, so I missed that.

@132ikl

132ikl commented Jan 28, 2025

Copy link
Copy Markdown
Member

lgtm, thank you!

@fdncred

fdncred commented Jan 28, 2025

Copy link
Copy Markdown
Contributor

if we can get the ci green, i'll land this pr

@fdncred
fdncred merged commit 66bc054 into nushell:main Jan 28, 2025
@fdncred

fdncred commented Jan 28, 2025

Copy link
Copy Markdown
Contributor

Great work here! Thanks so much!

@github-actions github-actions Bot added this to the v0.102.0 milestone Jan 28, 2025
@cptpiepmatz
cptpiepmatz deleted the consolidate-io-errors branch January 28, 2025 22:05
fdncred pushed a commit that referenced this pull request Jan 30, 2025
<!--
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.
-->

It seems in my PR #14927 I missed a few calls to `IoError::new` that had
`Span::unknown` inside them, which shouldn't be used but rather
`IoError::new_internal`. I replaced these calls.

Thanks to @132ikl to finding out that I forgot some. 😄 

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

Pretty much none really.

# 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
> ```
-->

- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`

# 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.
-->
fdncred pushed a commit that referenced this pull request Feb 3, 2025
<!--
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.
-->

Tweaks the error style for I/O errors introduced #14927. Moves the
additional context to below the text that says "I/O error", and always
shows the error kind in the label.

Additional context|Before PR|After PR
:-:|:-:|:-:

yes|![image](https://github.com/user-attachments/assets/df4f2e28-fdf5-4693-b60c-255d019af25f)
|
![image](https://github.com/user-attachments/assets/5915e9d0-78d4-49a6-b495-502d0c6444fa)
no|
![image](https://github.com/user-attachments/assets/e4ecaada-ec8c-4940-b08a-bbfaa45083d5)
|
![image](https://github.com/user-attachments/assets/467163d8-ab39-47f0-a74f-e2effe2fe6af)



# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

N/A, as this is a follow-up to #14927 which has not been included in a
release

# 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
> ```
-->
N/A

# 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.
-->
N/A

---------

Co-authored-by: Piepmatz <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api-change This PR should be mentioned in #api-updates channel on Discord category:refactor deprecated:pr-errors Deprecated: use A:error-handling, A:error-unhelpful, or A:error-silent-fail instead

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rm returns directory not found error for both directories and files. Provide more context to OS errors

4 participants