Skip to content

Commit 413d8b1

Browse files
committed
Add safe wrappers around fs in run_make_support
1 parent 93724a2 commit 413d8b1

File tree

28 files changed

+165
-74
lines changed

28 files changed

+165
-74
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

+32-33
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,10 +34,6 @@ 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())
40-
}
41-
4237
/// `TARGET`
4338
pub fn target() -> String {
4439
env::var("TARGET").unwrap()
@@ -62,7 +57,7 @@ pub fn is_darwin() -> bool {
6257
/// Construct a path to a static library under `$TMPDIR` given the library name. This will return a
6358
/// path with `$TMPDIR` joined with platform-and-compiler-specific library name.
6459
pub fn static_lib(name: &str) -> PathBuf {
65-
tmp_path(static_lib_name(name))
60+
tmp_dir().join(static_lib_name(name))
6661
}
6762

6863
pub fn python_command() -> Command {
@@ -80,6 +75,28 @@ pub fn source_path() -> PathBuf {
8075
std::env::var("S").expect("S variable does not exist").into()
8176
}
8277

78+
/// Creates a new symlink to a path on the filesystem, adjusting for Windows or Unix.
79+
#[cfg(target_family = "windows")]
80+
pub fn create_symlink<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) {
81+
use std::os::windows::fs;
82+
fs::symlink_file(original.as_ref(), link.as_ref()).expect(&format!(
83+
"failed to create symlink {:?} for {:?}",
84+
link.as_ref().display(),
85+
original.as_ref().display(),
86+
));
87+
}
88+
89+
/// Creates a new symlink to a path on the filesystem, adjusting for Windows or Unix.
90+
#[cfg(target_family = "unix")]
91+
pub fn create_symlink<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) {
92+
use std::os::unix::fs;
93+
fs::symlink(original.as_ref(), link.as_ref()).expect(&format!(
94+
"failed to create symlink {:?} for {:?}",
95+
link.as_ref().display(),
96+
original.as_ref().display(),
97+
));
98+
}
99+
83100
/// Construct the static library name based on the platform.
84101
pub fn static_lib_name(name: &str) -> String {
85102
// See tools.mk (irrelevant lines omitted):
@@ -107,7 +124,7 @@ pub fn static_lib_name(name: &str) -> String {
107124
/// Construct a path to a dynamic library under `$TMPDIR` given the library name. This will return a
108125
/// path with `$TMPDIR` joined with platform-and-compiler-specific library name.
109126
pub fn dynamic_lib(name: &str) -> PathBuf {
110-
tmp_path(dynamic_lib_name(name))
127+
tmp_dir().join(dynamic_lib_name(name))
111128
}
112129

113130
/// Construct the dynamic library name based on the platform.
@@ -139,7 +156,7 @@ pub fn dynamic_lib_name(name: &str) -> String {
139156
/// Construct a path to a rust library (rlib) under `$TMPDIR` given the library name. This will return a
140157
/// path with `$TMPDIR` joined with the library name.
141158
pub fn rust_lib(name: &str) -> PathBuf {
142-
tmp_path(format!("lib{name}.rlib"))
159+
tmp_dir().join(format!("lib{name}.rlib"))
143160
}
144161

145162
/// Construct the binary name based on platform.
@@ -212,15 +229,15 @@ pub fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) {
212229
fn copy_dir_all_inner(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> io::Result<()> {
213230
let dst = dst.as_ref();
214231
if !dst.is_dir() {
215-
fs::create_dir_all(&dst)?;
232+
std::fs::create_dir_all(&dst)?;
216233
}
217-
for entry in fs::read_dir(src)? {
234+
for entry in std::fs::read_dir(src)? {
218235
let entry = entry?;
219236
let ty = entry.file_type()?;
220237
if ty.is_dir() {
221238
copy_dir_all_inner(entry.path(), dst.join(entry.file_name()))?;
222239
} else {
223-
fs::copy(entry.path(), dst.join(entry.file_name()))?;
240+
std::fs::copy(entry.path(), dst.join(entry.file_name()))?;
224241
}
225242
}
226243
Ok(())
@@ -239,15 +256,8 @@ pub fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) {
239256

240257
/// Check that all files in `dir1` exist and have the same content in `dir2`. Panic otherwise.
241258
pub fn recursive_diff(dir1: impl AsRef<Path>, dir2: impl AsRef<Path>) {
242-
fn read_file(path: &Path) -> Vec<u8> {
243-
match fs::read(path) {
244-
Ok(c) => c,
245-
Err(e) => panic!("Failed to read `{}`: {:?}", path.display(), e),
246-
}
247-
}
248-
249259
let dir2 = dir2.as_ref();
250-
for entry in fs::read_dir(dir1).unwrap() {
260+
for entry in fs::read_dir(dir1) {
251261
let entry = entry.unwrap();
252262
let entry_name = entry.file_name();
253263
let path = entry.path();
@@ -256,8 +266,8 @@ pub fn recursive_diff(dir1: impl AsRef<Path>, dir2: impl AsRef<Path>) {
256266
recursive_diff(&path, &dir2.join(entry_name));
257267
} else {
258268
let path2 = dir2.join(entry_name);
259-
let file1 = read_file(&path);
260-
let file2 = read_file(&path2);
269+
let file1 = fs::read(&path);
270+
let file2 = fs::read(&path2);
261271

262272
// We don't use `assert_eq!` because they are `Vec<u8>`, so not great for display.
263273
// Why not using String? Because there might be minified files or even potentially
@@ -272,17 +282,6 @@ pub fn recursive_diff(dir1: impl AsRef<Path>, dir2: impl AsRef<Path>) {
272282
}
273283
}
274284

275-
/// Check that `haystack` does not contain `needle`. Panic otherwise.
276-
pub fn assert_not_contains(haystack: &str, needle: &str) {
277-
if haystack.contains(needle) {
278-
eprintln!("=== HAYSTACK ===");
279-
eprintln!("{}", haystack);
280-
eprintln!("=== NEEDLE ===");
281-
eprintln!("{}", needle);
282-
panic!("needle was unexpectedly found in haystack");
283-
}
284-
}
285-
286285
/// Implement common helpers for command wrappers. This assumes that the command wrapper is a struct
287286
/// containing a `cmd: Command` field and a `output` function. The provided helpers are:
288287
///
@@ -366,7 +365,7 @@ macro_rules! impl_common_helpers {
366365
self
367366
}
368367

369-
/// Inspect what the underlying [`Command`] is up to the
368+
/// Inspect what the underlying [`Command`][::std::process::Command] is up to the
370369
/// current construction.
371370
pub fn inspect<I>(&mut self, inspector: I) -> &mut Self
372371
where

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
}

0 commit comments

Comments
 (0)