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
use nu_protocol::ShellError;

use crate::{plugin::PluginEncoder, protocol::PluginResponse};

/// A `PluginEncoder` that enables the plugin to communicate with Nushel with JSON
/// serialized data.
#[derive(Clone, Debug)]
pub struct JsonSerializer;

impl PluginEncoder for JsonSerializer {
    fn name(&self) -> &str {
        "json"
    }

    fn encode_call(
        &self,
        plugin_call: &crate::protocol::PluginCall,
        writer: &mut impl std::io::Write,
    ) -> Result<(), nu_protocol::ShellError> {
        serde_json::to_writer(writer, plugin_call)
            .map_err(|err| ShellError::PluginFailedToEncode(err.to_string()))
    }

    fn decode_call(
        &self,
        reader: &mut impl std::io::BufRead,
    ) -> Result<crate::protocol::PluginCall, nu_protocol::ShellError> {
        serde_json::from_reader(reader)
            .map_err(|err| ShellError::PluginFailedToEncode(err.to_string()))
    }

    fn encode_response(
        &self,
        plugin_response: &PluginResponse,
        writer: &mut impl std::io::Write,
    ) -> Result<(), ShellError> {
        serde_json::to_writer(writer, plugin_response)
            .map_err(|err| ShellError::PluginFailedToEncode(err.to_string()))
    }

