Skip to content

Commit

Permalink
init: Make sure out directory does not exist
Browse files Browse the repository at this point in the history
Initializing templates (accidentally) on an existing directory causes
various problems, obviously.

Resolves #289
  • Loading branch information
srid committed Oct 11, 2024
1 parent f04ff57 commit 105b50e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
5 changes: 5 additions & 0 deletions crates/omnix-init/src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 6 additions & 5 deletions crates/omnix-init/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand All @@ -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())
Expand All @@ -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(())
Expand Down

0 comments on commit 105b50e

Please sign in to comment.