nu-plugin-engine 0.115.0

Functionality for running Nushell plugins from a Nushell engine
Documentation
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
use crate::util::MutableCow;
use nu_engine::{ClosureEvalOnce, get_eval_block_with_early_return, get_full_help};
use nu_plugin_protocol::{DynamicCompletionCall, EvaluatedCall};
use nu_protocol::{
    BlockId, Config, DeclId, DynamicCompletionCallRef, IntoSpanned, OutDest, PipelineData,
    PluginIdentity, ShellError, Signals, Span, Spanned, Value,
    engine::{Call, Closure, EngineState, Redirection, Stack},
    ir::{self, IrBlock},
    shell_error::generic::GenericError,
};
use std::{
    borrow::Cow,
    collections::HashMap,
    sync::{Arc, atomic::AtomicU32},
};

/// Object safe trait for abstracting operations required of the plugin context.
pub trait PluginExecutionContext: Send + Sync {
    /// A span pointing to the command being executed
    fn span(&self) -> Span;
    /// The [`Signals`] struct, if present
    fn signals(&self) -> &Signals;
    /// The pipeline externals state, for tracking the foreground process group, if present
    fn pipeline_externals_state(&self) -> Option<&Arc<(AtomicU32, AtomicU32)>>;
    /// Get engine configuration
    fn get_config(&self) -> Result<Arc<Config>, ShellError>;
    /// Get plugin configuration
    fn get_plugin_config(&self) -> Result<Option<Value>, ShellError>;
    /// Get an environment variable from `$env`
    fn get_env_var(&self, name: &str) -> Result<Option<&Value>, ShellError>;
    /// Get all environment variables
    fn get_env_vars(&self) -> Result<HashMap<String, Value>, ShellError>;
    /// Get current working directory
    fn get_current_dir(&self) -> Result<Spanned<String>, ShellError>;
    /// Set an environment variable
    fn add_env_var(&mut self, name: String, value: Value) -> Result<(), ShellError>;
    /// Get help for the current command
    fn get_help(&self) -> Result<Spanned<String>, ShellError>;
    /// Get the contents of a [`Span`]
    fn get_span_contents(&self, span: Span) -> Result<Spanned<Vec<u8>>, ShellError>;
    /// Evaluate a closure passed to the plugin
    fn eval_closure(
        &self,
        closure: Spanned<Closure>,
        positional: Vec<Value>,
        input: PipelineData,
        redirect_stdout: bool,
        redirect_stderr: bool,
    ) -> Result<PipelineData, ShellError>;
    /// Find a declaration by name
    fn find_decl(&self, name: &str) -> Result<Option<DeclId>, ShellError>;
    /// Get the compiled IR for a block
    fn get_block_ir(&self, block_id: BlockId) -> Result<IrBlock, ShellError>;
    /// Call a declaration with arguments and input
    fn call_decl(
        &mut self,
        decl_id: DeclId,
        call: EvaluatedCall,
        input: PipelineData,
        redirect_stdout: bool,
        redirect_stderr: bool,
    ) -> Result<PipelineData, ShellError>;
    /// Create an owned version of the context with `'static` lifetime
    fn boxed(&self) -> Box<dyn PluginExecutionContext>;
}

/// The execution context of a plugin command. Can be borrowed.
pub struct PluginExecutionCommandContext<'a> {
    identity: Arc<PluginIdentity>,
    engine_state: Cow<'a, EngineState>,
    stack: MutableCow<'a, Stack>,
    call: Call<'a>,
}

impl<'a> PluginExecutionCommandContext<'a> {
    pub fn new(
        identity: Arc<PluginIdentity>,
        engine_state: &'a EngineState,
        stack: &'a mut Stack,
        call: &'a Call<'a>,
    ) -> PluginExecutionCommandContext<'a> {
        PluginExecutionCommandContext {
            identity,
            engine_state: Cow::Borrowed(engine_state),
            stack: MutableCow::Borrowed(stack),
            call: call.clone(),
        }
    }
}

