Skip to content

Replace try with ? #572

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 1, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/bin/fill-in-user-id.rs
Original file line number Diff line number Diff line change
@@ -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)))
232 changes: 116 additions & 116 deletions src/bin/migrate.rs

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/bin/populate.rs
Original file line number Diff line number Diff line change
@@ -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(())
36 changes: 18 additions & 18 deletions src/bin/update-downloads.rs
Original file line number Diff line number Diff line change
@@ -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))
}
64 changes: 32 additions & 32 deletions src/category.rs
Original file line number Diff line number Diff line change
@@ -45,19 +45,19 @@ pub struct EncodableCategoryWithSubcategories {
impl Category {
pub fn find_by_category(conn: &GenericConnection, name: &str)
-> CargoResult<Category> {
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))
}

pub fn find_by_slug(conn: &GenericConnection, slug: &str)
-> CargoResult<Category> {
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<Vec<String>> {
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,21 +112,21 @@ 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() {
let insert: Vec<_> = to_add.into_iter().map(|id| {
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::<Self>
));
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<Vec<Category>> {
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<Response> {
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<EncodableCategory>, meta: Meta }
@@ -238,9 +238,9 @@ pub fn index(req: &mut Request) -> CargoResult<Response> {
/// Handles the `GET /categories/:category_id` route.
pub fn show(req: &mut Request) -> CargoResult<Response> {
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<Response> {

/// Handles the `GET /category_slugs` route.
pub fn slugs(req: &mut Request) -> CargoResult<Response> {
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 }
16 changes: 8 additions & 8 deletions src/db.rs
Original file line number Diff line number Diff line change
@@ -58,7 +58,7 @@ pub fn tls_handshake() -> Box<TlsHandshake + Sync + Send> {
_domain: &str,
stream: Stream)
-> Result<Box<TlsStream>, Box<Error + Send + Sync>> {
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<r2d2_postgres::PostgresConnectionManager>> {
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<Error+Send>
}));
transaction.finish().map_err(|e| {
Box::new(e) as Box<Error + Send>
})?;
}
return res
}
10 changes: 5 additions & 5 deletions src/dependency.rs
Original file line number Diff line number Diff line change
@@ -51,14 +51,14 @@ impl Dependency {
-> CargoResult<Dependency> {
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()))
}

Loading