From 3b92e7b3cec8052c5684a33b155c2b9954ae4804 Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Sat, 28 Jan 2023 03:29:21 +1100 Subject: [PATCH] Fix `gcc-shim`, apply clippy warning & optimizations to it (#777) --- src/bin/gcc-shim.rs | 72 +++++++++++++++++++++++++++++---------------- 1 file changed, 47 insertions(+), 25 deletions(-) diff --git a/src/bin/gcc-shim.rs b/src/bin/gcc-shim.rs index 1731df8..e5b5372 100644 --- a/src/bin/gcc-shim.rs +++ b/src/bin/gcc-shim.rs @@ -2,7 +2,7 @@ use std::env; use std::fs::File; -use std::io::prelude::*; +use std::io::{self, prelude::*}; use std::path::PathBuf; fn main() { @@ -10,39 +10,61 @@ fn main() { let program = args.next().expect("Unexpected empty args"); let out_dir = PathBuf::from( - env::var_os("GCCTEST_OUT_DIR").expect(&format!("{}: GCCTEST_OUT_DIR not found", program)), + env::var_os("GCCTEST_OUT_DIR") + .unwrap_or_else(|| panic!("{}: GCCTEST_OUT_DIR not found", program)), ); // Find the first nonexistent candidate file to which the program's args can be written. - for i in 0.. { - let candidate = &out_dir.join(format!("out{}", i)); + let candidate = (0..).find_map(|i| { + let candidate = out_dir.join(format!("out{}", i)); - // If the file exists, commands have already run. Try again. if candidate.exists() { - continue; + // If the file exists, commands have already run. Try again. + None + } else { + Some(candidate) + } + }).unwrap_or_else(|| panic!("Cannot find the first nonexistent candidate file to which the program's args can be written under out_dir '{}'", out_dir.display())); + + // Create a file and record the args passed to the command. + let f = File::create(&candidate).unwrap_or_else(|e| { + panic!( + "{}: can't create candidate: {}, error: {}", + program, + candidate.display(), + e + ) + }); + let mut f = io::BufWriter::new(f); + + (|| { + for arg in args { + writeln!(f, "{}", arg)?; } - // Create a file and record the args passed to the command. - let mut f = File::create(candidate).expect(&format!( - "{}: can't create candidate: {}", + f.flush()?; + + let mut f = f.into_inner()?; + f.flush()?; + f.sync_all() + })() + .unwrap_or_else(|e| { + panic!( + "{}: can't write to candidate: {}, error: {}", program, - candidate.to_string_lossy() - )); - for arg in args { - writeln!(f, "{}", arg).expect(&format!( - "{}: can't write to candidate: {}", - program, - candidate.to_string_lossy() - )); - } - break; - } + candidate.display(), + e + ) + }); // Create a file used by some tests. let path = &out_dir.join("libfoo.a"); - File::create(path).expect(&format!( - "{}: can't create libfoo.a: {}", - program, - path.to_string_lossy() - )); + File::create(path).unwrap_or_else(|e| { + panic!( + "{}: can't create libfoo.a: {}, error: {}", + program, + path.display(), + e + ) + }); }