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
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
    Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, Type, Value,
};

#[derive(Clone)]
pub struct SubCommand;

impl Command for SubCommand {
    fn name(&self) -> &str {
        "url join"
    }

    fn signature(&self) -> nu_protocol::Signature {
        Signature::build("url join")
            .input_output_types(vec![(Type::Record(vec![]), Type::String)])
            .category(Category::Network)
    }

    fn usage(&self) -> &str {
        "Converts a record to url."
    }

    fn search_terms(&self) -> Vec<&str> {
        vec![
            "scheme", "username", "password", "hostname", "port", "path", "query", "fragment",
        ]
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Outputs a url representing the contents of this record",
                example: r#"{
        "scheme": "http",
        "username": "",
        "password": "",
        "host": "www.pixiv.net",
        "port": "",
        "path": "/member_illust.php",
        "query": "mode=medium&illust_id=99260204",
        "fragment": "",
        "params":
        {
            "mode": "medium",
            "illust_id": "99260204"
        }
    } | url join"#,
                result: Some(Value::test_string(
                    "http://www.pixiv.net/member_illust.php?mode=medium&illust_id=99260204",
                )),
            },
            Example {
                description: "Outputs a url representing the contents of this record",
                example: r#"{
        "scheme": "http",
        "username": "user",
        "password": "pwd",
        "host": "www.pixiv.net",
        "port": "1234",
        "query": "test=a",
        "fragment": ""
    } | url join"#,
                result: Some(Value::test_string(
                    "http://user:pwd@www.pixiv.net:1234?test=a",
                )),
            },
            Example {
                description: "Outputs a url representing the contents of this record",
                example: r#"{
        "scheme": "http",
        "host": "www.pixiv.net",
        "port": "1234",
        "path": "user",
        "fragment": "frag"
    } | url join"#,
                result: Some(Value::test_string("http://www.pixiv.net:1234/user#frag")),
            },
        ]
    }

    fn run(
        &self,
        _engine_state: &EngineState,
        _stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        let head = call.head;

        let output: Result<String, ShellError> = input
            .into_iter()
            .map(move |value| {
                let span = value.span();
                match value {
                    Value::Record { val, .. } => {
                        let url_components = val
                            .into_iter()
                            .try_fold(UrlComponents::new(), |url, (k, v)| {
                                url.add_component(k, v, span)
                            });

                        url_components?.to_url(span)
                    }
                    Value::Error { error, .. } => Err(*error),
                    other => Err(ShellError::UnsupportedInput(
                        "Expected a record from pipeline".to_string(),
                        "value originates from here".into(),
                        head,
                        other.span(),
                    )),
                }
            })
            .collect();

        Ok(Value::string(output?, head).into_pipeline_data())
    }
}

#[derive(Default)]
struct UrlComponents {
    scheme: Option<String>,
    username: Option<String>,
    password: Option<String>,
    host: Option<String>,
    port: Option<i64>,
    path: Option<String>,
    query: Option<String>,
    fragment: Option<String>,
    query_span: Option<Span>,
    params_span: Option<Span>,
}

impl UrlComponents {
    fn new() -> Self {
        Default::default()
    }

