1use crate::network::http::client::{
2 HttpBody, RequestFlags, check_response_redirection, http_client, http_parse_redirect_mode,
3 http_parse_url, request_add_authorization_header, request_add_custom_headers,
4 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 ).named(
72 "redirect-mode",
73 SyntaxShape::String,
74 "What to do when encountering redirects. Default: 'follow'. Valid options: 'follow' ('f'), 'manual' ('m'), 'error' ('e').",
75 Some('R')
76 )
77 .filter()
78 .category(Category::Network)
79 }
80
81 fn description(&self) -> &str {
82 "Patch a body to a URL."
83 }
84
85 fn extra_description(&self) -> &str {
86 "Performs HTTP PATCH operation."
87 }
88
89 fn search_terms(&self) -> Vec<&str> {
90 vec!["network", "send", "push"]
91 }
92
93 fn run(
94 &self,
95 engine_state: &EngineState,
96 stack: &mut Stack,
97 call: &Call,
98 input: PipelineData,
99 ) -> Result<PipelineData, ShellError> {
100 run_patch(engine_state, stack, call, input)
101 }
102
103 fn examples(&self) -> Vec<Example> {
104 vec![
105 Example {
106 description: "Patch content to example.com",
107 example: "http patch https://www.example.com 'body'",
108 result: None,
109 },
110 Example {
111 description: "Patch content to example.com, with username and password",
112 example: "http patch --user myuser --password mypass https://www.example.com 'body'",
113 result: None,
114 },
115 Example {
116 description: "Patch content to example.com, with custom header using a record",
117 example: "http patch --headers {my-header-key: my-header-value} https://www.example.com",
118 result: None,
119 },
120 Example {
121 description: "Patch content to example.com, with custom header using a list",
122 example: "http patch --headers [my-header-key-A my-header-value-A my-header-key-B my-header-value-B] https://www.example.com",
123 result: None,
124 },
125 Example {
126 description: "Patch content to example.com, with JSON body",
127 example: "http patch --content-type application/json https://www.example.com { field: value }",
128 result: None,
129 },
130 Example {
131 description: "Patch JSON content from a pipeline to example.com",
132 example: "open --raw foo.json | http patch https://www.example.com",
133 result: None,
134 },
135 ]
136 }
137}
138
139struct Arguments {
140 url: Value,
141 headers: Option<Value>,
142 data: HttpBody,
143 content_type: Option<String>,
144 raw: bool,
145 insecure: bool,
146 user: Option<String>,
147 password: Option<String>,
148 timeout: Option<Value>,
149 full: bool,
150 allow_errors: bool,
151 redirect: Option<Spanned<String>>,
152}
153
154fn run_patch(
155 engine_state: &EngineState,
156 stack: &mut Stack,
157 call: &Call,
158 input: PipelineData,
159) -> Result<PipelineData, ShellError> {
160 let (data, maybe_metadata) = call
161 .opt::<Value>(engine_state, stack, 1)?
162 .map(|v| (HttpBody::Value(v), None))
163 .unwrap_or_else(|| match input {
164 PipelineData::Value(v, metadata) => (HttpBody::Value(v), metadata),
165 PipelineData::ByteStream(byte_stream, metadata) => {
166 (HttpBody::ByteStream(byte_stream), metadata)
167 }
168 _ => (HttpBody::None, None),
169 });
170 let content_type = call
171 .get_flag(engine_state, stack, "content-type")?
172 .or_else(|| maybe_metadata.and_then(|m| m.content_type));
173
174 if let HttpBody::None = data {
175 return Err(ShellError::GenericError {
176 error: "Data must be provided either through pipeline or positional argument".into(),
177 msg: "".into(),
178 span: Some(call.head),
179 help: None,
180 inner: vec![],
181 });
182 }
183
184 let args = Arguments {
185 url: call.req(engine_state, stack, 0)?,
186 headers: call.get_flag(engine_state, stack, "headers")?,
187 data,
188 content_type,
189 raw: call.has_flag(engine_state, stack, "raw")?,
190 insecure: call.has_flag(engine_state, stack, "insecure")?,
191 user: call.get_flag(engine_state, stack, "user")?,
192 password: call.get_flag(engine_state, stack, "password")?,
193 timeout: call.get_flag(engine_state, stack, "max-time")?,
194 full: call.has_flag(engine_state, stack, "full")?,
195 allow_errors: call.has_flag(engine_state, stack, "allow-errors")?,
196 redirect: call.get_flag(engine_state, stack, "redirect-mode")?,
197 };
198
199 helper(engine_state, stack, call, args)
200}
201
202fn helper(
205 engine_state: &EngineState,
206 stack: &mut Stack,
207 call: &Call,
208 args: Arguments,
209) -> Result<PipelineData, ShellError> {
210 let span = args.url.span();
211 let (requested_url, _) = http_parse_url(call, span, args.url)?;
212 let redirect_mode = http_parse_redirect_mode(args.redirect)?;
213
214 let client = http_client(args.insecure, redirect_mode, engine_state, stack)?;
215 let mut request = client.patch(&requested_url);
216
217 request = request_set_timeout(args.timeout, request)?;
218 request = request_add_authorization_header(args.user, args.password, request);
219 request = request_add_custom_headers(args.headers, request)?;
220
221 let response = send_request(
222 engine_state,
223 request.clone(),
224 args.data,
225 args.content_type,
226 call.head,
227 engine_state.signals(),
228 );
229
230 let request_flags = RequestFlags {
231 raw: args.raw,
232 full: args.full,
233 allow_errors: args.allow_errors,
234 };
235
236 check_response_redirection(redirect_mode, span, &response)?;
237 request_handle_response(
238 engine_state,
239 stack,
240 span,
241 &requested_url,
242 request_flags,
243 response,
244 request,
245 )
246}
247
248#[cfg(test)]
249mod tests {
250 use super::*;
251
252 #[test]
253 fn test_examples() {
254 use crate::test_examples;
255
256 test_examples(HttpPatch {})
257 }
258}