nu_parser/
known_external.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::{
3    CustomExample,
4    ast::{self, Expr, Expression},
5    engine::{self, CallImpl, CommandType, UNKNOWN_SPAN_ID},
6    ir::{self, DataSlice},
7};
8
9#[derive(Clone)]
10pub struct KnownExternal {
11    pub signature: Box<Signature>,
12    pub attributes: Vec<(String, Value)>,
13    pub examples: Vec<CustomExample>,
14}
15
16impl Command for KnownExternal {
17    fn name(&self) -> &str {
18        &self.signature.name
19    }
20
21    fn signature(&self) -> Signature {
22        *self.signature.clone()
23    }
24
25    fn description(&self) -> &str {
26        &self.signature.description
27    }
28
29    fn extra_description(&self) -> &str {
30        &self.signature.extra_description
31    }
32
33    fn search_terms(&self) -> Vec<&str> {
34        self.signature
35            .search_terms
36            .iter()
37            .map(String::as_str)
38            .collect()
39    }
40
41    fn command_type(&self) -> CommandType {
42        CommandType::External
43    }
44
45    fn run(
46        &self,
47        engine_state: &EngineState,
48        stack: &mut Stack,
49        call: &Call,
50        input: PipelineData,
51    ) -> Result<PipelineData, ShellError> {
52        let head_span = call.head;
53        let decl_id = engine_state
54            .find_decl("run-external".as_bytes(), &[])
55            .ok_or(ShellError::ExternalNotSupported { span: head_span })?;
56
57        let command = engine_state.get_decl(decl_id);
58
59        let extern_name = if let Some(name_bytes) = engine_state.find_decl_name(call.decl_id, &[]) {
60            String::from_utf8_lossy(name_bytes)
61        } else {
62            return Err(ShellError::NushellFailedSpanned {
63                msg: "known external name not found".to_string(),
64                label: "could not find name for this command".to_string(),
65                span: call.head,
66            });
67        };
68
69        let extern_name: Vec<_> = extern_name.split(' ').collect();
70
71        match &call.inner {
72            CallImpl::AstRef(call) => {
73                let extern_call = ast_call_to_extern_call(engine_state, call, &extern_name)?;
74                command.run(engine_state, stack, &(&extern_call).into(), input)
75            }
76            CallImpl::AstBox(call) => {
77                let extern_call = ast_call_to_extern_call(engine_state, call, &extern_name)?;
78                command.run(engine_state, stack, &(&extern_call).into(), input)
79            }
80            CallImpl::IrRef(call) => {
81                let extern_call = ir_call_to_extern_call(stack, call, &extern_name)?;
82                command.run(engine_state, stack, &(&extern_call).into(), input)
83            }
84            CallImpl::IrBox(call) => {
85                let extern_call = ir_call_to_extern_call(stack, call, &extern_name)?;
86                command.run(engine_state, stack, &(&extern_call).into(), input)
87            }
88        }
89    }
90
91    fn attributes(&self) -> Vec<(String, Value)> {
92        self.attributes.clone()
93    }
94
95    fn examples(&self) -> Vec<Example<'_>> {
96        self.examples
97            .iter()
98            .map(CustomExample::to_example)
99            .collect()
100    }
101}
102
103/// Transform the args from an `ast::Call` onto a `run-external` call
104fn ast_call_to_extern_call(
105    engine_state: &EngineState,
106    call: &ast::Call,
107    extern_name: &[&str],
108) -> Result<ast::Call, ShellError> {
109    let head_span = call.head;
110
111    let mut extern_call = ast::Call::new(head_span);
112
113    let call_head_id = engine_state
114        .find_span_id(call.head)
115        .unwrap_or(UNKNOWN_SPAN_ID);
116
117    let arg_extern_name = Expression::new_existing(
118        Expr::String(extern_name[0].to_string()),
119        call.head,
120        call_head_id,
121        Type::String,
122    );
123
124    extern_call.add_positional(arg_extern_name);
125
126    for subcommand in extern_name.iter().skip(1) {
127        extern_call.add_positional(Expression::new_existing(
128            Expr::String(subcommand.to_string()),
129            call.head,
130            call_head_id,
131            Type::String,
132        ));
133    }
134
135    for arg in &call.arguments {
136        match arg {
137            ast::Argument::Positional(positional) => extern_call.add_positional(positional.clone()),
138            ast::Argument::Named(named) => {
139                let named_span_id = engine_state
140                    .find_span_id(named.0.span)
141                    .unwrap_or(UNKNOWN_SPAN_ID);
142                if let Some(short) = &named.1 {
143                    extern_call.add_positional(Expression::new_existing(
144                        Expr::String(format!("-{}", short.item)),
145                        named.0.span,
146                        named_span_id,
147                        Type::String,
148                    ));
149                } else {
150                    extern_call.add_positional(Expression::new_existing(
151                        Expr::String(format!("--{}", named.0.item)),
152                        named.0.span,
153                        named_span_id,
154                        Type::String,
155                    ));
156                }
157                if let Some(arg) = &named.2 {
158                    extern_call.add_positional(arg.clone());
159                }
160            }
161            ast::Argument::Unknown(unknown) => extern_call.add_unknown(unknown.clone()),
162            ast::Argument::Spread(args) => extern_call.add_spread(args.clone()),
163        }
164    }
165
166    Ok(extern_call)
167}
168
169/// Transform the args from an `ir::Call` onto a `run-external` call
170fn ir_call_to_extern_call(
171    stack: &mut Stack,
172    call: &ir::Call,
173    extern_name: &[&str],
174) -> Result<ir::Call, ShellError> {
175    let mut extern_call = ir::Call::build(call.decl_id, call.head);
176
177    // Add the command and subcommands
178    for name in extern_name {
179        extern_call.add_positional(stack, call.head, Value::string(*name, call.head));
180    }
181
182    // Add the arguments, reformatting named arguments into string positionals
183    for index in 0..call.args_len {
184        match &call.arguments(stack)[index] {
185            engine::Argument::Flag {
186                data,
187                name,
188                short,
189                span,
190            } => {
191                let name_arg = engine::Argument::Positional {
192                    span: *span,
193                    val: Value::string(known_external_option_name(data, *name, *short), *span),
194                    ast: None,
195                };
196                extern_call.add_argument(stack, name_arg);
197            }
198            engine::Argument::Named {
199                data,
200                name,
201                short,
202                span,
203                val,
204                ..
205            } => {
206                let name_arg = engine::Argument::Positional {
207                    span: *span,
208                    val: Value::string(known_external_option_name(data, *name, *short), *span),
209                    ast: None,
210                };
211                let val_arg = engine::Argument::Positional {
212                    span: *span,
213                    val: val.clone(),
214                    ast: None,
215                };
216                extern_call.add_argument(stack, name_arg);
217                extern_call.add_argument(stack, val_arg);
218            }
219            a @ (engine::Argument::Positional { .. }
220            | engine::Argument::Spread { .. }
221            | engine::Argument::ParserInfo { .. }) => {
222                let argument = a.clone();
223                extern_call.add_argument(stack, argument);
224            }
225        }
226    }
227
228    Ok(extern_call.finish())
229}
230
231fn known_external_option_name(data: &[u8], name: DataSlice, short: DataSlice) -> String {
232    if !data[name].is_empty() {
233        format!(
234            "--{}",
235            std::str::from_utf8(&data[name]).expect("invalid utf-8 in flag name")
236        )
237    } else {
238        format!(
239            "-{}",
240            std::str::from_utf8(&data[short]).expect("invalid utf-8 in flag short name")
241        )
242    }
243}