1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
use crate::error::Error;
use crate::raur::*;
use reqwest::blocking::Client;
use reqwest::Url;
use serde_derive::Deserialize;
use url::ParseError;

/// The default URL used for the AUR.
pub static AUR_URL: &str = "https://aur.archlinux.org/rpc/";

#[derive(Deserialize)]
struct Response {
    #[serde(rename = "type")]
    response_type: String,
    error: Option<String>,
    results: Vec<Package>,
}

/// The trait for RPC functionality.
///
/// [`Handle`] Implements this and can be used directly in user code. However is may be useful to
/// be Generic over this trait to allow for testing using mock implementors.
pub trait Raur {
    /// The error type that functions may return.
    type Err;

    /// Performs an AUR info request.
    ///
    /// This function sends an info request to the AUR RPC. This kind of request takes a list
    /// of package names and returns a list of AUR [`Package`](struct.Package.html)s who's name exactly matches
    /// the input.
    ///
    /// **Note:** If a package being queried does not exist then it will be silently ignored
    /// and not appear in return value.
    ///
    /// **Note:** The return value has no guaranteed order.
    fn info<S: AsRef<str>>(&self, pkg_names: &[S]) -> Result<Vec<Package>, Self::Err>;

    /// Performs an AUR search request.
    ///
    /// This function sends a search request to the AUR RPC. This kind of request takes a
    /// single query and returns a list of matching packages.
    ///
    /// **Note:** Unlike info, search results will never inclide:
    ///
    /// - Dependency types
    /// - Licence
    /// - Groups
    ///
    /// See [`SearchBy`](enum.SearchBy.html) for how packages are matched.
    fn search_by<S: AsRef<str>>(
        &self,
        query: S,
        strategy: SearchBy,
    ) -> Result<Vec<Package>, Self::Err>;

    /// Performs an AUR search request by NameDesc.
    ///
    /// This is the same as [`fn.search_by`](fn.search_by.html) except it always searches by
    /// NameDesc (the default for the AUR).
    fn search<S: AsRef<str>>(&self, query: S) -> Result<Vec<Package>, Self::Err> {
        self.search_by(query, SearchBy::NameDesc)
    }

    /// Returns a list of all orphan packages in the AUR.
    fn orphans(&self) -> Result<Vec<Package>, Self::Err> {
        self.search_by("", SearchBy::Maintainer)
    }
}

/// A handle for making AUR requests.
#[derive(Clone, Debug)]
pub struct Handle {
    client: Client,
    url: Url,
}

impl Raur for Handle {
    type Err = Error;

    fn info<S: AsRef<str>>(&self, pkg_names: &[S]) -> Result<Vec<Package>, Error> {
        let mut params = pkg_names
            .iter()
            .map(|name| ("arg[]", name.as_ref()))
            .collect::<Vec<_>>();
        params.extend(&[("v", "5"), ("type", "info")]);

        self.request(&params)
    }

    fn search_by<S: AsRef<str>>(
        &self,
        query: S,
        strategy: SearchBy,
    ) -> Result<Vec<Package>, Error> {
        self.request(&[
            ("v", "5"),
            ("type", "search"),
            ("by", &strategy.to_string()),
            ("arg", query.as_ref()),
        ])
    }
}

impl Default for Handle {
    fn default() -> Self {
        Handle {
            url: AUR_URL.parse().unwrap(),
            client: Client::new(),
        }
    }
}

impl Handle {
    /// Used to manually specify the client that should be used.
    pub fn with_client(mut self, cli: Client) -> Self {
        self.client = cli;
        self
    }

    /// Used to manually specify a URL to be used. If not specified,
    /// aur.archlinux.org/rpc is used.
    pub fn with_url(mut self, url: &str) -> Result<Self, ParseError> {
        let url: Url = Url::parse(url)?;
        self.url = url;
        Ok(self)
    }

    /// Used to retrieve the internal URL. This just points to AUR_URL if you did not explicitly
    /// set it.
    pub fn url(&self) -> Url {
        self.url.clone()
    }

    /// Used to retrieve the client stored inside the struct. This consumes the struct as
    /// duplication could be expensive.
    pub fn client(self) -> Client {
        self.client
    }

    /// A helper function for making a request with given parameters.
    fn request(&self, params: &[(&str, &str)]) -> Result<Vec<Package>, Error> {
        let new_url = Url::parse_with_params(self.url.as_str(), params)?;

        let response = self.client.get(new_url).send()?;
        let response: Response = response.json()?;

        if response.response_type == "error" {
            Err(Error::Aur(
                response
                    .error
                    .unwrap_or_else(|| "No error message provided".to_string()),
            ))
        } else {
            Ok(response.results)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_search() {
        let handle = Handle::default();

        let query = handle.search("zzzzzzz").unwrap();
        assert_eq!(0, query.len());

        let query = handle.search("spotify").unwrap();
        assert!(query.len() > 0);
    }

    #[test]
    fn test_info() {
        let handle = Handle::default();

        let query = handle.info(&["pacman-git"]).unwrap();
        assert_eq!(query[0].name, "pacman-git");

        // I maintain these two packages, so I can verify they exist.
        let query = handle.info(&["screens", "screens-git"]);
        assert!(query.is_ok());

        let query = query.unwrap();
        assert_eq!(2, query.len());
    }
}