1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
use crate::command_args::CommandArgs;
use crate::documentation::get_full_help;
use crate::evaluate::block::run_block;
use crate::example::Example;
use nu_errors::ShellError;
use nu_parser::ParserScope;
use nu_protocol::hir::Block;
use nu_protocol::{ReturnSuccess, Signature, UntaggedValue};
use nu_source::{DbgDocBldr, DebugDocBuilder, PrettyDebugWithSource, Span, Tag};
use nu_stream::{ActionStream, InputStream, IntoOutputStream, OutputStream};
use std::sync::Arc;

pub trait WholeStreamCommand: Send + Sync {
    fn name(&self) -> &str;

    fn signature(&self) -> Signature {
        Signature::new(self.name()).desc(self.usage()).filter()
    }

    fn usage(&self) -> &str;

    fn extra_usage(&self) -> &str {
        ""
    }

    fn run_with_actions(&self, _args: CommandArgs) -> Result<ActionStream, ShellError> {
        return Err(ShellError::unimplemented(&format!(
            "{} does not implement run or run_with_actions",
            self.name()
        )));
    }

    fn run(&self, args: CommandArgs) -> Result<InputStream, ShellError> {
        let context = args.context.clone();
        let stream = self.run_with_actions(args)?;

        Ok(Box::new(crate::evaluate::internal::InternalIterator {
            context,
            input: stream,
            leftovers: InputStream::empty(),
        })
        .into_output_stream())
    }

    fn is_binary(&self) -> bool {
        false
    }

    // Commands that are not meant to be run by users
    fn is_private(&self) -> bool {
        false
    }

    fn examples(&self) -> Vec<Example> {
        Vec::new()
    }

    // This is a built-in command
    fn is_builtin(&self) -> bool {
        true
    }

    // Is a sub command
    fn is_sub(&self) -> bool {
        self.name().contains(' ')
    }

    // Is a plugin command
    fn is_plugin(&self) -> bool {
        false
    }

    // Is a custom command i.e. def blah [] { }
    fn is_custom(&self) -> bool {
        false
    }
}

// Custom commands are blocks, so we can use the information in the block to also
// implement a WholeStreamCommand
#[allow(clippy::suspicious_else_formatting)]
impl WholeStreamCommand for Arc<Block> {
    fn name(&self) -> &str {
        &self.params.name
    }

    fn signature(&self) -> Signature {
        self.params.clone()
    }

    fn usage(&self) -> &str {
        &self.params.usage
    }

    fn extra_usage(&self) -> &str {
        &self.params.extra_usage
    }

    fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
        let call_info = args.call_info.clone();

        let block = self.clone();

        let external_redirection = args.call_info.args.external_redirection;

        let ctx = &args.context;
        let evaluated = call_info.evaluate(ctx)?;

