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 } => {
163 let quest = QuestCommand::Post {
164 url_spec: QuestUrl::Direct { url },
165 body: BodyOptions::default(),
166 options: RequestOptions::default(),
167 };
168 Self::execute_quest_command(options, quest)
169 }
170 Command::Put { url } => {
171 let quest = QuestCommand::Put {
172 url_spec: QuestUrl::Direct { url },
173 body: BodyOptions::default(),
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 } => {
186 let quest = QuestCommand::Patch {
187 url_spec: QuestUrl::Direct { url },
188 body: BodyOptions::default(),
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, quest_body) = match &quest {
305 QuestCommand::Get { options, .. } => (options.clone(), None),
306 QuestCommand::Post { options, body, .. } => (options.clone(), Some(body)),
307 QuestCommand::Put { options, body, .. } => (options.clone(), Some(body)),
308 QuestCommand::Delete { options, .. } => (options.clone(), None),
309 QuestCommand::Patch { options, body, .. } => (options.clone(), Some(body)),
310 };
311
312 if let Some(body) = quest_body {
314 quest_options.body = body.clone();
315 }
316
317 quest_options.merge_with(&cli_options);
319
320 let client = QuestClientBuilder::new().apply(&quest_options)?.build()?;
322
323 let (request_builder, method, url) = match &quest {
325 QuestCommand::Get { url_spec, .. } => {
326 let url = url_spec.to_url()?;
327 (client.get(url.as_str()), "GET", url)
328 }
329 QuestCommand::Post { url_spec, .. } => {
330 let url = url_spec.to_url()?;
331 (client.post(url.as_str()), "POST", url)
332 }
333 QuestCommand::Put { url_spec, .. } => {
334 let url = url_spec.to_url()?;
335 (client.put(url.as_str()), "PUT", url)
336 }
337 QuestCommand::Delete { url_spec, .. } => {
338 let url = url_spec.to_url()?;
339 (client.delete(url.as_str()), "DELETE", url)
340 }
341 QuestCommand::Patch { url_spec, .. } => {
342 let url = url_spec.to_url()?;
343 (client.patch(url.as_str()), "PATCH", url)
344 }
345 };
346
347 if quest_options.output.verbose {
349 Self::log_request_verbose(
350 &url,
351 method,
352 &quest_options.headers,
353 &quest_options.authorization,
354 )?;
355 }
356
357 let request = QuestRequestBuilder::from_request(request_builder).apply(&quest_options)?;
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 },
442 Put {
443 url: Url,
444 },
445 Delete {
446 url: Url,
447 },
448 Patch {
449 url: Url,
450 },
451 Go {
453 name: String,
455
456 #[arg(
457 short,
458 long,
459 default_value = ".quests.yaml",
460 help = "Quest file to load from"
461 )]
462 file: PathBuf,
463 },
464 List {
466 #[arg(
467 short,
468 long,
469 default_value = ".quests.yaml",
470 help = "Quest file to load from"
471 )]
472 file: PathBuf,
473 },
474}
475
476#[derive(Debug, Args, Clone, Default, Deserialize)]
477#[serde(default)]
478pub struct RequestOptions {
479 #[serde(flatten)]
480 #[clap(flatten)]
481 pub authorization: AuthOptions,
482 #[serde(flatten)]
483 #[clap(flatten)]
484 pub headers: HeaderOptions,
485 #[serde(flatten)]
486 #[clap(flatten)]
487 pub params: ParamOptions,
488 #[serde(flatten)]
489 #[clap(flatten)]
490 pub body: BodyOptions,
491 #[serde(flatten)]
492 #[clap(flatten)]
493 pub timeouts: TimeoutOptions,
494 #[serde(flatten)]
495 #[clap(flatten)]
496 pub redirects: RedirectOptions,
497 #[serde(flatten)]
498 #[clap(flatten)]
499 pub tls: TlsOptions,
500 #[serde(flatten)]
501 #[clap(flatten)]
502 pub proxy: ProxyOptions,
503 #[serde(flatten)]
504 #[clap(flatten)]
505 pub output: OutputOptions,
506 #[serde(flatten)]
507 #[clap(flatten)]
508 pub compression: CompressionOptions,
509}
510
511#[derive(Debug, Args, Clone, Default, Deserialize)]
512#[serde(default)]
513pub struct AuthOptions {
514 #[arg(short, long, global = true)]
515 pub auth: Option<SecretString>,
516 #[arg(long, global = true)]
517 pub basic: Option<SecretString>,
518 #[arg(long, global = true)]
519 pub bearer: Option<SecretString>,
520}
521
522#[derive(Debug, Args, Clone, Default, Deserialize)]
523#[serde(default)]
524pub struct HeaderOptions {
525 #[serde(rename = "headers")]
526 #[arg(
527 short = 'H',
528 long = "header",
529 global = true,
530 help = "Custom header (repeatable)"
531 )]
532 pub header: Vec<String>,
533 #[arg(
534 short = 'U',
535 long = "user-agent",
536 global = true,
537 help = "Set User-Agent header"
538 )]
539 pub user_agent: Option<String>,
540 #[arg(
541 short = 'R',
542 long = "referer",
543 global = true,
544 help = "Set Referer header"
545 )]
546 pub referer: Option<String>,
547 #[arg(long = "content-type", global = true, help = "Set Content-Type header")]
548 pub content_type: Option<String>,
549 #[arg(long = "accept", global = true, help = "Set Accept header")]
550 pub accept: Option<String>,
551}
552
553#[derive(Debug, Args, Clone, Default, Deserialize)]
554#[serde(default)]
555pub struct ParamOptions {
556 #[serde(rename = "params")]
557 #[arg(
558 short = 'p',
559 long = "param",
560 global = true,
561 help = "Query parameter (repeatable)"
562 )]
563 pub param: Vec<String>,
564}
565
566#[derive(Debug, Args, Clone, Default, Deserialize)]
567#[serde(default)]
568pub struct TimeoutOptions {
569 #[arg(
570 short = 't',
571 long = "timeout",
572 global = true,
573 help = "Overall request timeout (e.g., '30s', '1m')"
574 )]
575 pub timeout: Option<DurationString>,
576 #[arg(
577 long = "connect-timeout",
578 global = true,
579 help = "Connection timeout (e.g., '10s')"
580 )]
581 pub connect_timeout: Option<DurationString>,
582}
583
584#[derive(Debug, Args, Clone, Default, Deserialize)]
585#[serde(default)]
586pub struct BodyOptions {
587 #[arg(
588 short = 'j',
589 long = "json",
590 group = "body",
591 global = true,
592 help = "Send data as JSON (auto sets Content-Type)",
593 value_hint = clap::ValueHint::FilePath
594 )]
595 pub json: Option<StringOrFile>,
596 #[arg(
597 short = 'F',
598 long = "form",
599 group = "body",
600 global = true,
601 help = "Form data (repeatable)"
602 )]
603 pub form: Vec<FormField>,
604 #[arg(
605 long = "raw",
606 group = "body",
607 global = true,
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 global = true,
616 help = "Send binary data",
617 value_hint = clap::ValueHint::FilePath
618 )]
619 pub binary: Option<StringOrFile>,
620}
621
622#[derive(Debug, Args, Clone, Default, Deserialize)]
623#[serde(default)]
624pub struct RedirectOptions {
625 #[arg(
626 short = 'L',
627 long = "location",
628 global = true,
629 help = "Follow redirects"
630 )]
631 pub location: bool,
632 #[arg(
633 long = "max-redirects",
634 global = true,
635 help = "Maximum number of redirects to follow"
636 )]
637 pub max_redirects: Option<u32>,
638}
639
640#[derive(Debug, Args, Clone, Default, Deserialize)]
641#[serde(default)]
642pub struct TlsOptions {
643 #[arg(
644 short = 'k',
645 long = "insecure",
646 global = true,
647 help = "Skip TLS verification"
648 )]
649 pub insecure: bool,
650 #[arg(
651 long = "cert",
652 global = true,
653 help = "Client certificate file (PEM format)"
654 )]
655 pub cert: Option<PathBuf>,
656 #[arg(
657 long = "key",
658 global = true,
659 help = "Client certificate key file (PEM format)"
660 )]
661 pub key: Option<PathBuf>,
662 #[arg(
663 long = "cacert",
664 global = true,
665 help = "CA certificate to verify peer against"
666 )]
667 pub cacert: Option<PathBuf>,
668}
669
670#[derive(Debug, Args, Clone, Default, Deserialize)]
671#[serde(default)]
672pub struct ProxyOptions {
673 #[arg(short = 'x', long = "proxy", global = true, help = "Proxy server URL")]
674 pub proxy: Option<Url>,
675 #[arg(long = "proxy-auth", global = true, help = "Proxy authentication")]
676 pub proxy_auth: Option<SecretString>,
677}
678
679#[derive(Debug, Args, Clone, Default, Deserialize)]
680#[serde(default)]
681pub struct OutputOptions {
682 #[arg(
683 short = 'o',
684 long = "output",
685 global = true,
686 help = "Write output to file instead of stdout"
687 )]
688 pub output: Option<PathBuf>,
689 #[arg(
690 short = 'i',
691 long = "include",
692 global = true,
693 help = "Include response headers in output"
694 )]
695 pub include: bool,
696 #[arg(
697 short,
698 long = "verbose",
699 global = true,
700 help = "Show detailed request/response info"
701 )]
702 pub verbose: bool,
703 #[arg(
704 short,
705 long = "simple",
706 global = true,
707 help = "Show response without color formatting"
708 )]
709 pub simple: bool,
710}
711
712#[derive(Debug, Args, Clone, Default, Deserialize)]
713#[serde(default)]
714pub struct CompressionOptions {
715 #[arg(
716 long = "compressed",
717 global = true,
718 help = "Request compressed response (gzip, deflate, br)"
719 )]
720 pub compressed: bool,
721}
722
723impl RequestOptions {
725 pub fn merge_with(&mut self, cli_options: &RequestOptions) {
726 self.authorization.merge_with(&cli_options.authorization);
727 self.headers.merge_with(&cli_options.headers);
728 self.params.merge_with(&cli_options.params);
729 self.body.merge_with(&cli_options.body);
730 self.timeouts.merge_with(&cli_options.timeouts);
731 self.redirects.merge_with(&cli_options.redirects);
732 self.tls.merge_with(&cli_options.tls);
733 self.proxy.merge_with(&cli_options.proxy);
734 self.output.merge_with(&cli_options.output);
735 self.compression.merge_with(&cli_options.compression);
736 }
737}
738
739impl AuthOptions {
740 pub fn merge_with(&mut self, cli: &AuthOptions) {
741 if cli.auth.is_some() {
742 self.auth = cli.auth.clone();
743 }
744 if cli.basic.is_some() {
745 self.basic = cli.basic.clone();
746 }
747 if cli.bearer.is_some() {
748 self.bearer = cli.bearer.clone();
749 }
750 }
751}
752
753impl HeaderOptions {
754 pub fn merge_with(&mut self, cli: &HeaderOptions) {
755 self.header.extend(cli.header.clone());
757
758 if cli.user_agent.is_some() {
760 self.user_agent = cli.user_agent.clone();
761 }
762 if cli.referer.is_some() {
763 self.referer = cli.referer.clone();
764 }
765 if cli.content_type.is_some() {
766 self.content_type = cli.content_type.clone();
767 }
768 if cli.accept.is_some() {
769 self.accept = cli.accept.clone();
770 }
771 }
772}
773
774impl ParamOptions {
775 pub fn merge_with(&mut self, cli: &ParamOptions) {
776 use std::collections::BTreeSet;
779
780 let mut param_set: BTreeSet<String> = BTreeSet::new();
781
782 param_set.extend(self.param.iter().cloned());
784
785 param_set.extend(cli.param.iter().cloned());
787
788 self.param = param_set.into_iter().collect();
790 }
791}
792
793impl TimeoutOptions {
794 pub fn merge_with(&mut self, cli: &TimeoutOptions) {
795 if cli.timeout.is_some() {
796 self.timeout = cli.timeout;
797 }
798 if cli.connect_timeout.is_some() {
799 self.connect_timeout = cli.connect_timeout;
800 }
801 }
802}
803
804impl RedirectOptions {
805 pub fn merge_with(&mut self, cli: &RedirectOptions) {
806 if cli.location {
807 self.location = cli.location;
808 }
809 if cli.max_redirects.is_some() {
810 self.max_redirects = cli.max_redirects;
811 }
812 }
813}
814
815impl TlsOptions {
816 pub fn merge_with(&mut self, cli: &TlsOptions) {
817 if cli.insecure {
818 self.insecure = cli.insecure;
819 }
820 if cli.cert.is_some() {
821 self.cert = cli.cert.clone();
822 }
823 if cli.key.is_some() {
824 self.key = cli.key.clone();
825 }
826 if cli.cacert.is_some() {
827 self.cacert = cli.cacert.clone();
828 }
829 }
830}
831
832impl ProxyOptions {
833 pub fn merge_with(&mut self, cli: &ProxyOptions) {
834 if cli.proxy.is_some() {
835 self.proxy = cli.proxy.clone();
836 }
837 if cli.proxy_auth.is_some() {
838 self.proxy_auth = cli.proxy_auth.clone();
839 }
840 }
841}
842
843impl OutputOptions {
844 pub fn merge_with(&mut self, cli: &OutputOptions) {
845 if cli.output.is_some() {
846 self.output = cli.output.clone();
847 }
848 if cli.include {
849 self.include = cli.include;
850 }
851 if cli.verbose {
852 self.verbose = cli.verbose;
853 }
854 if cli.simple {
855 self.simple = cli.simple;
856 }
857 }
858}
859
860impl CompressionOptions {
861 pub fn merge_with(&mut self, cli: &CompressionOptions) {
862 if cli.compressed {
863 self.compressed = cli.compressed;
864 }
865 }
866}
867
868impl BodyOptions {
869 pub fn merge_with(&mut self, cli: &BodyOptions) {
870 if cli.json.is_some() | !cli.form.is_empty() | cli.raw.is_some() | cli.binary.is_some() {
873 *self = cli.clone();
874 }
875 }
877}