Skip to content

Commit 2fc417f

Browse files
committed
some initial cleanups
1 parent b8e0d36 commit 2fc417f

File tree

2 files changed

+65
-49
lines changed

2 files changed

+65
-49
lines changed

src/krate.rs

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ use git;
2828
use keyword::EncodableKeyword;
2929
use upload;
3030
use user::RequestUser;
31-
use owner::{EncodableOwner, Owner, Rights, rights};
31+
use owner::{EncodableOwner, Owner, Rights, OwnerKind, rights};
3232
use util::errors::{NotFound, CargoError};
3333
use util::{LimitErrorReader, HashingReader};
3434
use util::{RequestUtils, CargoResult, internal, ChainError, human};
@@ -177,8 +177,8 @@ impl Crate {
177177
try!(conn.execute("INSERT INTO crate_owners
178178
(crate_id, owner_id, created_by, created_at,
179179
updated_at, deleted, owner_kind)
180-
VALUES ($1, $2, $2, $3, $3, FALSE, 0)",
181-
&[&ret.id, &user_id, &now]));
180+
VALUES ($1, $2, $2, $3, $3, FALSE, $4)",
181+
&[&ret.id, &user_id, &now, &(OwnerKind::User as u32)]));
182182
return Ok(ret);
183183

184184
fn validate_url(url: Option<&str>, field: &str) -> CargoResult<()> {
@@ -298,16 +298,16 @@ impl Crate {
298298
ON crate_owners.owner_id = users.id
299299
WHERE crate_owners.crate_id = $1
300300
AND crate_owners.deleted = FALSE
301-
AND crate_owners.owner_kind = 0"));
302-
let user_rows = try!(stmt.query(&[&self.id]));
301+
AND crate_owners.owner_kind = $2"));
302+
let user_rows = try!(stmt.query(&[&self.id, &(OwnerKind::User as u32)]));
303303

304304
let stmt = try!(conn.prepare("SELECT * FROM teams
305305
INNER JOIN crate_owners
306306
ON crate_owners.owner_id = teams.id
307307
WHERE crate_owners.crate_id = $1
308308
AND crate_owners.deleted = FALSE
309-
AND crate_owners.owner_kind = 1"));
310-
let team_rows = try!(stmt.query(&[&self.id]));
309+
AND crate_owners.owner_kind = $2"));
310+
let team_rows = try!(stmt.query(&[&self.id, &(OwnerKind::Team as u32)]));
311311

312312
let mut owners = vec![];
313313
owners.extend(user_rows.iter().map(|r| Owner::User(Model::from_row(&r))));
@@ -1004,19 +1004,29 @@ fn modify_owners(req: &mut Request, add: bool) -> CargoResult<Response> {
10041004
}
10051005
}
10061006

1007-
#[derive(RustcDecodable)] struct Request { users: Vec<String> }
1007+
#[derive(RustcDecodable)]
1008+
struct Request {
1009+
// identical, for back-compat (owners preferred)
1010+
users: Option<Vec<String>>,
1011+
owners: Option<Vec<String>>,
1012+
}
1013+
10081014
let request: Request = try!(json::decode(&body).map_err(|_| {
10091015
human("invalid json request")
10101016
}));
10111017

1012-
for name in &request.users {
1018+
let names = try!(request.owners.or(request.users).ok_or_else(|| {
1019+
human("invalid json request")
1020+
}));
1021+
1022+
for name in &names {
10131023
if add {
10141024
if owners.iter().any(|owner| owner.name() == *name) {
10151025
return Err(human(format!("`{}` is already an owner", name)))
10161026
}
10171027
try!(krate.owner_add(tx, &user, &name));
10181028
} else {
1019-
// Removing the team the gives you rights is prevented because
1029+
// Removing the team that gives you rights is prevented because
10201030
// team members only have Rights::Publish
10211031
if *name == user.gh_login {
10221032
return Err(human("cannot remove yourself as an owner"))

src/owner.rs

Lines changed: 45 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,50 @@
11
use {Model, User};
22
use util::{RequestUtils, CargoResult, internal, ChainError, human};
33
use db::Connection;
4-
use curl::http;
4+
use curl;
55
use pg::rows::Row;
66
use rustc_serialize::json;
77
use util::errors::NotFound;
88
use std::str;
99

10+
pub fn json_http(url: &str, auth_token: &str)
11+
-> Result<curl::http::Response, curl::ErrCode> {
12+
curl::http::handle()
13+
.get(url)
14+
.header("Accept", "application/vnd.github.v3+json")
15+
.header("User-Agent", "hello!")
16+
.header("Authorization", &format!("token {}", auth_token))
17+
.exec()
18+
}
19+
20+
#[repr(u32)]
21+
pub enum OwnerKind {
22+
User = 0,
23+
Team = 1,
24+
}
1025

1126
/// Unifies the notion of a User or a Team.
1227
pub enum Owner {
1328
User(User),
14-
Team(Team)
29+
Team(Team),
1530
}
1631

1732
/// For now, just a Github Team. Can be upgraded to other teams
1833
/// later if desirable.
1934
pub struct Team {
20-
/// Github annoyingly has some APIs talk about teams by name,
21-
/// and others by some opaque id. I couldn't find any docs
22-
/// suggesting these ids are stable, so let's just always
23-
/// ask github for it. *shrug*
24-
github_id: i32,
35+
/// We're assuming these are stable
36+
pub github_id: i32,
2537
/// Unique table id
26-
cargo_id: i32,
38+
pub id: i32,
2739
/// "github:org:team"
2840
/// An opaque unique ID, that was at one point parsed out to query Github.
2941
/// We only query membership with github using the github_id, though.
30-
name: String,
42+
pub name: String,
3143
}
3244

3345
#[derive(RustcDecodable, RustcEncodable)]
3446
pub struct EncodableOwner {
3547
pub id: i32,
36-
// Login is deprecated in favour of name, but needs to be printed for back-compat
3748
pub login: String,
3849
pub kind: String,
3950
pub email: Option<String>,
@@ -70,9 +81,7 @@ impl Team {
7081
// github:rust-lang:owners
7182
"github" => {
7283
// Ok to unwrap since we know one ":" is contained
73-
let org = try!(chunks.next().ok_or_else(||
74-
human("missing github org argument; format is github:org:team")
75-
));
84+
let org = chunks.next().unwrap();
7685
let team = try!(chunks.next().ok_or_else(||
7786
human("missing github team argument; format is github:org:team")
7887
));
@@ -105,12 +114,8 @@ impl Team {
105114
c)));
106115
}
107116

108-
let resp = try!(http::handle()
109-
.get(format!("https://api.github.com/orgs/{}/teams", org_name))
110-
.header("Accept", "application/vnd.github.v3+json")
111-
.header("User-Agent", "hello!")
112-
.header("Authorization", &format!("token {}", &req_user.gh_access_token))
113-
.exec());
117+
let resp = try!(json_http(&format!("https://api.github.com/orgs/{}/teams", org_name),
118+
&req_user.gh_access_token));
114119

115120
match resp.get_code() {
116121
200 => {} // Ok!
@@ -154,20 +159,25 @@ impl Team {
154159
human(format!("could not find the github team {}/{}", org_name, team_name))
155160
}));
156161

157-
// mock Team (only need ID to check team status)
158-
let team = Team { github_id: github_id, cargo_id: 0, name: String::new() };
162+
// mock Team (only need github_id to check team status)
163+
let team = Team { github_id: github_id, id: 0, name: String::new() };
159164
if !try!(team.contains_user(req_user)) {
160165
return Err(human("only members of a team can add it as an owner"));
161166
}
162167

168+
Team::insert(conn, name, github_id)
169+
}
170+
171+
pub fn insert(conn: &Connection, name: &str, github_id: i32) -> CargoResult<Self> {
163172
// insert into DB for reals
164-
try!(conn.execute("INSERT INTO teams
165-
(name, github_id)
166-
VALUES ($1, $2)",
167-
&[&name, &github_id]));
173+
let stmt = try!(conn.prepare("INSERT INTO teams
174+
(name, github_id)
175+
VALUES ($1, $2)
176+
RETURNING *"));
168177

169-
// read it right back out:
170-
Team::find_by_name(conn, name)
178+
let rows = try!(stmt.query(&[&name, &github_id]));
179+
let row = rows.iter().next().unwrap();
180+
Ok(Model::from_row(&row))
171181
}
172182

173183
/// Phones home to Github to ask if this User is a member of the given team.
@@ -178,13 +188,9 @@ impl Team {
178188
// GET teams/:team_id/memberships/:user_name
179189
// check that "state": "active"
180190

181-
let resp = try!(http::handle()
182-
.get(format!("https://api.github.com/teams/{}/memberships/{}",
183-
self.github_id, &user.gh_login))
184-
.header("Accept", "application/vnd.github.v3+json")
185-
.header("User-Agent", "hello!")
186-
.header("Authorization", &format!("token {}", &user.gh_access_token))
187-
.exec());
191+
let resp = try!(json_http(&format!("https://api.github.com/teams/{}/memberships/{}",
192+
self.github_id, &user.gh_login),
193+
&user.gh_access_token));
188194

189195
match resp.get_code() {
190196
200 => {} // Ok!
@@ -226,7 +232,7 @@ impl Team {
226232
impl Model for Team {
227233
fn from_row(row: &Row) -> Self {
228234
Team {
229-
cargo_id: row.get("id"),
235+
id: row.get("id"),
230236
name: row.get("name"),
231237
github_id: row.get("github_id"),
232238
}
@@ -302,7 +308,7 @@ impl Owner {
302308
pub fn id(&self) -> i32 {
303309
match *self {
304310
Owner::User(ref user) => user.id,
305-
Owner::Team(ref team) => team.cargo_id,
311+
Owner::Team(ref team) => team.id,
306312
}
307313
}
308314

@@ -318,14 +324,14 @@ impl Owner {
318324
kind: String::from("user"),
319325
}
320326
}
321-
Owner::Team(Team { cargo_id, name, .. }) => {
327+
Owner::Team(Team { id, name, .. }) => {
322328
EncodableOwner {
323-
id: cargo_id,
329+
id: id,
324330
login: name,
325331
email: None,
326332
avatar: None,
327333
name: None,
328-
kind: String::from("owner"),
334+
kind: String::from("team"),
329335
}
330336
}
331337
}

0 commit comments

Comments
 (0)