nu_command/network/http/
patch.rs

1use crate::network::http::client::add_unix_socket_flag;
2use crate::network::http::client::{
3    HttpBody, RequestFlags, RequestMetadata, check_response_redirection, expand_unix_socket_path,
4    http_client, http_parse_redirect_mode, http_parse_url, request_add_authorization_header,
5    request_add_custom_headers, request_handle_response, request_set_timeout, send_request,
6};
7use nu_engine::command_prelude::*;
8
9#[derive(Clone)]
10pub struct HttpPatch;
11
12impl Command for HttpPatch {
13    fn name(&self) -> &str {
14        "http patch"
15    }
16
17    fn signature(&self) -> Signature {
18        let sig = Signature::build("http patch")
19            .input_output_types(vec![(Type::Any, Type::Any)])
20            .allow_variants_without_examples(true)
21            .required("URL", SyntaxShape::String, "The URL to post to.")
22            .optional("data", SyntaxShape::Any, "The contents of the post body.")
23            .named(
24                "user",
25                SyntaxShape::Any,
26                "the username when authenticating",
27                Some('u'),
28            )
29            .named(
30                "password",
31                SyntaxShape::Any,
32                "the password when authenticating",
33                Some('p'),
34            )
35            .named(
36                "content-type",
37                SyntaxShape::Any,
38                "the MIME type of content to post",
39                Some('t'),
40            )
41            .named(
42                "max-time",
43                SyntaxShape::Duration,
44                "max duration before timeout occurs",
45                Some('m'),
46            )
47            .named(
48                "headers",
49                SyntaxShape::Any,
50                "custom headers you want to add ",
51                Some('H'),
52            )
53            .switch(
54                "raw",
55                "return values as a string instead of a table",
56                Some('r'),
57            )
58            .switch(
59                "insecure",
60                "allow insecure server connections when using SSL",
61                Some('k'),
62            )
63            .switch(
64                "full",
65                "returns the full response instead of only the body",
66                Some('f'),
67            )
68            .switch(
69                "allow-errors",
70                "do not fail if the server returns an error code",
71                Some('e'),
72            )
73            .param(
74                Flag::new("redirect-mode")
75                    .short('R')
76                    .arg(SyntaxShape::String)
77                    .desc(
78                        "What to do when encountering redirects. Default: 'follow'. Valid \
79                         options: 'follow' ('f'), 'manual' ('m'), 'error' ('e').",
80                    )
81                    .completion(nu_protocol::Completion::new_list(
82                        super::client::RedirectMode::MODES,
83                    )),
84            )
85            .filter()
86            .category(Category::Network);
87
88        add_unix_socket_flag(sig)
89    }
90
91    fn description(&self) -> &str {
92        "Patch a body to a URL."
93    }
94
95    fn extra_description(&self) -> &str {
96        "Performs HTTP PATCH operation."
97    }
98
99    fn search_terms(&self) -> Vec<&str> {
100        vec!["network", "send", "push"]
101    }
102
103    fn run(
104        &self,
105        engine_state: &EngineState,
106        stack: &mut Stack,
107        call: &Call,
108        input: PipelineData,
109    ) -> Result<PipelineData, ShellError> {
110        run_patch(engine_state, stack, call, input)
111    }
112
113    fn examples(&self) -> Vec<Example<'_>> {
114        vec![
115            Example {
116                description: "Patch content to example.com",
117                example: "http patch https://www.example.com 'body'",
118                result: None,
119            },
120            Example {
121                description: "Patch content to example.com, with username and password",
122                example: "http patch --user myuser --password mypass https://www.example.com 'body'",
123                result: None,
124            },
125            Example {
126                description: "Patch content to example.com, with custom header using a record",
127                example: "http patch --headers {my-header-key: my-header-value} https://www.example.com",
128                result: None,
129            },
130            Example {
131                description: "Patch content to example.com, with custom header using a list",
132                example: "http patch --headers [my-header-key-A my-header-value-A my-header-key-B my-header-value-B] https://www.example.com",
133                result: None,
134            },
135            Example {
136                description: "Patch content to example.com, with JSON body",
137                example: "http patch --content-type application/json https://www.example.com { field: value }",
138                result: None,
139            },
140            Example {
141                description: "Patch JSON content from a pipeline to example.com",
142                example: "open --raw foo.json | http patch https://www.example.com",
143                result: None,
144            },
145        ]
146    }
147}
148
149struct Arguments {
150    url: Value,
151    headers: Option<Value>,
152    data: HttpBody,
153    content_type: Option<String>,
154    raw: bool,
155    insecure: bool,
156    user: Option<String>,
157    password: Option<String>,
158    timeout: Option<Value>,
159    full: bool,
160    allow_errors: bool,
161    redirect: Option<Spanned<String>>,
162    unix_socket: Option<Spanned<String>>,
163}
164
165fn run_patch(
166    engine_state: &EngineState,
167    stack: &mut Stack,
168    call: &Call,
169    input: PipelineData,
170) -> Result<PipelineData, ShellError> {
171    let (data, maybe_metadata) = call
172        .opt::<Value>(engine_state, stack, 1)?
173        .map(|v| (Some(HttpBody::Value(v)), None))
174        .unwrap_or_else(|| match input {
175            PipelineData::Value(v, metadata) => (Some(HttpBody::Value(v)), metadata),
176            PipelineData::ByteStream(byte_stream, metadata) => {
177                (Some(HttpBody::ByteStream(byte_stream)), metadata)
178            }
179            _ => (None, None),
180        });
181    let content_type = call
182        .get_flag(engine_state, stack, "content-type")?
183        .or_else(|| maybe_metadata.and_then(|m| m.content_type));
184
185    let Some(data) = data else {
186        return Err(ShellError::GenericError {
187            error: "Data must be provided either through pipeline or positional argument".into(),
188            msg: "".into(),
189            span: Some(call.head),
190            help: None,
191            inner: vec![],
192        });
193    };
194
195    let args = Arguments {
196        url: call.req(engine_state, stack, 0)?,
197        headers: call.get_flag(engine_state, stack, "headers")?,
198        data,
199        content_type,
200        raw: call.has_flag(engine_state, stack, "raw")?,
201        insecure: call.has_flag(engine_state, stack, "insecure")?,
202        user: call.get_flag(engine_state, stack, "user")?,
203        password: call.get_flag(engine_state, stack, "password")?,
204        timeout: call.get_flag(engine_state, stack, "max-time")?,
205        full: call.has_flag(engine_state, stack, "full")?,
206        allow_errors: call.has_flag(engine_state, stack, "allow-errors")?,
207        redirect: call.get_flag(engine_state, stack, "redirect-mode")?,
208        unix_socket: call.get_flag(engine_state, stack, "unix-socket")?,
209    };
210
211    helper(engine_state, stack, call, args)
212}
213
214// Helper function that actually goes to retrieve the resource from the url given
215// The Option<String> return a possible file extension which can be used in AutoConvert commands
216fn helper(
217    engine_state: &EngineState,
218    stack: &mut Stack,
219    call: &Call,
220    args: Arguments,
221) -> Result<PipelineData, ShellError> {
222    let span = args.url.span();
223    let Spanned {
224        item: (requested_url, _),
225        span: request_span,
226    } = http_parse_url(call, span, args.url)?;
227    let redirect_mode = http_parse_redirect_mode(args.redirect)?;
228
229    let cwd = engine_state.cwd(None)?;
230    let unix_socket_path = expand_unix_socket_path(args.unix_socket, &cwd);
231
232    let client = http_client(
233        args.insecure,
234        redirect_mode,
235        unix_socket_path,
236        engine_state,
237        stack,
238    )?;
239    let mut request = client.patch(&requested_url);
240
241    request = request_set_timeout(args.timeout, request)?;
242    request = request_add_authorization_header(args.user, args.password, request);
243    request = request_add_custom_headers(args.headers, request)?;
244
245    let (response, request_headers) = send_request(
246        engine_state,
247        request,
248        request_span,
249        args.data,
250        args.content_type,
251        call.head,
252        engine_state.signals(),
253    );
254
255    let request_flags = RequestFlags {
256        raw: args.raw,
257        full: args.full,
258        allow_errors: args.allow_errors,
259    };
260
261    let response = response?;
262
263    check_response_redirection(redirect_mode, span, &response)?;
264    request_handle_response(
265        engine_state,
266        stack,
267        RequestMetadata {
268            requested_url: &requested_url,
269            span,
270            headers: request_headers,
271            redirect_mode,
272            flags: request_flags,
273        },
274        response,
275    )
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281
282    #[test]
283    fn test_examples() {
284        use crate::test_examples;
285
286        test_examples(HttpPatch {})
287    }
288}