Skip to content

Implemented Warehouse Pypi API Call #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 114 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@ repository = "https://github.com/John15321/rust-pip"
anyhow = { version = "1.0.58", features = ["backtrace"] }
clap = { version = "3.2", features = ["derive"] }
reqwest = { version = "0.11", features = ["blocking", "json"] }
structopt = { version = "0.3.26", features = ["color"] }
strum = { version = "0.24.1", features = ["derive"] }
strum_macros = "0.24.2"
log = "0.4"
serde = {version = "1", features = ["derive"]}
serde_json = "1.0"



[dev-dependencies]
17 changes: 15 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use anyhow::Result;
use clap::{AppSettings, Parser};

mod pypi;
use pypi::{request_package_info, PyPIData};

/// Python package manager written in Rust
#[derive(Parser, Debug)]
#[clap(global_setting = AppSettings::DeriveDisplayOrder)]
Expand Down Expand Up @@ -43,7 +47,16 @@ enum Opt {
Help {},
}

fn download_package(_package_name: String, _package_index: &str) {}
fn download_package(package_name: String, package_index: &String) -> Result<()> {
let package_info: PyPIData = request_package_info(&package_name, package_index)?;

// Example of getting data this will be more robust as the
// PyPIData struct gets expanded (meaning less calls to .get())
let latest_version = package_info.info.version;
println!("Latest Version of {} is {}", package_name, latest_version);

Ok(())
}

fn main() {
let opt = Opt::parse();
Expand All @@ -53,7 +66,7 @@ fn main() {
Opt::Download { name, index } => {
println!("Package name {:?}", name);
println!("Index name: {:?}", index);
download_package(name, &index);
let _ = download_package(name, &index);
}
_ => todo!(),
}
Expand Down
126 changes: 126 additions & 0 deletions src/pypi.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
//! Warehouse PyPI API Implementation

use log::info;
use serde::{Deserialize, Serialize};
use std::fmt::Display;

/// Download stats
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct PyPIPackageDownloadInfo {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
pub struct PyPIPackageDownloadInfo {
pub struct PypiPackageDownloadInfo {

The typical Rust convention is to keep acronyms with the first letter in uppercase, and the rest in lowercase. This would also need to be updated in the rest of the file.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

John wanted this formatting and I think matching the Offical naming looks better.

last_day: i32,
last_week: i32,
last_month: i32,
}
/// Public package information
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct PyPIPackageInfo {
pub author: String,
pub author_email: String,
pub bugtrack_url: serde_json::value::Value,
pub classifiers: Vec<String>,
pub description: String,
pub description_content_type: String,
pub docs_url: serde_json::value::Value,
pub download_url: String,
pub downloads: PyPIPackageDownloadInfo,
pub home_page: String,
pub keywords: String,
pub license: String,
pub maintainer: String,
pub maintainer_email: String,
/// Package name
pub name: String,
pub package_url: String,
pub platform: String,
pub project_url: String,
pub project_urls: serde_json::value::Value,
pub release_url: String,
pub requires_dist: serde_json::value::Value,
/// Minimum required python version
pub requires_python: String,
/// Project Summary
pub summary: String,
/// Latest stable version number
pub version: String,
pub yanked: bool,
pub yanked_reason: serde_json::value::Value,
}

/// Set of Information describing a Python package hosted on a Warehouse instance
/// for exact details of what is contained go to <https://warehouse.pypa.io/api-reference/json.html#project>
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct PyPIData {
/// Contains data such as package name, author and license
pub info: PyPIPackageInfo,
pub last_serial: i32,
/// List of releases containing Object with downloads for each release and it's versions
pub releases: serde_json::value::Value,
/// Link and related data to sdist & bdist_wheel
pub urls: Vec<serde_json::value::Value>,
/// Vector of known vulnerabilities of the package
pub vulnerabilities: Vec<serde_json::value::Value>,
}

/// Implements Warehouse PyPI API call & JSON conversion
///
/// # Example
/// ```
/// use pypi::request_package_info;
///
/// let data = request_package_info("numpy", "https://pypi.org/").unwrap();
/// assert_eq!(data.info.license, "BSD");
/// ```
pub fn request_package_info<T>(
package_name: T,
package_index: T,
) -> Result<PyPIData, reqwest::Error>
where
T: ToString + Display,
{
let path = format!("{}/pypi/{}/json", package_index, package_name);

info!("Requesting data from {}", path);
let resp: reqwest::blocking::Response = reqwest::blocking::get(path)?;

let decoded_json: PyPIData = resp.json()?;

Ok(decoded_json)
}

#[cfg(test)]
mod tests {
use crate::pypi::request_package_info;

#[test]
fn check_numpy_licence() {
let data = request_package_info("numpy", "https://pypi.org/").unwrap();

assert_eq!(data.info.license, "BSD");
}

#[test]
fn check_pytorch_name() {
let data = request_package_info("pytorch", "https://pypi.org/").unwrap();

assert_eq!(data.info.name, "pytorch");
}

#[test]
fn check_numpy_download_name_v1() {
let data = request_package_info("numpy", "https://pypi.org/").unwrap();

assert_eq!(
data.releases.get("1.0").unwrap()[0]
.get("filename")
.unwrap(),
"numpy-1.0.1.dev3460.win32-py2.4.exe"
);
}

#[test]
#[should_panic(expected = "`Err` value: reqwest::Error")]
fn check_fails_invalid_url() {
let _err =
request_package_info("numpy", "invalid_url obviously wrong").unwrap();
}
}