From 931f5226163c63c2521d2d79e65165dcaf9ab636 Mon Sep 17 00:00:00 2001 From: Devyn Cairns Date: Tue, 19 Mar 2024 03:00:22 -0700 Subject: [PATCH] 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. - :green_circle: `toolkit fmt` - :green_circle: `toolkit clippy` - :green_circle: `toolkit test` - :green_circle: `toolkit test stdlib` --- crates/nu-command/src/conversions/into/string.rs | 15 +++++++++++++++ tests/plugins/custom_values.rs | 11 +++++++++++ 2 files changed, 26 insertions(+) diff --git a/crates/nu-command/src/conversions/into/string.rs b/crates/nu-command/src/conversions/into/string.rs index f034bee4e7..9cd6d900ef 100644 --- a/crates/nu-command/src/conversions/into/string.rs +++ b/crates/nu-command/src/conversions/into/string.rs @@ -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"), diff --git a/tests/plugins/custom_values.rs b/tests/plugins/custom_values.rs index 784e9c09af..34aa3ddf6e 100644 --- a/tests/plugins/custom_values.rs +++ b/tests/plugins/custom_values.rs @@ -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)"); +}