use std::path::{Path, PathBuf};
use isoloom_manifest::ignore::{Rules, never_copied};
use crate::error::Error;
use crate::executor::Cx;
use crate::store::if_there;
pub(super) const COPY: &str = "module";
const TERRAFORM_FILES: [&str; 4] = [".tf", ".tf.json", ".tfvars", ".tfvars.json"];
pub(super) fn run(cx: &Cx<'_>, at: &str, from: Option<&str>, when: Option<&str>) -> crate::Result<()> {
let malformed = |field: &str, reason: String| Error::Malformed {
at: format!("{at}.with.{field}"),
reason,
};
let from = from.ok_or_else(|| malformed("from", "a `terraform.copy_module` needs the module to copy".into()))?;
let only_missing = match when {
None => false,
Some("missing") => true,
Some(other) => return Err(malformed("when", format!("`{other}`: only `missing` is a `when`"))),
};
let source = inside_project(cx.run.dir(), at, from)?;
let copy = cx.state_dir().join(COPY);
if only_missing && copy.is_dir() {
return Ok(());
}
crate::store::create_dir(©)?;
forget_terraform_files(©)?;
copy_tree(&source, ©)
}
fn never() -> Rules {
Rules::parse(&never_copied().collect::<Vec<_>>().join("\n"))
}
pub(super) fn inside_project(dir: &Path, at: &str, from: &str) -> crate::Result<PathBuf> {
let outside = || Error::Malformed {
at: format!("{at}.with.from"),
reason: format!("`{from}` isn't a folder inside the run's project"),
};
let resolve = |path: PathBuf| if_there(std::fs::canonicalize(&path)).map_err(Error::io(path, "resolved"));
let project = resolve(crate::container::run_root(dir).to_path_buf())?.ok_or_else(outside)?;
let source = resolve(dir.join(from))?.ok_or_else(outside)?;
if source.starts_with(&project) && source.is_dir() {
Ok(source)
} else {
Err(outside())
}
}
pub(super) fn has_terraform_files(dir: &Path) -> crate::Result<bool> {
let Some(entries) = if_there(std::fs::read_dir(dir)).map_err(Error::io(dir, "read"))? else {
return Ok(false);
};
for entry in entries {
if is_terraform_file(&entry.map_err(Error::io(dir, "read"))?.path()) {
return Ok(true);
}
}
Ok(false)
}
fn is_terraform_file(path: &Path) -> bool {
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
path.is_file() && TERRAFORM_FILES.iter().any(|ext| name.ends_with(ext))
}
fn forget_terraform_files(dir: &Path) -> crate::Result<()> {
let entries = std::fs::read_dir(dir).map_err(Error::io(dir, "read"))?;
for entry in entries {
let entry = entry.map_err(Error::io(dir, "read"))?;
let path = entry.path();
if path.is_dir() && entry.file_name() != ".terraform" {
forget_terraform_files(&path)?;
} else if is_terraform_file(&path) {
crate::store::remove(&path)?;
}
}
Ok(())
}
fn copy_tree(from: &Path, to: &Path) -> crate::Result<()> {
copy_below(from, to, "", &never())
}
fn copy_below(from: &Path, to: &Path, rel: &str, never: &Rules) -> crate::Result<()> {
let entries = std::fs::read_dir(from).map_err(Error::io(from, "read"))?;
for entry in entries {
let entry = entry.map_err(Error::io(from, "read"))?;
let name = entry.file_name();
let (source, target) = (entry.path(), to.join(&name));
let kind = entry.file_type().map_err(Error::io(&source, "read"))?;
let path = format!("{rel}{}", name.to_string_lossy());
if never.ignored(&if kind.is_dir() { format!("{path}/") } else { path.clone() }) {
continue;
}
if kind.is_symlink() {
return Err(Error::Unsupported {
what: format!(
"copying the symbolic link {} of a Terraform module (a copy takes files and folders)",
source.display()
),
});
} else if kind.is_dir() {
crate::store::create_dir(&target)?;
copy_below(&source, &target, &format!("{path}/"), never)?;
} else {
std::fs::copy(&source, &target).map_err(Error::io(&target, "written"))?;
}
}
Ok(())
}
#[cfg(test)]
mod tests;