impl PluginExecutionContext for PluginExecutionCommandContext<'_> {
    fn span(&self) -> Span {
        self.call.head
    }

    fn signals(&self) -> &Signals {
        self.engine_state.signals()
    }

    fn pipeline_externals_state(&self) -> Option<&Arc<(AtomicU32, AtomicU32)>> {
        Some(&self.engine_state.pipeline_externals_state)
    }

    fn get_config(&self) -> Result<Arc<Config>, ShellError> {
        Ok(self.stack.get_config(&self.engine_state))
    }

    fn get_plugin_config(&self) -> Result<Option<Value>, ShellError> {
        Ok(plugin_config(
            self.get_config()?,
            self.identity.name(),
            &self.engine_state,
            &self.stack,
            self.call.head,
        ))
    }

    fn get_env_var(&self, name: &str) -> Result<Option<&Value>, ShellError> {
        Ok(self.stack.get_env_var(&self.engine_state, name))
    }

    fn get_env_vars(&self) -> Result<HashMap<String, Value>, ShellError> {
        Ok(self.stack.get_env_vars(&self.engine_state))
    }

    fn get_current_dir(&self) -> Result<Spanned<String>, ShellError> {
        let cwd = self.engine_state.cwd_as_string(Some(&self.stack))?;
        // The span is not really used, so just give it call.head
        Ok(cwd.into_spanned(self.call.head))
    }

    fn add_env_var(&mut self, name: String, value: Value) -> Result<(), ShellError> {
        self.stack.add_env_var(name, value);
        Ok(())
    }

    fn get_help(&self) -> Result<Spanned<String>, ShellError> {
        let decl = self.engine_state.get_decl(self.call.decl_id);

        Ok(get_full_help(
            decl,
            &self.engine_state,
            &mut self.stack.clone(),
            self.call.head,
        )
        .into_spanned(self.call.head))
    }

    fn get_span_contents(&self, span: Span) -> Result<Spanned<Vec<u8>>, ShellError> {
        Ok(self
            .engine_state
            .get_span_contents(span)
            .to_vec()
            .into_spanned(self.call.head))
    }

    fn eval_closure(
        &self,
        closure: Spanned<Closure>,
        positional: Vec<Value>,
        input: PipelineData,
        redirect_stdout: bool,
        redirect_stderr: bool,
    ) -> Result<PipelineData, ShellError> {
        let block = self
            .engine_state
            .try_get_block(closure.item.block_id)
            .ok_or_else(|| {
                ShellError::Generic(GenericError::new(
                    "Plugin misbehaving",
                    format!(
                        "Tried to evaluate unknown block id: {}",
                        closure.item.block_id.get()
                    ),
                    closure.span,
                ))
            })?;

        let mut stack = self
            .stack
            .captures_to_stack(closure.item.captures)
            .reset_pipes();

        let stack = &mut stack.push_redirection(
            redirect_stdout.then_some(Redirection::Pipe(OutDest::PipeSeparate)),
            redirect_stderr.then_some(Redirection::Pipe(OutDest::PipeSeparate)),
        );

        // Set up the positional arguments
        for (idx, value) in positional.into_iter().enumerate() {
            if let Some(arg) = block.signature.get_positional(idx) {
                if let Some(var_id) = arg.var_id {
                    stack.add_var(var_id, value);
                } else {
                    return Err(ShellError::NushellFailedSpanned {
                        msg: "Error while evaluating closure from plugin".into(),
                        label: "closure argument missing var_id".into(),
                        span: closure.span,
                    });
                }
            }
        }

        let eval_block_with_early_return = get_eval_block_with_early_return(&self.engine_state);

        eval_block_with_early_return(&self.engine_state, stack, block, input).map(|p| p.body)
    }

    fn find_decl(&self, name: &str) -> Result<Option<DeclId>, ShellError> {
        Ok(self.engine_state.find_decl(name.as_bytes(), &[]))
    }

    fn get_block_ir(&self, block_id: BlockId) -> Result<IrBlock, ShellError> {
        let block = self.engine_state.try_get_block(block_id).ok_or_else(|| {
            ShellError::Generic(GenericError::new(
                "Plugin misbehaving",
                format!("Tried to get IR for unknown block id: {}", block_id.get()),
                self.call.head,
            ))
        })?;

        block.ir_block.clone().ok_or_else(|| {
            ShellError::Generic(
                GenericError::new(
                    "Block has no IR",
                    format!("Block {} was not compiled to IR", block_id.get()),
                    self.call.head,
                )
                .with_help(
                    "This block may be a declaration or built-in that has no IR representation",
                ),
            )
        })
    }

    fn call_decl(
        &mut self,
        decl_id: DeclId,
        call: EvaluatedCall,
        input: PipelineData,
        redirect_stdout: bool,
        redirect_stderr: bool,
    ) -> Result<PipelineData, ShellError> {
        if decl_id.get() >= self.engine_state.num_decls() {
            return Err(ShellError::Generic(GenericError::new(
                "Plugin misbehaving",
                format!("Tried to call unknown decl id: {}", decl_id.get()),
                call.head,
            )));
        }

        let decl = self.engine_state.get_decl(decl_id);

        let stack = &mut self.stack.push_redirection(
            redirect_stdout.then_some(Redirection::Pipe(OutDest::PipeSeparate)),
            redirect_stderr.then_some(Redirection::Pipe(OutDest::PipeSeparate)),
        );

        let mut call_builder = ir::Call::build(decl_id, call.head);

        for positional in call.positional {
            call_builder.add_positional(stack, positional.span(), positional);
        }

        for (name, value) in call.named {
            if let Some(value) = value {
                call_builder.add_named(stack, &name.item, "", name.span, value);
            } else {
                call_builder.add_flag(stack, &name.item, "", name.span);
            }
        }

        call_builder.with(stack, |stack, call| {
            decl.run(&self.engine_state, stack, call, input)
        })
    }

    fn boxed(&self) -> Box<dyn PluginExecutionContext + 'static> {
        Box::new(PluginExecutionCommandContext {
            identity: self.identity.clone(),
            engine_state: Cow::Owned(self.engine_state.clone().into_owned()),
            stack: self.stack.owned(),
            call: self.call.to_owned(),
        })
    }
}

