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
#![deny(missing_docs)]
#![cfg_attr(test, deny(warnings))]
#![feature(external_doc)]
#![doc(include = "../README.md")]
#![cfg_attr(test, feature(plugin))]
#![cfg_attr(test, plugin(clippy))]

#[macro_use]
extern crate failure;
extern crate reqwest;

use failure::Error;
use reqwest::{StatusCode, Url};

/// A description of availability on crates.io.
pub enum Availability {
  /// Crate is available.
  Available,
  /// Crate is unavailable.
  Unavailable,
  /// Availability is unknown because an unknown status code was returned.
  Unknown,
}

/// Get the availability for a crate on crates.io.
pub fn get(name: &str) -> Result<Availability, Error> {
  ensure!(!name.is_empty(), "name should be more than 0 characters");
  let addr = format!("https://crates.io/api/v1/crates/{}", name);
  let url = Url::parse(&addr)?;
  let res = reqwest::get(url)?;
  let status = match res.status() {
    StatusCode::OK => Availability::Unavailable,
    StatusCode::NOT_FOUND => Availability::Available,
    _ => Availability::Unknown,
  };
  Ok(status)
}