use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use cuno_build::layout::{Layout, is_claimed};
use cuno_core::{CunoError, ExitClass, Shell};
use cuno_manifest::{ConfigError, Settings};
use cuno_toolchain::HostOs;
use crate::build::{in_project, profile_named};
#[derive(Debug, Default)]
pub struct CleanArgs {
pub release: bool,
pub profile: Option<String>,
}
pub fn clean(
args: CleanArgs,
resolved: Result<Settings, ConfigError>,
cwd: &Path,
host: HostOs,
shell: &mut Shell,
) -> Result<(), Box<dyn CunoError>> {
let profile = match (args.release, &args.profile) {
(false, None) => None,
(release, name) => Some(profile_named(release, name.as_deref())?),
};
let settings = in_project(resolved, cwd)?;
let root = settings
.project
.as_ref()
.map_or_else(|| cwd.to_owned(), |package| package.root().to_owned());
let target_dir = settings.target_dir.clone();
let removed = if std::fs::symlink_metadata(&target_dir).is_err() {
0
} else if !is_claimed(&target_dir) {
return Err(Box::new(CleanError::NotMadeByCuno {
dir: target_dir.as_path().to_owned(),
}));
} else {
let dir = match profile {
None => target_dir.as_path().to_owned(),
Some(profile) => Layout::new(&target_dir, profile, &root, host)
.profile_dir()
.to_owned(),
};
remove(&dir).map_err(|e| {
Box::new(CleanError::Failed {
dir: dir.clone(),
reason: e.to_string(),
}) as Box<dyn CunoError>
})?
};
let noun = if removed == 1 { "file" } else { "files" };
shell.status("Removed", format!("{removed} {noun}"));
Ok(())
}
fn remove(dir: &Path) -> io::Result<u64> {
let mut files = 0;
let mut stack = Vec::new();
match std::fs::symlink_metadata(dir) {
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(0),
Err(e) => return Err(e),
Ok(meta) if meta.is_dir() => stack.push(dir.to_owned()),
Ok(_) => {}
}
while let Some(next) = stack.pop() {
for entry in std::fs::read_dir(&next)? {
let entry = entry?;
if entry.file_type()?.is_dir() {
stack.push(entry.path());
} else {
files += 1;
}
}
}
std::fs::remove_dir_all(dir)?;
Ok(files)
}
#[derive(Debug)]
enum CleanError {
NotMadeByCuno { dir: PathBuf },
Failed { dir: PathBuf, reason: String },
}
impl fmt::Display for CleanError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CleanError::NotMadeByCuno { dir } => {
write!(
f,
"`{}` was not made by cuno; not removing it",
dir.display()
)
}
CleanError::Failed { dir, reason } => {
write!(f, "could not remove {}: {reason}", dir.display())
}
}
}
}
impl std::error::Error for CleanError {}
impl CunoError for CleanError {
fn exit_class(&self) -> ExitClass {
match self {
CleanError::NotMadeByCuno { .. } | CleanError::Failed { .. } => ExitClass::Setup,
}
}
fn help(&self) -> Option<String> {
match self {
CleanError::NotMadeByCuno { .. } => Some(
"remove it yourself, or set target-dir to a directory cuno builds into".to_owned(),
),
CleanError::Failed { .. } => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn remove_counts_every_file_and_tolerates_none() {
let root = tempfile::tempdir().unwrap();
let dir = root.path().join("target");
std::fs::create_dir_all(dir.join("debug/obj/app")).unwrap();
for file in ["a", "debug/b", "debug/obj/app/c", "debug/obj/app/d"] {
std::fs::write(dir.join(file), "").unwrap();
}
assert_eq!(remove(&dir).unwrap(), 4);
assert!(!dir.exists());
assert_eq!(remove(&dir).unwrap(), 0);
}
#[cfg(windows)]
#[test]
fn a_junction_is_removed_not_followed() {
let root = tempfile::tempdir().unwrap();
let elsewhere = root.path().join("elsewhere");
std::fs::create_dir_all(&elsewhere).unwrap();
std::fs::write(elsewhere.join("keep"), "").unwrap();
let link = root.path().join("target");
let made = std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(&link)
.arg(&elsewhere)
.output()
.unwrap();
assert!(made.status.success(), "{made:?}");
assert_eq!(remove(&link).unwrap(), 0);
assert!(std::fs::symlink_metadata(&link).is_err());
assert!(elsewhere.join("keep").is_file());
std::fs::write(elsewhere.join("keep2"), "").unwrap();
let dir = root.path().join("target2");
std::fs::create_dir(&dir).unwrap();
let made = std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(dir.join("debug"))
.arg(&elsewhere)
.output()
.unwrap();
assert!(made.status.success(), "{made:?}");
assert_eq!(remove(&dir).unwrap(), 1);
assert!(elsewhere.join("keep").is_file());
}
}