nu-plugin 0.91.0

Functionality for building Nushell plugins
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
use nu_protocol::{ast::RangeInclusion, record, CustomValue, Range, ShellError, Span, Value};

use crate::{
    plugin::PluginIdentity,
    protocol::test_util::{
        expected_test_custom_value, test_plugin_custom_value, test_plugin_custom_value_with_source,
        TestCustomValue,
    },
};

use super::PluginCustomValue;

#[test]
fn serialize_deserialize() -> Result<(), ShellError> {
    let original_value = TestCustomValue(32);
    let span = Span::test_data();
    let serialized = PluginCustomValue::serialize_from_custom_value(&original_value, span)?;
    assert_eq!(original_value.value_string(), serialized.name);
    assert!(serialized.source.is_none());
    let deserialized = serialized.deserialize_to_custom_value(span)?;
    let downcasted = deserialized
        .as_any()
        .downcast_ref::<TestCustomValue>()
        .expect("failed to downcast: not TestCustomValue");
    assert_eq!(original_value, *downcasted);
    Ok(())
}

#[test]
fn expected_serialize_output() -> Result<(), ShellError> {
    let original_value = expected_test_custom_value();
    let span = Span::test_data();
    let serialized = PluginCustomValue::serialize_from_custom_value(&original_value, span)?;
    assert_eq!(
        test_plugin_custom_value().data,
        serialized.data,
        "The bincode configuration is probably different from what we expected. \
            Fix test_plugin_custom_value() to match it"
    );
    Ok(())
}

#[test]
fn add_source_at_root() -> Result<(), ShellError> {
    let mut val = Value::test_custom_value(Box::new(test_plugin_custom_value()));
    let source = PluginIdentity::new_fake("foo");
    PluginCustomValue::add_source(&mut val, &source);

    let custom_value = val.as_custom_value()?;
    let plugin_custom_value: &PluginCustomValue = custom_value
        .as_any()
        .downcast_ref()
        .expect("not PluginCustomValue");
    assert_eq!(Some(source), plugin_custom_value.source);
    Ok(())
}

fn check_range_custom_values(
    val: &Value,
    mut f: impl FnMut(&str, &dyn CustomValue) -> Result<(), ShellError>,
) -> Result<(), ShellError> {
    let range = val.as_range()?;
    for (name, val) in [
        ("from", &range.from),
        ("incr", &range.incr),
        ("to", &range.to),
    ] {
        let custom_value = val
            .as_custom_value()
            .unwrap_or_else(|_| panic!("{name} not custom value"));
        f(name, custom_value)?;
    }
    Ok(())
}

#[test]
fn add_source_nested_range() -> Result<(), ShellError> {
    let orig_custom_val = Value::test_custom_value(Box::new(test_plugin_custom_value()));
    let mut val = Value::test_range(Range {
        from: orig_custom_val.clone(),
        incr: orig_custom_val.clone(),
        to: orig_custom_val.clone(),
        inclusion: RangeInclusion::Inclusive,
    });
    let source = PluginIdentity::new_fake("foo");
    PluginCustomValue::add_source(&mut val, &source);

    check_range_custom_values(&val, |name, custom_value| {
        let plugin_custom_value: &PluginCustomValue = custom_value
            .as_any()
            .downcast_ref()
            .unwrap_or_else(|| panic!("{name} not PluginCustomValue"));
        assert_eq!(
            Some(&source),
            plugin_custom_value.source.as_ref(),
            "{name} source not set correctly"
        );
        Ok(())
    })
}

fn check_record_custom_values(
    val: &Value,
    keys: &[&str],
    mut f: impl FnMut(&str, &dyn CustomValue) -> Result<(), ShellError>,
) -> Result<(), ShellError> {
    let record = val.as_record()?;
    for key in keys {
        let val = record
            .get(key)
            .unwrap_or_else(|| panic!("record does not contain '{key}'"));
        let custom_value = val
            .as_custom_value()
            .unwrap_or_else(|_| panic!("'{key}' not custom value"));
        f(key, custom_value)?;
    }
    Ok(())
}

