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_client_pool, http_parse_redirect_mode, http_parse_url,
5 request_add_authorization_header, request_add_custom_headers, request_handle_response,
6 request_set_timeout, send_request,
7};
8use nu_engine::command_prelude::*;
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 "Patch a body to a URL."
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::GenericError {
190 error: "Data must be provided either through pipeline or positional argument".into(),
191 msg: "".into(),
192 span: Some(call.head),
193 help: None,
194 inner: vec![],
195 });
196 };
197
198 let args = Arguments {
199 url: call.req(engine_state, stack, 0)?,
200 headers: call.get_flag(engine_state, stack, "headers")?,
201 data,
202 content_type,
203 raw: call.has_flag(engine_state, stack, "raw")?,
204 insecure: call.has_flag(engine_state, stack, "insecure")?,
205 user: call.get_flag(engine_state, stack, "user")?,
206 password: call.get_flag(engine_state, stack, "password")?,
207 timeout: call.get_flag(engine_state, stack, "max-time")?,
208 full: call.has_flag(engine_state, stack, "full")?,
209 allow_errors: call.has_flag(engine_state, stack, "allow-errors")?,
210 redirect: call.get_flag(engine_state, stack, "redirect-mode")?,
211 unix_socket: call.get_flag(engine_state, stack, "unix-socket")?,
212 pool: call.has_flag(engine_state, stack, "pool")?,
213 };
214
215 helper(engine_state, stack, call, args)
216}
217
218fn helper(
221 engine_state: &EngineState,
222 stack: &mut Stack,
223 call: &Call,
224 args: Arguments,
225) -> Result<PipelineData, ShellError> {
226 let span = args.url.span();
227 let Spanned {
228 item: (requested_url, _),
229 span: request_span,
230 } = http_parse_url(call, span, args.url)?;
231 let redirect_mode = http_parse_redirect_mode(args.redirect)?;
232
233 let cwd = engine_state.cwd(None)?;
234 let unix_socket_path = expand_unix_socket_path(args.unix_socket, &cwd);
235
236 let mut request = if args.pool {
237 http_client_pool(engine_state, stack).patch(&requested_url)
238 } else {
239 let client = http_client(
240 args.insecure,
241 redirect_mode,
242 unix_socket_path,
243 engine_state,
244 stack,
245 )?;
246 client.patch(&requested_url)
247 };
248
249 request = request_set_timeout(args.timeout, request)?;
250 request = request_add_authorization_header(args.user, args.password, request);
251 request = request_add_custom_headers(args.headers, request)?;
252
253 let (response, request_headers) = send_request(
254 engine_state,
255 request,
256 request_span,
257 args.data,
258 args.content_type,
259 call.head,
260 engine_state.signals(),
261 );
262
263 let request_flags = RequestFlags {
264 raw: args.raw,
265 full: args.full,
266 allow_errors: args.allow_errors,
267 };
268
269 let response = response?;
270
271 check_response_redirection(redirect_mode, span, &response)?;
272 request_handle_response(
273 engine_state,
274 stack,
275 RequestMetadata {
276 requested_url: &requested_url,
277 span,
278 headers: request_headers,
279 redirect_mode,
280 flags: request_flags,
281 },
282 response,
283 )
284}
285
286#[cfg(test)]
287mod tests {
288 use super::*;
289
290 #[test]
291 fn test_examples() {
292 use crate::test_examples;
293
294 test_examples(HttpPatch {})
295 }
296}