diff --git a/src/bin/fill-in-user-id.rs b/src/bin/fill-in-user-id.rs index 401877e7a16..2f78983cd7d 100644 --- a/src/bin/fill-in-user-id.rs +++ b/src/bin/fill-in-user-id.rs @@ -67,16 +67,16 @@ fn update(app: &App, tx: &postgres::transaction::Transaction) { println!("attempt: {}/{}", id, login); let res = (|| -> CargoResult<()> { let url = format!("/users/{}", login); - let (handle, resp) = try!(http::github(app, &url, &token)); - let ghuser: GithubUser = try!(http::parse_github_response(handle, resp)); + let (handle, resp) = http::github(app, &url, &token)?; + let ghuser: GithubUser = http::parse_github_response(handle, resp)?; if let Some(ref avatar) = avatar { if !avatar.contains(&ghuser.id.to_string()) { return Err(human(format!("avatar: {}", avatar))) } } if ghuser.login == login { - try!(tx.execute("UPDATE users SET gh_id = $1 WHERE id = $2", - &[&ghuser.id, &id])); + tx.execute("UPDATE users SET gh_id = $1 WHERE id = $2", + &[&ghuser.id, &id])?; Ok(()) } else { Err(human(format!("different login: {}", ghuser.login))) diff --git a/src/bin/migrate.rs b/src/bin/migrate.rs index ce635d3db5a..f2c934aa580 100644 --- a/src/bin/migrate.rs +++ b/src/bin/migrate.rs @@ -26,9 +26,9 @@ fn main() { fn apply(tx: postgres::transaction::Transaction, migrations: Vec) -> postgres::Result<()> { - let mut mgr = try!(migrate::Manager::new(tx)); + let mut mgr = migrate::Manager::new(tx)?; for m in migrations.into_iter() { - try!(mgr.apply(m)); + mgr.apply(m)?; } mgr.set_commit(); mgr.finish() @@ -36,10 +36,10 @@ fn apply(tx: postgres::transaction::Transaction, fn rollback(tx: postgres::transaction::Transaction, migrations: Vec) -> postgres::Result<()> { - let mut mgr = try!(migrate::Manager::new(tx)); + let mut mgr = migrate::Manager::new(tx)?; for m in migrations.into_iter().rev() { if mgr.contains(m.version()) { - try!(mgr.rollback(m)); + mgr.rollback(m)?; break } } @@ -79,10 +79,10 @@ fn migrations() -> Vec { Migration::add_column(20140925132249, "packages", "created_at", "TIMESTAMP NOT NULL DEFAULT now()"), Migration::new(20140925132250, |tx| { - try!(tx.execute("UPDATE packages SET updated_at = now() \ - WHERE updated_at IS NULL", &[])); - try!(tx.execute("UPDATE packages SET created_at = now() \ - WHERE created_at IS NULL", &[])); + tx.execute("UPDATE packages SET updated_at = now() \ + WHERE updated_at IS NULL", &[])?; + tx.execute("UPDATE packages SET created_at = now() \ + WHERE created_at IS NULL", &[])?; Ok(()) }, |_| Ok(())), Migration::add_column(20140925132251, "versions", "updated_at", @@ -90,78 +90,78 @@ fn migrations() -> Vec { Migration::add_column(20140925132252, "versions", "created_at", "TIMESTAMP NOT NULL DEFAULT now()"), Migration::new(20140925132253, |tx| { - try!(tx.execute("UPDATE versions SET updated_at = now() \ - WHERE updated_at IS NULL", &[])); - try!(tx.execute("UPDATE versions SET created_at = now() \ - WHERE created_at IS NULL", &[])); + tx.execute("UPDATE versions SET updated_at = now() \ + WHERE updated_at IS NULL", &[])?; + tx.execute("UPDATE versions SET created_at = now() \ + WHERE created_at IS NULL", &[])?; Ok(()) }, |_| Ok(())), Migration::new(20140925132254, |tx| { - try!(tx.execute("ALTER TABLE versions ALTER COLUMN updated_at \ - DROP DEFAULT", &[])); - try!(tx.execute("ALTER TABLE versions ALTER COLUMN created_at \ - DROP DEFAULT", &[])); - try!(tx.execute("ALTER TABLE packages ALTER COLUMN updated_at \ - DROP DEFAULT", &[])); - try!(tx.execute("ALTER TABLE packages ALTER COLUMN created_at \ - DROP DEFAULT", &[])); + tx.execute("ALTER TABLE versions ALTER COLUMN updated_at \ + DROP DEFAULT", &[])?; + tx.execute("ALTER TABLE versions ALTER COLUMN created_at \ + DROP DEFAULT", &[])?; + tx.execute("ALTER TABLE packages ALTER COLUMN updated_at \ + DROP DEFAULT", &[])?; + tx.execute("ALTER TABLE packages ALTER COLUMN created_at \ + DROP DEFAULT", &[])?; Ok(()) }, |_| Ok(())), Migration::add_table(20140925153704, "metadata", " total_downloads BIGINT NOT NULL "), Migration::new(20140925153705, |tx| { - try!(tx.execute("INSERT INTO metadata (total_downloads) \ - VALUES ($1)", &[&0i64])); + tx.execute("INSERT INTO metadata (total_downloads) \ + VALUES ($1)", &[&0i64])?; Ok(()) }, |tx| { - try!(tx.execute("DELETE FROM metadata", &[])); Ok(()) + tx.execute("DELETE FROM metadata", &[])?; Ok(()) }), Migration::add_column(20140925161623, "packages", "downloads", "INTEGER NOT NULL DEFAULT 0"), Migration::add_column(20140925161624, "versions", "downloads", "INTEGER NOT NULL DEFAULT 0"), Migration::new(20140925161625, |tx| { - try!(tx.execute("ALTER TABLE versions ALTER COLUMN downloads \ - DROP DEFAULT", &[])); - try!(tx.execute("ALTER TABLE packages ALTER COLUMN downloads \ - DROP DEFAULT", &[])); + tx.execute("ALTER TABLE versions ALTER COLUMN downloads \ + DROP DEFAULT", &[])?; + tx.execute("ALTER TABLE packages ALTER COLUMN downloads \ + DROP DEFAULT", &[])?; Ok(()) }, |_| Ok(())), Migration::add_column(20140926130044, "packages", "max_version", "VARCHAR"), Migration::new(20140926130045, |tx| { - let stmt = try!(tx.prepare("SELECT * FROM packages")); - let rows = try!(stmt.query(&[])); + let stmt = tx.prepare("SELECT * FROM packages")?; + let rows = stmt.query(&[])?; for row in rows.iter() { let pkg: Crate = Model::from_row(&row); let versions = pkg.versions(tx).unwrap(); let v = versions.iter().max_by_key(|v| &v.num).unwrap(); let max = v.num.to_string(); - try!(tx.execute("UPDATE packages SET max_version = $1 \ + tx.execute("UPDATE packages SET max_version = $1 \ WHERE id = $2", - &[&max, &pkg.id])); + &[&max, &pkg.id])?; } Ok(()) }, |_| Ok(())), Migration::new(20140926130046, |tx| { - try!(tx.execute("ALTER TABLE versions ALTER COLUMN downloads \ - SET NOT NULL", &[])); + tx.execute("ALTER TABLE versions ALTER COLUMN downloads \ + SET NOT NULL", &[])?; Ok(()) }, |tx| { - try!(tx.execute("ALTER TABLE versions ALTER COLUMN downloads \ - DROP NOT NULL", &[])); + tx.execute("ALTER TABLE versions ALTER COLUMN downloads \ + DROP NOT NULL", &[])?; Ok(()) }), Migration::new(20140926174020, |tx| { - try!(tx.execute("ALTER TABLE packages RENAME TO crates", &[])); - try!(tx.execute("ALTER TABLE versions RENAME COLUMN package_id \ - TO crate_id", &[])); + tx.execute("ALTER TABLE packages RENAME TO crates", &[])?; + tx.execute("ALTER TABLE versions RENAME COLUMN package_id \ + TO crate_id", &[])?; Ok(()) }, |tx| { - try!(tx.execute("ALTER TABLE crates RENAME TO packages", &[])); - try!(tx.execute("ALTER TABLE versions RENAME COLUMN crate_id \ - TO package_id", &[])); + tx.execute("ALTER TABLE crates RENAME TO packages", &[])?; + tx.execute("ALTER TABLE versions RENAME COLUMN crate_id \ + TO package_id", &[])?; Ok(()) }), Migration::run(20140929103749, @@ -330,7 +330,7 @@ fn migrations() -> Vec { // http://www.postgresql.org/docs/8.3/static/textsearch-controls.html // http://www.postgresql.org/docs/8.3/static/textsearch-features.html Migration::new(20141020175650, |tx| { - try!(tx.batch_execute(" + tx.batch_execute(" CREATE FUNCTION trigger_crates_name_search() RETURNS trigger AS $$ begin new.textsearchable_index_col := @@ -349,13 +349,13 @@ fn migrations() -> Vec { CREATE TRIGGER trigger_crates_tsvector_update BEFORE INSERT OR UPDATE ON crates FOR EACH ROW EXECUTE PROCEDURE trigger_crates_name_search(); - ")); + ")?; Ok(()) }, |tx| { - try!(tx.execute("DROP TRIGGER trigger_crates_tsvector_update - ON crates", &[])); - try!(tx.execute("DROP FUNCTION trigger_crates_name_search()", &[])); + tx.execute("DROP TRIGGER trigger_crates_tsvector_update + ON crates", &[])?; + tx.execute("DROP FUNCTION trigger_crates_name_search()", &[])?; Ok(()) }), Migration::add_column(20141020175651, "crates", "keywords", "varchar"), @@ -381,64 +381,64 @@ fn migrations() -> Vec { Migration::add_column(20141023180231, "crates", "repository", "varchar"), Migration::new(20141112082527, |tx| { - try!(tx.execute("ALTER TABLE users DROP CONSTRAINT IF \ - EXISTS users_email_key", &[])); + tx.execute("ALTER TABLE users DROP CONSTRAINT IF \ + EXISTS users_email_key", &[])?; Ok(()) }, |_| Ok(())), Migration::add_column(20141120162357, "dependencies", "kind", "INTEGER"), Migration::new(20141121191309, |tx| { - try!(tx.execute("ALTER TABLE crates DROP CONSTRAINT \ - packages_name_key", &[])); - try!(tx.execute("CREATE UNIQUE INDEX index_crates_name \ - ON crates (lower(name))", &[])); + tx.execute("ALTER TABLE crates DROP CONSTRAINT \ + packages_name_key", &[])?; + tx.execute("CREATE UNIQUE INDEX index_crates_name \ + ON crates (lower(name))", &[])?; Ok(()) }, |tx| { - try!(tx.execute("DROP INDEX index_crates_name", &[])); - try!(tx.execute("ALTER TABLE crates ADD CONSTRAINT packages_name_key \ - UNIQUE (name)", &[])); + tx.execute("DROP INDEX index_crates_name", &[])?; + tx.execute("ALTER TABLE crates ADD CONSTRAINT packages_name_key \ + UNIQUE (name)", &[])?; Ok(()) }), Migration::new(20150209202206, |tx| { - try!(fix_duplicate_crate_owners(tx)); - try!(tx.execute("ALTER TABLE crate_owners ADD CONSTRAINT \ + fix_duplicate_crate_owners(tx)?; + tx.execute("ALTER TABLE crate_owners ADD CONSTRAINT \ crate_owners_unique_user_per_crate \ - UNIQUE (user_id, crate_id)", &[])); + UNIQUE (user_id, crate_id)", &[])?; Ok(()) }, |tx| { - try!(tx.execute("ALTER TABLE crate_owners DROP CONSTRAINT \ - crate_owners_unique_user_per_crate", &[])); + tx.execute("ALTER TABLE crate_owners DROP CONSTRAINT \ + crate_owners_unique_user_per_crate", &[])?; Ok(()) }), Migration::new(20150319224700, |tx| { - try!(tx.execute(" + tx.execute(" CREATE FUNCTION canon_crate_name(text) RETURNS text AS $$ SELECT replace(lower($1), '-', '_') $$ LANGUAGE SQL - ", &[])); + ", &[])?; Ok(()) }, |tx| { - try!(tx.execute("DROP FUNCTION canon_crate_name(text)", &[])); + tx.execute("DROP FUNCTION canon_crate_name(text)", &[])?; Ok(()) }), Migration::new(20150319224701, |tx| { - try!(tx.execute("DROP INDEX index_crates_name", &[])); - try!(tx.execute("CREATE UNIQUE INDEX index_crates_name \ - ON crates (canon_crate_name(name))", &[])); + tx.execute("DROP INDEX index_crates_name", &[])?; + tx.execute("CREATE UNIQUE INDEX index_crates_name \ + ON crates (canon_crate_name(name))", &[])?; Ok(()) }, |tx| { - try!(tx.execute("DROP INDEX index_crates_name", &[])); - try!(tx.execute("CREATE UNIQUE INDEX index_crates_name \ - ON crates (lower(name))", &[])); + tx.execute("DROP INDEX index_crates_name", &[])?; + tx.execute("CREATE UNIQUE INDEX index_crates_name \ + ON crates (lower(name))", &[])?; Ok(()) }), Migration::new(20150320174400, |tx| { - try!(tx.execute("CREATE INDEX index_keywords_lower_keyword ON keywords (lower(keyword))", - &[])); + tx.execute("CREATE INDEX index_keywords_lower_keyword ON keywords (lower(keyword))", + &[])?; Ok(()) }, |tx| { - try!(tx.execute("DROP INDEX index_keywords_lower_keyword", &[])); + tx.execute("DROP INDEX index_keywords_lower_keyword", &[])?; Ok(()) }), Migration::add_column(20150715170350, "crate_owners", "owner_kind", @@ -461,24 +461,24 @@ fn migrations() -> Vec { undo_foreign_key(20150804170130, "crate_owners", "user_id", "owner_id", "users (id)"), Migration::new(20150818112907, |tx| { - try!(tx.execute("ALTER TABLE crate_owners DROP CONSTRAINT \ - crate_owners_unique_user_per_crate", &[])); - try!(tx.execute("ALTER TABLE crate_owners ADD CONSTRAINT \ + tx.execute("ALTER TABLE crate_owners DROP CONSTRAINT \ + crate_owners_unique_user_per_crate", &[])?; + tx.execute("ALTER TABLE crate_owners ADD CONSTRAINT \ crate_owners_unique_owner_per_crate \ - UNIQUE (owner_id, crate_id, owner_kind)", &[])); + UNIQUE (owner_id, crate_id, owner_kind)", &[])?; Ok(()) }, |tx| { - try!(tx.execute("ALTER TABLE crate_owners DROP CONSTRAINT \ - crate_owners_unique_owner_per_crate", &[])); - try!(tx.execute("ALTER TABLE crate_owners ADD CONSTRAINT \ + tx.execute("ALTER TABLE crate_owners DROP CONSTRAINT \ + crate_owners_unique_owner_per_crate", &[])?; + tx.execute("ALTER TABLE crate_owners ADD CONSTRAINT \ crate_owners_unique_user_per_crate \ - UNIQUE (owner_id, crate_id)", &[])); + UNIQUE (owner_id, crate_id)", &[])?; Ok(()) }), Migration::add_column(20151118135514, "crates", "max_upload_size", "INTEGER"), Migration::new(20151126095136, |tx| { - try!(tx.batch_execute(" + tx.batch_execute(" ALTER TABLE version_downloads ALTER downloads SET DEFAULT 1; ALTER TABLE version_downloads ALTER counted SET DEFAULT 0; ALTER TABLE version_downloads ALTER date SET DEFAULT current_date; @@ -536,11 +536,11 @@ fn migrations() -> Vec { CREATE TRIGGER trigger_versions_set_updated_at BEFORE UPDATE ON versions FOR EACH ROW EXECUTE PROCEDURE set_updated_at(); - ")); + ")?; Ok(()) }, |tx| { - try!(tx.batch_execute(" + tx.batch_execute(" ALTER TABLE version_downloads ALTER downloads DROP DEFAULT; ALTER TABLE version_downloads ALTER counted DROP DEFAULT; ALTER TABLE version_downloads ALTER date DROP DEFAULT; @@ -570,11 +570,11 @@ fn migrations() -> Vec { DROP TRIGGER trigger_versions_set_updated_at ON versions; DROP FUNCTION set_updated_at(); - ")); + ")?; Ok(()) }), Migration::new(20151211122515, |tx| { - try!(tx.batch_execute(" + tx.batch_execute(" CREATE FUNCTION set_updated_at_ignore_downloads() RETURNS trigger AS $$ BEGIN IF (NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at AND @@ -594,10 +594,10 @@ fn migrations() -> Vec { CREATE TRIGGER trigger_versions_set_updated_at BEFORE UPDATE ON versions FOR EACH ROW EXECUTE PROCEDURE set_updated_at_ignore_downloads(); - ")); + ")?; Ok(()) }, |tx| { - try!(tx.batch_execute(" + tx.batch_execute(" DROP TRIGGER trigger_crates_set_updated_at ON crates; DROP TRIGGER trigger_versions_set_updated_at ON versions; DROP FUNCTION set_updated_at_ignore_downloads(); @@ -608,7 +608,7 @@ fn migrations() -> Vec { CREATE TRIGGER trigger_versions_set_updated_at BEFORE UPDATE ON versions FOR EACH ROW EXECUTE PROCEDURE set_updated_at(); - ")); + ")?; Ok(()) }), Migration::new(20160219125609, |tx| { @@ -683,16 +683,16 @@ fn migrations() -> Vec { Migration::new(20160326123149, |tx| { use postgres::error::{Error, SqlState}; - for row in try!(tx.query("SELECT id FROM keywords ORDER BY id", &[])).iter() { + for row in tx.query("SELECT id FROM keywords ORDER BY id", &[])?.iter() { let kw_id: i32 = row.get(0); let err = { - let tx = try!(tx.transaction()); + let tx = tx.transaction()?; let res = tx.execute("UPDATE keywords SET keyword = LOWER(keyword) WHERE id = $1", &[&kw_id]); match res { Ok(n) => { assert_eq!(n, 1); - try!(tx.commit()); + tx.commit()?; continue; }, Err(e) => /* Rollback update, fall through */ e @@ -703,20 +703,20 @@ fn migrations() -> Vec { Error::Db(ref e) if e.code == SqlState::UniqueViolation => { // There is already a lower-case version of this keyword. // Merge into the other one. - let target_id: i32 = try!(tx.query(" + let target_id: i32 = tx.query(" SELECT id FROM keywords WHERE keyword = LOWER(( SELECT keyword FROM keywords WHERE id = $1 )) - ", &[&kw_id])).get(0).get(0); + ", &[&kw_id])?.get(0).get(0); - try!(tx.batch_execute(&format!(" + tx.batch_execute(&format!(" UPDATE crates_keywords SET keyword_id = {} WHERE keyword_id = {}; UPDATE keywords SET crates_cnt = crates_cnt + ( SELECT crates_cnt FROM keywords WHERE id = {} ) WHERE id = {}; DELETE FROM keywords WHERE id = {}; - ", target_id, kw_id, kw_id, target_id, kw_id))); + ", target_id, kw_id, kw_id, target_id, kw_id))?; }, e => return Err(e) } @@ -741,12 +741,12 @@ fn migrations() -> Vec { Migration::add_column(20160811151953, "users", "gh_id", "INTEGER"), index(20160811151954, "users", "gh_id"), Migration::new(20160812094501, |tx| { - try!(tx.execute("ALTER TABLE users ALTER COLUMN gh_id \ - SET NOT NULL", &[])); + tx.execute("ALTER TABLE users ALTER COLUMN gh_id \ + SET NOT NULL", &[])?; Ok(()) }, |tx| { - try!(tx.execute("ALTER TABLE users ALTER COLUMN gh_id \ - DROP NOT NULL", &[])); + tx.execute("ALTER TABLE users ALTER COLUMN gh_id \ + DROP NOT NULL", &[])?; Ok(()) }), Migration::new(20160812094502, |tx| { @@ -755,11 +755,11 @@ fn migrations() -> Vec { // had to fill it in at one point after-the-fact. User rows that // couldn't be resolved either have a github id of 0 or -1 so they // can't ever be logged into again. - try!(tx.execute("CREATE UNIQUE INDEX users_gh_id \ - ON users (gh_id) WHERE gh_id > 0", &[])); + tx.execute("CREATE UNIQUE INDEX users_gh_id \ + ON users (gh_id) WHERE gh_id > 0", &[])?; Ok(()) }, |tx| { - try!(tx.execute("DROP INDEX users_gh_id", &[])); + tx.execute("DROP INDEX users_gh_id", &[])?; Ok(()) }), Migration::add_table(20161115110541, "categories", " \ @@ -783,7 +783,7 @@ fn migrations() -> Vec { index(20161115111853, "crates_categories", "crate_id"), index(20161115111900, "crates_categories", "category_id"), Migration::new(20161115111957, |tx| { - try!(tx.batch_execute(" \ + tx.batch_execute(" \ CREATE FUNCTION update_categories_crates_cnt() \ RETURNS trigger AS $$ \ BEGIN \ @@ -808,15 +808,15 @@ fn migrations() -> Vec { AFTER INSERT OR DELETE ON crates_categories \ FOR EACH ROW \ EXECUTE PROCEDURE touch_crate(); \ - ")); + ")?; Ok(()) }, |tx| { - try!(tx.batch_execute(" \ + tx.batch_execute(" \ DROP TRIGGER trigger_update_categories_crates_cnt \ ON crates_categories; \ DROP FUNCTION update_categories_crates_cnt(); \ DROP TRIGGER touch_crate_on_modify_categories \ - ON crates_categories;")); + ON crates_categories;")?; Ok(()) }), Migration::add_table(20170102131034, "badges", " \ @@ -824,11 +824,11 @@ fn migrations() -> Vec { badge_type VARCHAR NOT NULL, \ attributes JSONB NOT NULL"), Migration::new(20170102145236, |tx| { - try!(tx.execute("CREATE UNIQUE INDEX badges_crate_type \ - ON badges (crate_id, badge_type)", &[])); + tx.execute("CREATE UNIQUE INDEX badges_crate_type \ + ON badges (crate_id, badge_type)", &[])?; Ok(()) }, |tx| { - try!(tx.execute("DROP INDEX badges_crate_type", &[])); + tx.execute("DROP INDEX badges_crate_type", &[])?; Ok(()) }), ]; @@ -878,24 +878,24 @@ fn migrations() -> Vec { // DO NOT UPDATE OR USE FOR NEW MIGRATIONS fn fix_duplicate_crate_owners(tx: &postgres::transaction::Transaction) -> postgres::Result<()> { let v: Vec<(i32, i32)> = { - let stmt = try!(tx.prepare("SELECT user_id, crate_id + let stmt = tx.prepare("SELECT user_id, crate_id FROM crate_owners GROUP BY user_id, crate_id - HAVING COUNT(*) > 1")); - let rows = try!(stmt.query(&[])); + HAVING COUNT(*) > 1")?; + let rows = stmt.query(&[])?; rows.iter().map(|row| { (row.get("user_id"), row.get("crate_id")) }).collect() }; for &(user_id, crate_id) in v.iter() { - let stmt = try!(tx.prepare("SELECT id FROM crate_owners + let stmt = tx.prepare("SELECT id FROM crate_owners WHERE user_id = $1 AND crate_id = $2 ORDER BY created_at ASC - OFFSET 1")); - let rows = try!(stmt.query(&[&user_id, &crate_id])); + OFFSET 1")?; + let rows = stmt.query(&[&user_id, &crate_id])?; for row in rows.iter() { let id: i32 = row.get("id"); - try!(tx.execute("DELETE FROM crate_owners WHERE id = $1", &[&id])); + tx.execute("DELETE FROM crate_owners WHERE id = $1", &[&id])?; } } Ok(()) diff --git a/src/bin/populate.rs b/src/bin/populate.rs index bbb44d20616..b4567d6c367 100644 --- a/src/bin/populate.rs +++ b/src/bin/populate.rs @@ -38,10 +38,10 @@ fn update(tx: &postgres::transaction::Transaction) -> postgres::Result<()> { for day in 0..90 { let moment = now + Duration::days(-day); dls += rng.gen_range(-100, 100); - try!(tx.execute("INSERT INTO version_downloads \ + tx.execute("INSERT INTO version_downloads \ (version_id, downloads, date) \ VALUES ($1, $2, $3)", - &[&id, &dls, &moment])); + &[&id, &dls, &moment])?; } } Ok(()) diff --git a/src/bin/update-downloads.rs b/src/bin/update-downloads.rs index bbf8e87d071..3c8bffcfac9 100644 --- a/src/bin/update-downloads.rs +++ b/src/bin/update-downloads.rs @@ -36,20 +36,20 @@ fn update(conn: &postgres::GenericConnection) -> postgres::Result<()> { loop { // FIXME(rust-lang/rust#27401): weird declaration to make sure this // variable gets dropped. - let tx; tx = try!(conn.transaction()); + let tx; tx = conn.transaction()?; { - let stmt = try!(tx.prepare("SELECT * FROM version_downloads \ + let stmt = tx.prepare("SELECT * FROM version_downloads \ WHERE processed = FALSE AND id > $1 ORDER BY id ASC - LIMIT $2")); - let mut rows = try!(stmt.query(&[&max, &LIMIT])); - match try!(collect(&tx, &mut rows)) { + LIMIT $2")?; + let mut rows = stmt.query(&[&max, &LIMIT])?; + match collect(&tx, &mut rows)? { None => break, Some(m) => max = m, } } tx.set_commit(); - try!(tx.finish()); + tx.finish()?; } Ok(()) } @@ -87,10 +87,10 @@ fn collect(tx: &postgres::transaction::Transaction, // Flag this row as having been processed if we're passed the cutoff, // and unconditionally increment the number of counted downloads. - try!(tx.execute("UPDATE version_downloads + tx.execute("UPDATE version_downloads SET processed = $2, counted = counted + $3 WHERE id = $1", - &[id, &(download.date < cutoff), &amt])); + &[id, &(download.date < cutoff), &amt])?; println!("{}\n{}", time::at(download.date).rfc822(), time::at(cutoff).rfc822()); total += amt as i64; @@ -102,31 +102,31 @@ fn collect(tx: &postgres::transaction::Transaction, let crate_id = Version::find(tx, download.version_id).unwrap().crate_id; // Update the total number of version downloads - try!(tx.execute("UPDATE versions + tx.execute("UPDATE versions SET downloads = downloads + $1 WHERE id = $2", - &[&amt, &download.version_id])); + &[&amt, &download.version_id])?; // Update the total number of crate downloads - try!(tx.execute("UPDATE crates SET downloads = downloads + $1 - WHERE id = $2", &[&amt, &crate_id])); + tx.execute("UPDATE crates SET downloads = downloads + $1 + WHERE id = $2", &[&amt, &crate_id])?; // Update the total number of crate downloads for today - let cnt = try!(tx.execute("UPDATE crate_downloads + let cnt = tx.execute("UPDATE crate_downloads SET downloads = downloads + $2 WHERE crate_id = $1 AND date = date($3)", - &[&crate_id, &amt, &download.date])); + &[&crate_id, &amt, &download.date])?; if cnt == 0 { - try!(tx.execute("INSERT INTO crate_downloads + tx.execute("INSERT INTO crate_downloads (crate_id, downloads, date) VALUES ($1, $2, $3)", - &[&crate_id, &amt, &download.date])); + &[&crate_id, &amt, &download.date])?; } } // After everything else is done, update the global counter of total // downloads. - try!(tx.execute("UPDATE metadata SET total_downloads = total_downloads + $1", - &[&total])); + tx.execute("UPDATE metadata SET total_downloads = total_downloads + $1", + &[&total])?; Ok(Some(max)) } diff --git a/src/category.rs b/src/category.rs index 49920dfeb3c..f209acea690 100644 --- a/src/category.rs +++ b/src/category.rs @@ -45,9 +45,9 @@ pub struct EncodableCategoryWithSubcategories { impl Category { pub fn find_by_category(conn: &GenericConnection, name: &str) -> CargoResult { - let stmt = try!(conn.prepare("SELECT * FROM categories \ - WHERE category = $1")); - let rows = try!(stmt.query(&[&name])); + let stmt = conn.prepare("SELECT * FROM categories \ + WHERE category = $1")?; + let rows = stmt.query(&[&name])?; rows.iter().next() .chain_error(|| NotFound) .map(|row| Model::from_row(&row)) @@ -55,9 +55,9 @@ impl Category { pub fn find_by_slug(conn: &GenericConnection, slug: &str) -> CargoResult { - let stmt = try!(conn.prepare("SELECT * FROM categories \ - WHERE slug = LOWER($1)")); - let rows = try!(stmt.query(&[&slug])); + let stmt = conn.prepare("SELECT * FROM categories \ + WHERE slug = LOWER($1)")?; + let rows = stmt.query(&[&slug])?; rows.iter().next() .chain_error(|| NotFound) .map(|row| Model::from_row(&row)) @@ -80,7 +80,7 @@ impl Category { pub fn update_crate(conn: &GenericConnection, krate: &Crate, categories: &[String]) -> CargoResult> { - let old_categories = try!(krate.categories(conn)); + let old_categories = krate.categories(conn)?; let old_categories_ids: HashSet<_> = old_categories.iter().map(|cat| { cat.id }).collect(); @@ -112,10 +112,10 @@ impl Category { .collect(); if !to_rm.is_empty() { - try!(conn.execute("DELETE FROM crates_categories \ + conn.execute("DELETE FROM crates_categories \ WHERE category_id = ANY($1) \ AND crate_id = $2", - &[&to_rm, &krate.id])); + &[&to_rm, &krate.id])?; } if !to_add.is_empty() { @@ -123,10 +123,10 @@ impl Category { format!("({}, {})", krate.id, id) }).collect(); let insert = insert.join(", "); - try!(conn.execute(&format!("INSERT INTO crates_categories \ + conn.execute(&format!("INSERT INTO crates_categories \ (crate_id, category_id) VALUES {}", - insert), - &[])); + insert), + &[])?; } Ok(invalid_categories) @@ -139,8 +139,8 @@ impl Category { WHERE category NOT LIKE '%::%'", Model::table_name(None:: )); - let stmt = try!(conn.prepare(&sql)); - let rows = try!(stmt.query(&[])); + let stmt = conn.prepare(&sql)?; + let rows = stmt.query(&[])?; Ok(rows.iter().next().unwrap().get("count")) } @@ -156,7 +156,7 @@ impl Category { // Collect all the top-level categories and sum up the crates_cnt of // the crates in all subcategories - let stmt = try!(conn.prepare(&format!( + let stmt = conn.prepare(&format!( "SELECT c.id, c.category, c.slug, c.description, c.created_at, \ COALESCE (( \ SELECT sum(c2.crates_cnt)::int \ @@ -167,10 +167,10 @@ impl Category { FROM categories as c \ WHERE c.category NOT LIKE '%::%' {} \ LIMIT $1 OFFSET $2", - sort_sql - ))); + sort_sql + ))?; - let categories: Vec<_> = try!(stmt.query(&[&limit, &offset])) + let categories: Vec<_> = stmt.query(&[&limit, &offset])? .iter() .map(|row| Model::from_row(&row)) .collect(); @@ -180,7 +180,7 @@ impl Category { pub fn subcategories(&self, conn: &GenericConnection) -> CargoResult> { - let stmt = try!(conn.prepare("\ + let stmt = conn.prepare("\ SELECT c.id, c.category, c.slug, c.description, c.created_at, \ COALESCE (( \ SELECT sum(c2.crates_cnt)::int \ @@ -190,9 +190,9 @@ impl Category { ), 0) as crates_cnt \ FROM categories as c \ WHERE c.category ILIKE $1 || '::%' \ - AND c.category NOT ILIKE $1 || '::%::%'")); + AND c.category NOT ILIKE $1 || '::%::%'")?; - let rows = try!(stmt.query(&[&self.category])); + let rows = stmt.query(&[&self.category])?; Ok(rows.iter().map(|r| Model::from_row(&r)).collect()) } } @@ -213,16 +213,16 @@ impl Model for Category { /// Handles the `GET /categories` route. pub fn index(req: &mut Request) -> CargoResult { - let conn = try!(req.tx()); - let (offset, limit) = try!(req.pagination(10, 100)); + let conn = req.tx()?; + let (offset, limit) = req.pagination(10, 100)?; let query = req.query(); let sort = query.get("sort").map_or("alpha", String::as_str); - let categories = try!(Category::toplevel(conn, sort, limit, offset)); + let categories = Category::toplevel(conn, sort, limit, offset)?; let categories = categories.into_iter().map(Category::encodable).collect(); // Query for the total count of categories - let total = try!(Category::count_toplevel(conn)); + let total = Category::count_toplevel(conn)?; #[derive(RustcEncodable)] struct R { categories: Vec, meta: Meta } @@ -238,9 +238,9 @@ pub fn index(req: &mut Request) -> CargoResult { /// Handles the `GET /categories/:category_id` route. pub fn show(req: &mut Request) -> CargoResult { let slug = &req.params()["category_id"]; - let conn = try!(req.tx()); - let cat = try!(Category::find_by_slug(&*conn, &slug)); - let subcats = try!(cat.subcategories(&*conn)).into_iter().map(|s| { + let conn = req.tx()?; + let cat = Category::find_by_slug(&*conn, &slug)?; + let subcats = cat.subcategories(&*conn)?.into_iter().map(|s| { s.encodable() }).collect(); let cat = cat.encodable(); @@ -261,10 +261,10 @@ pub fn show(req: &mut Request) -> CargoResult { /// Handles the `GET /category_slugs` route. pub fn slugs(req: &mut Request) -> CargoResult { - let conn = try!(req.tx()); - let stmt = try!(conn.prepare("SELECT slug FROM categories \ - ORDER BY slug")); - let rows = try!(stmt.query(&[])); + let conn = req.tx()?; + let stmt = conn.prepare("SELECT slug FROM categories \ + ORDER BY slug")?; + let rows = stmt.query(&[])?; #[derive(RustcEncodable)] struct Slug { id: String, slug: String } diff --git a/src/db.rs b/src/db.rs index a50dfaf2272..3dd71d5acca 100644 --- a/src/db.rs +++ b/src/db.rs @@ -58,7 +58,7 @@ pub fn tls_handshake() -> Box { _domain: &str, stream: Stream) -> Result, Box> { - let stream = try!(self.0.danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication(stream)); + let stream = self.0.danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication(stream)?; Ok(Box::new(stream)) } } @@ -131,9 +131,9 @@ impl Transaction { pub fn conn(&self) -> CargoResult<&r2d2::PooledConnection> { if !self.slot.filled() { - let conn = try!(self.app.database.get().map_err(|e| { + let conn = self.app.database.get().map_err(|e| { internal(format!("failed to get a database connection: {}", e)) - })); + })?; self.slot.fill(Box::new(conn)); } Ok(&**self.slot.borrow().unwrap()) @@ -146,8 +146,8 @@ impl Transaction { // desired effect. unsafe { if !self.tx.filled() { - let conn = try!(self.conn()); - let t = try!(conn.transaction()); + let conn = self.conn()?; + let t = conn.transaction()?; let t = mem::transmute::<_, pg::transaction::Transaction<'static>>(t); self.tx.fill(t); } @@ -183,9 +183,9 @@ impl Middleware for TransactionMiddleware { if res.is_ok() && tx.commit.get() == Some(true) { transaction.set_commit(); } - try!(transaction.finish().map_err(|e| { - Box::new(e) as Box - })); + transaction.finish().map_err(|e| { + Box::new(e) as Box + })?; } return res } diff --git a/src/dependency.rs b/src/dependency.rs index 78db2f8afd5..29c88756640 100644 --- a/src/dependency.rs +++ b/src/dependency.rs @@ -51,14 +51,14 @@ impl Dependency { -> CargoResult { let req = req.to_string(); let features = features.join(","); - let stmt = try!(conn.prepare("INSERT INTO dependencies + let stmt = conn.prepare("INSERT INTO dependencies (version_id, crate_id, req, optional, default_features, features, target, kind) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) - RETURNING *")); - let rows = try!(stmt.query(&[&version_id, &crate_id, &req, - &optional, &default_features, - &features, target, &(kind as i32)])); + RETURNING *")?; + let rows = stmt.query(&[&version_id, &crate_id, &req, + &optional, &default_features, + &features, target, &(kind as i32)])?; Ok(Model::from_row(&rows.iter().next().unwrap())) } diff --git a/src/git.rs b/src/git.rs index 6d31c5c9c0c..37b20982ee4 100644 --- a/src/git.rs +++ b/src/git.rs @@ -53,16 +53,16 @@ pub fn add_crate(app: &App, krate: &Crate) -> CargoResult<()> { commit_and_push(repo, || { // Add the crate to its relevant file - try!(fs::create_dir_all(dst.parent().unwrap())); + fs::create_dir_all(dst.parent().unwrap())?; let mut prev = String::new(); if fs::metadata(&dst).is_ok() { - try!(File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev))); + File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev))?; } let s = json::encode(krate).unwrap(); let new = prev + &s; - let mut f = try!(File::create(&dst)); - try!(f.write_all(new.as_bytes())); - try!(f.write_all(b"\n")); + let mut f = File::create(&dst)?; + f.write_all(new.as_bytes())?; + f.write_all(b"\n")?; Ok((format!("Updating crate `{}#{}`", krate.name, krate.vers), dst.clone())) @@ -78,11 +78,11 @@ pub fn yank(app: &App, krate: &str, version: &semver::Version, commit_and_push(repo, || { let mut prev = String::new(); - try!(File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev))); + File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev))?; let new = prev.lines().map(|line| { - let mut git_crate = try!(json::decode::(line).map_err(|_| { + let mut git_crate = json::decode::(line).map_err(|_| { internal(format!("couldn't decode: `{}`", line)) - })); + })?; if git_crate.name != krate || git_crate.vers.to_string() != version.to_string() { return Ok(line.to_string()) @@ -90,10 +90,10 @@ pub fn yank(app: &App, krate: &str, version: &semver::Version, git_crate.yanked = Some(yanked); Ok(json::encode(&git_crate).unwrap()) }).collect::>>(); - let new = try!(new).join("\n"); - let mut f = try!(File::create(&dst)); - try!(f.write_all(new.as_bytes())); - try!(f.write_all(b"\n")); + let new = new?.join("\n"); + let mut f = File::create(&dst)?; + f.write_all(new.as_bytes())?; + f.write_all(b"\n")?; Ok((format!("{} crate `{}#{}`", if yanked {"Yanking"} else {"Unyanking"}, @@ -112,27 +112,27 @@ fn commit_and_push(repo: &git2::Repository, mut f: F) -> CargoResult<()> // race to commit the changes. For now we just cap out the maximum number of // retries at a fixed number. for _ in 0..20 { - let (msg, dst) = try!(f()); + let (msg, dst) = f()?; // git add $file - let mut index = try!(repo.index()); + let mut index = repo.index()?; let mut repo_path = repo_path.iter(); let dst = dst.iter().skip_while(|s| Some(*s) == repo_path.next()) .collect::(); - try!(index.add_path(&dst)); - try!(index.write()); - let tree_id = try!(index.write_tree()); - let tree = try!(repo.find_tree(tree_id)); + index.add_path(&dst)?; + index.write()?; + let tree_id = index.write_tree()?; + let tree = repo.find_tree(tree_id)?; // git commit -m "..." - let head = try!(repo.head()); - let parent = try!(repo.find_commit(head.target().unwrap())); - let sig = try!(repo.signature()); - try!(repo.commit(Some("HEAD"), &sig, &sig, &msg, &tree, &[&parent])); + let head = repo.head()?; + let parent = repo.find_commit(head.target().unwrap())?; + let sig = repo.signature()?; + repo.commit(Some("HEAD"), &sig, &sig, &msg, &tree, &[&parent])?; // git push let mut ref_status = None; - let mut origin = try!(repo.find_remote("origin")); + let mut origin = repo.find_remote("origin")?; let res = { let mut callbacks = git2::RemoteCallbacks::new(); callbacks.credentials(credentials); @@ -153,15 +153,15 @@ fn commit_and_push(repo: &git2::Repository, mut f: F) -> CargoResult<()> let mut callbacks = git2::RemoteCallbacks::new(); callbacks.credentials(credentials); - try!(origin.update_tips(Some(&mut callbacks), true, - git2::AutotagOption::Unspecified, - None)); + origin.update_tips(Some(&mut callbacks), true, + git2::AutotagOption::Unspecified, + None)?; // Ok, we need to update, so fetch and reset --hard - try!(origin.fetch(&["refs/heads/*:refs/heads/*"], None, None)); - let head = try!(repo.head()).target().unwrap(); - let obj = try!(repo.find_object(head, None)); - try!(repo.reset(&obj, git2::ResetType::Hard, None)); + origin.fetch(&["refs/heads/*:refs/heads/*"], None, None)?; + let head = repo.head()?.target().unwrap(); + let obj = repo.find_object(head, None)?; + repo.reset(&obj, git2::ResetType::Hard, None)?; } Err(internal("Too many rebase failures")) diff --git a/src/http.rs b/src/http.rs index a3e9ad022e7..7dbefd52734 100644 --- a/src/http.rs +++ b/src/http.rs @@ -32,7 +32,7 @@ pub fn github(app: &App, url: &str, auth: &Token) data.extend_from_slice(buf); Ok(buf.len()) }).unwrap(); - try!(transfer.perform()); + transfer.perform()?; } Ok((handle, data)) } @@ -58,9 +58,9 @@ pub fn parse_github_response(mut resp: Easy, data: Vec) } } - let json = try!(str::from_utf8(&data).ok().chain_error(||{ + let json = str::from_utf8(&data).ok().chain_error(|| { internal("github didn't send a utf8-response") - })); + })?; json::decode(json).chain_error(|| { internal("github didn't send a valid json response") diff --git a/src/keyword.rs b/src/keyword.rs index f82615c6fb2..6ebc5b64ab2 100644 --- a/src/keyword.rs +++ b/src/keyword.rs @@ -31,27 +31,27 @@ pub struct EncodableKeyword { impl Keyword { pub fn find_by_keyword(conn: &GenericConnection, name: &str) -> CargoResult> { - let stmt = try!(conn.prepare("SELECT * FROM keywords \ - WHERE keyword = LOWER($1)")); - let rows = try!(stmt.query(&[&name])); + let stmt = conn.prepare("SELECT * FROM keywords \ + WHERE keyword = LOWER($1)")?; + let rows = stmt.query(&[&name])?; Ok(rows.iter().next().map(|r| Model::from_row(&r))) } pub fn find_or_insert(conn: &GenericConnection, name: &str) -> CargoResult { // TODO: racy (the select then insert is not atomic) - let stmt = try!(conn.prepare("SELECT * FROM keywords - WHERE keyword = LOWER($1)")); - for row in try!(stmt.query(&[&name])).iter() { + let stmt = conn.prepare("SELECT * FROM keywords + WHERE keyword = LOWER($1)")?; + for row in stmt.query(&[&name])?.iter() { return Ok(Model::from_row(&row)) } - let stmt = try!(conn.prepare("INSERT INTO keywords (keyword) VALUES (LOWER($1)) - RETURNING *")); - let rows = try!(stmt.query(&[&name])); - Ok(Model::from_row(&try!(rows.iter().next().chain_error(|| { + let stmt = conn.prepare("INSERT INTO keywords (keyword) VALUES (LOWER($1)) + RETURNING *")?; + let rows = stmt.query(&[&name])?; + Ok(Model::from_row(&rows.iter().next().chain_error(|| { internal("no version returned") - })))) + })?)) } pub fn all(conn: &GenericConnection, sort: &str, limit: i64, offset: i64) @@ -62,11 +62,11 @@ impl Keyword { _ => "ORDER BY keyword ASC", }; - let stmt = try!(conn.prepare(&format!("SELECT * FROM keywords {} + let stmt = conn.prepare(&format!("SELECT * FROM keywords {} LIMIT $1 OFFSET $2", - sort_sql))); + sort_sql))?; - let keywords: Vec<_> = try!(stmt.query(&[&limit, &offset])) + let keywords: Vec<_> = stmt.query(&[&limit, &offset])? .iter() .map(|row| Model::from_row(&row)) .collect(); @@ -94,14 +94,14 @@ impl Keyword { pub fn update_crate(conn: &GenericConnection, krate: &Crate, keywords: &[String]) -> CargoResult<()> { - let old_kws = try!(krate.keywords(conn)); + let old_kws = krate.keywords(conn)?; let old_kws = old_kws.iter().map(|kw| { (&kw.keyword[..], kw) }).collect::>(); - let new_kws = try!(keywords.iter().map(|k| { - let kw = try!(Keyword::find_or_insert(conn, &k)); + let new_kws = keywords.iter().map(|k| { + let kw = Keyword::find_or_insert(conn, &k)?; Ok((&k[..], kw)) - }).collect::>>()); + }).collect::>>()?; let to_rm = old_kws.iter().filter(|&(kw, _)| { !new_kws.contains_key(kw) @@ -111,10 +111,10 @@ impl Keyword { }).map(|(_, v)| v.id).collect::>(); if to_rm.len() > 0 { - try!(conn.execute("DELETE FROM crates_keywords + conn.execute("DELETE FROM crates_keywords WHERE keyword_id = ANY($1) AND crate_id = $2", - &[&to_rm, &krate.id])); + &[&to_rm, &krate.id])?; } if to_add.len() > 0 { @@ -123,10 +123,10 @@ impl Keyword { let id: i32 = *id; format!("({}, {})", crate_id, id) }).collect::>().join(", "); - try!(conn.execute(&format!("INSERT INTO crates_keywords + conn.execute(&format!("INSERT INTO crates_keywords (crate_id, keyword_id) VALUES {}", - insert), - &[])); + insert), + &[])?; } Ok(()) @@ -147,16 +147,16 @@ impl Model for Keyword { /// Handles the `GET /keywords` route. pub fn index(req: &mut Request) -> CargoResult { - let conn = try!(req.tx()); - let (offset, limit) = try!(req.pagination(10, 100)); + let conn = req.tx()?; + let (offset, limit) = req.pagination(10, 100)?; let query = req.query(); let sort = query.get("sort").map(|s| &s[..]).unwrap_or("alpha"); - let keywords = try!(Keyword::all(conn, sort, limit, offset)); + let keywords = Keyword::all(conn, sort, limit, offset)?; let keywords = keywords.into_iter().map(Keyword::encodable).collect(); // Query for the total count of keywords - let total = try!(Keyword::count(conn)); + let total = Keyword::count(conn)?; #[derive(RustcEncodable)] struct R { keywords: Vec, meta: Meta } @@ -172,9 +172,9 @@ pub fn index(req: &mut Request) -> CargoResult { /// Handles the `GET /keywords/:keyword_id` route. pub fn show(req: &mut Request) -> CargoResult { let name = &req.params()["keyword_id"]; - let conn = try!(req.tx()); - let kw = try!(Keyword::find_by_keyword(&*conn, &name)); - let kw = try!(kw.chain_error(|| NotFound)); + let conn = req.tx()?; + let kw = Keyword::find_by_keyword(&*conn, &name)?; + let kw = kw.chain_error(|| NotFound)?; #[derive(RustcEncodable)] struct R { keyword: EncodableKeyword } diff --git a/src/krate.rs b/src/krate.rs index 19717660979..b2057221c52 100644 --- a/src/krate.rs +++ b/src/krate.rs @@ -85,12 +85,12 @@ pub struct CrateLinks { impl Crate { pub fn find_by_name(conn: &GenericConnection, name: &str) -> CargoResult { - let stmt = try!(conn.prepare("SELECT * FROM crates \ + let stmt = conn.prepare("SELECT * FROM crates \ WHERE canon_crate_name(name) = - canon_crate_name($1) LIMIT 1")); - let rows = try!(stmt.query(&[&name])); + canon_crate_name($1) LIMIT 1")?; + let rows = stmt.query(&[&name])?; let row = rows.iter().next(); - let row = try!(row.chain_error(|| NotFound)); + let row = row.chain_error(|| NotFound)?; Ok(Model::from_row(&row)) } @@ -113,14 +113,14 @@ impl Crate { let repository = repository.as_ref().map(|s| &s[..]); let mut license = license.as_ref().map(|s| &s[..]); let license_file = license_file.as_ref().map(|s| &s[..]); - try!(validate_url(homepage, "homepage")); - try!(validate_url(documentation, "documentation")); - try!(validate_url(repository, "repository")); + validate_url(homepage, "homepage")?; + validate_url(documentation, "documentation")?; + validate_url(repository, "repository")?; match license { // If a license is given, validate it to make sure it's actually a // valid license - Some(..) => try!(validate_license(license)), + Some(..) => validate_license(license)?, // If no license is given, but a license file is given, flag this // crate as having a nonstandard license. Note that we don't @@ -133,7 +133,7 @@ impl Crate { } // TODO: like with users, this is sadly racy - let stmt = try!(conn.prepare("UPDATE crates + let stmt = conn.prepare("UPDATE crates SET documentation = $1, homepage = $2, description = $3, @@ -142,11 +142,11 @@ impl Crate { repository = $6 WHERE canon_crate_name(name) = canon_crate_name($7) - RETURNING *")); - let rows = try!(stmt.query(&[&documentation, &homepage, - &description, &readme, - &license, &repository, - &name])); + RETURNING *")?; + let rows = stmt.query(&[&documentation, &homepage, + &description, &readme, + &license, &repository, + &name])?; match rows.iter().next() { Some(row) => return Ok(Model::from_row(&row)), None => {} @@ -159,23 +159,23 @@ impl Crate { return Err(human("cannot upload a crate with a reserved name")) } - let stmt = try!(conn.prepare("INSERT INTO crates + let stmt = conn.prepare("INSERT INTO crates (name, description, homepage, documentation, readme, repository, license, max_upload_size) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) - RETURNING *")); - let rows = try!(stmt.query(&[&name, &description, &homepage, - &documentation, &readme, - &repository, &license, &max_upload_size])); - let ret: Crate = Model::from_row(&try!(rows.iter().next().chain_error(|| { + RETURNING *")?; + let rows = stmt.query(&[&name, &description, &homepage, + &documentation, &readme, + &repository, &license, &max_upload_size])?; + let ret: Crate = Model::from_row(&rows.iter().next().chain_error(|| { internal("no crate returned") - }))); + })?); - try!(conn.execute("INSERT INTO crate_owners + conn.execute("INSERT INTO crate_owners (crate_id, owner_id, created_by, owner_kind) VALUES ($1, $2, $2, $3)", - &[&ret.id, &user_id, &(OwnerKind::User as i32)])); + &[&ret.id, &user_id, &(OwnerKind::User as i32)])?; return Ok(ret); fn validate_url(url: Option<&str>, field: &str) -> CargoResult<()> { @@ -183,9 +183,9 @@ impl Crate { Some(s) => s, None => return Ok(()) }; - let url = try!(Url::parse(url).map_err(|_| { + let url = Url::parse(url).map_err(|_| { human(format!("`{}` is not a valid url: `{}`", field, url)) - })); + })?; match &url.scheme()[..] { "http" | "https" => {} s => return Err(human(format!("`{}` has an invalid url \ @@ -282,9 +282,9 @@ impl Crate { } pub fn versions(&self, conn: &GenericConnection) -> CargoResult> { - let stmt = try!(conn.prepare("SELECT * FROM versions \ - WHERE crate_id = $1")); - let rows = try!(stmt.query(&[&self.id])); + let stmt = conn.prepare("SELECT * FROM versions \ + WHERE crate_id = $1")?; + let rows = stmt.query(&[&self.id])?; let mut ret = rows.iter().map(|r| { Model::from_row(&r) }).collect::>(); @@ -293,21 +293,21 @@ impl Crate { } pub fn owners(&self, conn: &GenericConnection) -> CargoResult> { - let stmt = try!(conn.prepare("SELECT * FROM users + let stmt = conn.prepare("SELECT * FROM users INNER JOIN crate_owners ON crate_owners.owner_id = users.id WHERE crate_owners.crate_id = $1 AND crate_owners.deleted = FALSE - AND crate_owners.owner_kind = $2")); - let user_rows = try!(stmt.query(&[&self.id, &(OwnerKind::User as i32)])); + AND crate_owners.owner_kind = $2")?; + let user_rows = stmt.query(&[&self.id, &(OwnerKind::User as i32)])?; - let stmt = try!(conn.prepare("SELECT * FROM teams + let stmt = conn.prepare("SELECT * FROM teams INNER JOIN crate_owners ON crate_owners.owner_id = teams.id WHERE crate_owners.crate_id = $1 AND crate_owners.deleted = FALSE - AND crate_owners.owner_kind = $2")); - let team_rows = try!(stmt.query(&[&self.id, &(OwnerKind::Team as i32)])); + AND crate_owners.owner_kind = $2")?; + let team_rows = stmt.query(&[&self.id, &(OwnerKind::Team as i32)])?; let mut owners = vec![]; owners.extend(user_rows.iter().map(|r| Owner::User(Model::from_row(&r)))); @@ -319,14 +319,14 @@ impl Crate { login: &str) -> CargoResult<()> { let owner = match Owner::find_by_login(conn, login) { Ok(owner @ Owner::User(_)) => { owner } - Ok(Owner::Team(team)) => if try!(team.contains_user(app, req_user)) { + Ok(Owner::Team(team)) => if team.contains_user(app, req_user)? { Owner::Team(team) } else { return Err(human(format!("only members of {} can add it as \ an owner", login))); }, Err(err) => if login.contains(":") { - Owner::Team(try!(Team::create(app, conn, login, req_user))) + Owner::Team(Team::create(app, conn, login, req_user)?) } else { return Err(err); }, @@ -334,18 +334,18 @@ impl Crate { // First try to un-delete if they've been soft deleted previously, then // do an insert if that didn't actually affect anything. - let amt = try!(conn.execute("UPDATE crate_owners + let amt = conn.execute("UPDATE crate_owners SET deleted = FALSE WHERE crate_id = $1 AND owner_id = $2 AND owner_kind = $3", - &[&self.id, &owner.id(), &owner.kind()])); + &[&self.id, &owner.id(), &owner.kind()])?; assert!(amt <= 1); if amt == 0 { - try!(conn.execute("INSERT INTO crate_owners + conn.execute("INSERT INTO crate_owners (crate_id, owner_id, created_by, owner_kind) VALUES ($1, $2, $3, $4)", - &[&self.id, &owner.id(), &req_user.id, - &owner.kind()])); + &[&self.id, &owner.id(), &req_user.id, + &owner.kind()])?; } Ok(()) @@ -355,14 +355,14 @@ impl Crate { conn: &GenericConnection, _req_user: &User, login: &str) -> CargoResult<()> { - let owner = try!(Owner::find_by_login(conn, login).map_err(|_| { + let owner = Owner::find_by_login(conn, login).map_err(|_| { human(format!("could not find owner with login `{}`", login)) - })); - try!(conn.execute("UPDATE crate_owners + })?; + conn.execute("UPDATE crate_owners SET deleted = TRUE WHERE crate_id = $1 AND owner_id = $2 AND owner_kind = $3", - &[&self.id, &owner.id(), &owner.kind()])); + &[&self.id, &owner.id(), &owner.kind()])?; Ok(()) } @@ -376,7 +376,7 @@ impl Crate { features: &HashMap>, authors: &[String]) -> CargoResult { - match try!(Version::find_by_num(conn, self.id, ver)) { + match Version::find_by_num(conn, self.id, ver)? { Some(..) => { return Err(human(format!("crate version `{}` is already uploaded", ver))) @@ -387,36 +387,36 @@ impl Crate { if *ver > self.max_version || self.max_version == zero { self.max_version = ver.clone(); } - let stmt = try!(conn.prepare("UPDATE crates SET max_version = $1 - WHERE id = $2 RETURNING updated_at")); - let rows = try!(stmt.query(&[&self.max_version.to_string(), &self.id])); + let stmt = conn.prepare("UPDATE crates SET max_version = $1 + WHERE id = $2 RETURNING updated_at")?; + let rows = stmt.query(&[&self.max_version.to_string(), &self.id])?; self.updated_at = rows.get(0).get("updated_at"); Version::insert(conn, self.id, ver, features, authors) } pub fn keywords(&self, conn: &GenericConnection) -> CargoResult> { - let stmt = try!(conn.prepare("SELECT keywords.* FROM keywords + let stmt = conn.prepare("SELECT keywords.* FROM keywords LEFT JOIN crates_keywords ON keywords.id = crates_keywords.keyword_id - WHERE crates_keywords.crate_id = $1")); - let rows = try!(stmt.query(&[&self.id])); + WHERE crates_keywords.crate_id = $1")?; + let rows = stmt.query(&[&self.id])?; Ok(rows.iter().map(|r| Model::from_row(&r)).collect()) } pub fn categories(&self, conn: &GenericConnection) -> CargoResult> { - let stmt = try!(conn.prepare("SELECT categories.* FROM categories \ + let stmt = conn.prepare("SELECT categories.* FROM categories \ LEFT JOIN crates_categories \ ON categories.id = \ crates_categories.category_id \ - WHERE crates_categories.crate_id = $1")); - let rows = try!(stmt.query(&[&self.id])); + WHERE crates_categories.crate_id = $1")?; + let rows = stmt.query(&[&self.id])?; Ok(rows.iter().map(|r| Model::from_row(&r)).collect()) } pub fn badges(&self, conn: &GenericConnection) -> CargoResult> { - let stmt = try!(conn.prepare("SELECT badges.* from badges \ - WHERE badges.crate_id = $1")); - let rows = try!(stmt.query(&[&self.id])); + let stmt = conn.prepare("SELECT badges.* from badges \ + WHERE badges.crate_id = $1")?; + let rows = stmt.query(&[&self.id])?; Ok(rows.iter().map(|r| Model::from_row(&r)).collect()) } @@ -446,13 +446,13 @@ impl Crate { select_sql); let count_sql = format!("SELECT COUNT(DISTINCT(crates.id)) {}", select_sql); - let stmt = try!(conn.prepare(&fetch_sql)); - let vec: Vec<_> = try!(stmt.query(&[&self.id, &offset, &limit])) + let stmt = conn.prepare(&fetch_sql)?; + let vec: Vec<_> = stmt.query(&[&self.id, &offset, &limit])? .iter() .map(|r| (Model::from_row(&r), r.get("crate_name"), r.get("crate_downloads"))) .collect(); - let stmt = try!(conn.prepare(&count_sql)); - let cnt: i64 = try!(stmt.query(&[&self.id])).iter().next().unwrap().get(0); + let stmt = conn.prepare(&count_sql)?; + let cnt: i64 = stmt.query(&[&self.id])?.iter().next().unwrap().get(0); Ok((vec, cnt)) } @@ -483,8 +483,8 @@ impl Model for Crate { /// Handles the `GET /crates` route. #[allow(trivial_casts)] pub fn index(req: &mut Request) -> CargoResult { - let conn = try!(req.tx()); - let (offset, limit) = try!(req.pagination(10, 100)); + let conn = req.tx()?; + let (offset, limit) = req.pagination(10, 100)?; let query = req.query(); let sort = query.get("sort").map(|s| &s[..]).unwrap_or("alpha"); let sort_sql = match sort { @@ -590,7 +590,7 @@ pub fn index(req: &mut Request) -> CargoResult { if needs_id { if id == -1 { - id = try!(req.user()).id; + id = req.user()?.id; } args.insert(0, &id); } else if needs_pattern { @@ -598,18 +598,18 @@ pub fn index(req: &mut Request) -> CargoResult { } // Collect all the crates - let stmt = try!(conn.prepare(&q)); + let stmt = conn.prepare(&q)?; let mut crates = Vec::new(); - for row in try!(stmt.query(&args)).iter() { + for row in stmt.query(&args)?.iter() { let krate: Crate = Model::from_row(&row); let badges = krate.badges(conn); crates.push(krate.minimal_encodable(badges.ok())); } // Query for the total count of crates - let stmt = try!(conn.prepare(&cnt)); + let stmt = conn.prepare(&cnt)?; let args = if args.len() > 2 {&args[..1]} else {&args[..0]}; - let rows = try!(stmt.query(args)); + let rows = stmt.query(args)?; let row = rows.iter().next().unwrap(); let total = row.get(0); @@ -626,36 +626,36 @@ pub fn index(req: &mut Request) -> CargoResult { /// Handles the `GET /summary` route. pub fn summary(req: &mut Request) -> CargoResult { - let tx = try!(req.tx()); - let num_crates = try!(Crate::count(tx)); + let tx = req.tx()?; + let num_crates = Crate::count(tx)?; let num_downloads = { - let stmt = try!(tx.prepare("SELECT total_downloads FROM metadata")); - let rows = try!(stmt.query(&[])); + let stmt = tx.prepare("SELECT total_downloads FROM metadata")?; + let rows = stmt.query(&[])?; rows.iter().next().unwrap().get("total_downloads") }; let to_crates = |stmt: pg::stmt::Statement| -> CargoResult> { - let rows = try!(stmt.query(&[])); + let rows = stmt.query(&[])?; Ok(rows.iter().map(|r| { let krate: Crate = Model::from_row(&r); krate.minimal_encodable(None) }).collect::>()) }; - let new_crates = try!(tx.prepare("SELECT * FROM crates \ - ORDER BY created_at DESC LIMIT 10")); - let just_updated = try!(tx.prepare("SELECT * FROM crates \ + let new_crates = tx.prepare("SELECT * FROM crates \ + ORDER BY created_at DESC LIMIT 10")?; + let just_updated = tx.prepare("SELECT * FROM crates \ WHERE updated_at::timestamp(0) != created_at::timestamp(0) - ORDER BY updated_at DESC LIMIT 10")); - let most_downloaded = try!(tx.prepare("SELECT * FROM crates \ - ORDER BY downloads DESC LIMIT 10")); + ORDER BY updated_at DESC LIMIT 10")?; + let most_downloaded = tx.prepare("SELECT * FROM crates \ + ORDER BY downloads DESC LIMIT 10")?; - let popular_keywords = try!(Keyword::all(tx, "crates", 10, 0)); + let popular_keywords = Keyword::all(tx, "crates", 10, 0)?; let popular_keywords = popular_keywords.into_iter() .map(Keyword::encodable) .collect(); - let popular_categories = try!(Category::toplevel(tx, "crates", 10, 0)); + let popular_categories = Category::toplevel(tx, "crates", 10, 0)?; let popular_categories = popular_categories.into_iter() .map(Category::encodable) .collect(); @@ -673,9 +673,9 @@ pub fn summary(req: &mut Request) -> CargoResult { Ok(req.json(&R { num_downloads: num_downloads, num_crates: num_crates, - new_crates: try!(to_crates(new_crates)), - most_downloaded: try!(to_crates(most_downloaded)), - just_updated: try!(to_crates(just_updated)), + new_crates: to_crates(new_crates)?, + most_downloaded: to_crates(most_downloaded)?, + just_updated: to_crates(just_updated)?, popular_keywords: popular_keywords, popular_categories: popular_categories, })) @@ -684,13 +684,13 @@ pub fn summary(req: &mut Request) -> CargoResult { /// Handles the `GET /crates/:crate_id` route. pub fn show(req: &mut Request) -> CargoResult { let name = &req.params()["crate_id"]; - let conn = try!(req.tx()); - let krate = try!(Crate::find_by_name(conn, &name)); - let versions = try!(krate.versions(conn)); + let conn = req.tx()?; + let krate = Crate::find_by_name(conn, &name)?; + let versions = krate.versions(conn)?; let ids = versions.iter().map(|v| v.id).collect(); - let kws = try!(krate.keywords(conn)); - let cats = try!(krate.categories(conn)); - let badges = try!(krate.badges(conn)); + let kws = krate.keywords(conn)?; + let cats = krate.categories(conn)?; + let badges = krate.badges(conn)?; #[derive(RustcEncodable)] struct R { @@ -715,7 +715,7 @@ pub fn show(req: &mut Request) -> CargoResult { pub fn new(req: &mut Request) -> CargoResult { let app = req.app().clone(); - let (new_crate, user) = try!(parse_new_headers(req)); + let (new_crate, user) = parse_new_headers(req)?; let name = &*new_crate.name; let vers = &*new_crate.vers; let features = new_crate.features.iter().map(|(k, v)| { @@ -730,18 +730,18 @@ pub fn new(req: &mut Request) -> CargoResult { let categories: Vec<_> = categories.iter().map(|k| k[..].to_string()).collect(); // Persist the new crate, if it doesn't already exist - let mut krate = try!(Crate::find_or_insert(try!(req.tx()), name, user.id, - &new_crate.description, - &new_crate.homepage, - &new_crate.documentation, - &new_crate.readme, - &new_crate.repository, - &new_crate.license, - &new_crate.license_file, - None)); - - let owners = try!(krate.owners(try!(req.tx()))); - if try!(rights(req.app(), &owners, &user)) < Rights::Publish { + let mut krate = Crate::find_or_insert(req.tx()?, name, user.id, + &new_crate.description, + &new_crate.homepage, + &new_crate.documentation, + &new_crate.readme, + &new_crate.repository, + &new_crate.license, + &new_crate.license_file, + None)?; + + let owners = krate.owners(req.tx()?)?; + if rights(req.app(), &owners, &user)? < Rights::Publish { return Err(human("crate name has already been claimed by \ another user")) } @@ -750,9 +750,9 @@ pub fn new(req: &mut Request) -> CargoResult { return Err(human(format!("crate was previously named `{}`", krate.name))) } - let length = try!(req.content_length().chain_error(|| { + let length = req.content_length().chain_error(|| { human("missing header: Content-Length") - })); + })?; let max = krate.max_upload_size.map(|m| m as u64) .unwrap_or(app.config.max_upload_size); if length > max { @@ -760,40 +760,36 @@ pub fn new(req: &mut Request) -> CargoResult { } // Persist the new version of this crate - let mut version = try!(krate.add_version(try!(req.tx()), vers, &features, - &new_crate.authors)); + let mut version = krate.add_version(req.tx()?, vers, &features, + &new_crate.authors)?; // Link this new version to all dependencies let mut deps = Vec::new(); for dep in new_crate.deps.iter() { - let (dep, krate) = try!(version.add_dependency(try!(req.tx()), dep)); + let (dep, krate) = version.add_dependency(req.tx()?, dep)?; deps.push(dep.git_encode(&krate.name)); } // Update all keywords for this crate - try!(Keyword::update_crate(try!(req.tx()), &krate, &keywords)); + Keyword::update_crate(req.tx()?, &krate, &keywords)?; // Update all categories for this crate, collecting any invalid categories // in order to be able to warn about them - let ignored_invalid_categories = try!( - Category::update_crate(try!(req.tx()), &krate, &categories) - ); + let ignored_invalid_categories = Category::update_crate(req.tx()?, &krate, &categories)?; // Update all badges for this crate, collecting any invalid badges in // order to be able to warn about them - let ignored_invalid_badges = try!( - Badge::update_crate( - try!(req.tx()), - &krate, - new_crate.badges.unwrap_or_else(HashMap::new) - ) - ); + let ignored_invalid_badges = Badge::update_crate( + req.tx()?, + &krate, + new_crate.badges.unwrap_or_else(HashMap::new) + )?; // Upload the crate to S3 let mut handle = req.app().handle(); let path = krate.s3_path(&vers.to_string()); let (response, cksum) = { - let length = try!(read_le_u32(req.body())); + let length = read_le_u32(req.body())?; let body = LimitErrorReader::new(req.body(), max); let mut body = HashingReader::new(body); let mut response = Vec::new(); @@ -805,9 +801,9 @@ pub fn new(req: &mut Request) -> CargoResult { response.extend(data); Ok(data.len()) }).unwrap(); - try!(s3req.perform().chain_error(|| { + s3req.perform().chain_error(|| { internal(format!("failed to upload to S3: `{}`", path)) - })); + })?; } (response, body.finalize()) }; @@ -838,9 +834,9 @@ pub fn new(req: &mut Request) -> CargoResult { deps: deps, yanked: Some(false), }; - try!(git::add_crate(&**req.app(), &git_crate).chain_error(|| { + git::add_crate(&**req.app(), &git_crate).chain_error(|| { internal(format!("could not add crate `{}` to the git repo", name)) - })); + })?; // Now that we've come this far, we're committed! bomb.path = None; @@ -865,19 +861,19 @@ pub fn new(req: &mut Request) -> CargoResult { fn parse_new_headers(req: &mut Request) -> CargoResult<(upload::NewCrate, User)> { // Read the json upload request - let amt = try!(read_le_u32(req.body())) as u64; + let amt = read_le_u32(req.body())? as u64; let max = req.app().config.max_upload_size; if amt > max { return Err(human(format!("max upload size is: {}", max))) } let mut json = vec![0; amt as usize]; - try!(read_fill(req.body(), &mut json)); - let json = try!(String::from_utf8(json).map_err(|_| { + read_fill(req.body(), &mut json)?; + let json = String::from_utf8(json).map_err(|_| { human("json body was not valid utf-8") - })); - let new: upload::NewCrate = try!(json::decode(&json).map_err(|e| { + })?; + let new: upload::NewCrate = json::decode(&json).map_err(|e| { human(format!("invalid upload request: {:?}", e)) - })); + })?; // Make sure required fields are provided fn empty(s: Option<&String>) -> bool { s.map_or(true, |s| s.is_empty()) } @@ -898,13 +894,13 @@ fn parse_new_headers(req: &mut Request) -> CargoResult<(upload::NewCrate, User)> how to upload metadata", missing.join(", ")))); } - let user = try!(req.user()); + let user = req.user()?; Ok((new, user.clone())) } fn read_le_u32(r: &mut R) -> io::Result { let mut b = [0; 4]; - try!(read_fill(r, &mut b)); + read_fill(r, &mut b)?; Ok(((b[0] as u32) << 0) | ((b[1] as u32) << 8) | ((b[2] as u32) << 16) | @@ -914,7 +910,7 @@ fn read_le_u32(r: &mut R) -> io::Result { fn read_fill(r: &mut R, mut slice: &mut [u8]) -> io::Result<()> { while slice.len() > 0 { - let n = try!(r.read(slice)); + let n = r.read(slice)?; if n == 0 { return Err(io::Error::new(io::ErrorKind::Other, "end of file reached")) @@ -936,7 +932,7 @@ pub fn download(req: &mut Request) -> CargoResult { if req.app().config.mirror { let _ = increment_download_counts(req, crate_name, version); } else { - try!(increment_download_counts(req, crate_name, version)); + increment_download_counts(req, crate_name, version)?; } let redirect_url = format!("https://{}/crates/{}/{}-{}.crate", @@ -953,19 +949,19 @@ pub fn download(req: &mut Request) -> CargoResult { } fn increment_download_counts(req: &Request, crate_name: &str, version: &str) -> CargoResult<()> { - let tx = try!(req.tx()); - let stmt = try!(tx.prepare("SELECT versions.id as version_id + let tx = req.tx()?; + let stmt = tx.prepare("SELECT versions.id as version_id FROM crates INNER JOIN versions ON crates.id = versions.crate_id WHERE canon_crate_name(crates.name) = canon_crate_name($1) AND versions.num = $2 - LIMIT 1")); - let rows = try!(stmt.query(&[&crate_name, &version])); - let row = try!(rows.iter().next().chain_error(|| { + LIMIT 1")?; + let rows = stmt.query(&[&crate_name, &version])?; + let row = rows.iter().next().chain_error(|| { human("crate or version not found") - })); + })?; let version_id: i32 = row.get("version_id"); let now = ::now(); @@ -980,13 +976,13 @@ fn increment_download_counts(req: &Request, crate_name: &str, version: &str) -> // Also, we only update the counter for *today*, nothing else. We have lots // of other counters, but they're all updated later on via the // update-downloads script. - let amt = try!(tx.execute("UPDATE version_downloads + let amt = tx.execute("UPDATE version_downloads SET downloads = downloads + 1 WHERE version_id = $1 AND date($2) = date(date)", - &[&version_id, &now])); + &[&version_id, &now])?; if amt == 0 { - try!(tx.execute("INSERT INTO version_downloads - (version_id) VALUES ($1)", &[&version_id])); + tx.execute("INSERT INTO version_downloads + (version_id) VALUES ($1)", &[&version_id])?; } Ok(()) } @@ -994,9 +990,9 @@ fn increment_download_counts(req: &Request, crate_name: &str, version: &str) -> /// Handles the `GET /crates/:crate_id/downloads` route. pub fn downloads(req: &mut Request) -> CargoResult { let crate_name = &req.params()["crate_id"]; - let tx = try!(req.tx()); - let krate = try!(Crate::find_by_name(tx, crate_name)); - let mut versions = try!(krate.versions(tx)); + let tx = req.tx()?; + let krate = Crate::find_by_name(tx, crate_name)?; + let mut versions = krate.versions(tx)?; versions.sort_by(|a, b| b.num.cmp(&a.num)); @@ -1004,17 +1000,17 @@ pub fn downloads(req: &mut Request) -> CargoResult { let ids = to_show.iter().map(|i| i.id).collect::>(); let cutoff_date = ::now() + Duration::days(-90); - let stmt = try!(tx.prepare("SELECT * FROM version_downloads + let stmt = tx.prepare("SELECT * FROM version_downloads WHERE date > $1 AND version_id = ANY($2) - ORDER BY date ASC")); + ORDER BY date ASC")?; let mut downloads = Vec::new(); - for row in try!(stmt.query(&[&cutoff_date, &ids])).iter() { + for row in stmt.query(&[&cutoff_date, &ids])?.iter() { let download: VersionDownload = Model::from_row(&row); downloads.push(download.encodable()); } - let stmt = try!(tx.prepare("\ + let stmt = tx.prepare("\ SELECT COALESCE(to_char(DATE(version_downloads.date), 'YYYY-MM-DD'), '') AS date, SUM(version_downloads.downloads) AS downloads FROM version_downloads @@ -1024,9 +1020,9 @@ pub fn downloads(req: &mut Request) -> CargoResult { AND versions.crate_id = $2 AND versions.id != ALL($3) GROUP BY DATE(version_downloads.date) - ORDER BY DATE(version_downloads.date) ASC")); + ORDER BY DATE(version_downloads.date) ASC")?; let mut extra = Vec::new(); - for row in try!(stmt.query(&[&cutoff_date, &krate.id, &ids])).iter() { + for row in stmt.query(&[&cutoff_date, &krate.id, &ids])?.iter() { extra.push(ExtraDownload { downloads: row.get("downloads"), date: row.get("date") @@ -1044,23 +1040,23 @@ pub fn downloads(req: &mut Request) -> CargoResult { } fn user_and_crate(req: &mut Request) -> CargoResult<(User, Crate)> { - let user = try!(req.user()); + let user = req.user()?; let crate_name = &req.params()["crate_id"]; - let tx = try!(req.tx()); - let krate = try!(Crate::find_by_name(tx, crate_name)); + let tx = req.tx()?; + let krate = Crate::find_by_name(tx, crate_name)?; Ok((user.clone(), krate)) } /// Handles the `PUT /crates/:crate_id/follow` route. pub fn follow(req: &mut Request) -> CargoResult { - let (user, krate) = try!(user_and_crate(req)); - let tx = try!(req.tx()); - let stmt = try!(tx.prepare("SELECT 1 FROM follows - WHERE user_id = $1 AND crate_id = $2")); - let rows = try!(stmt.query(&[&user.id, &krate.id])); + let (user, krate) = user_and_crate(req)?; + let tx = req.tx()?; + let stmt = tx.prepare("SELECT 1 FROM follows + WHERE user_id = $1 AND crate_id = $2")?; + let rows = stmt.query(&[&user.id, &krate.id])?; if !rows.iter().next().is_some() { - try!(tx.execute("INSERT INTO follows (user_id, crate_id) - VALUES ($1, $2)", &[&user.id, &krate.id])); + tx.execute("INSERT INTO follows (user_id, crate_id) + VALUES ($1, $2)", &[&user.id, &krate.id])?; } #[derive(RustcEncodable)] struct R { ok: bool } @@ -1069,11 +1065,11 @@ pub fn follow(req: &mut Request) -> CargoResult { /// Handles the `DELETE /crates/:crate_id/follow` route. pub fn unfollow(req: &mut Request) -> CargoResult { - let (user, krate) = try!(user_and_crate(req)); - let tx = try!(req.tx()); - try!(tx.execute("DELETE FROM follows + let (user, krate) = user_and_crate(req)?; + let tx = req.tx()?; + tx.execute("DELETE FROM follows WHERE user_id = $1 AND crate_id = $2", - &[&user.id, &krate.id])); + &[&user.id, &krate.id])?; #[derive(RustcEncodable)] struct R { ok: bool } Ok(req.json(&R { ok: true })) @@ -1081,11 +1077,11 @@ pub fn unfollow(req: &mut Request) -> CargoResult { /// Handles the `GET /crates/:crate_id/following` route. pub fn following(req: &mut Request) -> CargoResult { - let (user, krate) = try!(user_and_crate(req)); - let tx = try!(req.tx()); - let stmt = try!(tx.prepare("SELECT 1 FROM follows - WHERE user_id = $1 AND crate_id = $2")); - let rows = try!(stmt.query(&[&user.id, &krate.id])); + let (user, krate) = user_and_crate(req)?; + let tx = req.tx()?; + let stmt = tx.prepare("SELECT 1 FROM follows + WHERE user_id = $1 AND crate_id = $2")?; + let rows = stmt.query(&[&user.id, &krate.id])?; #[derive(RustcEncodable)] struct R { following: bool } Ok(req.json(&R { following: rows.iter().next().is_some() })) @@ -1094,9 +1090,9 @@ pub fn following(req: &mut Request) -> CargoResult { /// Handles the `GET /crates/:crate_id/versions` route. pub fn versions(req: &mut Request) -> CargoResult { let crate_name = &req.params()["crate_id"]; - let tx = try!(req.tx()); - let krate = try!(Crate::find_by_name(tx, crate_name)); - let versions = try!(krate.versions(tx)); + let tx = req.tx()?; + let krate = Crate::find_by_name(tx, crate_name)?; + let versions = krate.versions(tx)?; let versions = versions.into_iter().map(|v| v.encodable(crate_name)) .collect(); @@ -1108,9 +1104,9 @@ pub fn versions(req: &mut Request) -> CargoResult { /// Handles the `GET /crates/:crate_id/owners` route. pub fn owners(req: &mut Request) -> CargoResult { let crate_name = &req.params()["crate_id"]; - let tx = try!(req.tx()); - let krate = try!(Crate::find_by_name(tx, crate_name)); - let owners = try!(krate.owners(tx)); + let tx = req.tx()?; + let krate = Crate::find_by_name(tx, crate_name)?; + let owners = krate.owners(tx)?; let owners = owners.into_iter().map(|o| o.encodable()).collect(); #[derive(RustcEncodable)] @@ -1130,12 +1126,12 @@ pub fn remove_owners(req: &mut Request) -> CargoResult { fn modify_owners(req: &mut Request, add: bool) -> CargoResult { let mut body = String::new(); - try!(req.body().read_to_string(&mut body)); - let (user, krate) = try!(user_and_crate(req)); - let tx = try!(req.tx()); - let owners = try!(krate.owners(tx)); + req.body().read_to_string(&mut body)?; + let (user, krate) = user_and_crate(req)?; + let tx = req.tx()?; + let owners = krate.owners(tx)?; - match try!(rights(req.app(), &owners, &user)) { + match rights(req.app(), &owners, &user)? { Rights::Full => {} // Yes! Rights::Publish => { return Err(human("team members don't have permission to modify owners")); @@ -1152,27 +1148,27 @@ fn modify_owners(req: &mut Request, add: bool) -> CargoResult { owners: Option>, } - let request: Request = try!(json::decode(&body).map_err(|_| { + let request: Request = json::decode(&body).map_err(|_| { human("invalid json request") - })); + })?; - let logins = try!(request.owners.or(request.users).ok_or_else(|| { + let logins = request.owners.or(request.users).ok_or_else(|| { human("invalid json request") - })); + })?; for login in &logins { if add { if owners.iter().any(|owner| owner.login() == *login) { return Err(human(format!("`{}` is already an owner", login))) } - try!(krate.owner_add(req.app(), tx, &user, &login)); + krate.owner_add(req.app(), tx, &user, &login)?; } else { // Removing the team that gives you rights is prevented because // team members only have Rights::Publish if *login == user.gh_login { return Err(human("cannot remove yourself as an owner")) } - try!(krate.owner_remove(tx, &user, &login)); + krate.owner_remove(tx, &user, &login)?; } } @@ -1184,10 +1180,10 @@ fn modify_owners(req: &mut Request, add: bool) -> CargoResult { /// Handles the `GET /crates/:crate_id/reverse_dependencies` route. pub fn reverse_dependencies(req: &mut Request) -> CargoResult { let name = &req.params()["crate_id"]; - let conn = try!(req.tx()); - let krate = try!(Crate::find_by_name(conn, &name)); - let (offset, limit) = try!(req.pagination(10, 100)); - let (rev_deps, total) = try!(krate.reverse_dependencies(conn, offset, limit)); + let conn = req.tx()?; + let krate = Crate::find_by_name(conn, &name)?; + let (offset, limit) = req.pagination(10, 100)?; + let (rev_deps, total) = krate.reverse_dependencies(conn, offset, limit)?; let rev_deps = rev_deps.into_iter() .map(|(dep, crate_name, downloads)| dep.encodable(&crate_name, Some(downloads))) .collect(); diff --git a/src/migrate/lib.rs b/src/migrate/lib.rs index 3cdc09a2c0e..63fbcc93f02 100644 --- a/src/migrate/lib.rs +++ b/src/migrate/lib.rs @@ -74,19 +74,19 @@ fn run(sql: String) -> Step { impl<'a> Manager<'a> { pub fn new(tx: Transaction) -> PgResult { let mut mgr = Manager { tx: tx, versions: HashSet::new() }; - try!(mgr.load()); + mgr.load()?; Ok(mgr) } fn load(&mut self) -> PgResult<()> { - try!(self.tx.execute("CREATE TABLE IF NOT EXISTS schema_migrations ( + self.tx.execute("CREATE TABLE IF NOT EXISTS schema_migrations ( id SERIAL PRIMARY KEY, version INT8 NOT NULL UNIQUE - )", &[])); + )", &[])?; - let stmt = try!(self.tx.prepare("SELECT version FROM \ - schema_migrations")); - for row in try!(stmt.query(&[])).iter() { + let stmt = self.tx.prepare("SELECT version FROM \ + schema_migrations")?; + for row in stmt.query(&[])?.iter() { assert!(self.versions.insert(row.get("version"))); } Ok(()) @@ -99,20 +99,20 @@ impl<'a> Manager<'a> { pub fn apply(&mut self, mut migration: Migration) -> PgResult<()> { if !self.versions.insert(migration.version) { return Ok(()) } println!("applying {}", migration.version); - try!((migration.up)(A { t: &self.tx })); - let stmt = try!(self.tx.prepare("INSERT into schema_migrations - (version) VALUES ($1)")); - try!(stmt.execute(&[&migration.version])); + (migration.up)(A { t: &self.tx })?; + let stmt = self.tx.prepare("INSERT into schema_migrations + (version) VALUES ($1)")?; + stmt.execute(&[&migration.version])?; Ok(()) } pub fn rollback(&mut self, mut migration: Migration) -> PgResult<()> { if !self.versions.remove(&migration.version) { return Ok(()) } println!("rollback {}", migration.version); - try!((migration.down)(A { t: &self.tx })); - let stmt = try!(self.tx.prepare("DELETE FROM schema_migrations - WHERE version = $1")); - try!(stmt.execute(&[&migration.version])); + (migration.down)(A { t: &self.tx })?; + let stmt = self.tx.prepare("DELETE FROM schema_migrations + WHERE version = $1")?; + stmt.execute(&[&migration.version])?; Ok(()) } diff --git a/src/model.rs b/src/model.rs index 436924b2dfa..07381044776 100644 --- a/src/model.rs +++ b/src/model.rs @@ -11,16 +11,16 @@ pub trait Model: Sized { fn find(conn: &GenericConnection, id: i32) -> CargoResult { let sql = format!("SELECT * FROM {} WHERE id = $1", Model::table_name(None::)); - let stmt = try!(conn.prepare(&sql)); - let rows = try!(stmt.query(&[&id])); - let row = try!(rows.into_iter().next().chain_error(|| NotFound)); + let stmt = conn.prepare(&sql)?; + let rows = stmt.query(&[&id])?; + let row = rows.into_iter().next().chain_error(|| NotFound)?; Ok(Model::from_row(&row)) } fn count(conn: &GenericConnection) -> CargoResult { let sql = format!("SELECT COUNT(*) FROM {}", Model::table_name(None::)); - let stmt = try!(conn.prepare(&sql)); - let rows = try!(stmt.query(&[])); + let stmt = conn.prepare(&sql)?; + let rows = stmt.query(&[])?; Ok(rows.iter().next().unwrap().get("count")) } } diff --git a/src/owner.rs b/src/owner.rs index 62363d73892..9ad89160290 100644 --- a/src/owner.rs +++ b/src/owner.rs @@ -61,12 +61,12 @@ impl Team { /// Just gets the Team from the database by name. pub fn find_by_login(conn: &GenericConnection, login: &str) -> CargoResult { - let stmt = try!(conn.prepare("SELECT * FROM teams - WHERE login = $1")); - let rows = try!(stmt.query(&[&login])); - let row = try!(rows.iter().next().chain_error(|| { + let stmt = conn.prepare("SELECT * FROM teams + WHERE login = $1")?; + let rows = stmt.query(&[&login])?; + let row = rows.iter().next().chain_error(|| { NotFound - })); + })?; Ok(Model::from_row(&row)) } @@ -83,10 +83,10 @@ impl Team { "github" => { // Ok to unwrap since we know one ":" is contained let org = chunks.next().unwrap(); - let team = try!(chunks.next().ok_or_else(|| + let team = chunks.next().ok_or_else(|| human("missing github team argument; \ format is github:org:team") - )); + )?; Team::create_github_team(app, conn, login, org, team, req_user) } _ => { @@ -129,17 +129,16 @@ impl Team { // links. A hundred teams should be enough for any org, right? let url = format!("/orgs/{}/teams?per_page=100", org_name); let token = http::token(req_user.gh_access_token.clone()); - let (handle, data) = try!(http::github(app, &url, &token)); - let teams: Vec = try!(http::parse_github_response(handle, data)); + let (handle, data) = http::github(app, &url, &token)?; + let teams: Vec = http::parse_github_response(handle, data)?; - let team = try!(teams.into_iter().find(|team| team.slug == team_name) - .ok_or_else(||{ + let team = teams.into_iter().find(|team| team.slug == team_name) + .ok_or_else(|| { human(format!("could not find the github team {}/{}", - org_name, team_name)) - }) - ); + org_name, team_name)) + })?; - if !try!(team_with_gh_id_contains_user(app, team.id, req_user)) { + if !team_with_gh_id_contains_user(app, team.id, req_user)? { return Err(human("only members of a team can add it as an owner")); } @@ -149,8 +148,8 @@ impl Team { } let url = format!("/orgs/{}", org_name); - let (handle, resp) = try!(http::github(app, &url, &token)); - let org: Org = try!(http::parse_github_response(handle, resp)); + let (handle, resp) = http::github(app, &url, &token)?; + let org: Org = http::parse_github_response(handle, resp)?; Team::insert(conn, login, team.id, team.name, org.avatar_url) } @@ -162,12 +161,12 @@ impl Team { avatar: Option) -> CargoResult { - let stmt = try!(conn.prepare("INSERT INTO teams + let stmt = conn.prepare("INSERT INTO teams (login, github_id, name, avatar) VALUES ($1, $2, $3, $4) - RETURNING *")); + RETURNING *")?; - let rows = try!(stmt.query(&[&login, &github_id, &name, &avatar])); + let rows = stmt.query(&[&login, &github_id, &name, &avatar])?; let row = rows.iter().next().unwrap(); Ok(Model::from_row(&row)) } @@ -194,14 +193,14 @@ fn team_with_gh_id_contains_user(app: &App, github_id: i32, user: &User) let url = format!("/teams/{}/memberships/{}", &github_id, &user.gh_login); let token = http::token(user.gh_access_token.clone()); - let (mut handle, resp) = try!(http::github(app, &url, &token)); + let (mut handle, resp) = http::github(app, &url, &token)?; // Officially how `false` is returned if handle.response_code().unwrap() == 404 { return Ok(false) } - let membership: Membership = try!(http::parse_github_response(handle, resp)); + let membership: Membership = http::parse_github_response(handle, resp)?; // There is also `state: pending` for which we could possibly give // some feedback, but it's not obvious how that should work. @@ -229,13 +228,13 @@ impl Owner { pub fn find_by_login(conn: &GenericConnection, name: &str) -> CargoResult { let owner = if name.contains(":") { - Owner::Team(try!(Team::find_by_login(conn, name).map_err(|_| + Owner::Team(Team::find_by_login(conn, name).map_err(|_| human(format!("could not find team with name {}", name)) - ))) + )?) } else { - Owner::User(try!(User::find_by_login(conn, name).map_err(|_| + Owner::User(User::find_by_login(conn, name).map_err(|_| human(format!("could not find user with login `{}`", name)) - ))) + )?) }; Ok(owner) } @@ -311,7 +310,7 @@ pub fn rights(app: &App, owners: &[Owner], user: &User) -> CargoResult { Owner::User(ref other_user) => if other_user.id == user.id { return Ok(Rights::Full); }, - Owner::Team(ref team) => if try!(team.contains_user(app, user)) { + Owner::Team(ref team) => if team.contains_user(app, user)? { best = Rights::Publish; }, } diff --git a/src/upload.rs b/src/upload.rs index 3a775645f6e..eb551a150c4 100644 --- a/src/upload.rs +++ b/src/upload.rs @@ -50,7 +50,7 @@ pub struct CrateDependency { impl Decodable for CrateName { fn decode(d: &mut D) -> Result { - let s = try!(d.read_str()); + let s = d.read_str()?; if !Crate::valid_name(&s) { return Err(d.error(&format!("invalid crate name specified: {}", s))) } @@ -60,7 +60,7 @@ impl Decodable for CrateName { impl Decodable for Keyword { fn decode(d: &mut D) -> Result { - let s = try!(d.read_str()); + let s = d.read_str()?; if !CrateKeyword::valid_name(&s) { return Err(d.error(&format!("invalid keyword specified: {}", s))) } @@ -76,7 +76,7 @@ impl Decodable for Category { impl Decodable for Feature { fn decode(d: &mut D) -> Result { - let s = try!(d.read_str()); + let s = d.read_str()?; if !Crate::valid_feature_name(&s) { return Err(d.error(&format!("invalid feature name specified: {}", s))) } @@ -86,7 +86,7 @@ impl Decodable for Feature { impl Decodable for CrateVersion { fn decode(d: &mut D) -> Result { - let s = try!(d.read_str()); + let s = d.read_str()?; match semver::Version::parse(&s) { Ok(v) => Ok(CrateVersion(v)), Err(..) => Err(d.error(&format!("invalid semver: {}", s))), @@ -96,7 +96,7 @@ impl Decodable for CrateVersion { impl Decodable for CrateVersionReq { fn decode(d: &mut D) -> Result { - let s = try!(d.read_str()); + let s = d.read_str()?; match semver::VersionReq::parse(&s) { Ok(v) => Ok(CrateVersionReq(v)), Err(..) => Err(d.error(&format!("invalid version req: {}", s))), @@ -106,7 +106,7 @@ impl Decodable for CrateVersionReq { impl Decodable for KeywordList { fn decode(d: &mut D) -> Result { - let inner: Vec = try!(Decodable::decode(d)); + let inner: Vec = Decodable::decode(d)?; if inner.len() > 5 { return Err(d.error("a maximum of 5 keywords per crate are allowed")) } @@ -122,7 +122,7 @@ impl Decodable for KeywordList { impl Decodable for CategoryList { fn decode(d: &mut D) -> Result { - let inner: Vec = try!(Decodable::decode(d)); + let inner: Vec = Decodable::decode(d)?; if inner.len() > 5 { return Err(d.error("a maximum of 5 categories per crate are allowed")) } @@ -132,7 +132,7 @@ impl Decodable for CategoryList { impl Decodable for DependencyKind { fn decode(d: &mut D) -> Result { - let s: String = try!(Decodable::decode(d)); + let s: String = Decodable::decode(d)?; match &s[..] { "dev" => Ok(DependencyKind::Dev), "build" => Ok(DependencyKind::Build), diff --git a/src/user/middleware.rs b/src/user/middleware.rs index 2e6265e0085..4711ed7ee65 100644 --- a/src/user/middleware.rs +++ b/src/user/middleware.rs @@ -22,7 +22,7 @@ impl conduit_middleware::Middleware for Middleware { Some(id) => { // Look for a user in the database with the given `user_id` - match User::find(try!(req.tx().map_err(std_error)), id) { + match User::find(req.tx().map_err(std_error)?, id) { Ok(user) => user, Err(..) => return Ok(()), } @@ -36,7 +36,7 @@ impl conduit_middleware::Middleware for Middleware { Some(headers) => { // Look for a user in the database with a matching API token - let tx = try!(req.tx().map_err(std_error)); + let tx = req.tx().map_err(std_error)?; match User::find_by_api_token(tx, &headers[0]) { Ok(user) => user, Err(..) => return Ok(()) diff --git a/src/user/mod.rs b/src/user/mod.rs index 8e9bdf1e928..111127c5986 100644 --- a/src/user/mod.rs +++ b/src/user/mod.rs @@ -47,21 +47,21 @@ impl User { /// Queries the database for a user with a certain `gh_login` value. pub fn find_by_login(conn: &GenericConnection, login: &str) -> CargoResult { - let stmt = try!(conn.prepare("SELECT * FROM users - WHERE gh_login = $1")); - let rows = try!(stmt.query(&[&login])); - let row = try!(rows.iter().next().chain_error(|| { + let stmt = conn.prepare("SELECT * FROM users + WHERE gh_login = $1")?; + let rows = stmt.query(&[&login])?; + let row = rows.iter().next().chain_error(|| { NotFound - })); + })?; Ok(Model::from_row(&row)) } /// Queries the database for a user with a certain `api_token` value. pub fn find_by_api_token(conn: &GenericConnection, token: &str) -> CargoResult { - let stmt = try!(conn.prepare("SELECT * FROM users \ - WHERE api_token = $1 LIMIT 1")); - let rows = try!(stmt.query(&[&token])); + let stmt = conn.prepare("SELECT * FROM users \ + WHERE api_token = $1 LIMIT 1")?; + let rows = stmt.query(&[&token])?; rows.iter().next().map(|r| Model::from_row(&r)).chain_error(|| { NotFound }) @@ -80,39 +80,39 @@ impl User { // interesting! For now just do the racy thing which will report // more errors than it needs to. - let stmt = try!(conn.prepare("UPDATE users + let stmt = conn.prepare("UPDATE users SET gh_access_token = $1, email = $2, name = $3, gh_avatar = $4, gh_login = $5 WHERE gh_id = $6 - RETURNING *")); - let rows = try!(stmt.query(&[&access_token, - &email, - &name, - &avatar, - &login, - &id])); + RETURNING *")?; + let rows = stmt.query(&[&access_token, + &email, + &name, + &avatar, + &login, + &id])?; match rows.iter().next() { Some(ref row) => return Ok(Model::from_row(row)), None => {} } - let stmt = try!(conn.prepare("INSERT INTO users + let stmt = conn.prepare("INSERT INTO users (email, gh_access_token, api_token, gh_login, name, gh_avatar, gh_id) VALUES ($1, $2, $3, $4, $5, $6, $7) - RETURNING *")); - let rows = try!(stmt.query(&[&email, - &access_token, - &api_token, - &login, - &name, - &avatar, - &id])); - Ok(Model::from_row(&try!(rows.iter().next().chain_error(|| { + RETURNING *")?; + let rows = stmt.query(&[&email, + &access_token, + &api_token, + &login, + &name, + &avatar, + &id])?; + Ok(Model::from_row(&rows.iter().next().chain_error(|| { internal("no user with email we just found") - })))) + })?)) } /// Generates a new crates.io API token. @@ -237,22 +237,22 @@ pub fn github_access_token(req: &mut Request) -> CargoResult { Err(s) => return Err(human(s)), }; - let (handle, resp) = try!(http::github(req.app(), "/user", &token)); - let ghuser: GithubUser = try!(http::parse_github_response(handle, resp)); + let (handle, resp) = http::github(req.app(), "/user", &token)?; + let ghuser: GithubUser = http::parse_github_response(handle, resp)?; // Into the database! let api_token = User::new_api_token(); - let user = try!(User::find_or_insert(try!(req.tx()), - ghuser.id, - &ghuser.login, - ghuser.email.as_ref() - .map(|s| &s[..]), - ghuser.name.as_ref() - .map(|s| &s[..]), - ghuser.avatar_url.as_ref() - .map(|s| &s[..]), - &token.access_token, - &api_token)); + let user = User::find_or_insert(req.tx()?, + ghuser.id, + &ghuser.login, + ghuser.email.as_ref() + .map(|s| &s[..]), + ghuser.name.as_ref() + .map(|s| &s[..]), + ghuser.avatar_url.as_ref() + .map(|s| &s[..]), + &token.access_token, + &api_token)?; req.session().insert("user_id".to_string(), user.id.to_string()); req.mut_extensions().insert(user); me(req) @@ -266,12 +266,12 @@ pub fn logout(req: &mut Request) -> CargoResult { /// Handles the `GET /me/reset_token` route. pub fn reset_token(req: &mut Request) -> CargoResult { - let user = try!(req.user()); + let user = req.user()?; let token = User::new_api_token(); - let conn = try!(req.tx()); - try!(conn.execute("UPDATE users SET api_token = $1 WHERE id = $2", - &[&token, &user.id])); + let conn = req.tx()?; + conn.execute("UPDATE users SET api_token = $1 WHERE id = $2", + &[&token, &user.id])?; #[derive(RustcEncodable)] struct R { api_token: String } @@ -280,7 +280,7 @@ pub fn reset_token(req: &mut Request) -> CargoResult { /// Handles the `GET /me` route. pub fn me(req: &mut Request) -> CargoResult { - let user = try!(req.user()); + let user = req.user()?; #[derive(RustcEncodable)] struct R { user: EncodableUser, api_token: String } @@ -291,8 +291,8 @@ pub fn me(req: &mut Request) -> CargoResult { /// Handles the `GET /users/:user_id` route. pub fn show(req: &mut Request) -> CargoResult { let name = &req.params()["user_id"]; - let conn = try!(req.tx()); - let user = try!(User::find_by_login(conn, &name)); + let conn = req.tx()?; + let user = User::find_by_login(conn, &name)?; #[derive(RustcEncodable)] struct R { @@ -304,9 +304,9 @@ pub fn show(req: &mut Request) -> CargoResult { /// Handles the `GET /me/updates` route. pub fn updates(req: &mut Request) -> CargoResult { - let user = try!(req.user()); - let (offset, limit) = try!(req.pagination(10, 100)); - let tx = try!(req.tx()); + let user = req.user()?; + let (offset, limit) = req.pagination(10, 100)?; + let tx = req.tx()?; let sql = "SELECT versions.* FROM versions INNER JOIN follows ON follows.user_id = $1 AND @@ -314,10 +314,10 @@ pub fn updates(req: &mut Request) -> CargoResult { ORDER BY versions.created_at DESC OFFSET $2 LIMIT $3"; // Load all versions - let stmt = try!(tx.prepare(sql)); + let stmt = tx.prepare(sql)?; let mut versions = Vec::new(); let mut crate_ids = Vec::new(); - for row in try!(stmt.query(&[&user.id, &offset, &limit])).iter() { + for row in stmt.query(&[&user.id, &offset, &limit])?.iter() { let version: Version = Model::from_row(&row); crate_ids.push(version.crate_id); versions.push(version); @@ -327,8 +327,8 @@ pub fn updates(req: &mut Request) -> CargoResult { let mut map = HashMap::new(); let mut crates = Vec::new(); if crate_ids.len() > 0 { - let stmt = try!(tx.prepare("SELECT * FROM crates WHERE id = ANY($1)")); - for row in try!(stmt.query(&[&crate_ids])).iter() { + let stmt = tx.prepare("SELECT * FROM crates WHERE id = ANY($1)")?; + for row in stmt.query(&[&crate_ids])?.iter() { let krate: Crate = Model::from_row(&row); map.insert(krate.id, krate.name.clone()); crates.push(krate); @@ -346,8 +346,8 @@ pub fn updates(req: &mut Request) -> CargoResult { // Check if we have another let sql = format!("SELECT 1 WHERE EXISTS({})", sql); - let stmt = try!(tx.prepare(&sql)); - let more = try!(stmt.query(&[&user.id, &(offset + limit), &limit])) + let stmt = tx.prepare(&sql)?; + let more = stmt.query(&[&user.id, &(offset + limit), &limit])? .iter().next().is_some(); #[derive(RustcEncodable)] diff --git a/src/util/errors.rs b/src/util/errors.rs index 8c78b86a79b..4f421fb1cf7 100644 --- a/src/util/errors.rs +++ b/src/util/errors.rs @@ -141,9 +141,9 @@ struct ConcreteCargoError { impl fmt::Display for ConcreteCargoError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}", self.description)); + write!(f, "{}", self.description)?; match self.detail { - Some(ref s) => try!(write!(f, " ({})", s)), + Some(ref s) => write!(f, " ({})", s)?, None => {} } Ok(()) @@ -233,12 +233,12 @@ pub fn std_error(e: Box) -> Box { } impl fmt::Display for E { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}", self.0)); + write!(f, "{}", self.0)?; let mut err = &*self.0; while let Some(cause) = err.cause() { err = cause; - try!(write!(f, "\nCaused by: {}", err)); + write!(f, "\nCaused by: {}", err)?; } Ok(()) diff --git a/src/util/hasher.rs b/src/util/hasher.rs index 9f8def19d6a..660fb81242f 100644 --- a/src/util/hasher.rs +++ b/src/util/hasher.rs @@ -22,7 +22,7 @@ impl HashingReader { impl Read for HashingReader { fn read(&mut self, buf: &mut [u8]) -> io::Result { - let amt = try!(self.inner.read(buf)); + let amt = self.inner.read(buf)?; self.hasher.update(&buf[..amt]).unwrap(); return Ok(amt) } diff --git a/src/version.rs b/src/version.rs index 98c27b758b8..6316c56c178 100644 --- a/src/version.rs +++ b/src/version.rs @@ -65,9 +65,9 @@ impl Version { num: &semver::Version) -> CargoResult> { let num = num.to_string(); - let stmt = try!(conn.prepare("SELECT * FROM versions \ - WHERE crate_id = $1 AND num = $2")); - let rows = try!(stmt.query(&[&crate_id, &num])); + let stmt = conn.prepare("SELECT * FROM versions \ + WHERE crate_id = $1 AND num = $2")?; + let rows = stmt.query(&[&crate_id, &num])?; Ok(rows.iter().next().map(|r| Model::from_row(&r))) } @@ -79,16 +79,16 @@ impl Version { -> CargoResult { let num = num.to_string(); let features = json::encode(features).unwrap(); - let stmt = try!(conn.prepare("INSERT INTO versions \ + let stmt = conn.prepare("INSERT INTO versions \ (crate_id, num, features) \ VALUES ($1, $2, $3) \ - RETURNING *")); - let rows = try!(stmt.query(&[&crate_id, &num, &features])); - let ret: Version = Model::from_row(&try!(rows.iter().next().chain_error(|| { + RETURNING *")?; + let rows = stmt.query(&[&crate_id, &num, &features])?; + let ret: Version = Model::from_row(&rows.iter().next().chain_error(|| { internal("no version returned") - }))); + })?); for author in authors.iter() { - try!(ret.add_author(conn, &author)); + ret.add_author(conn, &author)?; } Ok(ret) } @@ -128,9 +128,9 @@ impl Version { dep: &upload::CrateDependency) -> CargoResult<(Dependency, Crate)> { let name = &dep.name; - let krate = try!(Crate::find_by_name(conn, name).map_err(|_| { + let krate = Crate::find_by_name(conn, name).map_err(|_| { human(format!("no known crate named `{}`", &**name)) - })); + })?; if dep.version_req.0 == semver::VersionReq::parse("*").unwrap() { return Err(human(format!("wildcard (`*`) dependency constraints are not allowed \ on crates.io. See http://doc.crates.io/faq.html#can-\ @@ -140,40 +140,40 @@ impl Version { let features: Vec = dep.features.iter().map(|s| { s[..].to_string() }).collect(); - let dep = try!(Dependency::insert(conn, self.id, krate.id, - &*dep.version_req, - dep.kind.unwrap_or(Kind::Normal), - dep.optional, - dep.default_features, - &features, - &dep.target)); + let dep = Dependency::insert(conn, self.id, krate.id, + &*dep.version_req, + dep.kind.unwrap_or(Kind::Normal), + dep.optional, + dep.default_features, + &features, + &dep.target)?; Ok((dep, krate)) } /// Returns (dependency, crate dependency name) pub fn dependencies(&self, conn: &GenericConnection) -> CargoResult> { - let stmt = try!(conn.prepare("SELECT dependencies.*, + let stmt = conn.prepare("SELECT dependencies.*, crates.name AS crate_name FROM dependencies LEFT JOIN crates ON crates.id = dependencies.crate_id - WHERE dependencies.version_id = $1")); - let rows = try!(stmt.query(&[&self.id])); + WHERE dependencies.version_id = $1")?; + let rows = stmt.query(&[&self.id])?; Ok(rows.iter().map(|r| { (Model::from_row(&r), r.get("crate_name")) }).collect()) } pub fn authors(&self, conn: &GenericConnection) -> CargoResult> { - let stmt = try!(conn.prepare("SELECT * FROM version_authors - WHERE version_id = $1")); - let rows = try!(stmt.query(&[&self.id])); + let stmt = conn.prepare("SELECT * FROM version_authors + WHERE version_id = $1")?; + let rows = stmt.query(&[&self.id])?; rows.into_iter().map(|row| { let user_id: Option = row.get("user_id"); let name: String = row.get("name"); Ok(match user_id { - Some(id) => Author::User(try!(User::find(conn, id))), + Some(id) => Author::User(User::find(conn, id)?), None => Author::Name(name), }) }).collect() @@ -184,14 +184,14 @@ impl Version { name: &str) -> CargoResult<()> { println!("add author: {}", name); // TODO: at least try to link `name` to a pre-existing user - try!(conn.execute("INSERT INTO version_authors (version_id, name) - VALUES ($1, $2)", &[&self.id, &name])); + conn.execute("INSERT INTO version_authors (version_id, name) + VALUES ($1, $2)", &[&self.id, &name])?; Ok(()) } pub fn yank(&self, conn: &GenericConnection, yanked: bool) -> CargoResult<()> { - try!(conn.execute("UPDATE versions SET yanked = $1 WHERE id = $2", - &[&yanked, &self.id])); + conn.execute("UPDATE versions SET yanked = $1 WHERE id = $2", + &[&yanked, &self.id])?; Ok(()) } } @@ -219,7 +219,7 @@ impl Model for Version { /// Handles the `GET /versions` route. pub fn index(req: &mut Request) -> CargoResult { - let conn = try!(req.tx()); + let conn = req.tx()?; // Extract all ids requested. let query = url::form_urlencoded::parse(req.query_string().unwrap_or("") @@ -237,13 +237,13 @@ pub fn index(req: &mut Request) -> CargoResult { // TODO: can rust-postgres do this for us? let mut versions = Vec::new(); if ids.len() > 0 { - let stmt = try!(conn.prepare("\ + let stmt = conn.prepare("\ SELECT versions.*, crates.name AS crate_name FROM versions LEFT JOIN crates ON crates.id = versions.crate_id WHERE versions.id = ANY($1) - ")); - for row in try!(stmt.query(&[&ids])).iter() { + ")?; + for row in stmt.query(&[&ids])?.iter() { let v: Version = Model::from_row(&row); let crate_name: String = row.get("crate_name"); versions.push(v.encodable(&crate_name)); @@ -258,13 +258,13 @@ pub fn index(req: &mut Request) -> CargoResult { /// Handles the `GET /versions/:version_id` route. pub fn show(req: &mut Request) -> CargoResult { let (version, krate) = match req.params().find("crate_id") { - Some(..) => try!(version_and_crate(req)), + Some(..) => version_and_crate(req)?, None => { let id = &req.params()["version_id"]; let id = id.parse().unwrap_or(0); - let conn = try!(req.tx()); - let version = try!(Version::find(&*conn, id)); - let krate = try!(Crate::find(&*conn, version.crate_id)); + let conn = req.tx()?; + let version = Version::find(&*conn, id)?; + let krate = Crate::find(&*conn, version.crate_id)?; (version, krate) } }; @@ -277,24 +277,24 @@ pub fn show(req: &mut Request) -> CargoResult { fn version_and_crate(req: &mut Request) -> CargoResult<(Version, Crate)> { let crate_name = &req.params()["crate_id"]; let semver = &req.params()["version"]; - let semver = try!(semver::Version::parse(semver).map_err(|_| { + let semver = semver::Version::parse(semver).map_err(|_| { human(format!("invalid semver: {}", semver)) - })); - let tx = try!(req.tx()); - let krate = try!(Crate::find_by_name(tx, crate_name)); - let version = try!(Version::find_by_num(tx, krate.id, &semver)); - let version = try!(version.chain_error(|| { + })?; + let tx = req.tx()?; + let krate = Crate::find_by_name(tx, crate_name)?; + let version = Version::find_by_num(tx, krate.id, &semver)?; + let version = version.chain_error(|| { human(format!("crate `{}` does not have a version `{}`", crate_name, semver)) - })); + })?; Ok((version, krate)) } /// Handles the `GET /crates/:crate_id/:version/dependencies` route. pub fn dependencies(req: &mut Request) -> CargoResult { - let (version, _) = try!(version_and_crate(req)); - let tx = try!(req.tx()); - let deps = try!(version.dependencies(tx)); + let (version, _) = version_and_crate(req)?; + let tx = req.tx()?; + let deps = version.dependencies(tx)?; let deps = deps.into_iter().map(|(dep, crate_name)| { dep.encodable(&crate_name, None) }).collect(); @@ -306,15 +306,15 @@ pub fn dependencies(req: &mut Request) -> CargoResult { /// Handles the `GET /crates/:crate_id/:version/downloads` route. pub fn downloads(req: &mut Request) -> CargoResult { - let (version, _) = try!(version_and_crate(req)); + let (version, _) = version_and_crate(req)?; - let tx = try!(req.tx()); + let tx = req.tx()?; let cutoff_date = ::now() + Duration::days(-90); - let stmt = try!(tx.prepare("SELECT * FROM version_downloads + let stmt = tx.prepare("SELECT * FROM version_downloads WHERE date > $1 AND version_id = $2 - ORDER BY date ASC")); + ORDER BY date ASC")?; let mut downloads = Vec::new(); - for row in try!(stmt.query(&[&cutoff_date, &version.id])).iter() { + for row in stmt.query(&[&cutoff_date, &version.id])?.iter() { let download: VersionDownload = Model::from_row(&row); downloads.push(download.encodable()); } @@ -326,10 +326,10 @@ pub fn downloads(req: &mut Request) -> CargoResult { /// Handles the `GET /crates/:crate_id/:version/authors` route. pub fn authors(req: &mut Request) -> CargoResult { - let (version, _) = try!(version_and_crate(req)); - let tx = try!(req.tx()); + let (version, _) = version_and_crate(req)?; + let tx = req.tx()?; let (mut users, mut names) = (Vec::new(), Vec::new()); - for author in try!(version.authors(tx)).into_iter() { + for author in version.authors(tx)?.into_iter() { match author { Author::User(u) => users.push(u.encodable()), Author::Name(n) => names.push(n), @@ -354,17 +354,17 @@ pub fn unyank(req: &mut Request) -> CargoResult { } fn modify_yank(req: &mut Request, yanked: bool) -> CargoResult { - let (version, krate) = try!(version_and_crate(req)); - let user = try!(req.user()); - let tx = try!(req.tx()); - let owners = try!(krate.owners(tx)); - if try!(rights(req.app(), &owners, &user)) < Rights::Publish { + let (version, krate) = version_and_crate(req)?; + let user = req.user()?; + let tx = req.tx()?; + let owners = krate.owners(tx)?; + if rights(req.app(), &owners, &user)? < Rights::Publish { return Err(human("must already be an owner to yank or unyank")) } if version.yanked != yanked { - try!(version.yank(tx, yanked)); - try!(git::yank(&**req.app(), &krate.name, &version.num, yanked)); + version.yank(tx, yanked)?; + git::yank(&**req.app(), &krate.name, &version.num, yanked)?; } #[derive(RustcEncodable)]