Skip to content

Commit 79177f1

Browse files
authored
Fixed clippy defects (#827)
1 parent 0c74f0e commit 79177f1

File tree

13 files changed

+88
-78
lines changed

13 files changed

+88
-78
lines changed

cargo/cargo_build_script_runner/bin.rs

+33-30
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,8 @@ fn run_buildrs() -> Result<(), String> {
5050

5151
let out_dir_abs = exec_root.join(&out_dir);
5252
// For some reason Google's RBE does not create the output directory, force create it.
53-
create_dir_all(&out_dir_abs).expect(&format!(
54-
"Failed to make output directory: {:?}",
55-
out_dir_abs
56-
));
53+
create_dir_all(&out_dir_abs)
54+
.unwrap_or_else(|_| panic!("Failed to make output directory: {:?}", out_dir_abs));
5755

5856
let target_env_vars =
5957
get_target_env_vars(&rustc_env).expect("Error getting target env vars from rustc");
@@ -119,47 +117,52 @@ fn run_buildrs() -> Result<(), String> {
119117
}
120118
}
121119

122-
let (buildrs_outputs, process_output) =
123-
BuildScriptOutput::from_command(&mut command).map_err(|process_output| {
124-
format!(
125-
"Build script process failed{}\n--stdout:\n{}\n--stderr:\n{}",
126-
if let Some(exit_code) = process_output.status.code() {
127-
format!(" with exit code {}", exit_code)
128-
} else {
129-
String::new()
130-
},
131-
String::from_utf8(process_output.stdout)
132-
.expect("Failed to parse stdout of child process"),
133-
String::from_utf8(process_output.stderr)
134-
.expect("Failed to parse stdout of child process"),
135-
)
136-
})?;
120+
let (buildrs_outputs, process_output) = BuildScriptOutput::outputs_from_command(&mut command)
121+
.map_err(|process_output| {
122+
format!(
123+
"Build script process failed{}\n--stdout:\n{}\n--stderr:\n{}",
124+
if let Some(exit_code) = process_output.status.code() {
125+
format!(" with exit code {}", exit_code)
126+
} else {
127+
String::new()
128+
},
129+
String::from_utf8(process_output.stdout)
130+
.expect("Failed to parse stdout of child process"),
131+
String::from_utf8(process_output.stderr)
132+
.expect("Failed to parse stdout of child process"),
133+
)
134+
})?;
137135

138136
write(
139137
&env_file,
140-
BuildScriptOutput::to_env(&buildrs_outputs, &exec_root.to_string_lossy()).as_bytes(),
138+
BuildScriptOutput::outputs_to_env(&buildrs_outputs, &exec_root.to_string_lossy())
139+
.as_bytes(),
141140
)
142-
.expect(&format!("Unable to write file {:?}", env_file));
141+
.unwrap_or_else(|_| panic!("Unable to write file {:?}", env_file));
143142
write(
144143
&output_dep_env_path,
145-
BuildScriptOutput::to_dep_env(&buildrs_outputs, &crate_links, &exec_root.to_string_lossy())
146-
.as_bytes(),
144+
BuildScriptOutput::outputs_to_dep_env(
145+
&buildrs_outputs,
146+
&crate_links,
147+
&exec_root.to_string_lossy(),
148+
)
149+
.as_bytes(),
147150
)
148-
.expect(&format!("Unable to write file {:?}", output_dep_env_path));
151+
.unwrap_or_else(|_| panic!("Unable to write file {:?}", output_dep_env_path));
149152
write(&stdout_path, process_output.stdout)
150-
.expect(&format!("Unable to write file {:?}", stdout_path));
153+
.unwrap_or_else(|_| panic!("Unable to write file {:?}", stdout_path));
151154
write(&stderr_path, process_output.stderr)
152-
.expect(&format!("Unable to write file {:?}", stderr_path));
155+
.unwrap_or_else(|_| panic!("Unable to write file {:?}", stderr_path));
153156

154157
let CompileAndLinkFlags {
155158
compile_flags,
156159
link_flags,
157-
} = BuildScriptOutput::to_flags(&buildrs_outputs, &exec_root.to_string_lossy());
160+
} = BuildScriptOutput::outputs_to_flags(&buildrs_outputs, &exec_root.to_string_lossy());
158161

