1use std::{
4 collections::HashMap,
5 fs,
6 path::{Path, PathBuf},
7};
8
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14pub enum Layer {
15 Domain,
17 Application,
19 Infrastructure,
21 Presentation,
23}
24
25impl Layer {
26 pub fn dir_name(&self) -> &'static str {
28 match self {
29 Layer::Domain => "domain",
30 Layer::Application => "application",
31 Layer::Infrastructure => "infrastructure",
32 Layer::Presentation => "presentation",
33 }
34 }
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct Entity {
40 pub name: String,
42 pub file_path: String,
44 pub fields: HashMap<String, String>,
46}
47
48#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct Service {
51 pub name: String,
53 pub file_path: String,
55 pub dependencies: Vec<String>,
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct Handler {
62 pub name: String,
64 pub file_path: String,
66 pub method: Option<String>,
68 pub path: Option<String>,
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
74pub struct Repository {
75 pub name: String,
77 pub file_path: String,
79 pub entity: Option<String>,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct ProjectStructure {
86 pub name: String,
88 pub root_path: String,
90 pub archetype: Option<String>,
92 pub entities: Vec<Entity>,
94 pub repositories: Vec<Repository>,
96 pub services: Vec<Service>,
98 pub handlers: Vec<Handler>,
100 pub files_by_layer: HashMap<String, Vec<String>>,
102 pub dependencies: Vec<String>,
104}
105
106pub struct ProjectAnalyzer {
108 project_path: PathBuf,
109}
110
111impl ProjectAnalyzer {
112 pub fn new(project_path: impl Into<PathBuf>) -> Result<Self, String> {
114 let project_path = project_path.into();
115
116 if !project_path.join("Cargo.toml").exists() {
118 return Err(format!(
119 "Not a Rust project: Cargo.toml not found in {}",
120 project_path.display()
121 ));
122 }
123
124 if !project_path.join("src").exists() {
126 return Err(format!(
127 "No src directory found in {}",
128 project_path.display()
129 ));
130 }
131
132 Ok(Self { project_path })
133 }
134
135 pub fn project_path(&self) -> &Path {
137 &self.project_path
138 }
139
140 pub fn analyze(&self) -> Result<ProjectStructure, String> {
142 let name = self.parse_project_name()?;
143 let archetype = self.detect_archetype();
144 let dependencies = self.parse_dependencies()?;
145 let files_by_layer = self.scan_layers()?;
146 let entities = self.find_entities(&files_by_layer)?;
147 let repositories = self.find_repositories(&files_by_layer)?;
148 let services = self.find_services(&files_by_layer)?;
149 let handlers = self.find_handlers(&files_by_layer)?;
150
151 Ok(ProjectStructure {
152 name,
153 root_path: self.project_path.display().to_string(),
154 archetype,
155 entities,
156 repositories,
157 services,
158 handlers,
159 files_by_layer,
160 dependencies,
161 })
162 }
163
164 fn parse_project_name(&self) -> Result<String, String> {
166 let cargo_toml = self.project_path.join("Cargo.toml");
167 let content = fs::read_to_string(&cargo_toml)
168 .map_err(|e| format!("Failed to read Cargo.toml: {}", e))?;
169
170 for line in content.lines() {
172 let line = line.trim();
173 if line.starts_with("name") && line.contains('=') {
174 if let Some(name) = line.split('=').nth(1) {
175 let name = name.trim().trim_matches('"').trim_matches('\'');
176 return Ok(name.to_string());
177 }
178 }
179 }
180
181 Err("Could not find project name in Cargo.toml".to_string())
182 }
183
184 fn parse_dependencies(&self) -> Result<Vec<String>, String> {
186 let cargo_toml = self.project_path.join("Cargo.toml");
187 let content = fs::read_to_string(&cargo_toml)
188 .map_err(|e| format!("Failed to read Cargo.toml: {}", e))?;
189
190 let mut deps = Vec::new();
191 let mut in_deps = false;
192
193 for line in content.lines() {
194 let line = line.trim();
195
196 if line.starts_with("[dependencies]") || line.starts_with("[dev-dependencies]") {
197 in_deps = true;
198 continue;
199 }
200
201 if line.starts_with('[') {
202 in_deps = false;
203 continue;
204 }
205
206 if in_deps && !line.is_empty() && !line.starts_with('#') {
207 if let Some(dep_name) = line.split(['=', ' ', '.']).next() {
208 let dep_name = dep_name.trim();
209 if !dep_name.is_empty() {
210 deps.push(dep_name.to_string());
211 }
212 }
213 }
214 }
215
216 Ok(deps)
217 }
218
219 fn detect_archetype(&self) -> Option<String> {
221 let src = self.project_path.join("src");
222 let deps = self.parse_dependencies().unwrap_or_default();
223
224 if self.project_path.join("proto").exists() {
226 return Some("gateway".to_string());
227 }
228
229 if deps.iter().any(|d| d.contains("rdkafka")) {
231 if src.join("application/consumer.rs").exists() {
232 return Some("consumer".to_string());
233 }
234 if src.join("infrastructure/outbox").exists() {
235 return Some("producer".to_string());
236 }
237 }
238
239 if deps.iter().any(|d| d.contains("async-graphql")) {
241 return Some("bff".to_string());
242 }
243
244 if deps.iter().any(|d| d.contains("tokio-cron-scheduler")) {
246 return Some("scheduled".to_string());
247 }
248
249 if src.join("application/hub.rs").exists() {
251 return Some("websocket-gateway".to_string());
252 }
253
254 if src.join("application/orchestrator.rs").exists() {
256 return Some("saga-orchestrator".to_string());
257 }
258
259 if src.join("domain/legacy.rs").exists() {
261 return Some("legacy-adapter".to_string());
262 }
263
264 if src.join("domain").exists() && src.join("application").exists() {
266 return Some("basic".to_string());
267 }
268
269 None
270 }
271
272 fn scan_layers(&self) -> Result<HashMap<String, Vec<String>>, String> {
274 let mut files_by_layer = HashMap::new();
275 let src = self.project_path.join("src");
276
277 for layer in [
278 Layer::Domain,
279 Layer::Application,
280 Layer::Infrastructure,
281 Layer::Presentation,
282 ] {
283 let layer_path = src.join(layer.dir_name());
284 let mut files = Vec::new();
285
286 if layer_path.exists() {
287 self.collect_rs_files(&layer_path, &mut files)?;
288 }
289
290 files_by_layer.insert(layer.dir_name().to_string(), files);
291 }
292
293 Ok(files_by_layer)
294 }
295
296 fn collect_rs_files(&self, dir: &Path, files: &mut Vec<String>) -> Result<(), String> {
298 if !dir.is_dir() {
299 return Ok(());
300 }
301
302 let entries = fs::read_dir(dir)
303 .map_err(|e| format!("Failed to read directory {}: {}", dir.display(), e))?;
304
305 for entry in entries {
306 let entry = entry.map_err(|e| format!("Failed to read entry: {}", e))?;
307 let path = entry.path();
308
309 if path.is_dir() {
310 self.collect_rs_files(&path, files)?;
311 } else if path.extension().is_some_and(|e| e == "rs") {
312 if let Ok(relative) = path.strip_prefix(&self.project_path) {
313 files.push(relative.display().to_string());
314 }
315 }
316 }
317
318 Ok(())
319 }
320
321 fn find_entities(
323 &self,
324 files_by_layer: &HashMap<String, Vec<String>>,
325 ) -> Result<Vec<Entity>, String> {
326 let mut entities = Vec::new();
327
328 let domain_files = files_by_layer.get("domain").cloned().unwrap_or_default();
329
330 for file_path in domain_files {
331 if file_path.ends_with("mod.rs") {
333 continue;
334 }
335
336 let full_path = self.project_path.join(&file_path);
337 let content = match fs::read_to_string(&full_path) {
338 Ok(c) => c,
339 Err(_) => continue,
340 };
341
342 let mut lines = content.lines().peekable();
344 while let Some(line) = lines.next() {
345 let line = line.trim();
346
347 if line.starts_with("pub struct ") && !line.contains("impl") {
349 let name = line
351 .trim_start_matches("pub struct ")
352 .split([' ', '{', '<', '('])
353 .next()
354 .unwrap_or("")
355 .to_string();
356
357 if name.is_empty() || name.ends_with("Error") || name.ends_with("Config") {
358 continue;
359 }
360
361 let mut fields = HashMap::new();
363 if line.contains('{') {
364 for field_line in lines.by_ref() {
366 let field_line = field_line.trim();
367 if field_line.starts_with('}') {
368 break;
369 }
370 if field_line.starts_with("pub ") && field_line.contains(':') {
371 let parts: Vec<&str> = field_line
372 .trim_start_matches("pub ")
373 .splitn(2, ':')
374 .collect();
375 if parts.len() == 2 {
376 let field_name = parts[0].trim().to_string();
377 let field_type =
378 parts[1].trim().trim_end_matches(',').to_string();
379 fields.insert(field_name, field_type);
380 }
381 }
382 }
383 }
384
385 entities.push(Entity {
386 name,
387 file_path: file_path.clone(),
388 fields,
389 });
390 }
391 }
392 }
393
394 Ok(entities)
395 }
396
397 fn find_repositories(
399 &self,
400 files_by_layer: &HashMap<String, Vec<String>>,
401 ) -> Result<Vec<Repository>, String> {
402 let mut repositories = Vec::new();
403
404 let domain_files = files_by_layer.get("domain").cloned().unwrap_or_default();
405
406 for file_path in domain_files {
407 let full_path = self.project_path.join(&file_path);
408 let content = match fs::read_to_string(&full_path) {
409 Ok(c) => c,
410 Err(_) => continue,
411 };
412
413 for line in content.lines() {
415 let line = line.trim();
416 if line.starts_with("pub trait ") && line.contains("Repository") {
417 let name = line
418 .trim_start_matches("pub trait ")
419 .split([' ', '{', '<', ':'])
420 .next()
421 .unwrap_or("")
422 .to_string();
423
424 if !name.is_empty() {
425 let entity = name.trim_end_matches("Repository").to_string();
427
428 repositories.push(Repository {
429 name,
430 file_path: file_path.clone(),
431 entity: if entity.is_empty() {
432 None
433 } else {
434 Some(entity)
435 },
436 });
437 }
438 }
439 }
440 }
441
442 Ok(repositories)
443 }
444
445 fn find_services(
447 &self,
448 files_by_layer: &HashMap<String, Vec<String>>,
449 ) -> Result<Vec<Service>, String> {
450 let mut services = Vec::new();
451
452 let app_files = files_by_layer
453 .get("application")
454 .cloned()
455 .unwrap_or_default();
456
457 for file_path in app_files {
458 if file_path.ends_with("mod.rs") {
459 continue;
460 }
461
462 let full_path = self.project_path.join(&file_path);
463 let content = match fs::read_to_string(&full_path) {
464 Ok(c) => c,
465 Err(_) => continue,
466 };
467
468 let mut lines = content.lines().peekable();
470 while let Some(line) = lines.next() {
471 let line = line.trim();
472 if line.starts_with("pub struct ")
473 && (line.contains("Service")
474 || line.contains("Orchestrator")
475 || line.contains("Handler"))
476 {
477 let name = line
478 .trim_start_matches("pub struct ")
479 .split([' ', '{', '<'])
480 .next()
481 .unwrap_or("")
482 .to_string();
483
484 if name.is_empty() {
485 continue;
486 }
487
488 let mut dependencies = Vec::new();
490 if line.contains('{') {
491 for field_line in lines.by_ref() {
492 let field_line = field_line.trim();
493 if field_line.starts_with('}') {
494 break;
495 }
496 if field_line.contains(':') {
497 let parts: Vec<&str> = field_line.splitn(2, ':').collect();
498 if parts.len() == 2 {
499 let field_type = parts[1].trim().trim_end_matches(',');
500 if field_type.contains("Arc<") || field_type.contains("Box<") {
502 dependencies.push(field_type.to_string());
503 }
504 }
505 }
506 }
507 }
508
509 services.push(Service {
510 name,
511 file_path: file_path.clone(),
512 dependencies,
513 });
514 }
515 }
516 }
517
518 Ok(services)
519 }
520
521 fn find_handlers(
523 &self,
524 files_by_layer: &HashMap<String, Vec<String>>,
525 ) -> Result<Vec<Handler>, String> {
526 let mut handlers = Vec::new();
527
528 let pres_files = files_by_layer
529 .get("presentation")
530 .cloned()
531 .unwrap_or_default();
532
533 for file_path in pres_files {
534 if file_path.ends_with("mod.rs") {
535 continue;
536 }
537
538 let full_path = self.project_path.join(&file_path);
539 let content = match fs::read_to_string(&full_path) {
540 Ok(c) => c,
541 Err(_) => continue,
542 };
543
544 for line in content.lines() {
546 let line = line.trim();
547 if line.starts_with("pub async fn ") || line.starts_with("async fn ") {
548 let name = line
549 .trim_start_matches("pub ")
550 .trim_start_matches("async fn ")
551 .split(['(', '<'])
552 .next()
553 .unwrap_or("")
554 .to_string();
555
556 if name.is_empty() || name == "main" {
557 continue;
558 }
559
560 let method = if name.starts_with("get_")
562 || name.starts_with("list_")
563 || name.starts_with("fetch_")
564 {
565 Some("GET".to_string())
566 } else if name.starts_with("create_") || name.starts_with("add_") {
567 Some("POST".to_string())
568 } else if name.starts_with("update_") || name.starts_with("modify_") {
569 Some("PUT".to_string())
570 } else if name.starts_with("delete_") || name.starts_with("remove_") {
571 Some("DELETE".to_string())
572 } else {
573 None
574 };
575
576 handlers.push(Handler {
577 name,
578 file_path: file_path.clone(),
579 method,
580 path: None,
581 });
582 }
583 }
584 }
585
586 Ok(handlers)
587 }
588}
589
590#[cfg(test)]
591mod tests {
592 use super::*;
593
594 #[test]
595 fn test_layer_dir_names() {
596 assert_eq!(Layer::Domain.dir_name(), "domain");
597 assert_eq!(Layer::Application.dir_name(), "application");
598 assert_eq!(Layer::Infrastructure.dir_name(), "infrastructure");
599 assert_eq!(Layer::Presentation.dir_name(), "presentation");
600 }
601}