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