// Fetch the configuration for a plugin
//
// The `plugin` must match the registered name of a plugin.  For `plugin add nu_plugin_example` the
// plugin config lookup uses `"example"`
fn plugin_config(
    config: Arc<Config>,
    plugin_name: &str,
    engine_state: &EngineState,
    stack: &Stack,
    head: Span,
) -> Option<Value> {
    config.plugins.get(plugin_name).cloned().map(|value| {
        let span = value.span();
        match value {
            Value::Closure { val, .. } => ClosureEvalOnce::new(engine_state, stack, *val)
                .run_with_input(PipelineData::empty())
                .and_then(|data| data.into_value(span))
                .unwrap_or_else(|err| Value::error(err, head)),
            _ => value.clone(),
        }
    })
}

/// The execution context of plugin completion.
///
/// This supports limited interactions suitable for generating completions from nushell
/// configuration, the environment, current working directory, or existing help.
pub struct PluginGetDynamicCompletionContext<'a> {
    identity: Arc<PluginIdentity>,
    engine_state: Cow<'a, EngineState>,
    stack: MutableCow<'a, Stack>,
    call: DynamicCompletionCall,
}

impl<'a> PluginGetDynamicCompletionContext<'a> {
    pub fn new(
        identity: Arc<PluginIdentity>,
        engine_state: &'a EngineState,
        stack: &'a mut Stack,
        call: &DynamicCompletionCallRef<'a>,
    ) -> Self {
        Self {
            identity,
            engine_state: Cow::Borrowed(engine_state),
            stack: MutableCow::Borrowed(stack),
            call: call.into(),
        }
    }
}

impl PluginExecutionContext for PluginGetDynamicCompletionContext<'_> {
    fn span(&self) -> Span {
        self.call.call.head
    }

    fn signals(&self) -> &Signals {
        &Signals::EMPTY
    }

    fn pipeline_externals_state(&self) -> Option<&Arc<(AtomicU32, AtomicU32)>> {
        Some(&self.engine_state.pipeline_externals_state)
    }

    fn get_config(&self) -> Result<Arc<Config>, ShellError> {
        Ok(self.stack.get_config(&self.engine_state))
    }

    fn get_plugin_config(&self) -> Result<Option<Value>, ShellError> {
        Ok(plugin_config(
            self.get_config()?,
            self.identity.name(),
            &self.engine_state,
            &self.stack,
            self.call.call.head,
        ))
    }

    fn get_env_var(&self, name: &str) -> Result<Option<&Value>, ShellError> {
        Ok(self.stack.get_env_var(&self.engine_state, name))
    }

    fn get_env_vars(&self) -> Result<HashMap<String, Value>, ShellError> {
        Ok(self.stack.get_env_vars(&self.engine_state))
    }

    fn get_current_dir(&self) -> Result<Spanned<String>, ShellError> {
        let cwd = self.engine_state.cwd_as_string(Some(&self.stack))?;
        // The span is not really used, so just give it call.head
        Ok(cwd.into_spanned(self.call.call.head))
    }

    fn add_env_var(&mut self, _name: String, _value: Value) -> Result<(), ShellError> {
        Err(ShellError::NushellFailed {
            msg: "add_env_var not implemented for PluginGetDynamicCompletionContext".into(),
        })
    }

    fn get_help(&self) -> Result<Spanned<String>, ShellError> {
        let decl = self.engine_state.get_decl(self.call.call.decl_id);

        Ok(get_full_help(
            decl,
            &self.engine_state,
            &mut self.stack.clone(),
            self.call.call.head,
        )
        .into_spanned(self.call.call.head))
    }

    fn get_span_contents(&self, span: Span) -> Result<Spanned<Vec<u8>>, ShellError> {
        Ok(self
            .engine_state
            .get_span_contents(span)
            .to_vec()
            .into_spanned(self.call.call.head))
    }

    fn eval_closure(
        &self,
        _closure: Spanned<Closure>,
        _positional: Vec<Value>,
        _input: PipelineData,
        _redirect_stdout: bool,
        _redirect_stderr: bool,
    ) -> Result<PipelineData, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "eval_closure not implemented for PluginGetDynamicCompletionContext".into(),
        })
    }

    fn find_decl(&self, _name: &str) -> Result<Option<DeclId>, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "find_decl not implemented for PluginGetDynamicCompletionContext".into(),
        })
    }

    fn get_block_ir(&self, _block_id: BlockId) -> Result<IrBlock, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "get_block_ir not implemented for PluginGetDynamicCompletionContext".into(),
        })
    }

    fn call_decl(
        &mut self,
        _decl_id: DeclId,
        _call: EvaluatedCall,
        _input: PipelineData,
        _redirect_stdout: bool,
        _redirect_stderr: bool,
    ) -> Result<PipelineData, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "call_decl not implemented for PluginGetDynamicCompletionContext".into(),
        })
    }

    fn boxed(&self) -> Box<dyn PluginExecutionContext + 'static> {
        Box::new(PluginGetDynamicCompletionContext {
            identity: self.identity.clone(),
            engine_state: Cow::Owned(self.engine_state.clone().into_owned()),
            stack: self.stack.owned(),
            call: self.call.to_owned(),
        })
    }
}

