]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/docfs.rs
Auto merge of #86231 - nagisa:nagisa/abi-allowlist, r=petrochenkov
[rust.git] / src / librustdoc / docfs.rs
1 //! Rustdoc's FileSystem abstraction module.
2 //!
3 //! On Windows this indirects IO into threads to work around performance issues
4 //! with Defender (and other similar virus scanners that do blocking operations).
5 //! On other platforms this is a thin shim to fs.
6 //!
7 //! Only calls needed to permit this workaround have been abstracted: thus
8 //! fs::read is still done directly via the fs module; if in future rustdoc
9 //! needs to read-after-write from a file, then it would be added to this
10 //! abstraction.
11
12 use std::fs;
13 use std::io;
14 use std::path::Path;
15 use std::string::ToString;
16 use std::sync::mpsc::Sender;
17
18 macro_rules! try_err {
19     ($e:expr, $file:expr) => {
20         match $e {
21             Ok(e) => e,
22             Err(e) => return Err(E::new(e, $file)),
23         }
24     };
25 }
26
27 crate trait PathError {
28     fn new<S, P: AsRef<Path>>(e: S, path: P) -> Self
29     where
30         S: ToString + Sized;
31 }
32
33 crate struct DocFS {
34     sync_only: bool,
35     errors: Option<Sender<String>>,
36 }
37
38 impl DocFS {
39     crate fn new(errors: Sender<String>) -> DocFS {
40         DocFS { sync_only: false, errors: Some(errors) }
41     }
42
43     crate fn set_sync_only(&mut self, sync_only: bool) {
44         self.sync_only = sync_only;
45     }
46
47     crate fn close(&mut self) {
48         self.errors = None;
49     }
50
51     crate fn create_dir_all<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
52         // For now, dir creation isn't a huge time consideration, do it
53         // synchronously, which avoids needing ordering between write() actions
54         // and directory creation.
55         fs::create_dir_all(path)
56     }
57
58     crate fn write<P, C, E>(&self, path: P, contents: C) -> Result<(), E>
59     where
60         P: AsRef<Path>,
61         C: AsRef<[u8]>,
62         E: PathError,
63     {
64         if !self.sync_only && cfg!(windows) {
65             // A possible future enhancement after more detailed profiling would
66             // be to create the file sync so errors are reported eagerly.
67             let path = path.as_ref().to_path_buf();
68             let contents = contents.as_ref().to_vec();
69             let sender = self.errors.clone().expect("can't write after closing");
70             rayon::spawn(move || {
71                 fs::write(&path, contents).unwrap_or_else(|e| {
72                     sender.send(format!("\"{}\": {}", path.display(), e)).unwrap_or_else(|_| {
73                         panic!("failed to send error on \"{}\"", path.display())
74                     })
75                 });
76             });
77         } else {
78             try_err!(fs::write(&path, contents), path);
79         }
80         Ok(())
81     }
82 }