Skip to main content

ggen_core/project_generator/
mod.rs

1//! Project generator for scaffolding new projects
2//!
3//! This module provides functionality for generating complete project structures
4//! from templates. It supports multiple project types including Rust (web, CLI, library)
5//! and JavaScript frameworks (Next.js, Nuxt).
6//!
7//! ## Features
8//!
9//! - **Multi-language support**: Generate Rust and JavaScript/TypeScript projects
10//! - **Project type detection**: Automatically select appropriate generator
11//! - **File system operations**: Create directories and write files
12//! - **Git integration**: Initialize git repositories for new projects
13//! - **Dependency management**: Install dependencies via cargo or npm
14//!
15//! ## Architecture
16//!
17//! The module uses a trait-based design with `ProjectGenerator` trait that allows
18//! different generators for different project types. The `GeneratorFactory` creates
19//! the appropriate generator based on project type.
20//!
21//! ## Examples
22//!
23//! ### Creating a Rust CLI Project
24//!
25//! ```rust,no_run
26//! use crate::project_generator::{ProjectConfig, ProjectType, create_new_project};
27//! use std::path::PathBuf;
28//!
29//! # async fn example() -> anyhow::Result<()> {
30//! let config = ProjectConfig {
31//!     name: "my-cli".to_string(),
32//!     project_type: ProjectType::RustCli,
33//!     framework: None,
34//!     path: PathBuf::from("."),
35//! };
36//!
37//! create_new_project(&config).await?;
38//! # Ok(())
39//! # }
40//! ```
41//!
42//! ### Creating a Next.js Project
43//!
44//! ```rust,no_run
45//! use crate::project_generator::{ProjectConfig, ProjectType, create_new_project};
46//! use std::path::PathBuf;
47//!
48//! # async fn example() -> anyhow::Result<()> {
49//! let config = ProjectConfig {
50//!     name: "my-app".to_string(),
51//!     project_type: ProjectType::NextJs,
52//!     framework: None,
53//!     path: PathBuf::from("."),
54//! };
55//!
56//! create_new_project(&config).await?;
57//! # Ok(())
58//! # }
59//! ```
60
61pub mod common;
62pub mod nextjs;
63pub mod rust;
64
65use crate::utils::error::{Error, Result};
66use std::path::{Path, PathBuf};
67
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub enum ProjectType {
70    RustWeb,
71    RustCli,
72    RustLib,
73    NextJs,
74    Nuxt,
75}
76
77impl std::fmt::Display for ProjectType {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        match self {
80            ProjectType::RustWeb => write!(f, "rust-web"),
81            ProjectType::RustCli => write!(f, "rust-cli"),
82            ProjectType::RustLib => write!(f, "rust-lib"),
83            ProjectType::NextJs => write!(f, "nextjs"),
84            ProjectType::Nuxt => write!(f, "nuxt"),
85        }
86    }
87}
88
89impl std::str::FromStr for ProjectType {
90    type Err = Error;
91
92    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
93        match s.to_lowercase().as_str() {
94            "rust-web" => Ok(ProjectType::RustWeb),
95            "rust-cli" => Ok(ProjectType::RustCli),
96            "rust-lib" => Ok(ProjectType::RustLib),
97            "nextjs" => Ok(ProjectType::NextJs),
98            "nuxt" => Ok(ProjectType::Nuxt),
99            _ => Err(Error::new(&format!("Unsupported project type: {}", s))),
100        }
101    }
102}
103
104#[derive(Debug, Clone)]
105pub struct ProjectConfig {
106    pub name: String,
107    pub project_type: ProjectType,
108    pub framework: Option<String>,
109    pub path: PathBuf,
110}
111
112#[derive(Debug, Clone, Default)]
113pub struct ProjectStructure {
114    pub files: Vec<(String, String)>,
115    pub directories: Vec<String>,
116}
117
118/// Trait for project generators
119pub trait ProjectGenerator: Send + Sync {
120    fn generate(&self, config: &ProjectConfig) -> Result<ProjectStructure>;
121    fn supported_types(&self) -> Vec<ProjectType>;
122}
123
124/// Factory for creating project generators
125pub struct GeneratorFactory;
126
127impl GeneratorFactory {
128    pub fn create(project_type: &ProjectType) -> Result<Box<dyn ProjectGenerator>> {
129        match project_type {
130            ProjectType::RustWeb | ProjectType::RustCli | ProjectType::RustLib => {
131                Ok(Box::new(rust::RustProjectGenerator::new()))
132            }
133            ProjectType::NextJs | ProjectType::Nuxt => Ok(Box::new(nextjs::NextJsGenerator::new())),
134        }
135    }
136}
137
138/// File system writer for creating files and directories
139pub struct FileSystemWriter;
140
141impl Default for FileSystemWriter {
142    fn default() -> Self {
143        Self
144    }
145}
146
147impl FileSystemWriter {
148    pub fn new() -> Self {
149        Self
150    }
151
152    pub fn write_file(&self, path: &Path, content: &str) -> Result<()> {
153        std::fs::write(path, content).map_err(|e| {
154            Error::with_source(
155                &format!("Failed to write file {}", path.display()),
156                Box::new(e),
157            )
158        })
159    }
160
161    pub fn create_directory(&self, path: &Path) -> Result<()> {
162        std::fs::create_dir_all(path).map_err(|e| {
163            Error::with_source(
164                &format!("Failed to create directory {}", path.display()),
165                Box::new(e),
166            )
167        })
168    }
169}
170
171/// Git repository initializer
172pub struct GitInitializer;
173
174impl Default for GitInitializer {
175    fn default() -> Self {
176        Self
177    }
178}
179
180impl GitInitializer {
181    pub fn new() -> Self {
182        Self
183    }
184
185    pub fn initialize(&self, path: &Path) -> Result<()> {
186        // SECURITY FIX (Week 4): Use SafeCommand instead of raw std::process::Command
187        use crate::security::command::SafeCommand;
188
189        let output = SafeCommand::new("git")?
190            .arg("init")?
191            .current_dir(path)?
192            .execute()
193            .map_err(|e| Error::with_source("Failed to run git init", Box::new(e)))?;
194
195        if !output.status.success() {
196            return Err(Error::new(&format!(
197                "git init failed: {}",
198                String::from_utf8_lossy(&output.stderr)
199            )));
200        }
201
202        Ok(())
203    }
204}
205
206/// Dependency installer for different project types
207pub struct DependencyInstaller;
208
209impl Default for DependencyInstaller {
210    fn default() -> Self {
211        Self
212    }
213}
214
215impl DependencyInstaller {
216    pub fn new() -> Self {
217        Self
218    }
219
220    pub fn install(&self, path: &Path, project_type: &ProjectType) -> Result<()> {
221        match project_type {
222            ProjectType::RustWeb | ProjectType::RustCli | ProjectType::RustLib => {
223                self.install_cargo_deps(path)
224            }
225            ProjectType::NextJs | ProjectType::Nuxt => self.install_npm_deps(path),
226        }
227    }
228
229    fn install_cargo_deps(&self, path: &Path) -> Result<()> {
230        // SECURITY FIX (Week 4): Use SafeCommand instead of raw std::process::Command
231        use crate::security::command::SafeCommand;
232
233        crate::alert_info!("Installing Cargo dependencies...");
234
235        let output = SafeCommand::new("cargo")?
236            .arg("fetch")?
237            .current_dir(path)?
238            .execute()
239            .map_err(|e| Error::with_source("Failed to run cargo fetch", Box::new(e)))?;
240
241        if !output.status.success() {
242            // Non-critical failure - dependencies will be fetched on first build
243            let error_msg = format!(
244                "cargo fetch failed: {}",
245                String::from_utf8_lossy(&output.stderr)
246            );
247            crate::alert_warning!(&error_msg);
248        }
249
250        Ok(())
251    }
252
253    fn install_npm_deps(&self, path: &Path) -> Result<()> {
254        // SECURITY FIX (Week 4): Use SafeCommand instead of raw std::process::Command
255        use crate::security::command::SafeCommand;
256
257        crate::alert_info!("Installing npm dependencies...");
258
259        let output = SafeCommand::new("npm")?
260            .arg("install")?
261            .current_dir(path)?
262            .execute()?;
263
264        if !output.status.success() {
265            return Err(Error::new(&format!(
266                "npm install failed: {}",
267                String::from_utf8_lossy(&output.stderr)
268            )));
269        }
270
271        Ok(())
272    }
273}
274
275/// Main entry point for creating new projects
276pub async fn create_new_project(config: &ProjectConfig) -> Result<()> {
277    let project_path = config.path.join(&config.name);
278
279    // Check if project already exists
280    if project_path.exists() {
281        return Err(Error::new(&format!(
282            "Project directory '{}' already exists",
283            config.name
284        )));
285    }
286
287    // Create generator
288    let generator = GeneratorFactory::create(&config.project_type)?;
289
290    // Generate project structure
291    let structure = generator.generate(config)?;
292
293    // Create file system writer
294    let fs_writer = FileSystemWriter::new();
295
296    // Create main project directory
297    fs_writer.create_directory(&project_path)?;
298
299    // Create subdirectories
300    for dir in &structure.directories {
301        let dir_path = project_path.join(dir);
302        fs_writer.create_directory(&dir_path)?;
303    }
304
305    // Write files
306    for (file_path, content) in &structure.files {
307        let full_path = project_path.join(file_path);
308
309        // Ensure parent directory exists
310        if let Some(parent) = full_path.parent() {
311            fs_writer.create_directory(parent)?;
312        }
313
314        fs_writer.write_file(&full_path, content)?;
315    }
316
317    // Initialize git repository
318    let git = GitInitializer::new();
319    git.initialize(&project_path)?;
320
321    // Install dependencies
322    let deps = DependencyInstaller::new();
323    deps.install(&project_path, &config.project_type)?;
324
325    crate::alert_success!(&format!("Successfully created project: {}", config.name));
326    crate::alert_info!(&format!("   Type: {}", config.project_type));
327    crate::alert_info!(&format!("   Path: {}", project_path.display()));
328
329    Ok(())
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn test_project_type_from_str() {
338        assert_eq!(
339            "rust-web".parse::<ProjectType>().unwrap(),
340            ProjectType::RustWeb
341        );
342        assert_eq!(
343            "nextjs".parse::<ProjectType>().unwrap(),
344            ProjectType::NextJs
345        );
346    }
347
348    #[test]
349    fn test_project_type_display() {
350        assert_eq!(ProjectType::RustWeb.to_string(), "rust-web");
351        assert_eq!(ProjectType::NextJs.to_string(), "nextjs");
352    }
353}