nu_command/strings/ansi/
strip.rs

1use std::sync::Arc;
2
3use nu_cmd_base::input_handler::{CmdArgument, operate};
4use nu_engine::command_prelude::*;
5use nu_protocol::Config;
6
7struct Arguments {
8    cell_paths: Option<Vec<CellPath>>,
9    config: Arc<Config>,
10}
11
12impl CmdArgument for Arguments {
13    fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
14        self.cell_paths.take()
15    }
16}
17
18#[derive(Clone)]
19pub struct AnsiStrip;
20
21impl Command for AnsiStrip {
22    fn name(&self) -> &str {
23        "ansi strip"
24    }
25
26    fn signature(&self) -> Signature {
27        Signature::build("ansi strip")
28            .input_output_types(vec![
29                (Type::String, Type::String),
30                (Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String))),
31                (Type::table(), Type::table()),
32                (Type::record(), Type::record()),
33            ])
34            .rest(
35                "cell path",
36                SyntaxShape::CellPath,
37                "For a data structure input, remove ANSI sequences from strings at the given cell paths.",
38            )
39            .allow_variants_without_examples(true)
40            .category(Category::Platform)
41    }
42
43    fn description(&self) -> &str {
44        "Strip ANSI escape sequences from a string."
45    }
46
47    fn run(
48        &self,
49        engine_state: &EngineState,
50        stack: &mut Stack,
51        call: &Call,
52        input: PipelineData,
53    ) -> Result<PipelineData, ShellError> {
54        let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?;
55        let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
56        let config = stack.get_config(engine_state);
57        let args = Arguments { cell_paths, config };
58        operate(action, args, input, call.head, engine_state.signals())
59    }
60
61    fn examples(&self) -> Vec<Example> {
62        vec![Example {
63            description: "Strip ANSI escape sequences from a string",
64            example: r#"$'(ansi green)(ansi cursor_on)hello' | ansi strip"#,
65            result: Some(Value::test_string("hello")),
66        }]
67    }
68}
69
70fn action(input: &Value, args: &Arguments, _span: Span) -> Value {
71    let span = input.span();
72    match input {
73        Value::String { val, .. } => {
74            Value::string(nu_utils::strip_ansi_likely(val).to_string(), span)
75        }
76        other => {
77            // Fake stripping ansi for other types and just show the abbreviated string
78            // instead of showing an error message
79            Value::string(other.to_abbreviated_string(&args.config), span)
80        }
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::{AnsiStrip, Arguments, action};
87    use nu_protocol::{Span, Value, engine::EngineState};
88
89    #[test]
90    fn examples_work_as_expected() {
91        use crate::test_examples;
92
93        test_examples(AnsiStrip {})
94    }
95
96    #[test]
97    fn test_stripping() {
98        let input_string =
99            Value::test_string("\u{1b}[3;93;41mHello\u{1b}[0m \u{1b}[1;32mNu \u{1b}[1;35mWorld");
100        let expected = Value::test_string("Hello Nu World");
101
102        let args = Arguments {
103            cell_paths: vec![].into(),
104            config: EngineState::new().get_config().clone(),
105        };
106
107        let actual = action(&input_string, &args, Span::test_data());
108        assert_eq!(actual, expected);
109    }
110}