openai_client_cli/program/loaders/
path.rs

1use crate::{Entry, Error, Result, traits::*};
2use std::str::FromStr;
3use regex::Regex;
4use tracing::{debug, info};
5
6/// The API request path.
7pub struct Path(String);
8
9impl FromStr for Path {
10  type Err = Error;
11
12  fn from_str(path: &str) -> Result<Self> {
13    Ok(Self(
14      Regex::new(include_str!("../../../assets/openai-openapi-paths-regex"))?
15        .find(path)
16        .ok_or(Error::msg("Invalid format of OpenAI API key"))?
17        .as_str()
18        .to_string()
19    ))
20  }
21}
22
23impl Loader<String> for Path {
24  fn fetch(entry: &Entry) -> Result<Self> {
25    let source = "the program arguments";
26    match Path::from_str(&entry.path) {
27      Ok(path) => {
28        info!(
29          "Successfully fetched the API request path from {source}: {:?}",
30          path.value_ref(),
31        );
32        Ok(path)
33      },
34      Err(err) => {
35        debug!("Failed to obtain the API request path from {source}: {err:?}");
36        Err(Error::msg("Failed to fetch the API request path"))
37      },
38    }
39  }
40  fn value(self) -> String {
41    self.0
42  }
43  fn value_ref(&self) -> &String {
44    &self.0
45  }
46}
47
48impl TryFrom<&str> for Path {
49  type Error = Error;
50
51  fn try_from(content: &str) -> Result<Self> {
52    Self::from_str(content)
53  }
54}
55
56impl TryFrom<String> for Path {
57  type Error = Error;
58
59  fn try_from(content: String) -> Result<Self> {
60    Self::from_str(&content)
61  }
62}
63
64impl TryFrom<&String> for Path {
65  type Error = Error;
66
67  fn try_from(content: &String) -> Result<Self> {
68    Self::from_str(content)
69  }
70}