Skip to main content

project_map_cli_rust/core/
orchestrator.rs

1use std::path::Path;
2use std::collections::HashMap;
3use ignore::WalkBuilder;
4use crate::core::parser::CodeParser;
5use crate::core::graph::{ProjectGraph, NodeData, NodeType, EdgeType};
6use crate::core::utils::{path_to_fqn, resolve_import_path};
7use crate::error::Result;
8
9pub struct Orchestrator {
10    parser: CodeParser,
11    graph: ProjectGraph,
12}
13
14impl Orchestrator {
15    pub fn new() -> Self {
16        Self {
17            parser: CodeParser::new(),
18            graph: ProjectGraph::new(),
19        }
20    }
21
22    pub fn build_index(&mut self, root: &Path) -> Result<()> {
23        let mut outlines = Vec::new();
24        let mut fqn_to_node = HashMap::new();
25        let mut path_to_node = HashMap::new();
26
27        // Pass 1: Parse all files and create nodes
28        // WalkBuilder respects .gitignore by default
29        let walk = WalkBuilder::new(root)
30            .filter_entry(|e| e.file_name() != ".project-map")
31            .build();
32
33        for result in walk {
34            let entry = match result {
35                Ok(e) => e,
36                Err(_) => continue,
37            };
38
39            let path = entry.path();
40            if entry.file_type().map(|ft| ft.is_file()).unwrap_or(false) {
41                let extension = path.extension().and_then(|s| s.to_str()).unwrap_or("");
42                if extension == "py" || extension == "rs" || extension == "ts" || extension == "tsx" || extension == "kt" || extension == "sql" || extension == "vue" {
43                    match self.parser.parse_file(path) {
44                        Ok(outline) => {
45                            let fqn = path_to_fqn(root, path);
46                            let file_node = self.graph.add_node(NodeData {
47                                path: outline.path.clone(),
48                                name: fqn.clone(),
49                                kind: "file".to_string(),
50                                line: 0,
51                                start_byte: 0,
52                                end_byte: 0,
53                                node_type: NodeType::File,
54                            });
55                            fqn_to_node.insert(fqn, file_node);
56                            path_to_node.insert(outline.path.clone(), file_node);
57
58                            for symbol in &outline.symbols {
59                                let symbol_node = self.graph.add_node(NodeData {
60                                    path: outline.path.clone(),
61                                    name: symbol.name.clone(),
62                                    kind: symbol.kind.clone(),
63                                    line: symbol.line,
64                                    start_byte: symbol.start_byte,
65                                    end_byte: symbol.end_byte,
66                                    node_type: NodeType::Symbol,
67                                });
68                                self.graph.add_edge(file_node, symbol_node, EdgeType::Contains);
69                            }
70                            outlines.push(outline);
71                        }
72                        Err(e) => {
73                            // If it's just invalid UTF-8, we can skip it silently or log it
74                            if !e.to_string().contains("valid UTF-8") {
75                                eprintln!("Error parsing {}: {}", path.display(), e);
76                            }
77                        }
78                    }
79                }
80            }
81        }
82
83        // Pass 2: Resolve imports and create edges
84        for outline in outlines {
85            if let Some(&from_node) = path_to_node.get(&outline.path) {
86                for imp in outline.imports {
87                    // Strategy 1: FQN Match (Python/General)
88                    if let Some(&to_node) = fqn_to_node.get(&imp) {
89                        self.graph.add_edge(from_node, to_node, EdgeType::Imports);
90                    } else {
91                        // Strategy 2: Relative Path Resolution (TypeScript)
92                        let resolved_rel = resolve_import_path(&outline.path, &imp);
93                        
94                        // Try matching resolved path with common TS extensions
95                        let mut found = false;
96                        for ext in &["", ".ts", ".tsx", "/index.ts", "/index.tsx"] {
97                            let candidate = format!("{}{}", resolved_rel, ext);
98                            if let Some(&to_node) = path_to_node.get(&candidate) {
99                                self.graph.add_edge(from_node, to_node, EdgeType::Imports);
100                                found = true;
101                                break;
102                            }
103                        }
104
105                        // Strategy 3: FQN Suffix match (Fallback)
106                        if !found {
107                            let matching_fqn = fqn_to_node.keys()
108                                .find(|&k| k.ends_with(&imp));
109                            if let Some(key) = matching_fqn {
110                                let &to_node = fqn_to_node.get(key).unwrap();
111                                self.graph.add_edge(from_node, to_node, EdgeType::Imports);
112                            }
113                        }
114                    }
115                }
116            }
117        }
118
119        Ok(())
120    }
121
122    pub fn save_index(&self, path: &Path) -> Result<()> {
123        self.graph.save(path)
124    }
125
126    pub fn save_index_versioned(&self, base_dir: &Path) -> Result<()> {
127        use chrono::Local;
128        use std::fs;
129        use std::os::unix::fs::symlink;
130
131        let timestamp = Local::now().format("%Y%m%d_%H%M%S").to_string();
132        let backups_dir = base_dir.join("backups");
133        let current_backup_dir = backups_dir.join(&timestamp);
134        
135        fs::create_dir_all(&current_backup_dir)?;
136        
137        let index_path = current_backup_dir.join(".project-map.json");
138        self.graph.save(&index_path)?;
139
140        // Limit backups to 5
141        if let Ok(entries) = fs::read_dir(&backups_dir) {
142            let mut dirs: Vec<_> = entries.filter_map(|e| e.ok()).collect();
143            dirs.sort_by_key(|e| e.metadata().and_then(|m| m.modified()).unwrap_or_else(|_| std::time::SystemTime::UNIX_EPOCH));
144            
145            while dirs.len() > 5 {
146                let oldest = dirs.remove(0);
147                fs::remove_dir_all(oldest.path()).ok();
148            }
149        }
150
151        let latest_link = base_dir.join("latest");
152        if latest_link.exists() {
153            fs::remove_file(&latest_link).ok();
154            fs::remove_dir_all(&latest_link).ok();
155        }
156
157        // On Unix, use a symlink. 
158        #[cfg(unix)]
159        {
160            // We want the symlink to be relative so it's portable
161            let rel_target = Path::new("backups").join(&timestamp);
162            symlink(rel_target, &latest_link)?;
163        }
164
165        // Fallback for non-Unix or if symlink fails
166        #[cfg(not(unix))]
167        {
168            fs::create_dir_all(&latest_link)?;
169            fs::copy(&index_path, latest_link.join(".project-map.json"))?;
170        }
171
172        Ok(())
173    }
174}