#[test]
fn add_source_nested_record() -> Result<(), ShellError> {
    let orig_custom_val = Value::test_custom_value(Box::new(test_plugin_custom_value()));
    let mut val = Value::test_record(record! {
        "foo" => orig_custom_val.clone(),
        "bar" => orig_custom_val.clone(),
    });
    let source = PluginIdentity::new_fake("foo");
    PluginCustomValue::add_source(&mut val, &source);

    check_record_custom_values(&val, &["foo", "bar"], |key, custom_value| {
        let plugin_custom_value: &PluginCustomValue = custom_value
            .as_any()
            .downcast_ref()
            .unwrap_or_else(|| panic!("'{key}' not PluginCustomValue"));
        assert_eq!(
            Some(&source),
            plugin_custom_value.source.as_ref(),
            "'{key}' source not set correctly"
        );
        Ok(())
    })
}

fn check_list_custom_values(
    val: &Value,
    indices: impl IntoIterator<Item = usize>,
    mut f: impl FnMut(usize, &dyn CustomValue) -> Result<(), ShellError>,
) -> Result<(), ShellError> {
    let list = val.as_list()?;
    for index in indices {
        let val = list
            .get(index)
            .unwrap_or_else(|| panic!("[{index}] not present in list"));
        let custom_value = val
            .as_custom_value()
            .unwrap_or_else(|_| panic!("[{index}] not custom value"));
        f(index, custom_value)?;
    }
    Ok(())
}

#[test]
fn add_source_nested_list() -> Result<(), ShellError> {
    let orig_custom_val = Value::test_custom_value(Box::new(test_plugin_custom_value()));
    let mut val = Value::test_list(vec![orig_custom_val.clone(), orig_custom_val.clone()]);
    let source = PluginIdentity::new_fake("foo");
    PluginCustomValue::add_source(&mut val, &source);

    check_list_custom_values(&val, 0..=1, |index, custom_value| {
        let plugin_custom_value: &PluginCustomValue = custom_value
            .as_any()
            .downcast_ref()
            .unwrap_or_else(|| panic!("[{index}] not PluginCustomValue"));
        assert_eq!(
            Some(&source),
            plugin_custom_value.source.as_ref(),
            "[{index}] source not set correctly"
        );
        Ok(())
    })
}

#[test]
fn verify_source_error_message() -> Result<(), ShellError> {
    let span = Span::new(5, 7);
    let mut ok_val = Value::custom_value(Box::new(test_plugin_custom_value_with_source()), span);
    let mut native_val = Value::custom_value(Box::new(TestCustomValue(32)), span);
    let mut foreign_val = {
        let mut val = test_plugin_custom_value();
        val.source = Some(PluginIdentity::new_fake("other"));
        Value::custom_value(Box::new(val), span)
    };
    let source = PluginIdentity::new_fake("test");

    PluginCustomValue::verify_source(&mut ok_val, &source).expect("ok_val should be verified ok");

    for (val, src_plugin) in [(&mut native_val, None), (&mut foreign_val, Some("other"))] {
        let error = PluginCustomValue::verify_source(val, &source).expect_err(&format!(
            "a custom value from {src_plugin:?} should result in an error"
        ));
        if let ShellError::CustomValueIncorrectForPlugin {
            name,
            span: err_span,
            dest_plugin,
            src_plugin: err_src_plugin,
        } = error
        {
            assert_eq!("TestCustomValue", name, "error.name from {src_plugin:?}");
            assert_eq!(span, err_span, "error.span from {src_plugin:?}");
            assert_eq!("test", dest_plugin, "error.dest_plugin from {src_plugin:?}");
            assert_eq!(src_plugin, err_src_plugin.as_deref(), "error.src_plugin");
        } else {
            panic!("the error returned should be CustomValueIncorrectForPlugin");
        }
    }

    Ok(())
}

#[test]
fn verify_source_nested_range() -> Result<(), ShellError> {
    let native_val = Value::test_custom_value(Box::new(TestCustomValue(32)));
    let source = PluginIdentity::new_fake("test");
    for (name, mut val) in [
        (
            "from",
            Value::test_range(Range {
                from: native_val.clone(),
                incr: Value::test_nothing(),
                to: Value::test_nothing(),
                inclusion: RangeInclusion::RightExclusive,
            }),
        ),
        (
            "incr",
            Value::test_range(Range {
                from: Value::test_nothing(),
                incr: native_val.clone(),
                to: Value::test_nothing(),
                inclusion: RangeInclusion::RightExclusive,
            }),
        ),
        (
            "to",
            Value::test_range(Range {
                from: Value::test_nothing(),
                incr: Value::test_nothing(),
                to: native_val.clone(),
                inclusion: RangeInclusion::RightExclusive,
            }),
        ),
    ] {
        PluginCustomValue::verify_source(&mut val, &source)
            .expect_err(&format!("error not generated on {name}"));
    }

    let mut ok_range = Value::test_range(Range {
        from: Value::test_nothing(),
        incr: Value::test_nothing(),
        to: Value::test_nothing(),
        inclusion: RangeInclusion::RightExclusive,
    });
    PluginCustomValue::verify_source(&mut ok_range, &source)
        .expect("ok_range should not generate error");

    Ok(())
}

