nu_command/network/url/
parse.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::Config;
3use url::Url;
4
5use super::query::query_string_to_table;
6
7#[derive(Clone)]
8pub struct UrlParse;
9
10impl Command for UrlParse {
11    fn name(&self) -> &str {
12        "url parse"
13    }
14
15    fn signature(&self) -> Signature {
16        Signature::build("url parse")
17            .input_output_types(vec![
18                (Type::String, Type::record()),
19                (Type::table(), Type::table()),
20                (Type::record(), Type::record()),
21            ])
22            .allow_variants_without_examples(true)
23            .rest(
24                "rest",
25                SyntaxShape::CellPath,
26                "Optionally operate by cell path.",
27            )
28            .category(Category::Network)
29    }
30
31    fn description(&self) -> &str {
32        "Parses a url."
33    }
34
35    fn search_terms(&self) -> Vec<&str> {
36        vec![
37            "scheme", "username", "password", "hostname", "port", "path", "query", "fragment",
38        ]
39    }
40
41    fn run(
42        &self,
43        engine_state: &EngineState,
44        stack: &mut Stack,
45        call: &Call,
46        input: PipelineData,
47    ) -> Result<PipelineData, ShellError> {
48        parse(
49            input.into_value(call.head)?,
50            call.head,
51            &stack.get_config(engine_state),
52        )
53    }
54
55    fn examples(&self) -> Vec<Example<'_>> {
56        vec![Example {
57            description: "Parses a url",
58            example: "'http://user123:pass567@www.example.com:8081/foo/bar?param1=section&p2=&f[name]=vldc&f[no]=42#hello' | url parse",
59            result: Some(Value::test_record(record! {
60                    "scheme" =>   Value::test_string("http"),
61                    "username" => Value::test_string("user123"),
62                    "password" => Value::test_string("pass567"),
63                    "host" =>     Value::test_string("www.example.com"),
64                    "port" =>     Value::test_string("8081"),
65                    "path" =>     Value::test_string("/foo/bar"),
66                    "query" =>    Value::test_string("param1=section&p2=&f[name]=vldc&f[no]=42"),
67                    "fragment" => Value::test_string("hello"),
68                    "params" =>   Value::test_list(vec![
69                        Value::test_record(record! {"key" => Value::test_string("param1"), "value" => Value::test_string("section") }),
70                        Value::test_record(record! {"key" => Value::test_string("p2"), "value" => Value::test_string("") }),
71                        Value::test_record(record! {"key" => Value::test_string("f[name]"), "value" => Value::test_string("vldc") }),
72                        Value::test_record(record! {"key" => Value::test_string("f[no]"), "value" => Value::test_string("42") }),
73                    ]),
74            })),
75        }]
76    }
77}
78
79fn get_url_string(value: &Value, config: &Config) -> String {
80    value.to_expanded_string("", config)
81}
82
83fn parse(value: Value, head: Span, config: &Config) -> Result<PipelineData, ShellError> {
84    let url_string = get_url_string(&value, config);
85
86    // This is the span of the original string, not the call head.
87    let span = value.span();
88
89    let url = Url::parse(url_string.as_str()).map_err(|_| ShellError::UnsupportedInput {
90        msg: "Incomplete or incorrect URL. Expected a full URL, e.g., https://www.example.com"
91            .to_string(),
92        input: "value originates from here".into(),
93        msg_span: head,
94        input_span: span,
95    })?;
96
97    let params = query_string_to_table(url.query().unwrap_or(""), head, span).map_err(|_| {
98        ShellError::UnsupportedInput {
99            msg: "String not compatible with url-encoding".to_string(),
100            input: "value originates from here".into(),
101            msg_span: head,
102            input_span: span,
103        }
104    })?;
105
106    let port = url.port().map(|p| p.to_string()).unwrap_or_default();
107
108    let record = record! {
109        "scheme" => Value::string(url.scheme(), head),
110        "username" => Value::string(url.username(), head),
111        "password" => Value::string(url.password().unwrap_or(""), head),
112        "host" => Value::string(url.host_str().unwrap_or(""), head),
113        "port" => Value::string(port, head),
114        "path" => Value::string(url.path(), head),
115        "query" => Value::string(url.query().unwrap_or(""), head),
116        "fragment" => Value::string(url.fragment().unwrap_or(""), head),
117        "params" => params,
118    };
119
120    Ok(PipelineData::value(Value::record(record, head), None))
121}
122
123#[cfg(test)]
124mod test {
125    use super::*;
126
127    #[test]
128    fn test_examples() {
129        use crate::test_examples;
130
131        test_examples(UrlParse {})
132    }
133}