run_make_support/
fs.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use std::io;
use std::path::{Path, PathBuf};

/// Copy a directory into another.
pub fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) {
    fn copy_dir_all_inner(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> io::Result<()> {
        let dst = dst.as_ref();
        if !dst.is_dir() {
            std::fs::create_dir_all(&dst)?;
        }
        for entry in std::fs::read_dir(src)? {
            let entry = entry?;
            let ty = entry.file_type()?;
            if ty.is_dir() {
                copy_dir_all_inner(entry.path(), dst.join(entry.file_name()))?;
            } else if ty.is_symlink() {
                // Traverse symlink once to find path of target entity.
                let target_path = std::fs::read_link(entry.path())?;

                let new_symlink_path = dst.join(entry.file_name());
                #[cfg(windows)]
                {
                    use std::os::windows::fs::FileTypeExt;
                    if ty.is_symlink_dir() {
                        std::os::windows::fs::symlink_dir(&target_path, new_symlink_path)?;
                    } else {
                        // Target may be a file or another symlink, in any case we can use
                        // `symlink_file` here.
                        std::os::windows::fs::symlink_file(&target_path, new_symlink_path)?;
                    }
                }
                #[cfg(unix)]
                {
                    std::os::unix::fs::symlink(target_path, new_symlink_path)?;
                }
                #[cfg(not(any(windows, unix)))]
                {
                    // Technically there's also wasi, but I have no clue about wasi symlink
                    // semantics and which wasi targets / environment support symlinks.
                    unimplemented!("unsupported target");
                }
            } else {
                std::fs::copy(entry.path(), dst.join(entry.file_name()))?;
            }
        }
        Ok(())
    }

    if let Err(e) = copy_dir_all_inner(&src, &dst) {
        // Trying to give more context about what exactly caused the failure
        panic!(
            "failed to copy `{}` to `{}`: {:?}",
            src.as_ref().display(),
            dst.as_ref().display(),
            e
        );
    }
}

/// Helper for reading entries in a given directory.
pub fn read_dir_entries<P: AsRef<Path>, F: FnMut(&Path)>(dir: P, mut callback: F) {
    for entry in read_dir(dir) {
        callback(&entry.unwrap().path());
    }
}

/// A wrapper around [`std::fs::remove_file`] which includes the file path in the panic message.
#[track_caller]
pub fn remove_file<P: AsRef<Path>>(path: P) {
    if let Err(e) = std::fs::remove_file(path.as_ref()) {
        panic!("failed to remove file at `{}`: {e}", path.as_ref().display());
    }
}

/// A wrapper around [`std::fs::remove_dir`] which includes the directory path in the panic message.
#[track_caller]
pub fn remove_dir<P: AsRef<Path>>(path: P) {
    if let Err(e) = std::fs::remove_dir(path.as_ref()) {
        panic!("failed to remove directory at `{}`: {e}", path.as_ref().display());
    }
}

/// A wrapper around [`std::fs::copy`] which includes the file path in the panic message.
#[track_caller]
pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) {
    std::fs::copy(from.as_ref(), to.as_ref()).expect(&format!(
        "the file \"{}\" could not be copied over to \"{}\"",
        from.as_ref().display(),
        to.as_ref().display(),
    ));
}

/// A wrapper around [`std::fs::File::create`] which includes the file path in the panic message.
#[track_caller]
pub fn create_file<P: AsRef<Path>>(path: P) {
    std::fs::File::create(path.as_ref())
        .expect(&format!("the file in path \"{}\" could not be created", path.as_ref().display()));
}

/// A wrapper around [`std::fs::read`] which includes the file path in the panic message.
#[track_caller]
pub fn read<P: AsRef<Path>>(path: P) -> Vec<u8> {
    std::fs::read(path.as_ref())
        .expect(&format!("the file in path \"{}\" could not be read", path.as_ref().display()))
}

/// A wrapper around [`std::fs::read_to_string`] which includes the file path in the panic message.
#[track_caller]
pub fn read_to_string<P: AsRef<Path>>(path: P) -> String {
    std::fs::read_to_string(path.as_ref()).expect(&format!(
        "the file in path \"{}\" could not be read into a String",
        path.as_ref().display()
    ))
}

/// A wrapper around [`std::fs::read_dir`] which includes the file path in the panic message.
#[track_caller]
pub fn read_dir<P: AsRef<Path>>(path: P) -> std::fs::ReadDir {
    std::fs::read_dir(path.as_ref())
        .expect(&format!("the directory in path \"{}\" could not be read", path.as_ref().display()))
}

/// A wrapper around [`std::fs::write`] which includes the file path in the panic message.
#[track_caller]
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) {
    std::fs::write(path.as_ref(), contents.as_ref()).expect(&format!(
        "the file in path \"{}\" could not be written to",
        path.as_ref().display()
    ));
}

/// A wrapper around [`std::fs::remove_dir_all`] which includes the file path in the panic message.
#[track_caller]
pub fn remove_dir_all<P: AsRef<Path>>(path: P) {
    std::fs::remove_dir_all(path.as_ref()).expect(&format!(
        "the directory in path \"{}\" could not be removed alongside all its contents",
        path.as_ref().display(),
    ));
}

