Skip to main content

nu_command/debug/
view_span.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::{PipelineMetadata, shell_error::generic::GenericError};
3
4#[derive(Clone)]
5pub struct ViewSpan;
6
7impl Command for ViewSpan {
8    fn name(&self) -> &str {
9        "view span"
10    }
11
12    fn description(&self) -> &str {
13        "View the contents of a span."
14    }
15
16    fn extra_description(&self) -> &str {
17        "This command is meant for debugging purposes.\nIt allows you to view the contents of nushell spans.\nOne way to get spans is to pipe something into 'debug --raw'.\nThen you can use the Span { start, end } values as the start and end values for this command."
18    }
19
20    fn signature(&self) -> nu_protocol::Signature {
21        Signature::build("view span")
22            .input_output_types(vec![(Type::Nothing, Type::String)])
23            .required("start", SyntaxShape::Int, "Start of the span.")
24            .required("end", SyntaxShape::Int, "End of the span.")
25            .category(Category::Debug)
26    }
27
28    fn run(
29        &self,
30        engine_state: &EngineState,
31        stack: &mut Stack,
32        call: &Call,
33        _input: PipelineData,
34    ) -> Result<PipelineData, ShellError> {
35        let start_span: Spanned<usize> = call.req(engine_state, stack, 0)?;
36        let end_span: Spanned<usize> = call.req(engine_state, stack, 1)?;
37
38        let span = if start_span.item <= end_span.item {
39            Ok(Span::new(start_span.item, end_span.item))
40        } else {
41            Err(ShellError::Generic(GenericError::new(
42                "Invalid span",
43                "the start position of this span is later than the end position",
44                call.head,
45            )))
46        }?;
47
48        let bin_contents = engine_state
49            .try_get_file_contents(span)
50            .map(String::from_utf8_lossy)
51            .ok_or_else(|| {
52                ShellError::Generic(GenericError::new(
53                    "Cannot view span",
54                    "this start and end does not correspond to a viewable value",
55                    call.head,
56                ))
57            })?;
58
59        let metadata = PipelineMetadata {
60            content_type: Some("application/x-nuscript".into()),
61            ..Default::default()
62        };
63
64        let value = Value::string(bin_contents, call.head)
65            .into_pipeline_data()
66            .set_metadata(Some(metadata));
67        Ok(value)
68    }
69
70    fn examples(&self) -> Vec<Example<'_>> {
71        vec![Example {
72            description: "View the source of a span. 1 and 2 are just example values. Use the return of debug --raw to get the actual values.",
73            example: "some | pipeline | or | variable | debug --raw; view span 1 2",
74            result: None,
75        }]
76    }
77}