Support into string for custom values (#12231)

Context: @abusch is working on a semver plugin with custom values and
wants users to be able to convert them back to strings

# Description
This allows `into string` to work on custom values if their base value
representation could be converted into a string with the same rules.

# User-Facing Changes
`into string` works on custom values.

Unfortunately, I couldn't really demo this with an example, because
there aren't any custom values that can be represented that way
included.

# Tests + Formatting
I was able to write a test using the custom values plugin.

- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`
This commit is contained in:
Devyn Cairns 2024-03-19 03:00:22 -07:00 committed by GitHub
parent 6e37ad0275
commit 931f522616
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 26 additions and 0 deletions

View File

@ -231,6 +231,21 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
},
span,
),
Value::CustomValue { val, .. } => {
// Only custom values that have a base value that can be converted to string are
// accepted.
val.to_base_value(input.span())
.and_then(|base_value| match action(&base_value, args, span) {
Value::Error { .. } => Err(ShellError::CantConvert {
to_type: String::from("string"),
from_type: val.value_string(),
span,
help: Some("this custom value can't be represented as a string".into()),
}),
success => Ok(success),
})
.unwrap_or_else(|err| Value::error(err, span))
}
x => Value::error(
ShellError::CantConvert {
to_type: String::from("string"),

View File

@ -194,3 +194,14 @@ fn custom_value_in_example_is_rendered() {
.contains("I used to be a custom value! My data was (abc)"));
assert!(actual.status.success());
}
#[test]
fn custom_value_into_string() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"custom-value generate | into string"
);
assert_eq!(actual.out, "I used to be a custom value! My data was (abc)");
}