/// A wrapper around [`std::fs::create_dir`] which includes the file path in the panic message.
#[track_caller]
pub fn create_dir<P: AsRef<Path>>(path: P) {
    std::fs::create_dir(path.as_ref()).expect(&format!(
        "the directory in path \"{}\" could not be created",
        path.as_ref().display()
    ));
}

/// A wrapper around [`std::fs::create_dir_all`] which includes the file path in the panic message.
#[track_caller]
pub fn create_dir_all<P: AsRef<Path>>(path: P) {
    std::fs::create_dir_all(path.as_ref()).expect(&format!(
        "the directory (and all its parents) in path \"{}\" could not be created",
        path.as_ref().display()
    ));
}

/// A wrapper around [`std::fs::metadata`] which includes the file path in the panic message. Note
/// that this will traverse symlinks and will return metadata about the target file. Use
/// [`symlink_metadata`] if you don't want to traverse symlinks.
///
/// See [`std::fs::metadata`] docs for more details.
#[track_caller]
pub fn metadata<P: AsRef<Path>>(path: P) -> std::fs::Metadata {
    match std::fs::metadata(path.as_ref()) {
        Ok(m) => m,
        Err(e) => panic!("failed to read file metadata at `{}`: {e}", path.as_ref().display()),
    }
}

/// A wrapper around [`std::fs::symlink_metadata`] which includes the file path in the panic
/// message. Note that this will not traverse symlinks and will return metadata about the filesystem
/// entity itself. Use [`metadata`] if you want to traverse symlinks.
///
/// See [`std::fs::symlink_metadata`] docs for more details.
#[track_caller]
pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> std::fs::Metadata {
    match std::fs::symlink_metadata(path.as_ref()) {
        Ok(m) => m,
        Err(e) => {
            panic!("failed to read file metadata (shallow) at `{}`: {e}", path.as_ref().display())
        }
    }
}

/// A wrapper around [`std::fs::rename`] which includes the file path in the panic message.
#[track_caller]
pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) {
    std::fs::rename(from.as_ref(), to.as_ref()).expect(&format!(
        "the file \"{}\" could not be moved over to \"{}\"",
        from.as_ref().display(),
        to.as_ref().display(),
    ));
}

/// A wrapper around [`std::fs::set_permissions`] which includes the file path in the panic message.
#[track_caller]
pub fn set_permissions<P: AsRef<Path>>(path: P, perm: std::fs::Permissions) {
    std::fs::set_permissions(path.as_ref(), perm).expect(&format!(
        "the file's permissions in path \"{}\" could not be changed",
        path.as_ref().display()
    ));
}

/// A function which prints all file names in the directory `dir` similarly to Unix's `ls`.
/// Useful for debugging.
/// Usage: `eprintln!("{:#?}", shallow_find_dir_entries(some_dir));`
#[track_caller]
pub fn shallow_find_dir_entries<P: AsRef<Path>>(dir: P) -> Vec<PathBuf> {
    let paths = read_dir(dir);
    let mut output = Vec::new();
    for path in paths {
        output.push(path.unwrap().path());
    }
    output
}

/// Create a new symbolic link to a directory.
///
/// # Removing the symlink
///
/// - On Windows, a symlink-to-directory needs to be removed with a corresponding [`fs::remove_dir`]
///   and not [`fs::remove_file`].
/// - On Unix, remove the symlink with [`fs::remove_file`].
///
/// [`fs::remove_dir`]: crate::fs::remove_dir
/// [`fs::remove_file`]: crate::fs::remove_file
pub fn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) {
    #[cfg(unix)]
    {
        if let Err(e) = std::os::unix::fs::symlink(original.as_ref(), link.as_ref()) {
            panic!(
                "failed to create symlink: original=`{}`, link=`{}`: {e}",
                original.as_ref().display(),
                link.as_ref().display()
            );
        }
    }
    #[cfg(windows)]
    {
        if let Err(e) = std::os::windows::fs::symlink_dir(original.as_ref(), link.as_ref()) {
            panic!(
                "failed to create symlink-to-directory: original=`{}`, link=`{}`: {e}",
                original.as_ref().display(),
                link.as_ref().display()
            );
        }
    }
    #[cfg(not(any(windows, unix)))]
    {
        unimplemented!("target family not currently supported")
    }
}

/// Create a new symbolic link to a file.
///
/// # Removing the symlink
///
/// On both Windows and Unix, a symlink-to-file needs to be removed with a corresponding
/// [`fs::remove_file`](crate::fs::remove_file) and not [`fs::remove_dir`](crate::fs::remove_dir).
pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) {
    #[cfg(unix)]
    {
        if let Err(e) = std::os::unix::fs::symlink(original.as_ref(), link.as_ref()) {
            panic!(
                "failed to create symlink: original=`{}`, link=`{}`: {e}",
                original.as_ref().display(),
                link.as_ref().display()
            );
        }
    }
    #[cfg(windows)]
    {
        if let Err(e) = std::os::windows::fs::symlink_file(original.as_ref(), link.as_ref()) {
            panic!(
                "failed to create symlink-to-file: original=`{}`, link=`{}`: {e}",
                original.as_ref().display(),
                link.as_ref().display()
            );
        }
    }
    #[cfg(not(any(windows, unix)))]
    {
        unimplemented!("target family not currently supported")
    }
}