    fn decode_response(
        &self,
        reader: &mut impl std::io::BufRead,
    ) -> Result<PluginResponse, ShellError> {
        serde_json::from_reader(reader)
            .map_err(|err| ShellError::PluginFailedToEncode(err.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::{
        CallInfo, CallInput, EvaluatedCall, LabeledError, PluginCall, PluginData, PluginResponse,
    };
    use nu_protocol::{PluginSignature, Span, Spanned, SyntaxShape, Value};

    #[test]
    fn callinfo_round_trip_signature() {
        let plugin_call = PluginCall::Signature;
        let encoder = JsonSerializer {};

        let mut buffer: Vec<u8> = Vec::new();
        encoder
            .encode_call(&plugin_call, &mut buffer)
            .expect("unable to serialize message");
        let returned = encoder
            .decode_call(&mut buffer.as_slice())
            .expect("unable to deserialize message");

        match returned {
            PluginCall::Signature => {}
            PluginCall::CallInfo(_) => panic!("decoded into wrong value"),
            PluginCall::CollapseCustomValue(_) => panic!("decoded into wrong value"),
        }
    }

    #[test]
    fn callinfo_round_trip_callinfo() {
        let name = "test".to_string();

        let input = Value::bool(false, Span::new(1, 20));

        let call = EvaluatedCall {
            head: Span::new(0, 10),
            positional: vec![
                Value::float(1.0, Span::new(0, 10)),
                Value::string("something", Span::new(0, 10)),
            ],
            named: vec![(
                Spanned {
                    item: "name".to_string(),
                    span: Span::new(0, 10),
                },
                Some(Value::float(1.0, Span::new(0, 10))),
            )],
        };

        let plugin_call = PluginCall::CallInfo(CallInfo {
            name: name.clone(),
            call: call.clone(),
            input: CallInput::Value(input.clone()),
        });

        let encoder = JsonSerializer {};
        let mut buffer: Vec<u8> = Vec::new();
        encoder
            .encode_call(&plugin_call, &mut buffer)
            .expect("unable to serialize message");
        let returned = encoder
            .decode_call(&mut buffer.as_slice())
            .expect("unable to deserialize message");

        match returned {
            PluginCall::Signature => panic!("returned wrong call type"),
            PluginCall::CallInfo(call_info) => {
                assert_eq!(name, call_info.name);
                assert_eq!(CallInput::Value(input), call_info.input);
                assert_eq!(call.head, call_info.call.head);
                assert_eq!(call.positional.len(), call_info.call.positional.len());

                call.positional
                    .iter()
                    .zip(call_info.call.positional.iter())
                    .for_each(|(lhs, rhs)| assert_eq!(lhs, rhs));

                call.named
                    .iter()
                    .zip(call_info.call.named.iter())
                    .for_each(|(lhs, rhs)| {
                        // Comparing the keys
                        assert_eq!(lhs.0.item, rhs.0.item);

                        match (&lhs.1, &rhs.1) {
                            (None, None) => {}
                            (Some(a), Some(b)) => assert_eq!(a, b),
                            _ => panic!("not matching values"),
                        }
                    });
            }
            PluginCall::CollapseCustomValue(_) => panic!("returned wrong call type"),
        }
    }

    #[test]
    fn callinfo_round_trip_collapsecustomvalue() {
        let data = vec![1, 2, 3, 4, 5, 6, 7];
        let span = Span::new(0, 20);

        let collapse_custom_value = PluginCall::CollapseCustomValue(PluginData {
            data: data.clone(),
            span,
        });

        let encoder = JsonSerializer {};
        let mut buffer: Vec<u8> = Vec::new();
        encoder
            .encode_call(&collapse_custom_value, &mut buffer)
            .expect("unable to serialize message");
        let returned = encoder
            .decode_call(&mut buffer.as_slice())
            .expect("unable to deserialize message");

        match returned {
            PluginCall::Signature => panic!("returned wrong call type"),
            PluginCall::CallInfo(_) => panic!("returned wrong call type"),
            PluginCall::CollapseCustomValue(plugin_data) => {
                assert_eq!(data, plugin_data.data);
                assert_eq!(span, plugin_data.span);
            }
        }
    }

    #[test]
    fn response_round_trip_signature() {
        let signature = PluginSignature::build("nu-plugin")
            .required("first", SyntaxShape::String, "first required")
            .required("second", SyntaxShape::Int, "second required")
            .required_named("first-named", SyntaxShape::String, "first named", Some('f'))
            .required_named(
                "second-named",
                SyntaxShape::String,
                "second named",
                Some('s'),
            )
            .rest("remaining", SyntaxShape::Int, "remaining");

        let response = PluginResponse::Signature(vec![signature.clone()]);

        let encoder = JsonSerializer {};
        let mut buffer: Vec<u8> = Vec::new();
        encoder
            .encode_response(&response, &mut buffer)
            .expect("unable to serialize message");
        let returned = encoder
            .decode_response(&mut buffer.as_slice())
            .expect("unable to deserialize message");

        match returned {
            PluginResponse::Error(_) => panic!("returned wrong call type"),
            PluginResponse::Value(_) => panic!("returned wrong call type"),
            PluginResponse::PluginData(..) => panic!("returned wrong call type"),
            PluginResponse::Signature(returned_signature) => {
                assert_eq!(returned_signature.len(), 1);
                assert_eq!(signature.sig.name, returned_signature[0].sig.name);
                assert_eq!(signature.sig.usage, returned_signature[0].sig.usage);
                assert_eq!(
                    signature.sig.extra_usage,
                    returned_signature[0].sig.extra_usage
                );
                assert_eq!(signature.sig.is_filter, returned_signature[0].sig.is_filter);

                signature
                    .sig
                    .required_positional
                    .iter()
                    .zip(returned_signature[0].sig.required_positional.iter())
                    .for_each(|(lhs, rhs)| assert_eq!(lhs, rhs));

                signature
                    .sig
                    .optional_positional
                    .iter()
                    .zip(returned_signature[0].sig.optional_positional.iter())
                    .for_each(|(lhs, rhs)| assert_eq!(lhs, rhs));

                signature
                    .sig
                    .named
                    .iter()
                    .zip(returned_signature[0].sig.named.iter())
                    .for_each(|(lhs, rhs)| assert_eq!(lhs, rhs));

                assert_eq!(
                    signature.sig.rest_positional,
                    returned_signature[0].sig.rest_positional,
                );
            }
        }
    }

    #[test]
    fn response_round_trip_value() {
        let value = Value::int(10, Span::new(2, 30));

        let response = PluginResponse::Value(Box::new(value.clone()));

        let encoder = JsonSerializer {};
        let mut buffer: Vec<u8> = Vec::new();
        encoder
            .encode_response(&response, &mut buffer)
            .expect("unable to serialize message");
        let returned = encoder
            .decode_response(&mut buffer.as_slice())
            .expect("unable to deserialize message");

        match returned {
            PluginResponse::Error(_) => panic!("returned wrong call type"),
            PluginResponse::Signature(_) => panic!("returned wrong call type"),
            PluginResponse::PluginData(..) => panic!("returned wrong call type"),
            PluginResponse::Value(returned_value) => {
                assert_eq!(&value, returned_value.as_ref())
            }
        }
    }

    #[test]
    fn response_round_trip_plugin_data() {
        let name = "test".to_string();

        let data = vec![1, 2, 3, 4, 5];
        let span = Span::new(2, 30);

        let response = PluginResponse::PluginData(
            name.clone(),
            PluginData {
                data: data.clone(),
                span,
            },
        );

        let encoder = JsonSerializer {};
        let mut buffer: Vec<u8> = Vec::new();
        encoder
            .encode_response(&response, &mut buffer)
            .expect("unable to serialize message");
        let returned = encoder
            .decode_response(&mut buffer.as_slice())
            .expect("unable to deserialize message");

        match returned {
            PluginResponse::Error(_) => panic!("returned wrong call type"),
            PluginResponse::Signature(_) => panic!("returned wrong call type"),
            PluginResponse::Value(_) => panic!("returned wrong call type"),
            PluginResponse::PluginData(returned_name, returned_plugin_data) => {
                assert_eq!(name, returned_name);
                assert_eq!(data, returned_plugin_data.data);
                assert_eq!(span, returned_plugin_data.span);
            }
        }
    }

    #[test]
    fn response_round_trip_error() {
        let error = LabeledError {
            label: "label".into(),
            msg: "msg".into(),
            span: Some(Span::new(2, 30)),
        };
        let response = PluginResponse::Error(error.clone());

        let encoder = JsonSerializer {};
        let mut buffer: Vec<u8> = Vec::new();
        encoder
            .encode_response(&response, &mut buffer)
            .expect("unable to serialize message");
        let returned = encoder
            .decode_response(&mut buffer.as_slice())
            .expect("unable to deserialize message");

        match returned {
            PluginResponse::Error(msg) => assert_eq!(error, msg),
            PluginResponse::Signature(_) => panic!("returned wrong call type"),
            PluginResponse::Value(_) => panic!("returned wrong call type"),
            PluginResponse::PluginData(..) => panic!("returned wrong call type"),
        }
    }

    #[test]
    fn response_round_trip_error_none() {
        let error = LabeledError {
            label: "label".into(),
            msg: "msg".into(),
            span: None,
        };
        let response = PluginResponse::Error(error.clone());

        let encoder = JsonSerializer {};
        let mut buffer: Vec<u8> = Vec::new();
        encoder
            .encode_response(&response, &mut buffer)
            .expect("unable to serialize message");
        let returned = encoder
            .decode_response(&mut buffer.as_slice())
            .expect("unable to deserialize message");

        match returned {
            PluginResponse::Error(msg) => assert_eq!(error, msg),
            PluginResponse::Signature(_) => panic!("returned wrong call type"),
            PluginResponse::Value(_) => panic!("returned wrong call type"),
            PluginResponse::PluginData(..) => panic!("returned wrong call type"),
        }
    }
}