Skip to content

Commit f4b7d3a

Browse files
committed
Replace try with ?
1 parent 17638f0 commit f4b7d3a

File tree

12 files changed

+258
-258
lines changed

12 files changed

+258
-258
lines changed

src/bin/fill-in-user-id.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -67,16 +67,16 @@ fn update(app: &App, tx: &postgres::transaction::Transaction) {
6767
println!("attempt: {}/{}", id, login);
6868
let res = (|| -> CargoResult<()> {
6969
let url = format!("/users/{}", login);
70-
let (handle, resp) = try!(http::github(app, &url, &token));
71-
let ghuser: GithubUser = try!(http::parse_github_response(handle, resp));
70+
let (handle, resp) = http::github(app, &url, &token)?;
71+
let ghuser: GithubUser = http::parse_github_response(handle, resp)?;
7272
if let Some(ref avatar) = avatar {
7373
if !avatar.contains(&ghuser.id.to_string()) {
7474
return Err(human(format!("avatar: {}", avatar)))
7575
}
7676
}
7777
if ghuser.login == login {
78-
try!(tx.execute("UPDATE users SET gh_id = $1 WHERE id = $2",
79-
&[&ghuser.id, &id]));
78+
tx.execute("UPDATE users SET gh_id = $1 WHERE id = $2",
79+
&[&ghuser.id, &id])?;
8080
Ok(())
8181
} else {
8282
Err(human(format!("different login: {}", ghuser.login)))

src/bin/migrate.rs

Lines changed: 116 additions & 116 deletions
Large diffs are not rendered by default.

src/bin/populate.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,10 @@ fn update(tx: &postgres::transaction::Transaction) -> postgres::Result<()> {
3838
for day in 0..90 {
3939
let moment = now + Duration::days(-day);
4040
dls += rng.gen_range(-100, 100);
41-
try!(tx.execute("INSERT INTO version_downloads \
41+
tx.execute("INSERT INTO version_downloads \
4242
(version_id, downloads, date) \
4343
VALUES ($1, $2, $3)",
44-
&[&id, &dls, &moment]));
44+
&[&id, &dls, &moment])?;
4545
}
4646
}
4747
Ok(())

src/bin/update-downloads.rs

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -36,20 +36,20 @@ fn update(conn: &postgres::GenericConnection) -> postgres::Result<()> {
3636
loop {
3737
// FIXME(rust-lang/rust#27401): weird declaration to make sure this
3838
// variable gets dropped.
39-
let tx; tx = try!(conn.transaction());
39+
let tx; tx = conn.transaction()?;
4040
{
41-
let stmt = try!(tx.prepare("SELECT * FROM version_downloads \
41+
let stmt = tx.prepare("SELECT * FROM version_downloads \
4242
WHERE processed = FALSE AND id > $1
4343
ORDER BY id ASC
44-
LIMIT $2"));
45-
let mut rows = try!(stmt.query(&[&max, &LIMIT]));
46-
match try!(collect(&tx, &mut rows)) {
44+
LIMIT $2")?;
45+
let mut rows = stmt.query(&[&max, &LIMIT])?;
46+
match collect(&tx, &mut rows)? {
4747
None => break,
4848
Some(m) => max = m,
4949
}
5050
}
5151
tx.set_commit();
52-
try!(tx.finish());
52+
tx.finish()?;
5353
}
5454
Ok(())
5555
}
@@ -87,10 +87,10 @@ fn collect(tx: &postgres::transaction::Transaction,
8787

8888
// Flag this row as having been processed if we're passed the cutoff,
8989
// and unconditionally increment the number of counted downloads.
90-
try!(tx.execute("UPDATE version_downloads
90+
tx.execute("UPDATE version_downloads
9191
SET processed = $2, counted = counted + $3
9292
WHERE id = $1",
93-
&[id, &(download.date < cutoff), &amt]));
93+
&[id, &(download.date < cutoff), &amt])?;
9494
println!("{}\n{}", time::at(download.date).rfc822(),
9595
time::at(cutoff).rfc822());
9696
total += amt as i64;
@@ -102,31 +102,31 @@ fn collect(tx: &postgres::transaction::Transaction,
102102
let crate_id = Version::find(tx, download.version_id).unwrap().crate_id;
103103

104104
// Update the total number of version downloads
105-
try!(tx.execute("UPDATE versions
105+
tx.execute("UPDATE versions
106106
SET downloads = downloads + $1
107107
WHERE id = $2",
108-
&[&amt, &download.version_id]));
108+
&[&amt, &download.version_id])?;
109109
// Update the total number of crate downloads
110-
try!(tx.execute("UPDATE crates SET downloads = downloads + $1
111-
WHERE id = $2", &[&amt, &crate_id]));
110+
tx.execute("UPDATE crates SET downloads = downloads + $1
111+
WHERE id = $2", &[&amt, &crate_id])?;
112112

113113
// Update the total number of crate downloads for today
114-
let cnt = try!(tx.execute("UPDATE crate_downloads
114+
let cnt = tx.execute("UPDATE crate_downloads
115115
SET downloads = downloads + $2
116116
WHERE crate_id = $1 AND date = date($3)",
117-
&[&crate_id, &amt, &download.date]));
117+
&[&crate_id, &amt, &download.date])?;
118118
if cnt == 0 {
119-
try!(tx.execute("INSERT INTO crate_downloads
119+
tx.execute("INSERT INTO crate_downloads
120120
(crate_id, downloads, date)
121121
VALUES ($1, $2, $3)",
122-
&[&crate_id, &amt, &download.date]));
122+
&[&crate_id, &amt, &download.date])?;
123123
}
124124
}
125125

126126
// After everything else is done, update the global counter of total
127127
// downloads.
128-
try!(tx.execute("UPDATE metadata SET total_downloads = total_downloads + $1",
129-
&[&total]));
128+
tx.execute("UPDATE metadata SET total_downloads = total_downloads + $1",
129+
&[&total])?;
130130

131131
Ok(Some(max))
132132
}

src/db.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ pub fn tls_handshake() -> Box<TlsHandshake + Sync + Send> {
5858
_domain: &str,
5959
stream: Stream)
6060
-> Result<Box<TlsStream>, Box<Error + Send + Sync>> {
61-
let stream = try!(self.0.danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication(stream));
61+
let stream = self.0.danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication(stream)?;
6262
Ok(Box::new(stream))
6363
}
6464
}
@@ -131,9 +131,9 @@ impl Transaction {
131131

132132
pub fn conn(&self) -> CargoResult<&r2d2::PooledConnection<r2d2_postgres::PostgresConnectionManager>> {
133133
if !self.slot.filled() {
134-
let conn = try!(self.app.database.get().map_err(|e| {
134+
let conn = self.app.database.get().map_err(|e| {
135135
internal(format!("failed to get a database connection: {}", e))
136-
}));
136+
})?;
137137
self.slot.fill(Box::new(conn));
138138
}
139139
Ok(&**self.slot.borrow().unwrap())
@@ -146,8 +146,8 @@ impl Transaction {
146146
// desired effect.
147147
unsafe {
148148
if !self.tx.filled() {
149-
let conn = try!(self.conn());
150-
let t = try!(conn.transaction());
149+
let conn = self.conn()?;
150+
let t = conn.transaction()?;
151151
let t = mem::transmute::<_, pg::transaction::Transaction<'static>>(t);
152152
self.tx.fill(t);
153153
}
@@ -183,9 +183,9 @@ impl Middleware for TransactionMiddleware {
183183
if res.is_ok() && tx.commit.get() == Some(true) {
184184
transaction.set_commit();
185185
}
186-
try!(transaction.finish().map_err(|e| {
187-
Box::new(e) as Box<Error+Send>
188-
}));
186+
transaction.finish().map_err(|e| {
187+
Box::new(e) as Box<Error + Send>
188+
})?;
189189
}
190190
return res
191191
}

src/git.rs

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -53,16 +53,16 @@ pub fn add_crate(app: &App, krate: &Crate) -> CargoResult<()> {
5353

5454
commit_and_push(repo, || {
5555
// Add the crate to its relevant file
56-
try!(fs::create_dir_all(dst.parent().unwrap()));
56+
fs::create_dir_all(dst.parent().unwrap())?;
5757
let mut prev = String::new();
5858
if fs::metadata(&dst).is_ok() {
59-
try!(File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev)));
59+
File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev))?;
6060
}
6161
let s = json::encode(krate).unwrap();
6262
let new = prev + &s;
63-
let mut f = try!(File::create(&dst));
64-
try!(f.write_all(new.as_bytes()));
65-
try!(f.write_all(b"\n"));
63+
let mut f = File::create(&dst)?;
64+
f.write_all(new.as_bytes())?;
65+
f.write_all(b"\n")?;
6666

6767
Ok((format!("Updating crate `{}#{}`", krate.name, krate.vers),
6868
dst.clone()))
@@ -78,22 +78,22 @@ pub fn yank(app: &App, krate: &str, version: &semver::Version,
7878

7979
commit_and_push(repo, || {
8080
let mut prev = String::new();
81-
try!(File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev)));
81+
File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev))?;
8282
let new = prev.lines().map(|line| {
83-
let mut git_crate = try!(json::decode::<Crate>(line).map_err(|_| {
83+
let mut git_crate = json::decode::<Crate>(line).map_err(|_| {
8484
internal(format!("couldn't decode: `{}`", line))
85-
}));
85+
})?;
8686
if git_crate.name != krate ||
8787
git_crate.vers.to_string() != version.to_string() {
8888
return Ok(line.to_string())
8989
}
9090
git_crate.yanked = Some(yanked);
9191
Ok(json::encode(&git_crate).unwrap())
9292
}).collect::<CargoResult<Vec<String>>>();
93-
let new = try!(new).join("\n");
94-
let mut f = try!(File::create(&dst));
95-
try!(f.write_all(new.as_bytes()));
96-
try!(f.write_all(b"\n"));
93+
let new = new?.join("\n");
94+
let mut f = File::create(&dst)?;
95+
f.write_all(new.as_bytes())?;
96+
f.write_all(b"\n")?;
9797

9898
Ok((format!("{} crate `{}#{}`",
9999
if yanked {"Yanking"} else {"Unyanking"},
@@ -112,27 +112,27 @@ fn commit_and_push<F>(repo: &git2::Repository, mut f: F) -> CargoResult<()>
112112
// race to commit the changes. For now we just cap out the maximum number of
113113
// retries at a fixed number.
114114
for _ in 0..20 {
115-
let (msg, dst) = try!(f());
115+
let (msg, dst) = f()?;
116116

117117
// git add $file
118-
let mut index = try!(repo.index());
118+
let mut index = repo.index()?;
119119
let mut repo_path = repo_path.iter();
120120
let dst = dst.iter().skip_while(|s| Some(*s) == repo_path.next())
121121
.collect::<PathBuf>();
122-
try!(index.add_path(&dst));
123-
try!(index.write());
124-
let tree_id = try!(index.write_tree());
125-
let tree = try!(repo.find_tree(tree_id));
122+
index.add_path(&dst)?;
123+
index.write()?;
124+
let tree_id = index.write_tree()?;
125+
let tree = repo.find_tree(tree_id)?;
126126

127127
// git commit -m "..."
128-
let head = try!(repo.head());
129-
let parent = try!(repo.find_commit(head.target().unwrap()));
130-
let sig = try!(repo.signature());
131-
try!(repo.commit(Some("HEAD"), &sig, &sig, &msg, &tree, &[&parent]));
128+
let head = repo.head()?;
129+
let parent = repo.find_commit(head.target().unwrap())?;
130+
let sig = repo.signature()?;
131+
repo.commit(Some("HEAD"), &sig, &sig, &msg, &tree, &[&parent])?;
132132

133133
// git push
134134
let mut ref_status = None;
135-
let mut origin = try!(repo.find_remote("origin"));
135+
let mut origin = repo.find_remote("origin")?;
136136
let res = {
137137
let mut callbacks = git2::RemoteCallbacks::new();
138138
callbacks.credentials(credentials);
@@ -153,15 +153,15 @@ fn commit_and_push<F>(repo: &git2::Repository, mut f: F) -> CargoResult<()>
153153

154154
let mut callbacks = git2::RemoteCallbacks::new();
155155
callbacks.credentials(credentials);
156-
try!(origin.update_tips(Some(&mut callbacks), true,
157-
git2::AutotagOption::Unspecified,
158-
None));
156+
origin.update_tips(Some(&mut callbacks), true,
157+
git2::AutotagOption::Unspecified,
158+
None)?;
159159

160160
// Ok, we need to update, so fetch and reset --hard
161-
try!(origin.fetch(&["refs/heads/*:refs/heads/*"], None, None));
162-
let head = try!(repo.head()).target().unwrap();
163-
let obj = try!(repo.find_object(head, None));
164-
try!(repo.reset(&obj, git2::ResetType::Hard, None));
161+
origin.fetch(&["refs/heads/*:refs/heads/*"], None, None)?;
162+
let head = repo.head()?.target().unwrap();
163+
let obj = repo.find_object(head, None)?;
164+
repo.reset(&obj, git2::ResetType::Hard, None)?;
165165
}
166166

167167
Err(internal("Too many rebase failures"))

src/http.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ pub fn github(app: &App, url: &str, auth: &Token)
3232
data.extend_from_slice(buf);
3333
Ok(buf.len())
3434
}).unwrap();
35-
try!(transfer.perform());
35+
transfer.perform()?;
3636
}
3737
Ok((handle, data))
3838
}
@@ -58,9 +58,9 @@ pub fn parse_github_response<T: Decodable>(mut resp: Easy, data: Vec<u8>)
5858
}
5959
}
6060

61-
let json = try!(str::from_utf8(&data).ok().chain_error(||{
61+
let json = str::from_utf8(&data).ok().chain_error(|| {
6262
internal("github didn't send a utf8-response")
63-
}));
63+
})?;
6464

6565
json::decode(json).chain_error(|| {
6666
internal("github didn't send a valid json response")

src/migrate/lib.rs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -74,19 +74,19 @@ fn run(sql: String) -> Step {
7474
impl<'a> Manager<'a> {
7575
pub fn new(tx: Transaction) -> PgResult<Manager> {
7676
let mut mgr = Manager { tx: tx, versions: HashSet::new() };
77-
try!(mgr.load());
77+
mgr.load()?;
7878
Ok(mgr)
7979
}
8080

8181
fn load(&mut self) -> PgResult<()> {
82-
try!(self.tx.execute("CREATE TABLE IF NOT EXISTS schema_migrations (
82+
self.tx.execute("CREATE TABLE IF NOT EXISTS schema_migrations (
8383
id SERIAL PRIMARY KEY,
8484
version INT8 NOT NULL UNIQUE
85-
)", &[]));
85+
)", &[])?;
8686

87-
let stmt = try!(self.tx.prepare("SELECT version FROM \
88-
schema_migrations"));
89-
for row in try!(stmt.query(&[])).iter() {
87+
let stmt = self.tx.prepare("SELECT version FROM \
88+
schema_migrations")?;
89+
for row in stmt.query(&[])?.iter() {
9090
assert!(self.versions.insert(row.get("version")));
9191
}
9292
Ok(())
@@ -99,20 +99,20 @@ impl<'a> Manager<'a> {
9999
pub fn apply(&mut self, mut migration: Migration) -> PgResult<()> {
100100
if !self.versions.insert(migration.version) { return Ok(()) }
101101
println!("applying {}", migration.version);
102-
try!((migration.up)(A { t: &self.tx }));
103-
let stmt = try!(self.tx.prepare("INSERT into schema_migrations
104-
(version) VALUES ($1)"));
105-
try!(stmt.execute(&[&migration.version]));
102+
(migration.up)(A { t: &self.tx })?;
103+
let stmt = self.tx.prepare("INSERT into schema_migrations
104+
(version) VALUES ($1)")?;
105+
stmt.execute(&[&migration.version])?;
106106
Ok(())
107107
}
108108

109109
pub fn rollback(&mut self, mut migration: Migration) -> PgResult<()> {
110110
if !self.versions.remove(&migration.version) { return Ok(()) }
111111
println!("rollback {}", migration.version);
112-
try!((migration.down)(A { t: &self.tx }));
113-
let stmt = try!(self.tx.prepare("DELETE FROM schema_migrations
114-
WHERE version = $1"));
115-
try!(stmt.execute(&[&migration.version]));
112+
(migration.down)(A { t: &self.tx })?;
113+
let stmt = self.tx.prepare("DELETE FROM schema_migrations
114+
WHERE version = $1")?;
115+
stmt.execute(&[&migration.version])?;
116116
Ok(())
117117
}
118118

src/user/middleware.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ impl conduit_middleware::Middleware for Middleware {
2222
Some(id) => {
2323

2424
// Look for a user in the database with the given `user_id`
25-
match User::find(try!(req.tx().map_err(std_error)), id) {
25+
match User::find(req.tx().map_err(std_error)?, id) {
2626
Ok(user) => user,
2727
Err(..) => return Ok(()),
2828
}
@@ -36,7 +36,7 @@ impl conduit_middleware::Middleware for Middleware {
3636
Some(headers) => {
3737

3838
// Look for a user in the database with a matching API token
39-
let tx = try!(req.tx().map_err(std_error));
39+
let tx = req.tx().map_err(std_error)?;
4040
match User::find_by_api_token(tx, &headers[0]) {
4141
Ok(user) => user,
4242
Err(..) => return Ok(())

0 commit comments

Comments
 (0)