ggen_core/project_generator/
mod.rs1pub 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
118pub trait ProjectGenerator: Send + Sync {
120 fn generate(&self, config: &ProjectConfig) -> Result<ProjectStructure>;
121 fn supported_types(&self) -> Vec<ProjectType>;
122}
123
124pub 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
138pub 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
171pub 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 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
206pub 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 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 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 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
275pub async fn create_new_project(config: &ProjectConfig) -> Result<()> {
277 let project_path = config.path.join(&config.name);
278
279 if project_path.exists() {
281 return Err(Error::new(&format!(
282 "Project directory '{}' already exists",
283 config.name
284 )));
285 }
286
287 let generator = GeneratorFactory::create(&config.project_type)?;
289
290 let structure = generator.generate(config)?;
292
293 let fs_writer = FileSystemWriter::new();
295
296 fs_writer.create_directory(&project_path)?;
298
299 for dir in &structure.directories {
301 let dir_path = project_path.join(dir);
302 fs_writer.create_directory(&dir_path)?;
303 }
304
305 for (file_path, content) in &structure.files {
307 let full_path = project_path.join(file_path);
308
309 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 let git = GitInitializer::new();
319 git.initialize(&project_path)?;
320
321 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}