JT 6cdfee3573
Move Value to helpers, separate span call (#10121)
# Description

As part of the refactor to split spans off of Value, this moves to using
helper functions to create values, and using `.span()` instead of
matching span out of Value directly.

Hoping to get a few more helping hands to finish this, as there are a
lot of commands to update :)

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
Co-authored-by: WindSoilder <windsoilder@outlook.com>
2023-09-03 07:27:29 -07:00

174 lines
4.9 KiB
Rust

use crate::grapheme_flags;
use nu_cmd_base::input_handler::{operate, CmdArgument};
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::ast::CellPath;
use nu_protocol::engine::{Command, EngineState, Stack, StateWorkingSet};
use nu_protocol::Category;
use nu_protocol::{Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value};
use unicode_segmentation::UnicodeSegmentation;
struct Arguments {
cell_paths: Option<Vec<CellPath>>,
graphemes: bool,
}
impl CmdArgument for Arguments {
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
self.cell_paths.take()
}
}
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"str length"
}
fn signature(&self) -> Signature {
Signature::build("str length")
.input_output_types(vec![
(Type::String, Type::Int),
(Type::List(Box::new(Type::String)), Type::List(Box::new(Type::Int))),
(Type::Table(vec![]), Type::Table(vec![])),
(Type::Record(vec![]), Type::Record(vec![])),
])
.allow_variants_without_examples(true)
.switch(
"grapheme-clusters",
"count length using grapheme clusters (all visible chars have length 1)",
Some('g'),
)
.switch(
"utf-8-bytes",
"count length using UTF-8 bytes (default; all non-ASCII chars have length 2+)",
Some('b'),
)
.rest(
"rest",
SyntaxShape::CellPath,
"For a data structure input, replace strings at the given cell paths with their length",
)
.category(Category::Strings)
}
fn usage(&self) -> &str {
"Output the length of any strings in the pipeline."
}
fn search_terms(&self) -> Vec<&str> {
vec!["size", "count"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?;
run(cell_paths, engine_state, call, input)
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let cell_paths: Vec<CellPath> = call.rest_const(working_set, 0)?;
run(cell_paths, working_set.permanent(), call, input)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Return the lengths of a string",
example: "'hello' | str length",
result: Some(Value::test_int(5)),
},
Example {
description: "Count length using grapheme clusters",
example: "'🇯🇵ほげ ふが ぴよ' | str length -g",
result: Some(Value::test_int(9)),
},
Example {
description: "Return the lengths of multiple strings",
example: "['hi' 'there'] | str length",
result: Some(Value::list(
vec![Value::test_int(2), Value::test_int(5)],
Span::test_data(),
)),
},
]
}
}
fn run(
cell_paths: Vec<CellPath>,
engine_state: &EngineState,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let args = Arguments {
cell_paths: (!cell_paths.is_empty()).then_some(cell_paths),
graphemes: grapheme_flags(call)?,
};
operate(action, args, input, call.head, engine_state.ctrlc.clone())
}
fn action(input: &Value, arg: &Arguments, head: Span) -> Value {
match input {
Value::String { val, .. } => Value::int(
if arg.graphemes {
val.graphemes(true).count()
} else {
val.len()
} as i64,
head,
),
Value::Error { .. } => input.clone(),
_ => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "string".into(),
wrong_type: input.get_type().to_string(),
dst_span: head,
src_span: input.span(),
},
head,
),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn use_utf8_bytes() {
let word = Value::string(String::from("🇯🇵ほげ ふが ぴよ"), Span::test_data());
let options = Arguments {
cell_paths: None,
graphemes: false,
};
let actual = action(&word, &options, Span::test_data());
assert_eq!(actual, Value::test_int(28));
}
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}