cargo/src/registry/lib.rs

264 lines
8.4 KiB
Rust
Raw Normal View History

#![feature(core, io, path, fs)]
2015-01-04 09:02:16 +00:00
extern crate curl;
extern crate "rustc-serialize" as rustc_serialize;
use std::collections::HashMap;
use std::fmt;
use std::fs::{self, File};
use std::io::prelude::*;
use std::io::{self, Cursor};
use std::path::Path;
use std::result;
use curl::http;
use curl::http::handle::Method::{Put, Get, Delete};
use curl::http::handle::{Method, Request};
use rustc_serialize::json;
pub struct Registry {
host: String,
2014-11-22 14:36:14 +00:00
token: Option<String>,
handle: http::Handle,
}
pub type Result<T> = result::Result<T, Error>;
2015-01-04 09:02:16 +00:00
#[derive(PartialEq, Copy)]
2014-11-22 14:36:14 +00:00
pub enum Auth {
Authorized,
Unauthorized
}
pub enum Error {
2014-11-19 06:29:19 +00:00
Curl(curl::ErrCode),
NotOkResponse(http::Response),
NonUtf8Body,
2014-11-19 06:29:19 +00:00
Api(Vec<String>),
Unauthorized,
2014-11-22 14:36:14 +00:00
TokenMissing,
Io(io::Error),
}
2015-01-04 09:02:16 +00:00
#[derive(RustcDecodable)]
2014-11-22 14:36:14 +00:00
pub struct Crate {
pub name: String,
pub description: Option<String>,
pub max_version: String
}
2015-01-04 09:02:16 +00:00
#[derive(RustcEncodable)]
pub struct NewCrate {
pub name: String,
pub vers: String,
pub deps: Vec<NewCrateDependency>,
pub features: HashMap<String, Vec<String>>,
pub authors: Vec<String>,
pub description: Option<String>,
pub documentation: Option<String>,
pub homepage: Option<String>,
pub readme: Option<String>,
pub keywords: Vec<String>,
pub license: Option<String>,
pub license_file: Option<String>,
pub repository: Option<String>,
}
2015-01-04 09:02:16 +00:00
#[derive(RustcEncodable)]
pub struct NewCrateDependency {
pub optional: bool,
pub default_features: bool,
pub name: String,
pub features: Vec<String>,
pub version_req: String,
pub target: Option<String>,
pub kind: String,
}
2015-01-04 09:02:16 +00:00
#[derive(RustcDecodable)]
pub struct User {
2015-01-13 16:41:04 +00:00
pub id: u32,
pub login: String,
pub avatar: String,
pub email: Option<String>,
pub name: Option<String>,
}
2015-01-04 09:02:16 +00:00
#[derive(RustcDecodable)] struct R { ok: bool }
#[derive(RustcDecodable)] struct ApiErrorList { errors: Vec<ApiError> }
#[derive(RustcDecodable)] struct ApiError { detail: String }
#[derive(RustcEncodable)] struct OwnersReq<'a> { users: &'a [&'a str] }
#[derive(RustcDecodable)] struct Users { users: Vec<User> }
#[derive(RustcDecodable)] struct Crates { crates: Vec<Crate> }
impl Registry {
2014-11-22 14:36:14 +00:00
pub fn new(host: String, token: Option<String>) -> Registry {
Registry::new_handle(host, token, http::Handle::new())
}
2014-11-22 14:36:14 +00:00
pub fn new_handle(host: String, token: Option<String>,
handle: http::Handle) -> Registry {
Registry {
host: host,
token: token,
handle: handle,
}
}
pub fn add_owners(&mut self, krate: &str, owners: &[&str]) -> Result<()> {
let body = json::encode(&OwnersReq { users: owners }).unwrap();
let body = try!(self.put(format!("/crates/{}/owners", krate),
body.as_bytes()));
2015-02-06 08:06:39 +00:00
assert!(json::decode::<R>(&body).unwrap().ok);
Ok(())
}
pub fn remove_owners(&mut self, krate: &str, owners: &[&str]) -> Result<()> {
let body = json::encode(&OwnersReq { users: owners }).unwrap();
let body = try!(self.delete(format!("/crates/{}/owners", krate),
Some(body.as_bytes())));
2015-02-06 08:06:39 +00:00
assert!(json::decode::<R>(&body).unwrap().ok);
Ok(())
}
pub fn list_owners(&mut self, krate: &str) -> Result<Vec<User>> {
let body = try!(self.get(format!("/crates/{}/owners", krate)));
2015-02-06 08:06:39 +00:00
Ok(json::decode::<Users>(&body).unwrap().users)
}
pub fn publish(&mut self, krate: &NewCrate, tarball: &Path) -> Result<()> {
let json = json::encode(krate).unwrap();
// Prepare the body. The format of the upload request is:
//
// <le u32 of json>
// <json request> (metadata for the package)
// <le u32 of tarball>
// <source tarball>
let stat = try!(fs::metadata(tarball).map_err(Error::Io));
let header = {
let mut w = Vec::new();
w.extend([
(json.len() >> 0) as u8,
(json.len() >> 8) as u8,
(json.len() >> 16) as u8,
(json.len() >> 24) as u8,
].iter().cloned());
w.extend(json.as_bytes().iter().cloned());
w.extend([
(stat.len() >> 0) as u8,
(stat.len() >> 8) as u8,
(stat.len() >> 16) as u8,
(stat.len() >> 24) as u8,
].iter().cloned());
w
};
2014-11-19 06:29:19 +00:00
let tarball = try!(File::open(tarball).map_err(Error::Io));
let size = stat.len() as usize + header.len();
let mut body = Cursor::new(header).chain(tarball);
let url = format!("{}/api/v1/crates/new", self.host);
2014-11-22 14:36:14 +00:00
2015-02-06 08:06:39 +00:00
let token = try!(self.token.as_ref().ok_or(Error::TokenMissing));
2014-11-22 14:36:14 +00:00
let request = self.handle.put(url, &mut body)
.content_length(size)
.header("Accept", "application/json")
2015-02-06 08:06:39 +00:00
.header("Authorization", &token);
2014-11-22 14:36:14 +00:00
let response = handle(request.exec());
let _body = try!(response);
Ok(())
}
2014-11-22 14:36:14 +00:00
pub fn search(&mut self, query: &str) -> Result<Vec<Crate>> {
2015-02-06 08:06:39 +00:00
let body = try!(self.req(format!("/crates?q={}", query), None, Get,
Auth::Unauthorized));
2014-11-22 14:36:14 +00:00
2015-02-06 08:06:39 +00:00
Ok(json::decode::<Crates>(&body).unwrap().crates)
2014-11-22 14:36:14 +00:00
}
pub fn yank(&mut self, krate: &str, version: &str) -> Result<()> {
let body = try!(self.delete(format!("/crates/{}/{}/yank", krate, version),
None));
2015-02-06 08:06:39 +00:00
assert!(json::decode::<R>(&body).unwrap().ok);
Ok(())
}
pub fn unyank(&mut self, krate: &str, version: &str) -> Result<()> {
let body = try!(self.put(format!("/crates/{}/{}/unyank", krate, version),
2014-11-22 10:04:40 +00:00
&[]));
2015-02-06 08:06:39 +00:00
assert!(json::decode::<R>(&body).unwrap().ok);
Ok(())
}
fn put(&mut self, path: String, b: &[u8]) -> Result<String> {
2014-11-22 14:36:14 +00:00
self.req(path, Some(b), Put, Auth::Authorized)
}
fn get(&mut self, path: String) -> Result<String> {
2014-11-22 14:36:14 +00:00
self.req(path, None, Get, Auth::Authorized)
}
fn delete(&mut self, path: String, b: Option<&[u8]>) -> Result<String> {
2014-11-22 14:36:14 +00:00
self.req(path, b, Delete, Auth::Authorized)
}
fn req(&mut self, path: String, body: Option<&[u8]>,
2014-11-22 14:36:14 +00:00
method: Method, authorized: Auth) -> Result<String> {
let mut req = Request::new(&mut self.handle, method)
.uri(format!("{}/api/v1{}", self.host, path))
.header("Accept", "application/json")
.content_type("application/json");
2014-11-22 14:36:14 +00:00
if authorized == Auth::Authorized {
2015-02-06 08:06:39 +00:00
let token = try!(self.token.as_ref().ok_or(Error::TokenMissing));
req = req.header("Authorization", &token);
2014-11-22 14:36:14 +00:00
}
match body {
Some(b) => req = req.body(b),
None => {}
}
handle(req.exec())
}
}
fn handle(response: result::Result<http::Response, curl::ErrCode>)
-> Result<String> {
2014-11-19 06:29:19 +00:00
let response = try!(response.map_err(Error::Curl));
match response.get_code() {
0 => {} // file upload url sometimes
200 => {}
2014-11-19 06:29:19 +00:00
403 => return Err(Error::Unauthorized),
_ => return Err(Error::NotOkResponse(response))
}
let body = match String::from_utf8(response.move_body()) {
Ok(body) => body,
2014-11-19 06:29:19 +00:00
Err(..) => return Err(Error::NonUtf8Body),
};
2015-02-06 08:06:39 +00:00
match json::decode::<ApiErrorList>(&body) {
Ok(errors) => {
2014-11-19 06:29:19 +00:00
return Err(Error::Api(errors.errors.into_iter().map(|s| s.detail)
.collect()))
}
Err(..) => {}
}
Ok(body)
}
2015-01-23 18:42:29 +00:00
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
2014-11-19 06:29:19 +00:00
Error::NonUtf8Body => write!(f, "reponse body was not utf-8"),
Error::Curl(ref err) => write!(f, "http error: {}", err),
Error::NotOkResponse(ref resp) => {
write!(f, "failed to get a 200 OK response: {}", resp)
}
2014-11-19 06:29:19 +00:00
Error::Api(ref errs) => {
write!(f, "api errors: {}", errs.connect(", "))
}
2014-11-19 06:29:19 +00:00
Error::Unauthorized => write!(f, "unauthorized API access"),
2014-11-22 14:36:14 +00:00
Error::TokenMissing => write!(f, "no upload token found, please run `cargo login`"),
2014-11-19 06:29:19 +00:00
Error::Io(ref e) => write!(f, "io error: {}", e),
}
}
}