Skip to content

Commit

Permalink
fix: ensure project gets deleted even on fails
Browse files Browse the repository at this point in the history
+ add test for this
  • Loading branch information
marcelohdez committed Feb 15, 2024
1 parent 8d5e0c2 commit 34ad174
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 11 deletions.
30 changes: 21 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub use templates::*;

use std::{env, fs, io, path::Path, process::Command};

use anyhow::Context;
use anyhow::{bail, Context, Ok};
use chrono::Local;

pub fn try_template(
Expand All @@ -24,24 +24,36 @@ pub fn try_template(
.join(format!("{template}_{time}"));
copy_dir_recursively(wanted_dir, &tmp_dir)?;

Command::new(editor)
.current_dir(&tmp_dir)
.arg(".")
.spawn()
.context("Failed to launch editor!")?
.wait()
.context("Failed waiting for editor!")?;
let res = summon_and_wait(editor, &tmp_dir);

if !delete && ask_y_n("Would you like to keep this project?")? {
if res.is_ok() && !delete && ask_y_n("Would you like to keep this project?")? {
println!("Saved as {tmp_dir:?}.");
} else {
fs::remove_dir_all(&tmp_dir)
.with_context(|| format!("Failed to remove directory {tmp_dir:?}"))?;

println!("Deleted.");

if let Err(e) = res {
bail!(e);
}
}

Ok(())
}

fn summon_and_wait(editor: &str, cwd: &Path) -> anyhow::Result<()> {
Command::new(editor)
.current_dir(cwd)
.arg(".")
.spawn()
.context("Failed to launch editor!")?
.wait()
.context("Failed waiting for editor!")?;

Ok(())
}

/// Will print out a question and wait for user input in the form of `y` or `n`
/// (returning true if `y`). Any capitalization works. Defaults to `n` on a
/// blank character (e.g. just pressing Enter).
Expand Down
11 changes: 9 additions & 2 deletions tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ fn cmd() -> Command {
Command::cargo_bin("atmpt").unwrap()
}

// FIXME: Due to the folder being named with the time of creation, multiple
// tests using the same language template may clash and fail...

// ======= Failures =======

#[test]
Expand All @@ -24,16 +27,20 @@ fn fail_on_conflicting_opts() {

#[test]
fn fail_on_conflicting_opts_with_template() {
cmd().args(["cpp", "-l", "-d"]).assert().failure();
cmd().args(["c", "-l", "-d"]).assert().failure();
}

#[test]
fn incorrect_template() {
cmd().arg("_blahblah!").assert().failure();
}

// ======= Successes =======
#[test]
fn incorrect_editor() {
cmd().args(["-e", "fakeeditor", "java"]).assert().failure();
}

// ======= Successes =======
#[test]
fn correct_template() {
cmd().arg("cpp").assert().success();
Expand Down

0 comments on commit 34ad174

Please sign in to comment.