Skip to main content

cargo/ops/
cargo_clean.rs

1use std::collections::HashMap;
2use std::fs;
3use std::path::Path;
4
5use crate::core::compiler::{BuildConfig, BuildContext, CompileMode, Context, Kind, Unit};
6use crate::core::profiles::UnitFor;
7use crate::core::Workspace;
8use crate::ops;
9use crate::util::errors::{CargoResult, CargoResultExt};
10use crate::util::paths;
11use crate::util::Config;
12
13pub struct CleanOptions<'a> {
14    pub config: &'a Config,
15    /// A list of packages to clean. If empty, everything is cleaned.
16    pub spec: Vec<String>,
17    /// The target arch triple to clean, or None for the host arch
18    pub target: Option<String>,
19    /// Whether to clean the release directory
20    pub release: bool,
21    /// Whether to just clean the doc directory
22    pub doc: bool,
23}
24
25/// Cleans the package's build artifacts.
26pub fn clean(ws: &Workspace<'_>, opts: &CleanOptions<'_>) -> CargoResult<()> {
27    let mut target_dir = ws.target_dir();
28    let config = ws.config();
29
30    // If the doc option is set, we just want to delete the doc directory.
31    if opts.doc {
32        target_dir = target_dir.join("doc");
33        return rm_rf(&target_dir.into_path_unlocked(), config);
34    }
35
36    // If the release option is set, we set target to release directory
37    if opts.release {
38        target_dir = target_dir.join("release");
39    }
40
41    // If we have a spec, then we need to delete some packages, otherwise, just
42    // remove the whole target directory and be done with it!
43    //
44    // Note that we don't bother grabbing a lock here as we're just going to
45    // blow it all away anyway.
46    if opts.spec.is_empty() {
47        return rm_rf(&target_dir.into_path_unlocked(), config);
48    }
49
50    let (packages, resolve) = ops::resolve_ws(ws)?;
51
52    let profiles = ws.profiles();
53    let mut units = Vec::new();
54
55    for spec in opts.spec.iter() {
56        // Translate the spec to a Package
57        let pkgid = resolve.query(spec)?;
58        let pkg = packages.get_one(pkgid)?;
59
60        // Generate all relevant `Unit` targets for this package
61        for target in pkg.targets() {
62            for kind in [Kind::Host, Kind::Target].iter() {
63                for mode in CompileMode::all_modes() {
64                    for unit_for in UnitFor::all_values() {
65                        let profile = if mode.is_run_custom_build() {
66                            profiles.get_profile_run_custom_build(&profiles.get_profile(
67                                pkg.package_id(),
68                                ws.is_member(pkg),
69                                *unit_for,
70                                CompileMode::Build,
71                                opts.release,
72                            ))
73                        } else {
74                            profiles.get_profile(
75                                pkg.package_id(),
76                                ws.is_member(pkg),
77                                *unit_for,
78                                *mode,
79                                opts.release,
80                            )
81                        };
82                        units.push(Unit {
83                            pkg,
84                            target,
85                            profile,
86                            kind: *kind,
87                            mode: *mode,
88                        });
89                    }
90                }
91            }
92        }
93    }
94
95    let mut build_config = BuildConfig::new(config, Some(1), &opts.target, CompileMode::Build)?;
96    build_config.release = opts.release;
97    let bcx = BuildContext::new(
98        ws,
99        &resolve,
100        &packages,
101        opts.config,
102        &build_config,
103        profiles,
104        HashMap::new(),
105    )?;
106    let mut cx = Context::new(config, &bcx)?;
107    cx.prepare_units(None, &units)?;
108
109    for unit in units.iter() {
110        rm_rf(&cx.files().fingerprint_dir(unit), config)?;
111        if unit.target.is_custom_build() {
112            if unit.mode.is_run_custom_build() {
113                rm_rf(&cx.files().build_script_out_dir(unit), config)?;
114            } else {
115                rm_rf(&cx.files().build_script_dir(unit), config)?;
116            }
117            continue;
118        }
119
120        for output in cx.outputs(unit)?.iter() {
121            rm_rf(&output.path, config)?;
122            if let Some(ref dst) = output.hardlink {
123                rm_rf(dst, config)?;
124            }
125        }
126    }
127
128    Ok(())
129}
130
131fn rm_rf(path: &Path, config: &Config) -> CargoResult<()> {
132    let m = fs::metadata(path);
133    if m.as_ref().map(|s| s.is_dir()).unwrap_or(false) {
134        config
135            .shell()
136            .verbose(|shell| shell.status("Removing", path.display()))?;
137        paths::remove_dir_all(path)
138            .chain_err(|| failure::format_err!("could not remove build directory"))?;
139    } else if m.is_ok() {
140        config
141            .shell()
142            .verbose(|shell| shell.status("Removing", path.display()))?;
143        paths::remove_file(path)
144            .chain_err(|| failure::format_err!("failed to remove build artifact"))?;
145    }
146    Ok(())
147}