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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
//! This is a library for interacting with the Arch User Repository (AUR).
//! It is a work in progress and is not ready for production use.
//! The goal is to provide a simple interface for interacting with the AUR.
//!
//! For a basic name search call `search_package` which takes a package name
//! and returns a `SearchResponse` struct.  This struct contains a `results`
//! field which is a vector of `Package` structs.  These structs contain
//! information about the package.
//!
//! # Example
//! ```rust
//! #[tokio::main]
//! async fn main() {
//!     let response = aur_rs::search_package("yay-bin").await.unwrap();
//!     println!("#{:#?}", response);
//! }
//! ```
//!
//! Another way to get information about a package is to use the `package_info`
//! function.  This function takes a package name and returns `ReturnData`.
//!
//! # Example
//! ```rust
//! #[tokio::main]
//! async fn main() {
//!     let response = aur_rs::package_info("yay-bin").await.unwrap();
//!
//!     if let Some(keywords) = &response.results[0].keywords {
//!        println!("Keywords: {:?}", keywords);
//!    }
//! }

#![warn(missing_docs)]

use serde::{Deserialize, Serialize};

const AUR_RPC_URL: &str = "https://aur.archlinux.org/rpc/v5";

/// This is a a response to a search request.
#[derive(Serialize, Deserialize, Debug)]
pub struct ReturnData {
    /// API version
    version: u32,
    #[serde(rename = "type")]
    /// Response type one of `error`, `search`, `multiinfo``
    type_: String,
    /// Number of packages found
    pub resultcount: u32,
    /// Vector of packages.  If this is empty then no packages were found,
    /// or there was an error.
    pub results: Vec<Package>,
    /// Error message if there was an error. (probably handle this internally
    /// for now)
    error: Option<String>,
}

/// This is a package.  TODO(2020-05-03): Add more documentation.
#[derive(Serialize, Deserialize, Debug)]
pub struct Package {
    /// Package name
    #[serde(rename = "Name")]
    pub name: String,
    /// Package version
    #[serde(rename = "Version")]
    pub version: String,
    /// Package description (nullable)
    #[serde(rename = "Description")]
    pub description: String,
    /// Package maintainer (nullable)
    #[serde(rename = "Maintainer")]
    pub maintainer: String,
    /// Package URL pointing to the package source (nullable)
    #[serde(rename = "URL")]
    pub url: String,
    /// Number of votes
    #[serde(rename = "NumVotes")]
    pub num_votes: u32,
    /// Popularity of the package from 0 to 10
    #[serde(rename = "Popularity")]
    pub popularity: f32,
    /// Out of date flag.  Could be a date or null.
    #[serde(rename = "OutOfDate")]
    pub out_of_date: Option<String>,
    /// Package base name.  Usually the same as the package name.
    #[serde(rename = "PackageBase")]
    pub package_base: String,
    /// ID of the package base for this specific package.
    #[serde(rename = "PackageBaseID")]
    pub package_base_id: u32,
    /// First submitted date in unix time.
    #[serde(rename = "FirstSubmitted")]
    pub first_submitted: u32,
    /// Last modified date in unix time.
    #[serde(rename = "LastModified")]
    pub last_modified: u32,
    /// URL path to the package snapshot. (null)
    #[serde(rename = "URLPath")]
    pub url_path: String,
    /// Unique ID of the package.
    #[serde(rename = "ID")]
    pub id: u32,

    // The following fields are optional and only returned when using the
    // `multiinfo` method.
    /// Vector of dependencies
    #[serde(rename = "Depends")]
    pub depends: Option<Vec<String>>,
    /// Vector of make dependencies
    #[serde(rename = "MakeDepends")]
    pub make_depends: Option<Vec<String>>,
    /// Vector of optional dependencies
    #[serde(rename = "OptDepends")]
    pub opt_depends: Option<Vec<String>>,
    /// Vector of check dependencies
    #[serde(rename = "CheckDepends")]
    pub check_depends: Option<Vec<String>>,
    /// Vector of conflicts
    #[serde(rename = "Conflicts")]
    pub conflicts: Option<Vec<String>>,
    /// Vector of provides
    #[serde(rename = "Provides")]
    pub provides: Option<Vec<String>>,
    /// Vector of packages replaced by this package
    #[serde(rename = "Replaces")]
    pub replaces: Option<Vec<String>>,
    /// Vector of groups
    #[serde(rename = "Groups")]
    pub groups: Option<Vec<String>>,
    /// Vector of licenses defind in the PKGBUILD
    #[serde(rename = "License")]
    pub license: Option<Vec<String>>,
    /// Vector of keywords
    #[serde(rename = "Keywords")]
    pub keywords: Option<Vec<String>>,
}

