mirror of
https://github.com/nushell/nushell.git
synced 2025-05-19 17:30:45 +02:00
<!-- 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. --> #14528 mentioned that trying to `open` a file in a directory where you don't have read access results in a "file not found" error. I investigated the error and could find the root issue in the `nu_engine::glob_from` function. It uses `std::path::Path::canonicalize` some layers down and that may return an `std::io::Error`. All these errors were handled as "directory not found" which will be translated to "file not found" in the `open` command. To fix this, I handled the `PermssionDenied` error kind of the io error and passed that down. Now trying to `open` a file from a directory with no permissions returns a "permission denied" error. Before/After:  # User-Facing Changes <!-- List of all changes that impact the user experience here. This helps us keep track of breaking changes. --> That error is fixed, so correct error message. # 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. --> fixes #14528
132 lines
4.8 KiB
Rust
132 lines
4.8 KiB
Rust
use nu_glob::MatchOptions;
|
|
use nu_path::{canonicalize_with, expand_path_with};
|
|
use nu_protocol::{NuGlob, ShellError, Span, Spanned};
|
|
use std::{
|
|
fs,
|
|
io::ErrorKind,
|
|
path::{Component, Path, PathBuf},
|
|
};
|
|
|
|
/// This function is like `nu_glob::glob` from the `glob` crate, except it is relative to a given cwd.
|
|
///
|
|
/// It returns a tuple of two values: the first is an optional prefix that the expanded filenames share.
|
|
/// This prefix can be removed from the front of each value to give an approximation of the relative path
|
|
/// to the user
|
|
///
|
|
/// The second of the two values is an iterator over the matching filepaths.
|
|
#[allow(clippy::type_complexity)]
|
|
pub fn glob_from(
|
|
pattern: &Spanned<NuGlob>,
|
|
cwd: &Path,
|
|
span: Span,
|
|
options: Option<MatchOptions>,
|
|
) -> Result<
|
|
(
|
|
Option<PathBuf>,
|
|
Box<dyn Iterator<Item = Result<PathBuf, ShellError>> + Send>,
|
|
),
|
|
ShellError,
|
|
> {
|
|
let no_glob_for_pattern = matches!(pattern.item, NuGlob::DoNotExpand(_));
|
|
let (prefix, pattern) = if nu_glob::is_glob(pattern.item.as_ref()) {
|
|
// Pattern contains glob, split it
|
|
let mut p = PathBuf::new();
|
|
let path = PathBuf::from(&pattern.item.as_ref());
|
|
let components = path.components();
|
|
let mut counter = 0;
|
|
|
|
for c in components {
|
|
if let Component::Normal(os) = c {
|
|
if nu_glob::is_glob(os.to_string_lossy().as_ref()) {
|
|
break;
|
|
}
|
|
}
|
|
p.push(c);
|
|
counter += 1;
|
|
}
|
|
|
|
let mut just_pattern = PathBuf::new();
|
|
for c in counter..path.components().count() {
|
|
if let Some(comp) = path.components().nth(c) {
|
|
just_pattern.push(comp);
|
|
}
|
|
}
|
|
if no_glob_for_pattern {
|
|
just_pattern = PathBuf::from(nu_glob::Pattern::escape(&just_pattern.to_string_lossy()));
|
|
}
|
|
|
|
// Now expand `p` to get full prefix
|
|
let path = expand_path_with(p, cwd, pattern.item.is_expand());
|
|
let escaped_prefix = PathBuf::from(nu_glob::Pattern::escape(&path.to_string_lossy()));
|
|
|
|
(Some(path), escaped_prefix.join(just_pattern))
|
|
} else {
|
|
let path = PathBuf::from(&pattern.item.as_ref());
|
|
let path = expand_path_with(path, cwd, pattern.item.is_expand());
|
|
let is_symlink = match fs::symlink_metadata(&path) {
|
|
Ok(attr) => attr.file_type().is_symlink(),
|
|
Err(_) => false,
|
|
};
|
|
|
|
if is_symlink {
|
|
(path.parent().map(|parent| parent.to_path_buf()), path)
|
|
} else {
|
|
let path = match canonicalize_with(path.clone(), cwd) {
|
|
Ok(p) if nu_glob::is_glob(p.to_string_lossy().as_ref()) => {
|
|
// our path might contain glob metacharacters too.
|
|
// in such case, we need to escape our path to make
|
|
// glob work successfully
|
|
PathBuf::from(nu_glob::Pattern::escape(&p.to_string_lossy()))
|
|
}
|
|
Ok(p) => p,
|
|
Err(err) => {
|
|
return match err.kind() {
|
|
ErrorKind::PermissionDenied => Err(ShellError::GenericError {
|
|
error: "Permission denied".into(),
|
|
msg: err.to_string(),
|
|
span: None,
|
|
help: None,
|
|
inner: vec![],
|
|
}),
|
|
// Previously, all these errors were treated as "directory not found."
|
|
// Now, permission denied errors are handled separately.
|
|
// TODO: Refine handling of I/O errors for more precise responses.
|
|
_ => Err(ShellError::DirectoryNotFound {
|
|
dir: path.to_string_lossy().to_string(),
|
|
span: pattern.span,
|
|
}),
|
|
};
|
|
}
|
|
};
|
|
(path.parent().map(|parent| parent.to_path_buf()), path)
|
|
}
|
|
};
|
|
|
|
let pattern = pattern.to_string_lossy().to_string();
|
|
let glob_options = options.unwrap_or_default();
|
|
|
|
let glob = nu_glob::glob_with(&pattern, glob_options).map_err(|e| {
|
|
nu_protocol::ShellError::GenericError {
|
|
error: "Error extracting glob pattern".into(),
|
|
msg: e.to_string(),
|
|
span: Some(span),
|
|
help: None,
|
|
inner: vec![],
|
|
}
|
|
})?;
|
|
|
|
Ok((
|
|
prefix,
|
|
Box::new(glob.map(move |x| match x {
|
|
Ok(v) => Ok(v),
|
|
Err(e) => Err(nu_protocol::ShellError::GenericError {
|
|
error: "Error extracting glob pattern".into(),
|
|
msg: e.to_string(),
|
|
span: Some(span),
|
|
help: None,
|
|
inner: vec![],
|
|
}),
|
|
})),
|
|
))
|
|
}
|