#[test]
fn verify_source_nested_record() -> Result<(), ShellError> {
    let native_val = Value::test_custom_value(Box::new(TestCustomValue(32)));
    let source = PluginIdentity::new_fake("test");
    for (name, mut val) in [
        (
            "first element foo",
            Value::test_record(record! {
                "foo" => native_val.clone(),
                "bar" => Value::test_nothing(),
            }),
        ),
        (
            "second element bar",
            Value::test_record(record! {
                "foo" => Value::test_nothing(),
                "bar" => native_val.clone(),
            }),
        ),
    ] {
        PluginCustomValue::verify_source(&mut val, &source)
            .expect_err(&format!("error not generated on {name}"));
    }

    let mut ok_record = Value::test_record(record! {"foo" => Value::test_nothing()});
    PluginCustomValue::verify_source(&mut ok_record, &source)
        .expect("ok_record should not generate error");

    Ok(())
}

#[test]
fn verify_source_nested_list() -> Result<(), ShellError> {
    let native_val = Value::test_custom_value(Box::new(TestCustomValue(32)));
    let source = PluginIdentity::new_fake("test");
    for (name, mut val) in [
        (
            "first element",
            Value::test_list(vec![native_val.clone(), Value::test_nothing()]),
        ),
        (
            "second element",
            Value::test_list(vec![Value::test_nothing(), native_val.clone()]),
        ),
    ] {
        PluginCustomValue::verify_source(&mut val, &source)
            .expect_err(&format!("error not generated on {name}"));
    }

    let mut ok_list = Value::test_list(vec![Value::test_nothing()]);
    PluginCustomValue::verify_source(&mut ok_list, &source)
        .expect("ok_list should not generate error");

    Ok(())
}

#[test]
fn serialize_in_root() -> Result<(), ShellError> {
    let span = Span::new(4, 10);
    let mut val = Value::custom_value(Box::new(expected_test_custom_value()), span);
    PluginCustomValue::serialize_custom_values_in(&mut val)?;

    assert_eq!(span, val.span());

    let custom_value = val.as_custom_value()?;
    if let Some(plugin_custom_value) = custom_value.as_any().downcast_ref::<PluginCustomValue>() {
        assert_eq!("TestCustomValue", plugin_custom_value.name);
        assert_eq!(test_plugin_custom_value().data, plugin_custom_value.data);
        assert!(plugin_custom_value.source.is_none());
    } else {
        panic!("Failed to downcast to PluginCustomValue");
    }
    Ok(())
}

#[test]
fn serialize_in_range() -> Result<(), ShellError> {
    let orig_custom_val = Value::test_custom_value(Box::new(TestCustomValue(-1)));
    let mut val = Value::test_range(Range {
        from: orig_custom_val.clone(),
        incr: orig_custom_val.clone(),
        to: orig_custom_val.clone(),
        inclusion: RangeInclusion::Inclusive,
    });
    PluginCustomValue::serialize_custom_values_in(&mut val)?;

    check_range_custom_values(&val, |name, custom_value| {
        let plugin_custom_value: &PluginCustomValue = custom_value
            .as_any()
            .downcast_ref()
            .unwrap_or_else(|| panic!("{name} not PluginCustomValue"));
        assert_eq!(
            "TestCustomValue", plugin_custom_value.name,
            "{name} name not set correctly"
        );
        Ok(())
    })
}