    pub fn add_component(self, key: String, value: Value, _span: Span) -> Result<Self, ShellError> {
        let span = value.span();
        if key == "port" {
            return match value {
                Value::String { val, .. } => {
                    if val.trim().is_empty() {
                        Ok(self)
                    } else {
                        match val.parse::<i64>() {
                            Ok(p) => Ok(Self {
                                port: Some(p),
                                ..self
                            }),
                            Err(_) => Err(ShellError::IncompatibleParametersSingle {
                                msg: String::from(
                                    "Port parameter should represent an unsigned integer",
                                ),
                                span,
                            }),
                        }
                    }
                }
                Value::Int { val, .. } => Ok(Self {
                    port: Some(val),
                    ..self
                }),
                Value::Error { error, .. } => Err(*error),
                other => Err(ShellError::IncompatibleParametersSingle {
                    msg: String::from(
                        "Port parameter should be an unsigned integer or a string representing it",
                    ),
                    span: other.span(),
                }),
            };
        }

        if key == "params" {
            return match value {
                Value::Record { ref val, .. } => {
                    let mut qs = val
                        .iter()
                        .map(|(k, v)| match v.as_string() {
                            Ok(val) => Ok(format!("{k}={val}")),
                            Err(err) => Err(err),
                        })
                        .collect::<Result<Vec<String>, ShellError>>()?
                        .join("&");

                    qs = if !qs.trim().is_empty() {
                        format!("?{qs}")
                    } else {
                        qs
                    };

                    if let Some(q) = self.query {
                        if q != qs {
                            // if query is present it means that also query_span is set.
                            return Err(ShellError::IncompatibleParameters {
                                left_message: format!("Mismatch, qs from params is: {qs}"),
                                left_span: value.span(),
                                right_message: format!("instead query is: {q}"),
                                right_span: self.query_span.unwrap_or(Span::unknown()),
                            });
                        }
                    }

                    Ok(Self {
                        query: Some(qs),
                        params_span: Some(span),
                        ..self
                    })
                }
                Value::Error { error, .. } => Err(*error),
                other => Err(ShellError::IncompatibleParametersSingle {
                    msg: String::from("Key params has to be a record"),
                    span: other.span(),
                }),
            };
        }

        // a part from port and params all other keys are strings.
        match value.as_string() {
            Ok(s) => {
                if s.trim().is_empty() {
                    Ok(self)
                } else {
                    match key.as_str() {
                        "host" => Ok(Self {
                            host: Some(s),
                            ..self
                        }),
                        "scheme" => Ok(Self {
                            scheme: Some(s),
                            ..self
                        }),
                        "username" => Ok(Self {
                            username: Some(s),
                            ..self
                        }),
                        "password" => Ok(Self {
                            password: Some(s),
                            ..self
                        }),
                        "path" => Ok(Self {
                            path: Some(if s.starts_with('/') {
                                s
                            } else {
                                format!("/{s}")
                            }),
                            ..self
                        }),
                        "query" => {
                            if let Some(q) = self.query {
                                if q != s {
                                    // if query is present it means that also params_span is set.
                                    return Err(ShellError::IncompatibleParameters {
                                        left_message: format!("Mismatch, query param is: {s}"),
                                        left_span: value.span(),
                                        right_message: format!("instead qs from params is: {q}"),
                                        right_span: self.params_span.unwrap_or(Span::unknown()),
                                    });
                                }
                            }

                            Ok(Self {
                                query: Some(format!("?{s}")),
                                query_span: Some(value.span()),
                                ..self
                            })
                        }
                        "fragment" => Ok(Self {
                            fragment: Some(if s.starts_with('#') {
                                s
                            } else {
                                format!("#{s}")
                            }),
                            ..self
                        }),
                        _ => Ok(self),
                    }
                }
            }
            _ => Ok(self),
        }
    }

    pub fn to_url(&self, span: Span) -> Result<String, ShellError> {
        let mut user_and_pwd: String = String::from("");

        if let Some(usr) = &self.username {
            if let Some(pwd) = &self.password {
                user_and_pwd = format!("{usr}:{pwd}@");
            }
        }

        let scheme_result = match &self.scheme {
            Some(s) => Ok(s),
            None => Err(UrlComponents::generate_shell_error_for_missing_parameter(
                String::from("scheme"),
                span,
            )),
        };

        let host_result = match &self.host {
            Some(h) => Ok(h),
            None => Err(UrlComponents::generate_shell_error_for_missing_parameter(
                String::from("host"),
                span,
            )),
        };

        Ok(format!(
            "{}://{}{}{}{}{}{}",
            scheme_result?,
            user_and_pwd,
            host_result?,
            self.port
                .map(|p| format!(":{p}"))
                .as_deref()
                .unwrap_or_default(),
            self.path.as_deref().unwrap_or_default(),
            self.query.as_deref().unwrap_or_default(),
            self.fragment.as_deref().unwrap_or_default()
        ))
    }

    fn generate_shell_error_for_missing_parameter(pname: String, span: Span) -> ShellError {
        ShellError::MissingParameter {
            param_name: pname,
            span,
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_examples() {
        use crate::test_examples;

        test_examples(SubCommand {})
    }
}