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::{Builder, RunConfig, ShouldRun, Step};
13 use crate::cache::Interned;
14 use crate::config::TargetSelection;
16 use crate::{Build, Mode, Subcommand};
18 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19 pub struct CleanAll {}
21 impl Step for CleanAll {
22 const DEFAULT: bool = true;
25 fn make_run(run: RunConfig<'_>) {
26 run.builder.ensure(CleanAll {})
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)
34 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
35 run.never() // handled by DEFAULT
39 macro_rules! clean_crate_tree {
40 ( $( $name:ident, $mode:path, $root_crate:literal);+ $(;)? ) => { $(
41 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43 target: TargetSelection,
44 crates: Interned<Vec<String>>,
50 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
51 let crates = run.builder.in_tree_crates($root_crate, None);
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");
60 builder.ensure(Self { crates: run.cargo_crates_in_set(), target: run.target });
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 {
70 builder.info(&format!(
71 "Cleaning stage{} {} artifacts ({} -> {})",
72 compiler.stage, stringify!($name).to_lowercase(), &compiler.host, self.target
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);
84 Rustc, Mode::Rustc, "rustc-main";
85 Std, Mode::Std, "test";
88 fn clean_default(build: &Build, all: bool) {
89 rm_rf("tmp".as_ref());
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"));
99 for host in &build.hosts {
100 let entries = match build.out.join(host.triple).read_dir() {
105 for entry in entries {
106 let entry = t!(entry);
107 if entry.file_name().to_str() == Some("llvm") {
110 let path = t!(entry.path().canonicalize());
117 fn rm_rf(path: &Path) {
118 match path.symlink_metadata() {
120 if e.kind() == ErrorKind::NotFound {
123 panic!("failed to get metadata for file {}: {}", path.display(), e);
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.
132 if e.kind() == std::io::ErrorKind::PermissionDenied
133 && p.file_name().and_then(std::ffi::OsStr::to_str)
134 == Some("bootstrap.exe")
136 eprintln!("warning: failed to delete '{}'.", p.display());
145 for file in t!(fs::read_dir(path)) {
146 rm_rf(&t!(file).path());
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.
154 if e.raw_os_error() == Some(145) {
165 fn do_op<F>(path: &Path, desc: &str, mut f: F)
167 F: FnMut(&Path) -> io::Result<()>,
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
182 if m.file_type().is_symlink() && path.is_dir() && fs::remove_dir(path).is_ok() {
185 panic!("failed to {} {}: {}", desc, path.display(), e);
189 panic!("failed to {} {}: {}", desc, path.display(), e);