espforge_lib/examples/
fs.rs1use crate::cli::interactive::Prompter;
2use crate::cli::model::ExampleConfig;
3use anyhow::{Context, Result, bail};
4use std::fs;
5use std::path::{Path, PathBuf};
6
7pub struct OutputDirectory {
8 path: PathBuf,
9}
10
11impl OutputDirectory {
12 pub fn prepare(config: &ExampleConfig, prompter: &dyn Prompter) -> Result<Self> {
13 let path = Self::resolve_path(&config.project_name)?;
14
15 if path.exists() {
16 Self::handle_existing_directory(&path, &config.project_name, prompter)?;
17 } else {
18 Self::create_directory(&path)?;
19 }
20
21 Ok(Self { path })
22 }
23
24 pub fn prepare_noninteractive(config: &ExampleConfig) -> Result<Self> {
25 let path = Self::resolve_path(&config.project_name)?;
26
27 if path.exists() {
28 anyhow::bail!(
29 "Directory '{}' already exists. Aborting.",
30 config.project_name
31 );
32 } else {
33 Self::create_directory(&path)?;
34 }
35
36 Ok(Self { path })
37 }
38
39 fn resolve_path(project_name: &str) -> Result<PathBuf> {
40 let current_dir = std::env::current_dir().context("Failed to get current directory")?;
41 Ok(current_dir.join(project_name))
42 }
43
44 fn handle_existing_directory(
45 path: &Path,
46 project_name: &str,
47 prompter: &dyn Prompter,
48 ) -> Result<()> {
49 let overwrite = prompter.confirm_overwrite(project_name)?;
50 if !overwrite {
51 bail!("Operation cancelled by user");
52 }
53 fs::remove_dir_all(path).context("Failed to remove existing directory")?;
54 Ok(())
55 }
56
57 fn create_directory(path: &Path) -> Result<()> {
58 fs::create_dir_all(path).context("Failed to create output directory")
59 }
60
61 pub fn path(&self) -> &Path {
62 &self.path
63 }
64}