1 //! Implementation of `make clean` in rustbuild.
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.
9 use std::io::{self, ErrorKind};
12 use crate::builder::{crate_description, Builder, RunConfig, ShouldRun, Step};
13 use crate::cache::Interned;
15 use crate::{Build, Compiler, Mode, Subcommand};
17 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18 pub struct CleanAll {}
20 impl Step for CleanAll {
21 const DEFAULT: bool = true;
24 fn make_run(run: RunConfig<'_>) {
25 run.builder.ensure(CleanAll {})
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)
33 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
34 run.never() // handled by DEFAULT
38 macro_rules! clean_crate_tree {
39 ( $( $name:ident, $mode:path, $root_crate:literal);+ $(;)? ) => { $(
40 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43 crates: Interned<Vec<String>>,
49 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
50 let crates = run.builder.in_tree_crates($root_crate, None);
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 });
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 {
68 builder.info(&format!(
69 "Cleaning{} stage{} {} artifacts ({} -> {})",
70 crate_description(&self.crates), compiler.stage, stringify!($name).to_lowercase(), &compiler.host, target,
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);
82 Rustc, Mode::Rustc, "rustc-main";
83 Std, Mode::Std, "test";
86 fn clean_default(build: &Build, all: bool) {
87 rm_rf("tmp".as_ref());
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"));
97 for host in &build.hosts {
98 let entries = match build.out.join(host.triple).read_dir() {
103 for entry in entries {
104 let entry = t!(entry);
105 if entry.file_name().to_str() == Some("llvm") {
108 let path = t!(entry.path().canonicalize());
115 fn rm_rf(path: &Path) {
116 match path.symlink_metadata() {
118 if e.kind() == ErrorKind::NotFound {
121 panic!("failed to get metadata for file {}: {}", path.display(), e);
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.
130 if e.kind() == std::io::ErrorKind::PermissionDenied
131 && p.file_name().and_then(std::ffi::OsStr::to_str)
132 == Some("bootstrap.exe")
134 eprintln!("warning: failed to delete '{}'.", p.display());
143 for file in t!(fs::read_dir(path)) {
144 rm_rf(&t!(file).path());
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.
152 if e.raw_os_error() == Some(145) {
163 fn do_op<F>(path: &Path, desc: &str, mut f: F)
165 F: FnMut(&Path) -> io::Result<()>,
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
180 if m.file_type().is_symlink() && path.is_dir() && fs::remove_dir(path).is_ok() {
183 panic!("failed to {} {}: {}", desc, path.display(), e);
187 panic!("failed to {} {}: {}", desc, path.display(), e);