From 1b37f510f91773acda462592dd2f60ca60c80829 Mon Sep 17 00:00:00 2001 From: Sridhar Ratnakumar Date: Fri, 11 Oct 2024 17:45:52 -0400 Subject: [PATCH] init: Make sure out directory does not exist Initializing templates (accidentally) on an existing directory causes various problems, obviously. Resolves #289 --- crates/omnix-init/src/template.rs | 5 +++++ crates/omnix-init/src/test.rs | 11 ++++++----- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/omnix-init/src/template.rs b/crates/omnix-init/src/template.rs index f45be497..8b93dd00 100644 --- a/crates/omnix-init/src/template.rs +++ b/crates/omnix-init/src/template.rs @@ -31,6 +31,11 @@ pub struct NixTemplate { impl Template { // Scaffold the [Template] at the given path. pub async fn scaffold_at(&self, out_dir: &Path) -> anyhow::Result<()> { + // Make sure that the directory does not already exist. We don't risk mutating accidentally incorrect location! + if out_dir.exists() { + anyhow::bail!("Output directory already exists: {}", out_dir.display()); + } + // Recursively copy the self.template.path to the output directory omnix_common::fs::copy_dir_all(&self.template.path, out_dir) .await diff --git a/crates/omnix-init/src/test.rs b/crates/omnix-init/src/test.rs index eebcb204..513866cb 100644 --- a/crates/omnix-init/src/test.rs +++ b/crates/omnix-init/src/test.rs @@ -41,6 +41,7 @@ impl OmInitTest { template: &FlakeTemplate<'a>, ) -> anyhow::Result<()> { let temp_dir = assert_fs::TempDir::new().unwrap(); + let out_dir = temp_dir.path().join("output"); let mut template = template.clone(); tracing::info!( @@ -59,15 +60,15 @@ impl OmInitTest { template.template.set_param_values(&self.params); template .template - .scaffold_at(&temp_dir) + .scaffold_at(&out_dir) .await .with_context(|| "Unable to scaffold")?; - // Recursively print the contents of temp_dir to debug test failures - let paths = omnix_common::fs::find_paths(&temp_dir).await?; + // Recursively print the contents of out_dir to debug test failures + let paths = omnix_common::fs::find_paths(&out_dir).await?; tracing::debug!( "Template files (under {}): {}", - temp_dir.path().display(), + out_dir.display(), paths .iter() .map(|path| path.display().to_string()) @@ -76,7 +77,7 @@ impl OmInitTest { ); // Run assertion tests - self.asserts.assert(&temp_dir).await?; + self.asserts.assert(&out_dir).await?; temp_dir.close().unwrap(); Ok(())