nushell/crates/nu-protocol/src/value/glob.rs
Wind 87c5f6e455
ls, rm, cp, open, touch, mkdir: Don't expand tilde if input path is quoted string or a variable. (#12232)
# Description
Fixes:  #11887
Fixes: #11626

This pr unify the tilde expand behavior over several filesystem relative
commands. It follows the same rule with glob expansion:
|  command  |  result |
| ----------- |  ------ |
| ls ~/aaa  | expand tilde
| ls "~/aaa"  | don't expand tilde
| let f = "~/aaa"; ls $f | don't expand tilde, if you want to: use `ls
($f \| path expand)`
| let f: glob = "~/aaa"; ls $f | expand tilde, they don't expand on
`mkdir`, `touch` comamnd.

Actually I'm not sure for 4th item, currently it's expanding is just
because it followes the same rule with glob expansion.

### About the change
It changes `expand_path_with` to accept a new argument called
`expand_tilde`, if it's true, expand it, if not, just keep it as `~`
itself.

# User-Facing Changes
After this change, `ls "~/aaa"` won't expand tilde.

# Tests + Formatting
Done
2024-03-25 10:08:38 +08:00

42 lines
1.3 KiB
Rust

use serde::Deserialize;
use std::fmt::Display;
// Introduce this `NuGlob` enum rather than using `Value::Glob` directlry
// So we can handle glob easily without considering too much variant of `Value` enum.
#[derive(Debug, Clone, Deserialize)]
pub enum NuGlob {
/// Don't expand the glob pattern, normally it includes a quoted string(except backtick)
/// And a variable that doesn't annotated with `glob` type
DoNotExpand(String),
/// A glob pattern that is required to expand, it includes bare word
/// And a variable which is annotated with `glob` type
Expand(String),
}
impl NuGlob {
pub fn strip_ansi_string_unlikely(self) -> Self {
match self {
NuGlob::DoNotExpand(s) => NuGlob::DoNotExpand(nu_utils::strip_ansi_string_unlikely(s)),
NuGlob::Expand(s) => NuGlob::Expand(nu_utils::strip_ansi_string_unlikely(s)),
}
}
pub fn is_expand(&self) -> bool {
matches!(self, NuGlob::Expand(..))
}
}
impl AsRef<str> for NuGlob {
fn as_ref(&self) -> &str {
match self {
NuGlob::DoNotExpand(s) | NuGlob::Expand(s) => s,
}
}
}
impl Display for NuGlob {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_ref())
}
}