]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/clean.rs
Rollup merge of #94145 - ssomers:binary_heap_tests, r=jyn514
[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
98         for host in &build.hosts {
99             let entries = match build.out.join(host.triple).read_dir() {
100                 Ok(iter) => iter,
101                 Err(_) => continue,
102             };
103
104             for entry in entries {
105                 let entry = t!(entry);
106                 if entry.file_name().to_str() == Some("llvm") {
107                     continue;
108                 }
109                 let path = t!(entry.path().canonicalize());
110                 rm_rf(&path);
111             }
112         }
113     }
114 }
115
116 fn rm_rf(path: &Path) {
117     match path.symlink_metadata() {
118         Err(e) => {
119             if e.kind() == ErrorKind::NotFound {
120                 return;
121             }
122             panic!("failed to get metadata for file {}: {}", path.display(), e);
123         }
124         Ok(metadata) => {
125             if metadata.file_type().is_file() || metadata.file_type().is_symlink() {
126                 do_op(path, "remove file", |p| {
127                     fs::remove_file(p).or_else(|e| {
128                         // Work around the fact that we cannot
129                         // delete an executable while it runs on Windows.
130                         #[cfg(windows)]
131                         if e.kind() == std::io::ErrorKind::PermissionDenied
132                             && p.file_name().and_then(std::ffi::OsStr::to_str)
133                                 == Some("bootstrap.exe")
134                         {
135                             eprintln!("warning: failed to delete '{}'.", p.display());
136                             return Ok(());
137                         }
138                         Err(e)
139                     })
140                 });
141                 return;
142             }
143
144             for file in t!(fs::read_dir(path)) {
145                 rm_rf(&t!(file).path());
146             }
147             do_op(path, "remove dir", |p| {
148                 fs::remove_dir(p).or_else(|e| {
149                     // Check for dir not empty on Windows
150                     // FIXME: Once `ErrorKind::DirectoryNotEmpty` is stabilized,
151                     // match on `e.kind()` instead.
152                     #[cfg(windows)]
153                     if e.raw_os_error() == Some(145) {
154                         return Ok(());
155                     }
156
157                     Err(e)
158                 })
159             });
160         }
161     };
162 }
163
164 fn do_op<F>(path: &Path, desc: &str, mut f: F)
165 where
166     F: FnMut(&Path) -> io::Result<()>,
167 {
168     match f(path) {
169         Ok(()) => {}
170         // On windows we can't remove a readonly file, and git will often clone files as readonly.
171         // As a result, we have some special logic to remove readonly files on windows.
172         // This is also the reason that we can't use things like fs::remove_dir_all().
173         Err(ref e) if cfg!(windows) && e.kind() == ErrorKind::PermissionDenied => {
174             let m = t!(path.symlink_metadata());
175             let mut p = m.permissions();
176             p.set_readonly(false);
177             t!(fs::set_permissions(path, p));
178             f(path).unwrap_or_else(|e| {
179                 // Delete symlinked directories on Windows
180                 #[cfg(windows)]
181                 if m.file_type().is_symlink() && path.is_dir() && fs::remove_dir(path).is_ok() {
182                     return;
183                 }
184                 panic!("failed to {} {}: {}", desc, path.display(), e);
185             });
186         }
187         Err(e) => {
188             panic!("failed to {} {}: {}", desc, path.display(), e);
189         }
190     }
191 }