/// A bogus execution context for testing that doesn't really implement anything properly
#[cfg(test)]
pub(crate) struct PluginExecutionBogusContext;

#[cfg(test)]
impl PluginExecutionContext for PluginExecutionBogusContext {
    fn span(&self) -> Span {
        Span::test_data()
    }

    fn signals(&self) -> &Signals {
        &Signals::EMPTY
    }

    fn pipeline_externals_state(&self) -> Option<&Arc<(AtomicU32, AtomicU32)>> {
        None
    }

    fn get_config(&self) -> Result<Arc<Config>, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "get_config not implemented on bogus".into(),
        })
    }

    fn get_plugin_config(&self) -> Result<Option<Value>, ShellError> {
        Ok(None)
    }

    fn get_env_var(&self, _name: &str) -> Result<Option<&Value>, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "get_env_var not implemented on bogus".into(),
        })
    }

    fn get_env_vars(&self) -> Result<HashMap<String, Value>, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "get_env_vars not implemented on bogus".into(),
        })
    }

    fn get_current_dir(&self) -> Result<Spanned<String>, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "get_current_dir not implemented on bogus".into(),
        })
    }

    fn add_env_var(&mut self, _name: String, _value: Value) -> Result<(), ShellError> {
        Err(ShellError::NushellFailed {
            msg: "add_env_var not implemented on bogus".into(),
        })
    }

    fn get_help(&self) -> Result<Spanned<String>, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "get_help not implemented on bogus".into(),
        })
    }

    fn get_span_contents(&self, _span: Span) -> Result<Spanned<Vec<u8>>, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "get_span_contents not implemented on bogus".into(),
        })
    }

    fn eval_closure(
        &self,
        _closure: Spanned<Closure>,
        _positional: Vec<Value>,
        _input: PipelineData,
        _redirect_stdout: bool,
        _redirect_stderr: bool,
    ) -> Result<PipelineData, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "eval_closure not implemented on bogus".into(),
        })
    }

    fn find_decl(&self, _name: &str) -> Result<Option<DeclId>, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "find_decl not implemented on bogus".into(),
        })
    }

    fn get_block_ir(&self, _block_id: BlockId) -> Result<IrBlock, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "get_block_ir not implemented on bogus".into(),
        })
    }

    fn call_decl(
        &mut self,
        _decl_id: DeclId,
        _call: EvaluatedCall,
        _input: PipelineData,
        _redirect_stdout: bool,
        _redirect_stderr: bool,
    ) -> Result<PipelineData, ShellError> {
        Err(ShellError::NushellFailed {
            msg: "call_decl not implemented on bogus".into(),
        })
    }

    fn boxed(&self) -> Box<dyn PluginExecutionContext + 'static> {
        Box::new(PluginExecutionBogusContext)
    }
}