Skip to content

Commit 2c0f892

Browse files
committed
Add safe wrappers around fs in run_make_support
1 parent 20ad958 commit 2c0f892

File tree

30 files changed

+146
-61
lines changed

30 files changed

+146
-61
lines changed

src/tools/run-make-support/src/fs.rs

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
use std::fs;
2+
use std::path::Path;
3+
4+
/// A safe wrapper around `std::fs::remove_file` that prints the file path if an operation fails.
5+
pub fn remove_file<P: AsRef<Path> + std::fmt::Debug>(path: P) {
6+
fs::remove_file(path.as_ref())
7+
.expect(&format!("The file in path \"{:?}\" could not be removed.", path.as_ref()));
8+
}
9+
10+
/// A safe wrapper around `std::fs::copy` that prints the file paths if an operation fails.
11+
pub fn copy<P: AsRef<Path> + std::fmt::Debug, Q: AsRef<Path> + std::fmt::Debug>(from: P, to: Q) {
12+
fs::copy(from.as_ref(), to.as_ref()).expect(&format!(
13+
"The file \"{:?}\" could not be copied over to \"{:?}\".",
14+
from.as_ref(),
15+
to.as_ref(),
16+
));
17+
}
18+
19+
/// A safe wrapper around `std::fs::File::create` that prints the file path if an operation fails.
20+
pub fn create_file<P: AsRef<Path> + std::fmt::Debug>(path: P) {
21+
fs::File::create(path.as_ref())
22+
.expect(&format!("The file in path \"{:?}\" could not be created.", path.as_ref()));
23+
}
24+
25+
/// A safe wrapper around `std::fs::read` that prints the file path if an operation fails.
26+
pub fn read<P: AsRef<Path> + std::fmt::Debug>(path: P) -> Vec<u8> {
27+
fs::read(path.as_ref())
28+
.expect(&format!("The file in path \"{:?}\" could not be read.", path.as_ref()))
29+
}
30+
31+
/// A safe wrapper around `std::fs::read_to_string` that prints the file path if an operation fails.
32+
pub fn read_to_string<P: AsRef<Path> + std::fmt::Debug>(path: P) -> String {
33+
fs::read_to_string(path.as_ref()).expect(&format!(
34+
"The file in path \"{:?}\" could not be read into a String.",
35+
path.as_ref()
36+
))
37+
}
38+
39+
/// A safe wrapper around `std::fs::read_dir` that prints the file path if an operation fails.
40+
pub fn read_dir<P: AsRef<Path> + std::fmt::Debug>(path: P) -> fs::ReadDir {
41+
fs::read_dir(path.as_ref())
42+
.expect(&format!("The directory in path \"{:?}\" could not be read.", path.as_ref()))
43+
}
44+
45+
/// A safe wrapper around `std::fs::write` that prints the file path if an operation fails.
46+
pub fn write<P: AsRef<Path> + std::fmt::Debug, C: AsRef<[u8]>>(path: P, contents: C) {
47+
fs::read(path.as_ref(), contents.as_ref())
48+
.expect(&format!("The file in path \"{:?}\" could not be written to.", path.as_ref()));
49+
}
50+
51+
/// A safe wrapper around `std::fs::remove_dir_all` that prints the file path if an operation fails.
52+
pub fn remove_dir_all<P: AsRef<Path> + std::fmt::Debug>(path: P) {
53+
fs::remove_dir_all(path.as_ref()).expect(&format!(
54+
"The directory in path \"{:?}\" could not be removed alongside all its contents.",
55+
path.as_ref(),
56+
));
57+
}
58+
59+
/// A safe wrapper around `std::fs::create_dir` that prints the file path if an operation fails.
60+
pub fn create_dir<P: AsRef<Path> + std::fmt::Debug>(path: P) {
61+
fs::create_dir(path.as_ref())
62+
.expect(&format!("The directory in path \"{:?}\" could not be created.", path.as_ref()));
63+
}
64+
65+
/// A safe wrapper around `std::fs::create_dir_all` that prints the file path if an operation fails.
66+
pub fn create_dir_all<P: AsRef<Path> + std::fmt::Debug>(path: P) {
67+
fs::create_dir_all(path.as_ref()).expect(&format!(
68+
"The directory (and all its parents) in path \"{:?}\" could not be created.",
69+
path.as_ref()
70+
));
71+
}
72+
73+
/// A safe wrapper around `std::fs::metadata` that prints the file path if an operation fails.
74+
pub fn metadata<P: AsRef<Path> + std::fmt::Debug>(path: P) -> fs::Metadata {
75+
fs::metadata(path.as_ref())
76+
.expect(&format!("The file's metadata in path \"{:?}\" could not be read.", path.as_ref()))
77+
}
78+
79+
/// A safe wrapper around `std::fs::rename` that prints the file paths if an operation fails.
80+
pub fn rename<P: AsRef<Path> + std::fmt::Debug, Q: AsRef<Path> + std::fmt::Debug>(from: P, to: Q) {
81+
fs::rename(from.as_ref(), to.as_ref()).expect(&format!(
82+
"The file \"{:?}\" could not be moved over to \"{:?}\".",
83+
from.as_ref(),
84+
to.as_ref(),
85+
));
86+
}