#[test]
fn serialize_in_record() -> Result<(), ShellError> {
    let orig_custom_val = Value::test_custom_value(Box::new(TestCustomValue(32)));
    let mut val = Value::test_record(record! {
        "foo" => orig_custom_val.clone(),
        "bar" => orig_custom_val.clone(),
    });
    PluginCustomValue::serialize_custom_values_in(&mut val)?;

    check_record_custom_values(&val, &["foo", "bar"], |key, custom_value| {
        let plugin_custom_value: &PluginCustomValue = custom_value
            .as_any()
            .downcast_ref()
            .unwrap_or_else(|| panic!("'{key}' not PluginCustomValue"));
        assert_eq!(
            "TestCustomValue", plugin_custom_value.name,
            "'{key}' name not set correctly"
        );
        Ok(())
    })
}

#[test]
fn serialize_in_list() -> Result<(), ShellError> {
    let orig_custom_val = Value::test_custom_value(Box::new(TestCustomValue(24)));
    let mut val = Value::test_list(vec![orig_custom_val.clone(), orig_custom_val.clone()]);
    PluginCustomValue::serialize_custom_values_in(&mut val)?;

    check_list_custom_values(&val, 0..=1, |index, custom_value| {
        let plugin_custom_value: &PluginCustomValue = custom_value
            .as_any()
            .downcast_ref()
            .unwrap_or_else(|| panic!("[{index}] not PluginCustomValue"));
        assert_eq!(
            "TestCustomValue", plugin_custom_value.name,
            "[{index}] name not set correctly"
        );
        Ok(())
    })
}

#[test]
fn deserialize_in_root() -> Result<(), ShellError> {
    let span = Span::new(4, 10);
    let mut val = Value::custom_value(Box::new(test_plugin_custom_value()), span);
    PluginCustomValue::deserialize_custom_values_in(&mut val)?;

    assert_eq!(span, val.span());

    let custom_value = val.as_custom_value()?;
    if let Some(test_custom_value) = custom_value.as_any().downcast_ref::<TestCustomValue>() {
        assert_eq!(expected_test_custom_value(), *test_custom_value);
    } else {
        panic!("Failed to downcast to TestCustomValue");
    }
    Ok(())
}

#[test]
fn deserialize_in_range() -> Result<(), ShellError> {
    let orig_custom_val = Value::test_custom_value(Box::new(test_plugin_custom_value()));
    let mut val = Value::test_range(Range {
        from: orig_custom_val.clone(),
        incr: orig_custom_val.clone(),
        to: orig_custom_val.clone(),
        inclusion: RangeInclusion::Inclusive,
    });
    PluginCustomValue::deserialize_custom_values_in(&mut val)?;

    check_range_custom_values(&val, |name, custom_value| {
        let test_custom_value: &TestCustomValue = custom_value
            .as_any()
            .downcast_ref()
            .unwrap_or_else(|| panic!("{name} not TestCustomValue"));
        assert_eq!(
            expected_test_custom_value(),
            *test_custom_value,
            "{name} not deserialized correctly"
        );
        Ok(())
    })
}

#[test]
fn deserialize_in_record() -> Result<(), ShellError> {
    let orig_custom_val = Value::test_custom_value(Box::new(test_plugin_custom_value()));
    let mut val = Value::test_record(record! {
        "foo" => orig_custom_val.clone(),
        "bar" => orig_custom_val.clone(),
    });
    PluginCustomValue::deserialize_custom_values_in(&mut val)?;

    check_record_custom_values(&val, &["foo", "bar"], |key, custom_value| {
        let test_custom_value: &TestCustomValue = custom_value
            .as_any()
            .downcast_ref()
            .unwrap_or_else(|| panic!("'{key}' not TestCustomValue"));
        assert_eq!(
            expected_test_custom_value(),
            *test_custom_value,
            "{key} not deserialized correctly"
        );
        Ok(())
    })
}

#[test]
fn deserialize_in_list() -> Result<(), ShellError> {
    let orig_custom_val = Value::test_custom_value(Box::new(test_plugin_custom_value()));
    let mut val = Value::test_list(vec![orig_custom_val.clone(), orig_custom_val.clone()]);
    PluginCustomValue::deserialize_custom_values_in(&mut val)?;

    check_list_custom_values(&val, 0..=1, |index, custom_value| {
        let test_custom_value: &TestCustomValue = custom_value
            .as_any()
            .downcast_ref()
            .unwrap_or_else(|| panic!("[{index}] not TestCustomValue"));
        assert_eq!(
            expected_test_custom_value(),
            *test_custom_value,
            "[{index}] name not deserialized correctly"
        );
        Ok(())
    })
}