async fn search(url: &str) -> Result<ReturnData, Box<dyn std::error::Error>> {
    let resp = reqwest::get(url).await?.text().await?;

    let search_response: ReturnData = serde_json::from_str(&resp)?;

    Ok(search_response)
}

/// Search for package by package name asynchronously by using tokio.
pub async fn search_package(name: &str) -> Result<ReturnData, Box<dyn std::error::Error>> {
    let url = format!("{}/search/{}?by=name", AUR_RPC_URL, name);

    let search_response: ReturnData = search(&url).await?;

    Ok(search_response)
}

/// Gets the info of a single package.
pub async fn package_info(name: &str) -> Result<ReturnData, Box<dyn std::error::Error>> {
    let url = format!("{}/info/{}", AUR_RPC_URL, name);

    let search_response: ReturnData = search(&url).await?;

    Ok(search_response)
}

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

    #[tokio::test]
    async fn pkg_search() {
        let server = MockServer::start();

        let search_mock = server.mock(|_, then| {
            then.status(200)
                .body(r#"
                {
                    "resultcount": 1,
                    "results": [
                      {
                        "Description": "Yet another yogurt. Pacman wrapper and AUR helper written in go. Pre-compiled.",
                        "FirstSubmitted": 1480777574,
                        "ID": 1261849,
                        "LastModified": 1684794463,
                        "Maintainer": "jguer",
                        "Name": "yay-bin",
                        "NumVotes": 237,
                        "OutOfDate": null,
                        "PackageBase": "yay-bin",
                        "PackageBaseID": 117489,
                        "Popularity": 5.519401,
                        "URL": "https://github.com/Jguer/yay",
                        "URLPath": "/cgit/aur.git/snapshot/yay-bin.tar.gz",
                        "Version": "12.0.5-1"
                      }
                    ],
                    "type": "search",
                    "version": 5
                  }
                "#);
        });

        let url: String = server.url("/rpc/v5/search/yay-bin?&by=name");
        let response = search(&url).await.unwrap();

        search_mock.assert();

        // Check the response for a few things.
        assert_eq!(response.results.len(), 1);
        assert_eq!(response.results[0].name, "yay-bin");
        assert_eq!(response.results[0].version, "12.0.5-1");
    }

    #[tokio::test]
    async fn pkg_search_info() {
        let server = MockServer::start();
        let url: String = server.url("/rpc/v5/info/yay-bin");

        let resp_json = r#"
        {
            "resultcount": 1,
            "results": [
              {
                "Conflicts": [
                  "yay"
                ],
                "Depends": [
                  "pacman>5",
                  "git"
                ],
                "Description": "Yet another yogurt. Pacman wrapper and AUR helper written in go. Pre-compiled.",
                "FirstSubmitted": 1480777574,
                "ID": 1277781,
                "Keywords": [
                  "AUR",
                  "go",
                  "helper",
                  "pacman",
                  "wrapper"
                ],
                "LastModified": 1687546172,
                "License": [
                  "GPL3"
                ],
                "Maintainer": "jguer",
                "Name": "yay-bin",
                "NumVotes": 237,
                "OptDepends": [
                  "sudo",
                  "doas"
                ],
                "OutOfDate": null,
                "PackageBase": "yay-bin",
                "PackageBaseID": 117489,
                "Popularity": 5.519401,
                "Provides": [
                  "yay"
                ],
                "Submitter": "jguer",
                "URL": "https://github.com/Jguer/yay",
                "URLPath": "/cgit/aur.git/snapshot/yay-bin.tar.gz",
                "Version": "12.1.0-1"
              }
            ],
            "type": "multiinfo",
            "version": 5
          }
           
                "#;

        let info_mock = server.mock(|_, then| {
            then.status(200).body(resp_json);
        });

        let response = search(&url).await.unwrap();

        // Check the response for a few things.
        assert_eq!(response.results.len(), 1);
        assert_eq!(response.results[0].name, "yay-bin");

        // keywords should match
        if let Some(keywords) = &response.results[0].keywords {
            assert_eq!(keywords[0], "AUR");
        } else {
            panic!("Keywords is None");
        }

        if let Some(license) = &response.results[0].license {
            assert_eq!(license[0], "GPL3");
        } else {
            panic!("License is None");
        }

        info_mock.assert();
    }
}