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