1use std::path::PathBuf;
2
3use anyhow::{Context, Result};
4use clap::{Args, Parser, Subcommand};
5use duration_string::DurationString;
6use secrecy::SecretString;
7use serde::Deserialize;
8use url::Url;
9
10use crate::{
11 builder::{QuestClientBuilder, QuestRequestBuilder},
12 quest::{QuestCommand, QuestFile, QuestUrl},
13 types::{FormField, StringOrFile},
14};
15
16#[derive(Clone, Debug, Parser)]
17#[command(name = "quest")]
18#[command(version, about = "Cli for all the http fetch (re)quests you may go on.", long_about = None)]
19pub struct QuestCli {
20 #[arg(
21 short,
22 long,
23 global = true,
24 default_value = ".env",
25 help = "Load environment variables from file"
26 )]
27 env: PathBuf,
28 #[clap(flatten)]
29 pub options: RequestOptions,
30
31 #[command(subcommand)]
32 command: Command,
33}
34
35impl QuestCli {
36 pub fn init_logging(self) -> Self {
37 env_logger::init();
38 self
39 }
40 fn list_quests(quest_file: QuestFile) -> Result<()> {
41 use colored::Colorize;
42 use std::io::Write;
43
44 let mut quest_data: Vec<(String, String, String)> = Vec::new();
46
47 for (name, command) in quest_file.iter() {
48 let (method, url) = match command {
49 QuestCommand::Get { url_spec, .. } => ("GET", url_spec.to_url()?),
50 QuestCommand::Post { url_spec, .. } => ("POST", url_spec.to_url()?),
51 QuestCommand::Put { url_spec, .. } => ("PUT", url_spec.to_url()?),
52 QuestCommand::Delete { url_spec, .. } => ("DELETE", url_spec.to_url()?),
53 QuestCommand::Patch { url_spec, .. } => ("PATCH", url_spec.to_url()?),
54 };
55
56 quest_data.push((name.clone(), method.to_string(), url.to_string()));
57 }
58
59 let stdout = std::io::stdout();
60 let mut handle = stdout.lock();
61
62 if quest_data.is_empty() {
63 writeln!(handle, "No quests found in the quest file.")?;
64 return Ok(());
65 }
66
67 let max_name_width = quest_data
69 .iter()
70 .map(|(name, _, _)| name.len())
71 .max()
72 .unwrap_or(4)
73 .max(4); let max_method_width = 6; writeln!(
79 handle,
80 "{:<name_width$} {:<method_width$} {}",
81 "NAME".bold(),
82 "METHOD".bold(),
83 "URL".bold(),
84 name_width = max_name_width,
85 method_width = max_method_width
86 )?;
87
88 writeln!(
90 handle,
91 "{} {} {}",
92 "─".repeat(max_name_width),
93 "─".repeat(max_method_width),
94 "─".repeat(40)
95 )?;
96
97 for (name, method, url) in quest_data {
99 let colored_method = match method.as_str() {
100 "GET" => method.green().bold(),
101 "POST" => method.blue().bold(),
102 "PUT" => method.yellow().bold(),
103 "DELETE" => method.red().bold(),
104 "PATCH" => method.magenta().bold(),
105 _ => method.white().bold(),
106 };
107
108 writeln!(
109 handle,
110 "{:<name_width$} {:<method_width$} {}",
111 name.cyan(),
112 colored_method,
113 url.bright_black(),
114 name_width = max_name_width,
115 method_width = max_method_width
116 )?;
117 }
118
119 handle.flush()?;
120 Ok(())
121 }
122
123 pub fn execute(self) -> Result<()> {
124 if self.env.exists() {
126 dotenvy::from_path(&self.env).ok();
127 log::debug!("Loaded environment variables from {}", self.env.display());
128 }
129
130 let options = self.options;
131 match self.command {
132 Command::List { file } => {
133 let quest_file = QuestFile::load(&file)
135 .with_context(|| format!("Failed to load quest file: {}", file.display()))?;
136
137 Self::list_quests(quest_file)?;
138 Ok(())
139 }
140 Command::Go { name, file } => {
141 let quest_file = QuestFile::load(&file)
143 .with_context(|| format!("Failed to load quest file: {}", file.display()))?;
144
145 let quest_command = quest_file
147 .get(&name)
148 .ok_or_else(|| anyhow::anyhow!("Quest '{}' not found.", name))?
149 .clone();
150
151 log::info!("Executing quest '{}' from {}", name, file.display());
153 Self::execute_quest_command(options, quest_command)
154 }
155 Command::Get { url } => {
156 let quest = QuestCommand::Get {
157 url_spec: QuestUrl::Direct { url },
158 options: RequestOptions::default(),
159 };
160 Self::execute_quest_command(options, quest)
161 }
162 Command::Post { url, body } => {
163 let quest = QuestCommand::Post {
164 url_spec: QuestUrl::Direct { url },
165 body,
166 options: RequestOptions::default(),
167 };
168 Self::execute_quest_command(options, quest)
169 }
170 Command::Put { url, body } => {
171 let quest = QuestCommand::Put {
172 url_spec: QuestUrl::Direct { url },
173 body,
174 options: RequestOptions::default(),
175 };
176 Self::execute_quest_command(options, quest)
177 }
178 Command::Delete { url } => {
179 let quest = QuestCommand::Delete {
180 url_spec: QuestUrl::Direct { url },
181 options: RequestOptions::default(),
182 };
183 Self::execute_quest_command(options, quest)
184 }
185 Command::Patch { url, body } => {
186 let quest = QuestCommand::Patch {
187 url_spec: QuestUrl::Direct { url },
188 body,
189 options: RequestOptions::default(),
190 };
191 Self::execute_quest_command(options, quest)
192 }
193 }
194 }
195
196 fn log_request_verbose(
197 url: &Url,
198 method: &str,
199 headers: &HeaderOptions,
200 auth: &AuthOptions,
201 ) -> Result<()> {
202 use colored::Colorize;
203 use std::io::Write;
204
205 let stderr = std::io::stderr();
206 let mut handle = stderr.lock();
207
208 writeln!(
210 handle,
211 "{} {} HTTP/1.1",
212 method.cyan().bold(),
213 url.as_str().cyan().bold()
214 )?;
215
216 writeln!(
218 handle,
219 "{} {}",
220 "Host:".blue(),
221 url.host_str().unwrap_or("unknown")
222 )?;
223
224 if let Some(user_agent) = &headers.user_agent {
226 writeln!(handle, "{} {}", "User-Agent:".blue(), user_agent)?;
227 } else {
228 writeln!(handle, "{} quest/0.1.0", "User-Agent:".blue())?;
229 }
230
231 for header in &headers.header {
232 if let Some((key, value)) = header.split_once(':') {
233 writeln!(
234 handle,
235 "{} {}",
236 format!("{}:", key.trim()).blue(),
237 value.trim()
238 )?;
239 }
240 }
241
242 if auth.bearer.is_some() {
244 writeln!(handle, "{} Bearer [REDACTED]", "Authorization:".blue())?;
245 } else if auth.auth.is_some() || auth.basic.is_some() {
246 writeln!(handle, "{} Basic [REDACTED]", "Authorization:".blue())?;
247 }
248
249 if let Some(referer) = &headers.referer {
251 writeln!(handle, "{} {}", "Referer:".blue(), referer)?;
252 }
253
254 if let Some(accept) = &headers.accept {
255 writeln!(handle, "{} {}", "Accept:".blue(), accept)?;
256 }
257
258 if let Some(content_type) = &headers.content_type {
259 writeln!(handle, "{} {}", "Content-Type:".blue(), content_type)?;
260 }
261
262 writeln!(handle)?;
263 handle.flush()?;
264 Ok(())
265 }
266
267 fn log_response_verbose(response: &reqwest::blocking::Response) -> Result<()> {
268 use colored::Colorize;
269 use std::io::Write;
270
271 let stderr = std::io::stderr();
272 let mut handle = stderr.lock();
273
274 let status = response.status();
276 let status_line = format!(
277 "HTTP/1.1 {} {}",
278 status.as_u16(),
279 status.canonical_reason().unwrap_or("")
280 );
281
282 if status.is_success() {
283 writeln!(handle, "{}", status_line.green().bold())?;
284 } else if status.is_client_error() || status.is_server_error() {
285 writeln!(handle, "{}", status_line.red().bold())?;
286 } else {
287 writeln!(handle, "{}", status_line.cyan().bold())?;
288 }
289
290 for (name, value) in response.headers() {
292 if let Ok(val_str) = value.to_str() {
293 writeln!(handle, "{} {}", format!("{}:", name).cyan(), val_str)?;
294 }
295 }
296
297 writeln!(handle)?;
298 handle.flush()?;
299 Ok(())
300 }
301
302 fn execute_quest_command(cli_options: RequestOptions, quest: QuestCommand) -> Result<()> {
303 let mut quest_options = match &quest {
305 QuestCommand::Get { options, .. } => options,
306 QuestCommand::Post { options, .. } => options,
307 QuestCommand::Put { options, .. } => options,
308 QuestCommand::Delete { options, .. } => options,
309 QuestCommand::Patch { options, .. } => options,
310 }
311 .clone();
312 quest_options.merge_with(&cli_options);
313
314 let client = QuestClientBuilder::new().apply(&quest_options)?.build()?;
316
317 let (request_builder, body_options, method, url) = match &quest {
319 QuestCommand::Get { url_spec, .. } => {
320 let url = url_spec.to_url()?;
321 (client.get(url.as_str()), None, "GET", url)
322 }
323 QuestCommand::Post { url_spec, body, .. } => {
324 let url = url_spec.to_url()?;
325 (client.post(url.as_str()), Some(body.clone()), "POST", url)
326 }
327 QuestCommand::Put { url_spec, body, .. } => {
328 let url = url_spec.to_url()?;
329 (client.put(url.as_str()), Some(body.clone()), "PUT", url)
330 }
331 QuestCommand::Delete { url_spec, .. } => {
332 let url = url_spec.to_url()?;
333 (client.delete(url.as_str()), None, "DELETE", url)
334 }
335 QuestCommand::Patch { url_spec, body, .. } => {
336 let url = url_spec.to_url()?;
337 (client.patch(url.as_str()), Some(body.clone()), "PATCH", url)
338 }
339 };
340
341 if quest_options.output.verbose {
343 Self::log_request_verbose(
344 &url,
345 method,
346 &quest_options.headers,
347 &quest_options.authorization,
348 )?;
349 }
350
351 let mut request =
353 QuestRequestBuilder::from_request(request_builder).apply(&quest_options)?;
354
355 if let Some(body) = body_options {
357 request = request.apply(&body)?;
358 }
359
360 let response = request.send()?;
362
363 Self::handle_response(response, &quest_options.output)?;
365
366 Ok(())
367 }
368
369 fn handle_response(
370 response: reqwest::blocking::Response,
371 output_opts: &OutputOptions,
372 ) -> Result<()> {
373 use std::io::Write;
374
375 let mut output_parts = Vec::new();
377
378 if output_opts.include {
380 let status_line = format!(
381 "HTTP/1.1 {} {}\n",
382 response.status().as_u16(),
383 response.status().canonical_reason().unwrap_or("")
384 );
385 output_parts.push(status_line);
386
387 for (name, value) in response.headers() {
388 if let Ok(val_str) = value.to_str() {
389 output_parts.push(format!("{}: {}\n", name, val_str));
390 }
391 }
392 output_parts.push("\n".to_string());
393 }
394
395 if output_opts.verbose {
396 Self::log_response_verbose(&response)?;
397 }
398
399 let body_text = if response
401 .headers()
402 .get("content-type")
403 .and_then(|v| v.to_str().ok())
404 .map(|ct| ct.contains("application/json") || ct.contains("application/vnd.api+json"))
405 .unwrap_or(false)
406 && !output_opts.simple
407 {
408 let json_value = response.json::<serde_json::Value>()?;
410 colored_json::to_colored_json_auto(&json_value)?
411 } else {
412 response.text()?
414 };
415
416 output_parts.push(body_text);
417
418 let full_output = output_parts.join("");
419
420 if let Some(output_file) = &output_opts.output {
422 let mut file = std::fs::File::create(output_file).with_context(|| {
423 format!("Failed to create output file: {}", output_file.display())
424 })?;
425 file.write_all(full_output.as_bytes())?;
426 } else {
427 println!("{full_output}");
428 }
429
430 Ok(())
431 }
432}
433
434#[derive(Debug, Subcommand, Clone)]
435pub enum Command {
436 Get {
437 url: Url,
438 },
439 Post {
440 url: Url,
441 #[clap(flatten)]
442 body: BodyOptions,
443 },
444 Put {
445 url: Url,
446 #[clap(flatten)]
447 body: BodyOptions,
448 },
449 Delete {
450 url: Url,
451 },
452 Patch {
453 url: Url,
454 #[clap(flatten)]
455 body: BodyOptions,
456 },
457 Go {
459 name: String,
461
462 #[arg(
463 short,
464 long,
465 default_value = ".quests.yaml",
466 help = "Quest file to load from"
467 )]
468 file: PathBuf,
469 },
470 List {
472 #[arg(
473 short,
474 long,
475 default_value = ".quests.yaml",
476 help = "Quest file to load from"
477 )]
478 file: PathBuf,
479 },
480}
481
482#[derive(Debug, Args, Clone, Default, Deserialize)]
483#[serde(default)]
484pub struct RequestOptions {
485 #[serde(flatten)]
486 #[clap(flatten)]
487 pub authorization: AuthOptions,
488 #[serde(flatten)]
489 #[clap(flatten)]
490 pub headers: HeaderOptions,
491 #[serde(flatten)]
492 #[clap(flatten)]
493 pub params: ParamOptions,
494 #[serde(flatten)]
495 #[clap(flatten)]
496 pub timeouts: TimeoutOptions,
497 #[serde(flatten)]
498 #[clap(flatten)]
499 pub redirects: RedirectOptions,
500 #[serde(flatten)]
501 #[clap(flatten)]
502 pub tls: TlsOptions,
503 #[serde(flatten)]
504 #[clap(flatten)]
505 pub proxy: ProxyOptions,
506 #[serde(flatten)]
507 #[clap(flatten)]
508 pub output: OutputOptions,
509 #[serde(flatten)]
510 #[clap(flatten)]
511 pub compression: CompressionOptions,
512}
513
514#[derive(Debug, Args, Clone, Default, Deserialize)]
515#[serde(default)]
516pub struct AuthOptions {
517 #[arg(short, long, global = true)]
518 pub auth: Option<SecretString>,
519 #[arg(long, global = true)]
520 pub basic: Option<SecretString>,
521 #[arg(long, global = true)]
522 pub bearer: Option<SecretString>,
523}
524
525#[derive(Debug, Args, Clone, Default, Deserialize)]
526#[serde(default)]
527pub struct HeaderOptions {
528 #[serde(rename = "headers")]
529 #[arg(
530 short = 'H',
531 long = "header",
532 global = true,
533 help = "Custom header (repeatable)"
534 )]
535 pub header: Vec<String>,
536 #[arg(
537 short = 'U',
538 long = "user-agent",
539 global = true,
540 help = "Set User-Agent header"
541 )]
542 pub user_agent: Option<String>,
543 #[arg(
544 short = 'R',
545 long = "referer",
546 global = true,
547 help = "Set Referer header"
548 )]
549 pub referer: Option<String>,
550 #[arg(long = "content-type", global = true, help = "Set Content-Type header")]
551 pub content_type: Option<String>,
552 #[arg(long = "accept", global = true, help = "Set Accept header")]
553 pub accept: Option<String>,
554}
555
556#[derive(Debug, Args, Clone, Default, Deserialize)]
557#[serde(default)]
558pub struct ParamOptions {
559 #[serde(rename = "params")]
560 #[arg(
561 short = 'p',
562 long = "param",
563 global = true,
564 help = "Query parameter (repeatable)"
565 )]
566 pub param: Vec<String>,
567}
568
569#[derive(Debug, Args, Clone, Default, Deserialize)]
570#[serde(default)]
571pub struct TimeoutOptions {
572 #[arg(
573 short = 't',
574 long = "timeout",
575 global = true,
576 help = "Overall request timeout (e.g., '30s', '1m')"
577 )]
578 pub timeout: Option<DurationString>,
579 #[arg(
580 long = "connect-timeout",
581 global = true,
582 help = "Connection timeout (e.g., '10s')"
583 )]
584 pub connect_timeout: Option<DurationString>,
585}
586
587#[derive(Debug, Args, Clone, Default, Deserialize)]
588#[serde(default)]
589pub struct BodyOptions {
590 #[arg(
591 short = 'j',
592 long = "json",
593 group = "body",
594 help = "Send data as JSON (auto sets Content-Type)",
595 value_hint = clap::ValueHint::FilePath
596 )]
597 pub json: Option<StringOrFile>,
598 #[arg(
599 short = 'F',
600 long = "form",
601 group = "body",
602 help = "Form data (repeatable)"
603 )]
604 pub form: Vec<FormField>,
605 #[arg(
606 long = "raw",
607 group = "body",
608 help = "Send raw data without processing",
609 value_hint = clap::ValueHint::FilePath
610 )]
611 pub raw: Option<StringOrFile>,
612 #[arg(
613 long = "binary",
614 group = "body",
615 help = "Send binary data",
616 value_hint = clap::ValueHint::FilePath
617 )]
618 pub binary: Option<StringOrFile>,
619}
620
621#[derive(Debug, Args, Clone, Default, Deserialize)]
622#[serde(default)]
623pub struct RedirectOptions {
624 #[arg(
625 short = 'L',
626 long = "location",
627 global = true,
628 help = "Follow redirects"
629 )]
630 pub location: bool,
631 #[arg(
632 long = "max-redirects",
633 global = true,
634 help = "Maximum number of redirects to follow"
635 )]
636 pub max_redirects: Option<u32>,
637}
638
639#[derive(Debug, Args, Clone, Default, Deserialize)]
640#[serde(default)]
641pub struct TlsOptions {
642 #[arg(
643 short = 'k',
644 long = "insecure",
645 global = true,
646 help = "Skip TLS verification"
647 )]
648 pub insecure: bool,
649 #[arg(
650 long = "cert",
651 global = true,
652 help = "Client certificate file (PEM format)"
653 )]
654 pub cert: Option<PathBuf>,
655 #[arg(
656 long = "key",
657 global = true,
658 help = "Client certificate key file (PEM format)"
659 )]
660 pub key: Option<PathBuf>,
661 #[arg(
662 long = "cacert",
663 global = true,
664 help = "CA certificate to verify peer against"
665 )]
666 pub cacert: Option<PathBuf>,
667}
668
669#[derive(Debug, Args, Clone, Default, Deserialize)]
670#[serde(default)]
671pub struct ProxyOptions {
672 #[arg(short = 'x', long = "proxy", global = true, help = "Proxy server URL")]
673 pub proxy: Option<Url>,
674 #[arg(long = "proxy-auth", global = true, help = "Proxy authentication")]
675 pub proxy_auth: Option<SecretString>,
676}
677
678#[derive(Debug, Args, Clone, Default, Deserialize)]
679#[serde(default)]
680pub struct OutputOptions {
681 #[arg(
682 short = 'o',
683 long = "output",
684 global = true,
685 help = "Write output to file instead of stdout"
686 )]
687 pub output: Option<PathBuf>,
688 #[arg(
689 short = 'i',
690 long = "include",
691 global = true,
692 help = "Include response headers in output"
693 )]
694 pub include: bool,
695 #[arg(
696 short,
697 long = "verbose",
698 global = true,
699 help = "Show detailed request/response info"
700 )]
701 pub verbose: bool,
702 #[arg(
703 short,
704 long = "simple",
705 global = true,
706 help = "Show response without color formatting"
707 )]
708 pub simple: bool,
709}
710
711#[derive(Debug, Args, Clone, Default, Deserialize)]
712#[serde(default)]
713pub struct CompressionOptions {
714 #[arg(
715 long = "compressed",
716 global = true,
717 help = "Request compressed response (gzip, deflate, br)"
718 )]
719 pub compressed: bool,
720}
721
722impl RequestOptions {
724 pub fn merge_with(&mut self, cli_options: &RequestOptions) {
725 self.authorization.merge_with(&cli_options.authorization);
726 self.headers.merge_with(&cli_options.headers);
727 self.params.merge_with(&cli_options.params);
728 self.timeouts.merge_with(&cli_options.timeouts);
729 self.redirects.merge_with(&cli_options.redirects);
730 self.tls.merge_with(&cli_options.tls);
731 self.proxy.merge_with(&cli_options.proxy);
732 self.output.merge_with(&cli_options.output);
733 self.compression.merge_with(&cli_options.compression);
734 }
735}
736
737impl AuthOptions {
738 pub fn merge_with(&mut self, cli: &AuthOptions) {
739 if cli.auth.is_some() {
740 self.auth = cli.auth.clone();
741 }
742 if cli.basic.is_some() {
743 self.basic = cli.basic.clone();
744 }
745 if cli.bearer.is_some() {
746 self.bearer = cli.bearer.clone();
747 }
748 }
749}
750
751impl HeaderOptions {
752 pub fn merge_with(&mut self, cli: &HeaderOptions) {
753 self.header.extend(cli.header.clone());
755
756 if cli.user_agent.is_some() {
758 self.user_agent = cli.user_agent.clone();
759 }
760 if cli.referer.is_some() {
761 self.referer = cli.referer.clone();
762 }
763 if cli.content_type.is_some() {
764 self.content_type = cli.content_type.clone();
765 }
766 if cli.accept.is_some() {
767 self.accept = cli.accept.clone();
768 }
769 }
770}
771
772impl ParamOptions {
773 pub fn merge_with(&mut self, cli: &ParamOptions) {
774 use std::collections::BTreeSet;
777
778 let mut param_set: BTreeSet<String> = BTreeSet::new();
779
780 param_set.extend(self.param.iter().cloned());
782
783 param_set.extend(cli.param.iter().cloned());
785
786 self.param = param_set.into_iter().collect();
788 }
789}
790
791impl TimeoutOptions {
792 pub fn merge_with(&mut self, cli: &TimeoutOptions) {
793 if cli.timeout.is_some() {
794 self.timeout = cli.timeout;
795 }
796 if cli.connect_timeout.is_some() {
797 self.connect_timeout = cli.connect_timeout;
798 }
799 }
800}
801
802impl RedirectOptions {
803 pub fn merge_with(&mut self, cli: &RedirectOptions) {
804 if cli.location {
805 self.location = cli.location;
806 }
807 if cli.max_redirects.is_some() {
808 self.max_redirects = cli.max_redirects;
809 }
810 }
811}
812
813impl TlsOptions {
814 pub fn merge_with(&mut self, cli: &TlsOptions) {
815 if cli.insecure {
816 self.insecure = cli.insecure;
817 }
818 if cli.cert.is_some() {
819 self.cert = cli.cert.clone();
820 }
821 if cli.key.is_some() {
822 self.key = cli.key.clone();
823 }
824 if cli.cacert.is_some() {
825 self.cacert = cli.cacert.clone();
826 }
827 }
828}
829
830impl ProxyOptions {
831 pub fn merge_with(&mut self, cli: &ProxyOptions) {
832 if cli.proxy.is_some() {
833 self.proxy = cli.proxy.clone();
834 }
835 if cli.proxy_auth.is_some() {
836 self.proxy_auth = cli.proxy_auth.clone();
837 }
838 }
839}
840
841impl OutputOptions {
842 pub fn merge_with(&mut self, cli: &OutputOptions) {
843 if cli.output.is_some() {
844 self.output = cli.output.clone();
845 }
846 if cli.include {
847 self.include = cli.include;
848 }
849 if cli.verbose {
850 self.verbose = cli.verbose;
851 }
852 if cli.simple {
853 self.simple = cli.simple;
854 }
855 }
856}
857
858impl CompressionOptions {
859 pub fn merge_with(&mut self, cli: &CompressionOptions) {
860 if cli.compressed {
861 self.compressed = cli.compressed;
862 }
863 }
864}