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"));
98 for host in &build.hosts {
99 let entries = match build.out.join(host.triple).read_dir() {
104 for entry in entries {
105 let entry = t!(entry);
106 if entry.file_name().to_str() == Some("llvm") {
109 let path = t!(entry.path().canonicalize());
116 fn rm_rf(path: &Path) {
117 match path.symlink_metadata() {
119 if e.kind() == ErrorKind::NotFound {
122 panic!("failed to get metadata for file {}: {}", path.display(), e);
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.
131 if e.kind() == std::io::ErrorKind::PermissionDenied
132 && p.file_name().and_then(std::ffi::OsStr::to_str)
133 == Some("bootstrap.exe")
135 eprintln!("warning: failed to delete '{}'.", p.display());
144 for file in t!(fs::read_dir(path)) {
145 rm_rf(&t!(file).path());
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.
153 if e.raw_os_error() == Some(145) {
164 fn do_op<F>(path: &Path, desc: &str, mut f: F)
166 F: FnMut(&Path) -> io::Result<()>,
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
181 if m.file_type().is_symlink() && path.is_dir() && fs::remove_dir(path).is_ok() {
184 panic!("failed to {} {}: {}", desc, path.display(), e);
188 panic!("failed to {} {}: {}", desc, path.display(), e);