nushell/crates/nu-protocol/src/value/from_value.rs
WindSoilder c59d6d31bc
do not attempt to glob expand if the file path is wrapped in quotes (#11569)
# Description
Fixes: #11455

### For arguments which is annotated with `:path/:directory/:glob`
To fix the issue, we need to have a way to know if a path is originally
quoted during runtime. So the information needed to be added at several
levels:
* parse time (from user input to expression)
We need to add quoted information into `Expr::Filepath`,
`Expr::Directory`, `Expr::GlobPattern`
* eval time
When convert from `Expr::Filepath`, `Expr::Directory`,
`Expr::GlobPattern` to `Value::String` during runtime, we won't auto
expanded the path if it's quoted

### For `ls`
It's really special, because it accepts a `String` as a pattern, and it
generates `glob` expression inside the command itself.

So the idea behind the change is introducing a special SyntaxShape to
ls: `SyntaxShape::LsGlobPattern`. So we can track if the pattern is
originally quoted easier, and we don't auto expand the path either.

Then when constructing a glob pattern inside ls, we check if input
pattern is quoted, if so: we escape the input pattern, so we can run `ls
a[123]b`, because it's already escaped.
Finally, to accomplish the checking process, we also need to introduce a
new value type called `Value::QuotedString` to differ from
`Value::String`, it's used to generate an enum called `NuPath`, which is
finally used in `ls` function. `ls` learned from `NuPath` to know if
user input is quoted.

# User-Facing Changes
Actually it contains several changes
### For arguments which is annotated with `:path/:directory/:glob`
#### Before
```nushell
> def foo [p: path] { echo $p }; print (foo "~/a"); print (foo '~/a')
/home/windsoilder/a
/home/windsoilder/a
> def foo [p: directory] { echo $p }; print (foo "~/a"); print (foo '~/a')
/home/windsoilder/a
/home/windsoilder/a
> def foo [p: glob] { echo $p }; print (foo "~/a"); print (foo '~/a')
/home/windsoilder/a
/home/windsoilder/a
```
#### After
```nushell
> def foo [p: path] { echo $p }; print (foo "~/a"); print (foo '~/a')
~/a
~/a
> def foo [p: directory] { echo $p }; print (foo "~/a"); print (foo '~/a')
~/a
~/a
> def foo [p: glob] { echo $p }; print (foo "~/a"); print (foo '~/a')
~/a
~/a
```
### For ls command
`touch '[uwu]'`
#### Before
```
❯ ls -D "[uwu]"
Error:   × No matches found for [uwu]
   ╭─[entry #6:1:1]
 1 │ ls -D "[uwu]"
   ·       ───┬───
   ·          ╰── Pattern, file or folder not found
   ╰────
  help: no matches found
```

#### After
```
❯ ls -D "[uwu]"
╭───┬───────┬──────┬──────┬──────────╮
│ # │ name  │ type │ size │ modified │
├───┼───────┼──────┼──────┼──────────┤
│ 0 │ [uwu] │ file │  0 B │ now      │
╰───┴───────┴──────┴──────┴──────────╯
```

# Tests + Formatting
Done

# After Submitting
NaN
2024-01-21 23:22:25 +08:00

578 lines
18 KiB
Rust

use std::path::PathBuf;
use super::NuPath;
use crate::ast::{CellPath, PathMember};
use crate::engine::{Block, Closure};
use crate::{Range, Record, ShellError, Spanned, Value};
use chrono::{DateTime, FixedOffset};
pub trait FromValue: Sized {
fn from_value(v: Value) -> Result<Self, ShellError>;
}
impl FromValue for Value {
fn from_value(v: Value) -> Result<Self, ShellError> {
Ok(v)
}
}
impl FromValue for Spanned<i64> {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Int { val, .. } => Ok(Spanned { item: val, span }),
Value::Filesize { val, .. } => Ok(Spanned { item: val, span }),
Value::Duration { val, .. } => Ok(Spanned { item: val, span }),
v => Err(ShellError::CantConvert {
to_type: "int".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for i64 {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Int { val, .. } => Ok(val),
Value::Filesize { val, .. } => Ok(val),
Value::Duration { val, .. } => Ok(val),
v => Err(ShellError::CantConvert {
to_type: "int".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Spanned<f64> {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Int { val, .. } => Ok(Spanned {
item: val as f64,
span,
}),
Value::Float { val, .. } => Ok(Spanned { item: val, span }),
v => Err(ShellError::CantConvert {
to_type: "float".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for f64 {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Float { val, .. } => Ok(val),
Value::Int { val, .. } => Ok(val as f64),
v => Err(ShellError::CantConvert {
to_type: "float".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Spanned<usize> {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Int { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue { span })
} else {
Ok(Spanned {
item: val as usize,
span,
})
}
}
Value::Filesize { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue { span })
} else {
Ok(Spanned {
item: val as usize,
span,
})
}
}
Value::Duration { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue { span })
} else {
Ok(Spanned {
item: val as usize,
span,
})
}
}
v => Err(ShellError::CantConvert {
to_type: "non-negative int".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for usize {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Int { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue { span })
} else {
Ok(val as usize)
}
}
Value::Filesize { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue { span })
} else {
Ok(val as usize)
}
}
Value::Duration { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue { span })
} else {
Ok(val as usize)
}
}
v => Err(ShellError::CantConvert {
to_type: "non-negative int".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for String {
fn from_value(v: Value) -> Result<Self, ShellError> {
// FIXME: we may want to fail a little nicer here
match v {
Value::CellPath { val, .. } => Ok(val.to_string()),
Value::String { val, .. } => Ok(val),
v => Err(ShellError::CantConvert {
to_type: "string".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Spanned<String> {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
Ok(Spanned {
item: match v {
Value::CellPath { val, .. } => val.to_string(),
Value::String { val, .. } => val,
v => {
return Err(ShellError::CantConvert {
to_type: "string".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
})
}
},
span,
})
}
}
impl FromValue for NuPath {
fn from_value(v: Value) -> Result<Self, ShellError> {
// FIXME: we may want to fail a little nicer here
match v {
Value::CellPath { val, .. } => Ok(NuPath::UnQuoted(val.to_string())),
Value::String { val, .. } => Ok(NuPath::UnQuoted(val)),
Value::QuotedString { val, .. } => Ok(NuPath::Quoted(val)),
v => Err(ShellError::CantConvert {
to_type: "string".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Spanned<NuPath> {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
Ok(Spanned {
item: match v {
Value::CellPath { val, .. } => NuPath::UnQuoted(val.to_string()),
Value::String { val, .. } => NuPath::UnQuoted(val),
Value::QuotedString { val, .. } => NuPath::Quoted(val),
v => {
return Err(ShellError::CantConvert {
to_type: "string".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
})
}
},
span,
})
}
}
impl FromValue for Vec<String> {
fn from_value(v: Value) -> Result<Self, ShellError> {
// FIXME: we may want to fail a little nicer here
match v {
Value::List { vals, .. } => vals
.into_iter()
.map(|val| match val {
Value::String { val, .. } => Ok(val),
c => Err(ShellError::CantConvert {
to_type: "string".into(),
from_type: c.get_type().to_string(),
span: c.span(),
help: None,
}),
})
.collect::<Result<Vec<String>, ShellError>>(),
v => Err(ShellError::CantConvert {
to_type: "string".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Vec<Spanned<String>> {
fn from_value(v: Value) -> Result<Self, ShellError> {
// FIXME: we may want to fail a little nicer here
match v {
Value::List { vals, .. } => vals
.into_iter()
.map(|val| {
let val_span = val.span();
match val {
Value::String { val, .. } => Ok(Spanned {
item: val,
span: val_span,
}),
c => Err(ShellError::CantConvert {
to_type: "string".into(),
from_type: c.get_type().to_string(),
span: c.span(),
help: None,
}),
}
})
.collect::<Result<Vec<Spanned<String>>, ShellError>>(),
v => Err(ShellError::CantConvert {
to_type: "string".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Vec<bool> {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::List { vals, .. } => vals
.into_iter()
.map(|val| match val {
Value::Bool { val, .. } => Ok(val),
c => Err(ShellError::CantConvert {
to_type: "bool".into(),
from_type: c.get_type().to_string(),
span: c.span(),
help: None,
}),
})
.collect::<Result<Vec<bool>, ShellError>>(),
v => Err(ShellError::CantConvert {
to_type: "bool".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for CellPath {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::CellPath { val, .. } => Ok(val),
Value::String { val, .. } => Ok(CellPath {
members: vec![PathMember::String {
val,
span,
optional: false,
}],
}),
Value::Int { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue { span })
} else {
Ok(CellPath {
members: vec![PathMember::Int {
val: val as usize,
span,
optional: false,
}],
})
}
}
x => Err(ShellError::CantConvert {
to_type: "cell path".into(),
from_type: x.get_type().to_string(),
span,
help: None,
}),
}
}
}
impl FromValue for bool {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Bool { val, .. } => Ok(val),
v => Err(ShellError::CantConvert {
to_type: "bool".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Spanned<bool> {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Bool { val, .. } => Ok(Spanned { item: val, span }),
v => Err(ShellError::CantConvert {
to_type: "bool".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for DateTime<FixedOffset> {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Date { val, .. } => Ok(val),
v => Err(ShellError::CantConvert {
to_type: "date".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Spanned<DateTime<FixedOffset>> {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Date { val, .. } => Ok(Spanned { item: val, span }),
v => Err(ShellError::CantConvert {
to_type: "date".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Range {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Range { val, .. } => Ok(*val),
v => Err(ShellError::CantConvert {
to_type: "range".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Spanned<Range> {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Range { val, .. } => Ok(Spanned { item: *val, span }),
v => Err(ShellError::CantConvert {
to_type: "range".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Vec<u8> {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Binary { val, .. } => Ok(val),
Value::String { val, .. } => Ok(val.into_bytes()),
v => Err(ShellError::CantConvert {
to_type: "binary data".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Spanned<Vec<u8>> {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Binary { val, .. } => Ok(Spanned { item: val, span }),
Value::String { val, .. } => Ok(Spanned {
item: val.into_bytes(),
span,
}),
v => Err(ShellError::CantConvert {
to_type: "binary data".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Spanned<PathBuf> {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::String { val, .. } => Ok(Spanned {
item: val.into(),
span,
}),
v => Err(ShellError::CantConvert {
to_type: "range".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Vec<Value> {
fn from_value(v: Value) -> Result<Self, ShellError> {
// FIXME: we may want to fail a little nicer here
match v {
Value::List { vals, .. } => Ok(vals),
v => Err(ShellError::CantConvert {
to_type: "Vector of values".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Record {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Record { val, .. } => Ok(val),
v => Err(ShellError::CantConvert {
to_type: "Record".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Closure {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Closure { val, .. } => Ok(val),
Value::Block { val, .. } => Ok(Closure {
block_id: val,
captures: Vec::new(),
}),
v => Err(ShellError::CantConvert {
to_type: "Closure".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Block {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Block { val, .. } => Ok(Block { block_id: val }),
v => Err(ShellError::CantConvert {
to_type: "Block".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for Spanned<Closure> {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Closure { val, .. } => Ok(Spanned { item: val, span }),
v => Err(ShellError::CantConvert {
to_type: "Closure".into(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}