]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/clean.rs
Auto merge of #105651 - tgross35:once-cell-inline, r=m-ou-se
[rust.git] / src / bootstrap / clean.rs
1 //! Implementation of `make clean` in rustbuild.
2 //!
3 //! Responsible for cleaning out a build directory of all old and stale
4 //! artifacts to prepare for a fresh build. Currently doesn't remove the
5 //! `build/cache` directory (download cache) or the `build/$target/llvm`
6 //! directory unless the `--all` flag is present.
7
8 use std::fs;
9 use std::io::{self, ErrorKind};
10 use std::path::Path;
11
12 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
13 use crate::cache::Interned;
14 use crate::config::TargetSelection;
15 use crate::util::t;
16 use crate::{Build, Mode, Subcommand};
17
18 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19 pub struct CleanAll {}
20
21 impl Step for CleanAll {
22     const DEFAULT: bool = true;
23     type Output = ();
24
25     fn make_run(run: RunConfig<'_>) {
26         run.builder.ensure(CleanAll {})
27     }
28
29     fn run(self, builder: &Builder<'_>) -> Self::Output {
30         let Subcommand::Clean { all, .. } = builder.config.cmd else { unreachable!("wrong subcommand?") };
31         clean_default(builder.build, all)
32     }
33
34     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
35         run.never() // handled by DEFAULT
36     }
37 }
38
39 macro_rules! clean_crate_tree {
40     ( $( $name:ident, $mode:path, $root_crate:literal);+ $(;)? ) => { $(
41         #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
42         pub struct $name {
43             target: TargetSelection,
44             crates: Interned<Vec<String>>,
45         }
46
47         impl Step for $name {
48             type Output = ();
49
50             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
51                 let crates = run.builder.in_tree_crates($root_crate, None);
52                 run.crates(crates)
53             }
54
55             fn make_run(run: RunConfig<'_>) {
56                 let builder = run.builder;
57                 if builder.top_stage != 0 {
58                     panic!("non-stage-0 clean not supported for individual crates");
59                 }
60                 builder.ensure(Self { crates: run.cargo_crates_in_set(), target: run.target });
61             }
62
63             fn run(self, builder: &Builder<'_>) -> Self::Output {
64                 let compiler = builder.compiler(0, self.target);
65                 let mut cargo = builder.bare_cargo(compiler, $mode, self.target, "clean");
66                 for krate in &*self.crates {
67                     cargo.arg(krate);
68                 }
69
70                 builder.info(&format!(
71                     "Cleaning stage{} {} artifacts ({} -> {})",
72                     compiler.stage, stringify!($name).to_lowercase(), &compiler.host, self.target
73                 ));
74
75                 // NOTE: doesn't use `run_cargo` because we don't want to save a stamp file,
76                 // and doesn't use `stream_cargo` to avoid passing `--message-format` which `clean` doesn't accept.
77                 builder.run(&mut cargo);
78             }
79         }
80     )+ }
81 }
82
83 clean_crate_tree! {
84     Rustc, Mode::Rustc, "rustc-main";
85     Std, Mode::Std, "test";
86 }
87
88 fn clean_default(build: &Build, all: bool) {
89     rm_rf("tmp".as_ref());
90
91     if all {
92         rm_rf(&build.out);
93     } else {
94         rm_rf(&build.out.join("tmp"));
95         rm_rf(&build.out.join("dist"));
96         rm_rf(&build.out.join("bootstrap"));
97         rm_rf(&build.out.join("rustfmt.stamp"));
98
99         for host in &build.hosts {
100             let entries = match build.out.join(host.triple).read_dir() {
101                 Ok(iter) => iter,
102                 Err(_) => continue,
103             };
104
105             for entry in entries {
106                 let entry = t!(entry);
107                 if entry.file_name().to_str() == Some("llvm") {
108                     continue;
109                 }
110                 let path = t!(entry.path().canonicalize());
111                 rm_rf(&path);
112             }
113         }
114     }
115 }
116
117 fn rm_rf(path: &Path) {
118     match path.symlink_metadata() {
119         Err(e) => {
120             if e.kind() == ErrorKind::NotFound {
121                 return;
122             }
123             panic!("failed to get metadata for file {}: {}", path.display(), e);
124         }
125         Ok(metadata) => {
126             if metadata.file_type().is_file() || metadata.file_type().is_symlink() {
127                 do_op(path, "remove file", |p| {
128                     fs::remove_file(p).or_else(|e| {
129                         // Work around the fact that we cannot
130                         // delete an executable while it runs on Windows.
131                         #[cfg(windows)]
132                         if e.kind() == std::io::ErrorKind::PermissionDenied
133                             && p.file_name().and_then(std::ffi::OsStr::to_str)
134                                 == Some("bootstrap.exe")
135                         {
136                             eprintln!("warning: failed to delete '{}'.", p.display());
137                             return Ok(());
138                         }
139                         Err(e)
140                     })
141                 });
142                 return;
143             }
144
145             for file in t!(fs::read_dir(path)) {
146                 rm_rf(&t!(file).path());
147             }
148             do_op(path, "remove dir", |p| {
149                 fs::remove_dir(p).or_else(|e| {
150                     // Check for dir not empty on Windows
151                     // FIXME: Once `ErrorKind::DirectoryNotEmpty` is stabilized,
152                     // match on `e.kind()` instead.
153                     #[cfg(windows)]
154                     if e.raw_os_error() == Some(145) {
155                         return Ok(());
156                     }
157
158                     Err(e)
159                 })
160             });
161         }
162     };
163 }
164
165 fn do_op<F>(path: &Path, desc: &str, mut f: F)
166 where
167     F: FnMut(&Path) -> io::Result<()>,
168 {
169     match f(path) {
170         Ok(()) => {}
171         // On windows we can't remove a readonly file, and git will often clone files as readonly.
172         // As a result, we have some special logic to remove readonly files on windows.
173         // This is also the reason that we can't use things like fs::remove_dir_all().
174         Err(ref e) if cfg!(windows) && e.kind() == ErrorKind::PermissionDenied => {
175             let m = t!(path.symlink_metadata());
176             let mut p = m.permissions();
177             p.set_readonly(false);
178             t!(fs::set_permissions(path, p));
179             f(path).unwrap_or_else(|e| {
180                 // Delete symlinked directories on Windows
181                 #[cfg(windows)]
182                 if m.file_type().is_symlink() && path.is_dir() && fs::remove_dir(path).is_ok() {
183                     return;
184                 }
185                 panic!("failed to {} {}: {}", desc, path.display(), e);
186             });
187         }
188         Err(e) => {
189             panic!("failed to {} {}: {}", desc, path.display(), e);
190         }
191     }
192 }