make echo const (#14997)

# Description

Make `echo` const.
- It's a very simple command, there is no reason for it to not be const.
- It's return type `any` is utilized in tests to type erase values, this
might be useful for testing const evaluation too.
- The upcoming custom command attribute feature can make use of it as a
stopgap replacement for `const def` commands.

# User-Facing Changes

`echo` can be used in const contexts.

# Tests + Formatting

# After Submitting
N/A
This commit is contained in:
Bahex 2025-02-06 15:56:30 +03:00 committed by GitHub
parent c7d3014849
commit 5be818b5ee
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 31 additions and 7 deletions

View File

@ -34,13 +34,22 @@ little reason to use this over just writing the values as-is."#
call: &Call, call: &Call,
_input: PipelineData, _input: PipelineData,
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let mut args = call.rest(engine_state, stack, 0)?; let args = call.rest(engine_state, stack, 0)?;
let value = match args.len() { echo_impl(args, call.head)
0 => Value::string("", call.head), }
1 => args.pop().expect("one element"),
_ => Value::list(args, call.head), fn run_const(
}; &self,
Ok(value.into_pipeline_data()) working_set: &StateWorkingSet,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let args = call.rest_const(working_set, 0)?;
echo_impl(args, call.head)
}
fn is_const(&self) -> bool {
true
} }
fn examples(&self) -> Vec<Example> { fn examples(&self) -> Vec<Example> {
@ -63,6 +72,15 @@ little reason to use this over just writing the values as-is."#
} }
} }
fn echo_impl(mut args: Vec<Value>, head: Span) -> Result<PipelineData, ShellError> {
let value = match args.len() {
0 => Value::string("", head),
1 => args.pop().expect("one element"),
_ => Value::list(args, head),
};
Ok(value.into_pipeline_data())
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
#[test] #[test]

View File

@ -34,3 +34,9 @@ fn echo_range_handles_exclusive_down() {
assert_eq!(actual.out, "[3,2]"); assert_eq!(actual.out, "[3,2]");
} }
#[test]
fn echo_is_const() {
let actual = nu!(r#"const val = echo 1..3; $val | to json --raw"#);
assert_eq!(actual.out, "[1,2,3]");
}