159162
write(&compile_flags_file, compile_flags.as_bytes())
160-
.expect(&format!("Unable to write file {:?}", compile_flags_file));
163+
.unwrap_or_else(|_| panic!("Unable to write file {:?}", compile_flags_file));
161164
write(&link_flags_file, link_flags.as_bytes())
162-
.expect(&format!("Unable to write file {:?}", link_flags_file));
165+
.unwrap_or_else(|_| panic!("Unable to write file {:?}", link_flags_file));
163166
Ok(())
164167
}
165168

@@ -243,7 +246,7 @@ fn get_target_env_vars<P: AsRef<Path>>(rustc: &P) -> Result<BTreeMap<String, Str
243246
if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
244247
values
245248
.entry(key)
246-
.or_insert(vec![])
249+
.or_insert_with(Vec::new)
247250
.push(value[1..(value.len() - 1)].to_owned());
248251
}
249252
}

cargo/cargo_build_script_runner/lib.rs

+21-13
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ impl BuildScriptOutput {
9494
}
9595

9696
/// Converts a [BufReader] into a vector of [BuildScriptOutput] enums.
97-
fn from_reader<T: Read>(mut reader: BufReader<T>) -> Vec<BuildScriptOutput> {
97+
fn outputs_from_reader<T: Read>(mut reader: BufReader<T>) -> Vec<BuildScriptOutput> {
9898
let mut result = Vec::<BuildScriptOutput>::new();
9999
let mut line = String::new();
100100
while reader.read_line(&mut line).expect("Cannot read line") != 0 {
@@ -107,20 +107,23 @@ impl BuildScriptOutput {
107107
}
108108

109109
/// Take a [Command], execute it and converts its input into a vector of [BuildScriptOutput]
110-
pub fn from_command(cmd: &mut Command) -> Result<(Vec<BuildScriptOutput>, Output), Output> {
110+
pub fn outputs_from_command(
111+
cmd: &mut Command,
112+
) -> Result<(Vec<BuildScriptOutput>, Output), Output> {
111113
let child_output = cmd.output().expect("Unable to start binary");
112114
if child_output.status.success() {
113115
let reader = BufReader::new(child_output.stdout.as_slice());
114-
let output = Self::from_reader(reader);
116+
let output = Self::outputs_from_reader(reader);
115117
Ok((output, child_output))
116118
} else {
117119
Err(child_output)
118120
}
119121
}
120122

121123
/// Convert a vector of [BuildScriptOutput] into a list of environment variables.
122-
pub fn to_env(v: &Vec<BuildScriptOutput>, exec_root: &str) -> String {
123-
v.iter()
124+
pub fn outputs_to_env(outputs: &[BuildScriptOutput], exec_root: &str) -> String {
125+
outputs
126+
.iter()
124127
.filter_map(|x| {
125128
if let BuildScriptOutput::Env(env) = x {
126129
Some(Self::escape_for_serializing(Self::redact_exec_root(
@@ -135,9 +138,14 @@ impl BuildScriptOutput {
135138
}
136139

137140
/// Convert a vector of [BuildScriptOutput] into a list of dependencies environment variables.
138-
pub fn to_dep_env(v: &Vec<BuildScriptOutput>, crate_links: &str, exec_root: &str) -> String {
141+
pub fn outputs_to_dep_env(
142+
outputs: &[BuildScriptOutput],
143+
crate_links: &str,
144+
exec_root: &str,
145+
) -> String {
139146
let prefix = format!("DEP_{}_", crate_links.replace("-", "_").to_uppercase());
140-
v.iter()
147+
outputs
148+
.iter()
141149
.filter_map(|x| {
142150
if let BuildScriptOutput::DepEnv(env) = x {
143151
Some(format!(
@@ -154,11 +162,11 @@ impl BuildScriptOutput {
154162
}
155163

156164
/// Convert a vector of [BuildScriptOutput] into a flagfile.
157-
pub fn to_flags(v: &Vec<BuildScriptOutput>, exec_root: &str) -> CompileAndLinkFlags {
165+
pub fn outputs_to_flags(outputs: &[BuildScriptOutput], exec_root: &str) -> CompileAndLinkFlags {
158166
let mut compile_flags = Vec::new();
159167
let mut link_flags = Vec::new();
160168

161-
for flag in v {
169+
for flag in outputs {
162170
match flag {
163171
BuildScriptOutput::Cfg(e) => compile_flags.push(format!("--cfg={}", e)),
164172
BuildScriptOutput::Flags(e) => compile_flags.push(e.to_owned()),
@@ -214,7 +222,7 @@ cargo:rustc-env=SOME_PATH=/some/absolute/path/beep
214222
",
215223
);
216224
let reader = BufReader::new(buff);
217-
let result = BuildScriptOutput::from_reader(reader);
225+
let result = BuildScriptOutput::outputs_from_reader(reader);
218226
assert_eq!(result.len(), 10);
219227
assert_eq!(result[0], BuildScriptOutput::LinkLib("sdfsdf".to_owned()));
220228
assert_eq!(result[1], BuildScriptOutput::Env("FOO=BAR".to_owned()));
@@ -242,15 +250,15 @@ cargo:rustc-env=SOME_PATH=/some/absolute/path/beep
242250
);
243251

244252
assert_eq!(
245-
BuildScriptOutput::to_dep_env(&result, "ssh2", "/some/absolute/path"),
253+
BuildScriptOutput::outputs_to_dep_env(&result, "ssh2", "/some/absolute/path"),
246254
"DEP_SSH2_VERSION=123\nDEP_SSH2_VERSION_NUMBER=1010107f\nDEP_SSH2_INCLUDE_PATH=${pwd}/include".to_owned()
247255
);
248256
assert_eq!(
249-
BuildScriptOutput::to_env(&result, "/some/absolute/path"),
257+
BuildScriptOutput::outputs_to_env(&result, "/some/absolute/path"),
250258
"FOO=BAR\nBAR=FOO\nSOME_PATH=${pwd}/beep".to_owned()
251259
);
252260
assert_eq!(
253-
BuildScriptOutput::to_flags(&result, "/some/absolute/path"),
261+
BuildScriptOutput::outputs_to_flags(&result, "/some/absolute/path"),
254262
CompileAndLinkFlags {
255263
// -Lblah was output as a rustc-flags, so even though it probably _should_ be a link
256264
// flag, we don't treat it like one.

proto/optional_output_wrapper.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ fn ensure() -> Result<i32, Box<dyn error::Error>> {
2626
let optional_outputs = args().take(index).collect::<Vec<String>>();
2727
let exe = args().nth(index + 1).ok_or("no exe")?;
2828
let exe_args = args().skip(index + 2).collect::<Vec<String>>();
29-
if exe_args.len() < 1 {
29+
if exe_args.is_empty() {
3030
return Err("no exe args".into());
3131
}
3232
match Command::new(exe).args(exe_args).status()?.code() {

test/chained_direct_deps/mod3.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ pub fn greet_default() {
2525
/// );
2626
/// ```
2727
pub fn am_i_the_world(me: &str) -> bool {
28-
return me == mod1::world();
28+
me == mod1::world()
2929
}
3030

3131
#[cfg(test)]

test/renamed_deps/mod3.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ pub fn greet_default() {
2525
/// );
2626
/// ```
2727
pub fn am_i_the_world(me: &str) -> bool {
28-
return me == alias_a::world();
28+
me == alias_a::world()
2929
}
3030

3131
#[cfg(test)]

test/rust_analyzer/aspect_traversal_test/rust_project_json_test.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ mod tests {
99
r.rlocation("rules_rust/test/rust_analyzer/aspect_traversal_test/rust-project.json");
1010

1111
let content = std::fs::read_to_string(&rust_project_path)
12-
.expect(&format!("couldn't open {:?}", &rust_project_path));
12+
.unwrap_or_else(|_| panic!("couldn't open {:?}", &rust_project_path));
1313

1414
for dep in &[
1515
"lib_dep",

test/rust_analyzer/merging_crates_test/rust_project_json_test.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ mod tests {
99
r.rlocation("rules_rust/test/rust_analyzer/merging_crates_test/rust-project.json");
1010

1111
let content = std::fs::read_to_string(&rust_project_path)
12-
.expect(&format!("couldn't open {:?}", &rust_project_path));
12+
.unwrap_or_else(|_| panic!("couldn't open {:?}", &rust_project_path));
1313

1414
assert!(
1515
content.contains(r#""root_module":"test/rust_analyzer/merging_crates_test/mylib.rs","deps":[{"crate":0,"name":"lib_dep"},{"crate":2,"name":"extra_test_dep"}]"#),

test/rust_analyzer/merging_crates_test_reversed/rust_project_json_test.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ mod tests {
1010
);
1111

1212
let content = std::fs::read_to_string(&rust_project_path)
13-
.expect(&format!("couldn't open {:?}", &rust_project_path));
13+
.unwrap_or_else(|_| panic!("couldn't open {:?}", &rust_project_path));
1414

1515
assert!(
1616
content.contains(r#""root_module":"test/rust_analyzer/merging_crates_test_reversed/mylib.rs","deps":[{"crate":0,"name":"lib_dep"},{"crate":1,"name":"extra_test_dep"}]"#),

tools/runfiles/runfiles.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -97,10 +97,9 @@ impl Runfiles {
9797
Mode::DirectoryBased(runfiles_dir) => runfiles_dir.join(path),
9898
Mode::ManifestBased(path_mapping) => path_mapping
9999
.get(path)
100-
.expect(&format!(
101-
"Path {} not found among runfiles.",
102-
path.to_string_lossy()
103-
))
100+
.unwrap_or_else(|| {
101+
panic!("Path {} not found among runfiles.", path.to_string_lossy())
102+
})
104103
.clone(),
105104
}
106105
}
@@ -109,10 +108,11 @@ impl Runfiles {
109108
/// Returns the .runfiles directory for the currently executing binary.
110109
pub fn find_runfiles_dir() -> io::Result<PathBuf> {
111110
assert_ne!(
112-
std::env::var_os("RUNFILES_MANIFEST_ONLY").unwrap_or(OsString::from("0")),
111+
std::env::var_os("RUNFILES_MANIFEST_ONLY").unwrap_or_else(|| OsString::from("0")),
113112
"1"
114113
);
115-
let exec_path = std::env::args().nth(0).expect("arg 0 was not set");
114+
// Consume the first argument (argv[0])
115+
let exec_path = std::env::args().next().expect("arg 0 was not set");
116116

117117
let mut binary_path = PathBuf::from(&exec_path);
118118
loop {

tools/rustfmt/srcs/lib.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::fs;
33
use std::path::{Path, PathBuf};
44

55
/// The expected extension of rustfmt manifest files generated by `rustfmt_aspect`.
6-
pub const RUSTFMT_MANIFEST_EXTENSION: &'static str = "rustfmt";
6+
pub const RUSTFMT_MANIFEST_EXTENSION: &str = "rustfmt";
77

88
/// Generate an absolute path to a file without resolving symlinks
99
fn absolutify_existing<T: AsRef<Path>>(path: &T) -> std::io::Result<PathBuf> {
@@ -50,13 +50,11 @@ pub struct RustfmtManifest {
5050

5151
/// Parse rustfmt flags from a manifest generated by builds using `rustfmt_aspect`.
5252
pub fn parse_rustfmt_manifest(manifest: &Path) -> RustfmtManifest {
53-
let content = fs::read_to_string(manifest).expect(&format!(
54-
"Failed to read rustfmt manifest: {}",
55-
manifest.display()
56-
));
53+
let content = fs::read_to_string(manifest)
54+
.unwrap_or_else(|_| panic!("Failed to read rustfmt manifest: {}", manifest.display()));
5755

5856
let mut lines: Vec<String> = content
59-
.split("\n")
57+
.split('\n')
6058
.into_iter()
6159
.filter(|s| !s.is_empty())
6260
.map(|s| s.to_owned())
@@ -70,7 +68,7 @@ pub fn parse_rustfmt_manifest(manifest: &Path) -> RustfmtManifest {
7068
.expect("The edition should be a numeric value. eg `2018`.");
7169

7270
RustfmtManifest {
73-
edition: edition,
71+
edition,
7472
sources: lines,
7573
}
7674
}

tools/rustfmt/srcs/test_main.rs

-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,6 @@ use std::fs;
22
use std::path::{Path, PathBuf};
33
use std::process::Command;
44

5-
use runfiles;
6-
use rustfmt_lib;
7-
85
fn main() {
96
// Gather all and environment settings
107
let options = parse_args();

0 commit comments

Comments
 (0)