Skip to content

Commit 8fb139b

Browse files
authored
Little Refactors (#683)
* Refactors! * Removed duplicate CRATESFYI_PREFIX variable Co-Authored-By: Joshua Nelson <[email protected]> * Split reponame into a separate variable * Return query error * Changed ok_or_else to ok_or * Annotated &&str dereferences with reasoning
1 parent c29aa2b commit 8fb139b

17 files changed

+85
-51
lines changed

build.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ fn main() {
1919
fn write_git_version() {
2020
let maybe_hash = get_git_hash();
2121
let git_hash = maybe_hash.as_deref().unwrap_or("???????");
22+
2223
let build_date = time::strftime("%Y-%m-%d", &time::now_utc()).unwrap();
2324
let dest_path = Path::new(&env::var("OUT_DIR").unwrap()).join("git_version");
2425

src/db/add_package.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,7 @@ fn add_keywords_into_database(
410410
.get(0)
411411
}
412412
};
413+
413414
// add releationship
414415
let _ = conn.query(
415416
"INSERT INTO keyword_rels (rid, kid) VALUES ($1, $2)",

src/db/file.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,13 +127,15 @@ pub(super) fn s3_client() -> Option<S3Client> {
127127
if std::env::var_os("AWS_ACCESS_KEY_ID").is_none() && std::env::var_os("FORCE_S3").is_none() {
128128
return None;
129129
}
130+
130131
let creds = match DefaultCredentialsProvider::new() {
131132
Ok(creds) => creds,
132133
Err(err) => {
133134
warn!("failed to retrieve AWS credentials: {}", err);
134135
return None;
135136
}
136137
};
138+
137139
Some(S3Client::new_with(
138140
rusoto_core::request::HttpClient::new().unwrap(),
139141
creds,

src/docbuilder/crates.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,16 @@ where
1818
for line in reader.lines() {
1919
// some crates have invalid UTF-8 (nanny-sys-0.0.7)
2020
// skip them
21-
let line = match line {
22-
Ok(l) => l,
23-
Err(_) => continue,
21+
let line = if let Ok(line) = line {
22+
line
23+
} else {
24+
continue;
2425
};
25-
let data = match Json::from_str(line.trim()) {
26-
Ok(d) => d,
27-
Err(_) => continue,
26+
27+
let data = if let Ok(data) = Json::from_str(line.trim()) {
28+
data
29+
} else {
30+
continue;
2831
};
2932

3033
let obj = data

src/docbuilder/mod.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ impl DocBuilder {
3838
/// Loads build cache
3939
pub fn load_cache(&mut self) -> Result<()> {
4040
debug!("Loading cache");
41+
4142
let path = PathBuf::from(&self.options.prefix).join("cache");
4243
let reader = fs::File::open(path).map(BufReader::new);
4344

@@ -54,6 +55,7 @@ impl DocBuilder {
5455

5556
fn load_database_cache(&mut self) -> Result<()> {
5657
debug!("Loading database cache");
58+
5759
use crate::db::connect_db;
5860
let conn = connect_db()?;
5961

@@ -64,6 +66,7 @@ impl DocBuilder {
6466
)? {
6567
let name: String = row.get(0);
6668
let version: String = row.get(1);
69+
6770
self.db_cache.insert(format!("{}-{}", name, version));
6871
}
6972

@@ -73,11 +76,14 @@ impl DocBuilder {
7376
/// Saves build cache
7477
pub fn save_cache(&self) -> Result<()> {
7578
debug!("Saving cache");
79+
7680
let path = PathBuf::from(&self.options.prefix).join("cache");
7781
let mut file = fs::OpenOptions::new().write(true).create(true).open(path)?;
82+
7883
for krate in &self.cache {
7984
writeln!(file, "{}", krate)?;
8085
}
86+
8187
Ok(())
8288
}
8389

@@ -91,6 +97,7 @@ impl DocBuilder {
9197
if !path.exists() {
9298
fs::OpenOptions::new().write(true).create(true).open(path)?;
9399
}
100+
94101
Ok(())
95102
}
96103

@@ -100,6 +107,7 @@ impl DocBuilder {
100107
if path.exists() {
101108
fs::remove_file(path)?;
102109
}
110+
103111
Ok(())
104112
}
105113

@@ -121,6 +129,7 @@ impl DocBuilder {
121129
let name = format!("{}-{}", name, version);
122130
let local = self.options.skip_if_log_exists && self.cache.contains(&name);
123131
let db = self.options.skip_if_exists && self.db_cache.contains(&name);
132+
124133
!(local || db)
125134
}
126135
}

src/docbuilder/options.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ impl DocBuilderOptions {
5555
/// Creates new DocBuilderOptions from prefix
5656
pub fn from_prefix(prefix: PathBuf) -> DocBuilderOptions {
5757
let (prefix, crates_io_index_path) = generate_paths(prefix);
58+
5859
DocBuilderOptions {
5960
prefix,
6061
crates_io_index_path,
@@ -69,6 +70,7 @@ impl DocBuilderOptions {
6970
self.crates_io_index_path.display()
7071
);
7172
}
73+
7274
Ok(())
7375
}
7476
}

src/docbuilder/rustwide_builder.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,9 @@ impl RustwideBuilder {
122122

123123
let mut targets_to_install = TARGETS
124124
.iter()
125-
.map(|&t| t.to_string())
125+
.map(|&t| t.to_string()) // &str has a specialized ToString impl, while &&str goes through Display
126126
.collect::<HashSet<_>>();
127+
127128
let installed_targets = match self.toolchain.installed_targets(&self.workspace) {
128129
Ok(targets) => targets,
129130
Err(err) => {

src/utils/daemon.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,16 @@ use time;
1919
use ::{libc::fork, std::fs::File, std::io::Write, std::process::exit};
2020

2121
pub fn start_daemon(background: bool) {
22-
// first check required environment variables
23-
for v in [
22+
const CRATE_VARIABLES: [&str; 3] = [
2423
"CRATESFYI_PREFIX",
2524
"CRATESFYI_GITHUB_USERNAME",
2625
"CRATESFYI_GITHUB_ACCESSTOKEN",
27-
]
28-
.iter()
29-
{
26+
];
27+
28+
// first check required environment variables
29+
for v in CRATE_VARIABLES.iter() {
3030
if env::var(v).is_err() {
31-
panic!("Environment variable {} not found", v);
31+
panic!("Environment variable {} not found", v)
3232
}
3333
}
3434

@@ -42,6 +42,7 @@ pub fn start_daemon(background: bool) {
4242
{
4343
panic!("running in background not supported on windows");
4444
}
45+
4546
#[cfg(not(target_os = "windows"))]
4647
{
4748
// fork the process
@@ -87,6 +88,7 @@ pub fn start_daemon(background: bool) {
8788
.unwrap();
8889

8990
// build new crates every minute
91+
// REFACTOR: Break this into smaller functions
9092
thread::Builder::new().name("build queue reader".to_string()).spawn(move || {
9193
let opts = opts();
9294
let mut doc_builder = DocBuilder::new(opts);
@@ -146,6 +148,7 @@ pub fn start_daemon(background: bool) {
146148
error!("Failed to read the number of crates in the queue: {}", e);
147149
continue;
148150
}
151+
149152
Ok(0) => {
150153
if status.count() > 0 {
151154
// ping the hubs before continuing
@@ -162,6 +165,7 @@ pub fn start_daemon(background: bool) {
162165
status = BuilderState::EmptyQueue;
163166
continue;
164167
}
168+
165169
Ok(queue_count) => {
166170
info!("Starting build with {} crates in queue (currently on a {} crate streak)",
167171
queue_count, status.count());
@@ -185,7 +189,6 @@ pub fn start_daemon(background: bool) {
185189
Ok(crate_built) => if crate_built {
186190
status.increment();
187191
}
188-
189192
}
190193
}));
191194

@@ -257,6 +260,7 @@ pub fn start_daemon(background: bool) {
257260

258261
// at least start web server
259262
info!("Starting web server");
263+
260264
crate::Server::start(None);
261265
}
262266

src/utils/github_updater.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -136,16 +136,16 @@ fn get_github_path(url: &str) -> Option<String> {
136136
Some(cap) => {
137137
let username = cap.get(1).unwrap().as_str();
138138
let reponame = cap.get(2).unwrap().as_str();
139-
Some(format!(
140-
"{}/{}",
141-
username,
142-
if reponame.ends_with(".git") {
143-
reponame.split(".git").next().unwrap()
144-
} else {
145-
reponame
146-
}
147-
))
139+
140+
let reponame = if reponame.ends_with(".git") {
141+
reponame.split(".git").next().unwrap()
142+
} else {
143+
reponame
144+
};
145+
146+
Some(format!("{}/{}", username, reponame))
148147
}
148+
149149
None => None,
150150
}
151151
}

src/utils/html.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,15 @@ fn extract_from_rcdom(dom: &RcDom) -> Result<(Handle, Handle)> {
3232
head = Some(handle.clone());
3333
}
3434
}
35+
3536
"body" => {
3637
if body.is_some() {
3738
return Err(err_msg("duplicate <body> tag"));
3839
} else {
3940
body = Some(handle.clone());
4041
}
4142
}
43+
4244
_ => {} // do nothing
4345
}
4446
}
@@ -68,6 +70,7 @@ fn extract_class(node: &Handle) -> String {
6870
.find(|a| &a.name.local == "class")
6971
.map_or(String::new(), |a| a.value.to_string())
7072
}
73+
7174
_ => String::new(),
7275
}
7376
}
@@ -79,6 +82,7 @@ mod test {
7982
let (head, body, class) = super::extract_head_and_body(
8083
r#"<head><meta name="generator" content="rustdoc"></head><body class="rustdoc struct"><p>hello</p>"#
8184
).unwrap();
85+
8286
assert_eq!(head, r#"<meta name="generator" content="rustdoc">"#);
8387
assert_eq!(body, "<p>hello</p>");
8488
assert_eq!(class, "rustdoc struct");
@@ -91,6 +95,7 @@ mod test {
9195
let expected_head = std::fs::read_to_string("tests/regex/head.html").unwrap();
9296
let expected_body = std::fs::read_to_string("tests/regex/body.html").unwrap();
9397
let (head, body, class) = super::extract_head_and_body(&original).unwrap();
98+
9499
assert_eq!(head, expected_head.trim());
95100
assert_eq!(&body, &expected_body.trim());
96101
assert_eq!(class, "rustdoc struct");

src/utils/release_activity_updater.rs

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,17 @@ use time::{now, Duration};
66

77
pub fn update_release_activity() -> Result<()> {
88
let conn = connect_db()?;
9-
let mut dates = Vec::new();
10-
let mut crate_counts = Vec::new();
11-
let mut failure_counts = Vec::new();
9+
let mut dates = Vec::with_capacity(30);
10+
let mut crate_counts = Vec::with_capacity(30);
11+
let mut failure_counts = Vec::with_capacity(30);
1212

1313
for day in 0..30 {
1414
let rows = conn.query(
1515
&format!(
1616
"SELECT COUNT(*)
17-
FROM releases
18-
WHERE release_time < NOW() - INTERVAL '{} day' AND
19-
release_time > NOW() - INTERVAL '{} day'",
17+
FROM releases
18+
WHERE release_time < NOW() - INTERVAL '{} day' AND
19+
release_time > NOW() - INTERVAL '{} day'",
2020
day,
2121
day + 1
2222
),
@@ -25,22 +25,24 @@ pub fn update_release_activity() -> Result<()> {
2525
let failures_count_rows = conn.query(
2626
&format!(
2727
"SELECT COUNT(*)
28-
FROM releases
29-
WHERE is_library = TRUE AND
30-
build_status = FALSE AND
31-
release_time < NOW() - INTERVAL '{} day' AND
32-
release_time > NOW() - INTERVAL '{} day'",
28+
FROM releases
29+
WHERE is_library = TRUE AND
30+
build_status = FALSE AND
31+
release_time < NOW() - INTERVAL '{} day' AND
32+
release_time > NOW() - INTERVAL '{} day'",
3333
day,
3434
day + 1
3535
),
3636
&[],
3737
)?;
38+
3839
let release_count: i64 = rows.get(0).get(0);
3940
let failure_count: i64 = failures_count_rows.get(0).get(0);
4041
let now = now();
4142
let date = now - Duration::days(day);
43+
44+
// unwrap is fine here, as our date format is always valid
4245
dates.push(format!("{}", date.strftime("%d %b").unwrap()));
43-
// unwrap is fine here, ~~~~~~~~~~~~^ our date format is always valid
4446
crate_counts.push(release_count);
4547
failure_counts.push(failure_count);
4648
}
@@ -54,6 +56,7 @@ pub fn update_release_activity() -> Result<()> {
5456
map.insert("dates".to_owned(), dates.to_json());
5557
map.insert("counts".to_owned(), crate_counts.to_json());
5658
map.insert("failures".to_owned(), failure_counts.to_json());
59+
5760
map.to_json()
5861
};
5962

src/web/crate_details.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -163,10 +163,10 @@ impl CrateDetails {
163163
if let Some(version) = version.as_string() {
164164
if let Ok(sem_ver) = semver::Version::parse(&version) {
165165
versions.push(sem_ver);
166-
};
167-
};
166+
}
167+
}
168168
}
169-
};
169+
}
170170

171171
versions.sort();
172172
versions.reverse();

src/web/page.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ impl<T: ToJson> Page<T> {
114114
let status = self.status;
115115
let temp = Template::new(template, self);
116116
resp.set_mut(temp).set_mut(status);
117+
117118
Ok(resp)
118119
}
119120
}

src/web/releases.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,7 @@ pub fn author_handler(req: &mut Request) -> IronResult<Response> {
447447

448448
let (author_name, packages) = if author.starts_with('@') {
449449
let mut author = author.split('@');
450+
450451
get_releases_by_owner(
451452
&conn,
452453
page_number,
@@ -572,7 +573,7 @@ pub fn search_handler(req: &mut Request) -> IronResult<Response> {
572573
let search_query = query.replace(" ", " & ");
573574
#[allow(clippy::or_fun_call)]
574575
get_search_results(&conn, &search_query, 1, RELEASES_IN_RELEASES)
575-
.ok_or(IronError::new(Nope::NoResults, status::NotFound))
576+
.ok_or_else(|| IronError::new(Nope::NoResults, status::NotFound))
576577
.and_then(|(_, results)| {
577578
// FIXME: There is no pagination
578579
Page::new(results)

src/web/routes.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use std::collections::HashSet;
66

77
const DOC_RUST_LANG_ORG_REDIRECTS: &[&str] = &["alloc", "core", "proc_macro", "std", "test"];
88

9+
// REFACTOR: Break this into smaller initialization functions
910
pub(super) fn build_routes() -> Routes {
1011
let mut routes = Routes::new();
1112

0 commit comments

Comments
 (0)