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