src/tools/run-make-support/src/lib.rs

+9-16
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ pub mod rustc;
1212
pub mod rustdoc;
1313

1414
use std::env;
15-
use std::fs;
1615
use std::io;
1716
use std::path::{Path, PathBuf};
1817
use std::process::{Command, Output};
@@ -35,8 +34,9 @@ pub fn tmp_dir() -> PathBuf {
3534
env::var_os("TMPDIR").unwrap().into()
3635
}
3736

38-
pub fn tmp_path<P: AsRef<Path>>(path: P) -> PathBuf {
39-
tmp_dir().join(path.as_ref())
37+
/// Returns the directory TMPDIR/name.
38+
pub fn tmp_path<P: AsRef<Path>>(name: P) -> PathBuf {
39+
tmp_path(name.as_ref())
4040
}
4141

4242
/// `TARGET`
@@ -218,15 +218,15 @@ pub fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) {
218218
fn copy_dir_all_inner(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> io::Result<()> {
219219
let dst = dst.as_ref();
220220
if !dst.is_dir() {
221-
fs::create_dir_all(&dst)?;
221+
std::fs::create_dir_all(&dst)?;
222222
}
223-
for entry in fs::read_dir(src)? {
223+
for entry in std::fs::read_dir(src)? {
224224
let entry = entry?;
225225
let ty = entry.file_type()?;
226226
if ty.is_dir() {
227227
copy_dir_all_inner(entry.path(), dst.join(entry.file_name()))?;
228228
} else {
229-
fs::copy(entry.path(), dst.join(entry.file_name()))?;
229+
std::fs::copy(entry.path(), dst.join(entry.file_name()))?;
230230
}
231231
}
232232
Ok(())
@@ -245,15 +245,8 @@ pub fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) {
245245

246246
/// Check that all files in `dir1` exist and have the same content in `dir2`. Panic otherwise.
247247
pub fn recursive_diff(dir1: impl AsRef<Path>, dir2: impl AsRef<Path>) {
248-
fn read_file(path: &Path) -> Vec<u8> {
249-
match fs::read(path) {
250-
Ok(c) => c,
251-
Err(e) => panic!("Failed to read `{}`: {:?}", path.display(), e),
252-
}
253-
}
254-
255248
let dir2 = dir2.as_ref();
256-
for entry in fs::read_dir(dir1).unwrap() {
249+
for entry in fs::read_dir(dir1) {
257250
let entry = entry.unwrap();
258251
let entry_name = entry.file_name();
259252
let path = entry.path();
@@ -262,8 +255,8 @@ pub fn recursive_diff(dir1: impl AsRef<Path>, dir2: impl AsRef<Path>) {
262255
recursive_diff(&path, &dir2.join(entry_name));
263256
} else {
264257
let path2 = dir2.join(entry_name);
265-
let file1 = read_file(&path);
266-
let file2 = read_file(&path2);
258+
let file1 = fs::read(&path);
259+
let file2 = fs::read(&path2);
267260

268261
// We don't use `assert_eq!` because they are `Vec<u8>`, so not great for display.
269262
// Why not using String? Because there might be minified files or even potentially

tests/run-make/c-link-to-rust-staticlib/rmake.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,14 @@
33

44
//@ ignore-cross-compile
55

6+
use run_make_support::fs::remove_file;
67
use run_make_support::{cc, extra_c_flags, run, rustc, static_lib};
78
use std::fs;
89

910
fn main() {
1011
rustc().input("foo.rs").run();
1112
cc().input("bar.c").input(static_lib("foo")).out_exe("bar").args(&extra_c_flags()).run();
1213
run("bar");
13-
fs::remove_file(static_lib("foo"));
14+
remove_file(static_lib("foo"));
1415
run("bar");
1516
}

tests/run-make/compiler-builtins/rmake.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
#![deny(warnings)]
1616

17+
use run_make_support::fs::{read, read_dir, write};
1718
use run_make_support::object;
1819
use run_make_support::object::read::archive::ArchiveFile;
1920
use run_make_support::object::read::Object;
@@ -41,8 +42,8 @@ fn main() {
4142

4243
// Set up the tiniest Cargo project: An empty no_std library. Just enough to run -Zbuild-std.
4344
let manifest_path = tmp_path("Cargo.toml");
44-
std::fs::write(&manifest_path, MANIFEST.as_bytes()).unwrap();
45-
std::fs::write(tmp_path("lib.rs"), b"#![no_std]").unwrap();
45+
write(&manifest_path, MANIFEST.as_bytes());
46+
write(tmp_path("lib.rs"), b"#![no_std]");
4647

4748
let path = std::env::var("PATH").unwrap();
4849
let rustc = std::env::var("RUSTC").unwrap();
@@ -71,8 +72,7 @@ fn main() {
7172
assert!(status.success());
7273

7374
let rlibs_path = target_dir.join(target).join("debug").join("deps");
74-
let compiler_builtins_rlib = std::fs::read_dir(rlibs_path)
75-
.unwrap()
75+
let compiler_builtins_rlib = read_dir(rlibs_path)
7676
.find_map(|e| {
7777
let path = e.unwrap().path();
7878
let file_name = path.file_name().unwrap().to_str().unwrap();
@@ -86,7 +86,7 @@ fn main() {
8686

8787
// rlib files are archives, where the archive members each a CGU, and we also have one called
8888
// lib.rmeta which is the encoded metadata. Each of the CGUs is an object file.
89-
let data = std::fs::read(compiler_builtins_rlib).unwrap();
89+
let data = read(compiler_builtins_rlib);
9090

9191
let mut defined_symbols = HashSet::new();
9292
let mut undefined_relocations = HashSet::new();

tests/run-make/doctests-keep-binaries/rmake.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
// Check that valid binaries are persisted by running them, regardless of whether the
22
// --run or --no-run option is used.
33

4+
use run_make_support::fs::{create_dir, remove_dir_all};
45
use run_make_support::{run, rustc, rustdoc, tmp_dir, tmp_path};
5-
use std::fs::{create_dir, remove_dir_all};
66
use std::path::Path;
77

88
fn setup_test_env<F: FnOnce(&Path, &Path)>(callback: F) {
99
let out_dir = tmp_path("doctests");
10-
create_dir(&out_dir).expect("failed to create doctests folder");
10+
create_dir(&out_dir);
1111
rustc().input("t.rs").crate_type("rlib").run();
1212
callback(&out_dir, &tmp_path("libt.rlib"));
1313
remove_dir_all(out_dir);
@@ -46,7 +46,7 @@ fn main() {
4646
setup_test_env(|_out_dir, extern_path| {
4747
let run_dir = "rundir";
4848
let run_dir_path = tmp_path("rundir");
49-
create_dir(&run_dir_path).expect("failed to create rundir folder");
49+
create_dir(&run_dir_path);
5050

5151
rustdoc()
5252
.current_dir(tmp_dir())

tests/run-make/doctests-runtool/rmake.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
// Tests behavior of rustdoc `--runtool`.
22

3+
use run_make_support::fs::{create_dir, remove_dir_all};
34
use run_make_support::{rustc, rustdoc, tmp_dir, tmp_path};
45
use std::env::current_dir;
5-
use std::fs::{create_dir, remove_dir_all};
66
use std::path::PathBuf;
77

88
fn mkdir(name: &str) -> PathBuf {
99
let dir = tmp_path(name);
10-
create_dir(&dir).expect("failed to create doctests folder");
10+
create_dir(&dir);
1111
dir
1212
}
1313

tests/run-make/issue-107495-archive-permissions/rmake.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
#[cfg(unix)]
44
extern crate libc;
55

6+
use run_make_support::fs;
67
use run_make_support::{aux_build, tmp_path};
7-
use std::fs;
88
#[cfg(unix)]
99
use std::os::unix::fs::PermissionsExt;
1010
use std::path::Path;

tests/run-make/no-intermediate-extras/rmake.rs

+1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use std::fs;
1111
fn main() {
1212
rustc().crate_type("rlib").arg("--test").input("foo.rs").run();
1313
assert!(
14+
// Do not use run-make-support's fs wrapper here - this needs to return an Error.
1415
fs::remove_file(tmp_path("foo.bc")).is_err(),
1516
"An unwanted .bc file was created by run-make/no-intermediate-extras."
1617
);

tests/run-make/non-unicode-env/rmake.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use run_make_support::fs;
12
use run_make_support::rustc;
23

34
fn main() {
@@ -7,6 +8,6 @@ fn main() {
78
let non_unicode: std::ffi::OsString = std::os::windows::ffi::OsStringExt::from_wide(&[0xD800]);
89
let output = rustc().input("non_unicode_env.rs").env("NON_UNICODE_VAR", non_unicode).run_fail();
910
let actual = std::str::from_utf8(&output.stderr).unwrap();
10-
let expected = std::fs::read_to_string("non_unicode_env.stderr").unwrap();
11+
let expected = fs::read_to_string("non_unicode_env.stderr");
1112
assert_eq!(actual, expected);
1213
}

tests/run-make/non-unicode-in-incremental-dir/rmake.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ fn main() {
55
let non_unicode: &std::ffi::OsStr = std::os::unix::ffi::OsStrExt::from_bytes(&[0xFF]);
66
#[cfg(windows)]
77
let non_unicode: std::ffi::OsString = std::os::windows::ffi::OsStringExt::from_wide(&[0xD800]);
8+
// Do not use run-make-support's fs wrapper, this needs special handling.
89
match std::fs::create_dir(tmp_path(&non_unicode)) {
910
// If an error occurs, check if creating a directory with a valid Unicode name would
1011
// succeed.
@@ -17,8 +18,8 @@ fn main() {
1718
}
1819
let incr_dir = tmp_path("incr-dir");
1920
rustc().input("foo.rs").incremental(&incr_dir).run();
20-
for crate_dir in std::fs::read_dir(&incr_dir).unwrap() {
21-
std::fs::create_dir(crate_dir.unwrap().path().join(&non_unicode)).unwrap();
21+
for crate_dir in run_make_support::fs::read_dir(&incr_dir) {
22+
run_make_support::fs::create_dir(crate_dir.unwrap().path().join(&non_unicode));
2223
}
2324
rustc().input("foo.rs").incremental(&incr_dir).run();
2425
}

tests/run-make/print-cfg/rmake.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use std::ffi::OsString;
1010
use std::io::BufRead;
1111
use std::iter::FromIterator;
1212

13+
use run_make_support::fs;
1314
use run_make_support::{rustc, tmp_path};
1415

1516
struct PrintCfg {
@@ -97,7 +98,7 @@ fn check(PrintCfg { target, includes, disallow }: PrintCfg) {
9798

9899
let output = rustc().target(target).arg(print_arg).run();
99100

100-
let output = std::fs::read_to_string(&tmp_path).unwrap();
101+
let output = fs::read_to_string(&tmp_path).unwrap();
101102

102103
check_(&output, includes, disallow);
103104
}

tests/run-make/print-to-output/rmake.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
44
use std::ffi::OsString;
55

6+
use run_make_support::fs;
67
use run_make_support::{rustc, target, tmp_path};
78

89
struct Option<'a> {
@@ -52,7 +53,7 @@ fn check(args: Option) {
5253

5354
let _output = rustc().target(args.target).arg(print_arg).run();
5455

55-
std::fs::read_to_string(&tmp_path).unwrap()
56+
fs::read_to_string(&tmp_path)
5657
};
5758

5859
check_(&stdout, args.includes);

tests/run-make/repr128-dwarf/rmake.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
use gimli::{AttributeValue, Dwarf, EndianRcSlice, Reader, RunTimeEndian};
55
use object::{Object, ObjectSection};
6+
use run_make_support::fs;
67
use run_make_support::{gimli, object, rustc, tmp_path};
78
use std::borrow::Cow;
89
use std::collections::HashMap;
@@ -18,9 +19,7 @@ fn main() {
1819
.join("Resources")
1920
.join("DWARF")
2021
.join("repr128");
21-
let output =
22-
std::fs::read(if dsym_location.try_exists().unwrap() { dsym_location } else { output })
23-
.unwrap();
22+
let output = fs::read(if dsym_location.try_exists().unwrap() { dsym_location } else { output });
2423
let obj = object::File::parse(output.as_slice()).unwrap();
2524
let endian = if obj.is_little_endian() { RunTimeEndian::Little } else { RunTimeEndian::Big };
2625
let dwarf = gimli::Dwarf::load(|section| -> Result<_, ()> {

tests/run-make/reset-codegen-1/rmake.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77

88
//@ ignore-cross-compile
99

10+
use run_make_support::fs;
1011
use run_make_support::{rustc, tmp_path};
11-
use std::fs;
1212

1313
fn compile(output_file: &str, emit: Option<&str>) {
1414
let mut rustc = rustc();
@@ -31,7 +31,7 @@ fn main() {
3131
("multi-output", Some("asm,obj")),
3232
];
3333
for (output_file, emit) in flags {
34-
fs::remove_file(output_file).unwrap_or_default();
34+
std::fs::remove_file(output_file).unwrap_or_default();
3535
compile(output_file, emit);
3636
fs::remove_file(output_file);
3737
}

tests/run-make/rustdoc-test-args/rmake.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1+
use run_make_support::fs;
12
use run_make_support::{rustdoc, tmp_dir, tmp_path};
23
use std::path::Path;
3-
use std::{fs, iter};
4+
use std::iter;
45

56
fn generate_a_lot_of_cfgs(path: &Path) {
67
let content = iter::repeat("--cfg=a\n").take(100_000).collect::<String>();
7-
fs::write(path, content.as_bytes()).expect("failed to create args file");
8+
fs::write(path, content.as_bytes());
89
}
910

1011
fn main() {

0 commit comments

Comments
 (0)