        let input = args.input;
        ctx.scope.enter_scope();
        if let Some(args) = evaluated.args.positional {
            let mut args_iter = args.into_iter().peekable();
            let mut params_iter = self.params.positional.iter();
            loop {
                match (args_iter.peek(), params_iter.next()) {
                    (Some(_), Some(param)) => {
                        let name = param.0.name();
                        // we just checked the peek above, so this should be infallible
                        if let Some(arg) = args_iter.next() {
                            if name.starts_with('$') {
                                ctx.scope.add_var(name.to_string(), arg);
                            } else {
                                ctx.scope.add_var(format!("${}", name), arg);
                            }
                        }
                    }
                    (Some(arg), None) => {
                        if block.params.rest_positional.is_none() {
                            ctx.scope.exit_scope();
                            return Err(ShellError::labeled_error(
                                "Unexpected argument to command",
                                "unexpected argument",
                                arg.tag.span,
                            ));
                        } else {
                            break;
                        }
                    }
                    _ => break,
                }
            }
            if let Some(rest_pos) = &block.params.rest_positional {
                let elements: Vec<_> = args_iter.collect();
                let start = if let Some(first) = elements.first() {
                    first.tag.span.start()
                } else {
                    0
                };
                let end = if let Some(last) = elements.last() {
                    last.tag.span.end()
                } else {
                    0
                };

                ctx.scope.add_var(
                    format!("${}", rest_pos.0),
                    UntaggedValue::Table(elements).into_value(Span::new(start, end)),
                );
            }
        } else if let Some(rest_pos) = &block.params.rest_positional {
            //If there is a rest arg, but no args were provided,
            //we have to set $rest to an empty table
            ctx.scope.add_var(
                format!("${}", rest_pos.0),
                UntaggedValue::Table(Vec::new()).into_value(Span::new(0, 0)),
            );
        }
        if let Some(args) = evaluated.args.named {
            for named in &block.params.named {
                let name = named.0;
                if let Some(value) = args.get(name) {
                    if name.starts_with('$') {
                        ctx.scope.add_var(name, value.clone());
                    } else {
                        ctx.scope.add_var(format!("${}", name), value.clone());
                    }
                } else if name.starts_with('$') {
                    ctx.scope
                        .add_var(name, UntaggedValue::nothing().into_untagged_value());
                } else {
                    ctx.scope.add_var(
                        format!("${}", name),
                        UntaggedValue::nothing().into_untagged_value(),
                    );
                }
            }
        } else {
            for named in &block.params.named {
                let name = named.0;
                if name.starts_with('$') {
                    ctx.scope
                        .add_var(name, UntaggedValue::nothing().into_untagged_value());
                } else {
                    ctx.scope.add_var(
                        format!("${}", name),
                        UntaggedValue::nothing().into_untagged_value(),
                    );
                }
            }
        }
        let result = run_block(&block, ctx, input, external_redirection);
        ctx.scope.exit_scope();
        result
    }

    fn is_binary(&self) -> bool {
        false
    }

    fn is_private(&self) -> bool {
        false
    }

    fn examples(&self) -> Vec<Example> {
        vec![]
    }

    fn is_custom(&self) -> bool {
        true
    }

    fn is_builtin(&self) -> bool {
        false
    }
}

#[derive(Clone)]
pub struct Command(Arc<dyn WholeStreamCommand>);

impl PrettyDebugWithSource for Command {
    fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
        DbgDocBldr::typed(
            "whole stream command",
            DbgDocBldr::description(self.name())
                + DbgDocBldr::space()
                + DbgDocBldr::equals()
                + DbgDocBldr::space()
                + self.signature().pretty_debug(source),
        )
    }
}

impl std::fmt::Debug for Command {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Command({})", self.name())
    }
}

impl Command {
    pub fn name(&self) -> &str {
        self.0.name()
    }

    pub fn signature(&self) -> Signature {
        self.0.signature()
    }

    pub fn usage(&self) -> &str {
        self.0.usage()
    }

    pub fn extra_usage(&self) -> &str {
        self.0.extra_usage()
    }

    pub fn examples(&self) -> Vec<Example> {
        self.0.examples()
    }

    pub fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
        if args.call_info.switch_present("help") {
            let cl = self.0.clone();
            Ok(ActionStream::one(Ok(ReturnSuccess::Value(
                UntaggedValue::string(get_full_help(&*cl, &args.context.scope))
                    .into_value(Tag::unknown()),
            ))))
        } else {
            self.0.run_with_actions(args)
        }
    }

    pub fn run(&self, args: CommandArgs) -> Result<InputStream, ShellError> {
        if args.call_info.switch_present("help") {
            let cl = self.0.clone();
            Ok(InputStream::one(
                UntaggedValue::string(get_full_help(&*cl, &args.context.scope))
                    .into_value(Tag::unknown()),
            ))
        } else {
            self.0.run(args)
        }
    }

    pub fn is_binary(&self) -> bool {
        self.0.is_binary()
    }

    pub fn is_private(&self) -> bool {
        self.0.is_private()
    }

    pub fn stream_command(&self) -> &dyn WholeStreamCommand {
        &*self.0
    }

    pub fn is_builtin(&self) -> bool {
        self.0.is_builtin()
    }

    pub fn is_sub(&self) -> bool {
        self.0.is_sub()
    }

    pub fn is_plugin(&self) -> bool {
        self.0.is_plugin()
    }

    pub fn is_custom(&self) -> bool {
        self.0.is_custom()
    }
}

pub fn whole_stream_command(command: impl WholeStreamCommand + 'static) -> Command {
    Command(Arc::new(command))
}