1use crate::config::load_default_config;
8use crate::error::SpriteError;
9use crate::utils::project;
10use anyhow::{Context, Result};
11use std::collections::HashMap;
12use std::env;
13use std::path::{Path, PathBuf};
14
15#[derive(Debug, Clone)]
17pub struct WorkspaceNavigator {
18 pub project_root: PathBuf,
20 pub current_dir: PathBuf,
22 pub agent_workspaces: HashMap<String, PathBuf>,
24 pub main_workspace: PathBuf,
26 pub discovered_workspaces: HashMap<String, PathBuf>,
28}
29
30impl WorkspaceNavigator {
31 pub fn new() -> Result<Self> {
33 let project_root = project::find_project_root().context(
34 "Failed to locate Sprite project root. Run 'sprite init' in this repository first.",
35 )?;
36
37 let current_dir = env::current_dir().context("Failed to get current working directory")?;
38
39 let mut navigator = Self {
40 main_workspace: project_root.clone(),
41 project_root,
42 current_dir,
43 agent_workspaces: HashMap::new(),
44 discovered_workspaces: HashMap::new(),
45 };
46
47 navigator.load_agent_workspaces()?;
48 navigator.discover_workspaces()?;
49
50 Ok(navigator)
51 }
52
53 fn load_agent_workspaces(&mut self) -> Result<()> {
55 match load_default_config() {
56 Ok(config) => {
57 for agent in &config.agents {
58 if let Some(workspace) = &agent.worktree_path {
59 let resolved_path = if workspace.is_absolute() {
60 workspace.clone()
61 } else {
62 self.project_root.join(workspace)
63 };
64
65 self.agent_workspaces
66 .insert(agent.id.clone(), resolved_path);
67 }
68 }
69 }
70 Err(err) => {
71 eprintln!("â ī¸ Warning: Failed to load Sprite configuration: {}", err);
72 }
73 }
74
75 Ok(())
76 }
77
78 fn discover_workspaces(&mut self) -> Result<()> {
80 let agents_dir = self.project_root.join("agents");
81
82 if agents_dir.exists() && agents_dir.is_dir() {
83 let entries = std::fs::read_dir(&agents_dir).with_context(|| {
84 format!("Failed to read agents directory: {}", agents_dir.display())
85 })?;
86
87 for entry in entries {
88 let entry = entry.with_context(|| "Failed to read directory entry")?;
89 let path = entry.path();
90
91 if path.is_dir() {
92 if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
93 if !self.agent_workspaces.contains_key(name) {
95 self.discovered_workspaces.insert(name.to_string(), path);
96 }
97 }
98 }
99 }
100 }
101
102 Ok(())
103 }
104
105 pub fn get_all_workspaces(&self) -> Vec<WorkspaceInfo> {
107 let mut workspaces = Vec::new();
108
109 workspaces.push(WorkspaceInfo {
111 name: "main".to_string(),
112 path: self.main_workspace.clone(),
113 workspace_type: WorkspaceType::Main,
114 exists: true,
115 current: self.current_dir == self.main_workspace,
116 relative_path: self.get_relative_path(&self.main_workspace),
117 });
118
119 for (id, path) in &self.agent_workspaces {
121 workspaces.push(WorkspaceInfo {
122 name: id.clone(),
123 path: path.clone(),
124 workspace_type: WorkspaceType::Agent,
125 exists: path.exists(),
126 current: self.current_dir == *path,
127 relative_path: self.get_relative_path(path),
128 });
129 }
130
131 for (name, path) in &self.discovered_workspaces {
133 workspaces.push(WorkspaceInfo {
134 name: name.clone(),
135 path: path.clone(),
136 workspace_type: WorkspaceType::Discovered,
137 exists: true,
138 current: self.current_dir == *path,
139 relative_path: self.get_relative_path(path),
140 });
141 }
142
143 workspaces.sort_by(|a, b| a.name.cmp(&b.name));
145
146 workspaces
147 }
148
149 pub fn find_workspace(&self, name: &str) -> Option<WorkspaceInfo> {
151 if let Some(path) = self.agent_workspaces.get(name) {
153 return Some(WorkspaceInfo {
154 name: name.to_string(),
155 path: path.clone(),
156 workspace_type: WorkspaceType::Agent,
157 exists: path.exists(),
158 current: self.current_dir == *path,
159 relative_path: self.get_relative_path(path),
160 });
161 }
162
163 if let Some(path) = self.discovered_workspaces.get(name) {
165 return Some(WorkspaceInfo {
166 name: name.to_string(),
167 path: path.clone(),
168 workspace_type: WorkspaceType::Discovered,
169 exists: true,
170 current: self.current_dir == *path,
171 relative_path: self.get_relative_path(path),
172 });
173 }
174
175 if name == "main" || name == "root" {
177 return Some(WorkspaceInfo {
178 name: "main".to_string(),
179 path: self.main_workspace.clone(),
180 workspace_type: WorkspaceType::Main,
181 exists: true,
182 current: self.current_dir == self.main_workspace,
183 relative_path: self.get_relative_path(&self.main_workspace),
184 });
185 }
186
187 let relative_path = self.project_root.join(name);
189 if relative_path.exists() {
190 return Some(WorkspaceInfo {
191 name: name.to_string(),
192 path: relative_path.clone(),
193 workspace_type: WorkspaceType::Path,
194 exists: true,
195 current: self.current_dir == relative_path,
196 relative_path: self.get_relative_path(&relative_path),
197 });
198 }
199
200 None
201 }
202
203 pub fn get_current_workspace(&self) -> Option<WorkspaceInfo> {
205 if self.current_dir == self.main_workspace {
207 return Some(WorkspaceInfo {
208 name: "main".to_string(),
209 path: self.main_workspace.clone(),
210 workspace_type: WorkspaceType::Main,
211 exists: true,
212 current: true,
213 relative_path: ".".to_string(),
214 });
215 }
216
217 for (id, path) in &self.agent_workspaces {
219 if self.current_dir == *path {
220 return Some(WorkspaceInfo {
221 name: id.clone(),
222 path: path.clone(),
223 workspace_type: WorkspaceType::Agent,
224 exists: true,
225 current: true,
226 relative_path: self.get_relative_path(path),
227 });
228 }
229 }
230
231 for (name, path) in &self.discovered_workspaces {
233 if self.current_dir == *path {
234 return Some(WorkspaceInfo {
235 name: name.clone(),
236 path: path.clone(),
237 workspace_type: WorkspaceType::Discovered,
238 exists: true,
239 current: true,
240 relative_path: self.get_relative_path(path),
241 });
242 }
243 }
244
245 if let Some(workspace) = self.find_parent_workspace() {
247 return Some(workspace);
248 }
249
250 None
251 }
252
253 fn find_parent_workspace(&self) -> Option<WorkspaceInfo> {
255 if self.current_dir.starts_with(&self.main_workspace) {
257 return Some(WorkspaceInfo {
258 name: "main".to_string(),
259 path: self.main_workspace.clone(),
260 workspace_type: WorkspaceType::Main,
261 exists: true,
262 current: false,
263 relative_path: self.get_relative_path(&self.main_workspace),
264 });
265 }
266
267 for (id, path) in &self.agent_workspaces {
269 if self.current_dir.starts_with(path) {
270 return Some(WorkspaceInfo {
271 name: id.clone(),
272 path: path.clone(),
273 workspace_type: WorkspaceType::Agent,
274 exists: true,
275 current: false,
276 relative_path: self.get_relative_path(path),
277 });
278 }
279 }
280
281 None
282 }
283
284 pub fn get_relative_path(&self, target: &Path) -> String {
286 match pathdiff::diff_paths(target, &self.current_dir) {
287 Some(relative) => relative.to_string_lossy().to_string(),
288 None => target.display().to_string(),
289 }
290 }
291
292 #[allow(dead_code)]
294 pub fn workspace_exists(&self, name: &str) -> bool {
295 self.find_workspace(name).is_some_and(|w| w.exists)
296 }
297
298 #[allow(dead_code)]
300 pub fn get_navigation_command(&self, workspace_name: &str) -> Result<String> {
301 let workspace = self.find_workspace(workspace_name).ok_or_else(|| {
302 SpriteError::validation(
303 format!("Workspace '{}' not found", workspace_name),
304 Some("workspace".to_string()),
305 Some(workspace_name.to_string()),
306 )
307 })?;
308
309 if !workspace.exists {
310 return Err(SpriteError::filesystem(
311 format!(
312 "Workspace path does not exist: {}",
313 workspace.path.display()
314 ),
315 workspace_name.to_string(),
316 )
317 .into());
318 }
319
320 Ok(format!("cd {}", workspace.path.display()))
321 }
322
323 pub fn navigate_to_workspace(&self, workspace_name: &str) -> Result<NavigationResult> {
325 let workspace = self.find_workspace(workspace_name).ok_or_else(|| {
326 SpriteError::validation(
327 format!("Workspace '{}' not found", workspace_name),
328 Some("workspace".to_string()),
329 Some(workspace_name.to_string()),
330 )
331 })?;
332
333 if !workspace.exists {
334 return Err(SpriteError::filesystem(
335 format!(
336 "Workspace path does not exist: {}",
337 workspace.path.display()
338 ),
339 workspace_name.to_string(),
340 )
341 .into());
342 }
343
344 let current = self.get_current_workspace();
345
346 Ok(NavigationResult {
347 workspace: workspace.clone(),
348 current_workspace: current,
349 command: format!("cd {}", workspace.path.display()),
350 relative_command: format!("cd {}", workspace.relative_path),
351 })
352 }
353
354 #[allow(dead_code)]
356 pub fn generate_shell_integration(&self) -> String {
357 r#"# Sprite workspace navigation integration
358# Add this to your shell configuration (.bashrc, .zshrc, etc.)
359
360# Function to navigate to sprite workspaces
361sprite_warp() {
362 local workspace="$1"
363 local cmd
364 cmd=$(sprite warp --print "$workspace" 2>/dev/null)
365 if [ $? -eq 0 ]; then
366 cd "$cmd"
367 else
368 echo "Error: $cmd"
369 return 1
370 fi
371}
372
373# Tab completion for sprite warp
374_sprite_warp_completion() {
375 local cur="${COMP_WORDS[COMP_CWORD]}"
376 local workspaces
377 workspaces=$(sprite warp --list 2>/dev/null | grep "đ" | awk '{print $3}' | sed 's/://')
378
379 COMPREPLY=($(compgen -W "$workspaces" -- "$cur"))
380}
381
382# Register completion
383complete -F _sprite_warp_completion sprite_warp
384complete -F _sprite_warp_completion sprite warp
385
386# Alias for convenience
387alias sw='sprite_warp'
388"#
389 .to_string()
390 }
391
392 #[allow(dead_code)]
394 pub fn print_workspace_status(&self) -> Result<()> {
395 let current = self.get_current_workspace();
396 let all_workspaces = self.get_all_workspaces();
397
398 println!("đī¸ Workspace Status");
399 println!("====================");
400
401 if let Some(current) = ¤t {
402 println!("đ Current: {} ({})", current.name, current.path.display());
403 if current.workspace_type != WorkspaceType::Main {
404 println!(" Type: {:?}", current.workspace_type);
405 }
406 } else {
407 println!(
408 "đ Current: {} (outside any workspace)",
409 self.current_dir.display()
410 );
411 }
412
413 println!();
414 println!("đ Available Workspaces:");
415
416 for workspace in &all_workspaces {
417 let status = if workspace.current {
418 "đĸ current"
419 } else if workspace.exists {
420 "âĒ available"
421 } else {
422 "â missing"
423 };
424
425 let workspace_type = match workspace.workspace_type {
426 WorkspaceType::Main => "main",
427 WorkspaceType::Agent => "agent",
428 WorkspaceType::Discovered => "discovered",
429 WorkspaceType::Path => "path",
430 };
431
432 println!(
433 " {} {} ({}) - {}",
434 status, workspace.name, workspace_type, workspace.relative_path
435 );
436 }
437
438 println!();
439 println!("đĄ Navigation:");
440 println!(" sprite warp <name> # Navigate to workspace");
441 println!(" sprite warp --list # List all workspaces");
442 println!(" sprite warp --print <name> # Print path without changing");
443
444 Ok(())
445 }
446}
447
448#[derive(Debug, Clone)]
450pub struct WorkspaceInfo {
451 pub name: String,
453 pub path: PathBuf,
455 pub workspace_type: WorkspaceType,
457 pub exists: bool,
459 pub current: bool,
461 pub relative_path: String,
463}
464
465#[derive(Debug, Clone, PartialEq)]
467pub enum WorkspaceType {
468 Main,
470 Agent,
472 Discovered,
474 Path,
476}
477
478#[derive(Debug, Clone)]
480pub struct NavigationResult {
481 pub workspace: WorkspaceInfo,
483 #[allow(dead_code)]
485 pub current_workspace: Option<WorkspaceInfo>,
486 pub command: String,
488 #[allow(dead_code)]
490 pub relative_command: String,
491}
492
493#[allow(dead_code)]
495pub fn get_workspace_navigator() -> Result<WorkspaceNavigator> {
496 WorkspaceNavigator::new()
497}
498
499#[allow(dead_code)]
501pub fn quick_warp(workspace_name: &str) -> Result<()> {
502 let navigator = WorkspaceNavigator::new()?;
503 let result = navigator.navigate_to_workspace(workspace_name)?;
504
505 println!("đ Navigating to workspace: {}", result.workspace.name);
506 println!("đ Target: {}", result.workspace.path.display());
507 println!("â¨ī¸ Command: {}", result.command);
508
509 if result.workspace.current {
510 println!("âšī¸ Already in this workspace");
511 } else {
512 println!("đĄ Execute: cd $(sprite warp --print {})", workspace_name);
513 }
514
515 Ok(())
516}
517
518#[allow(dead_code)]
520pub fn list_workspaces_detailed() -> Result<()> {
521 let navigator = WorkspaceNavigator::new()?;
522 navigator.print_workspace_status()
523}
524
525#[allow(dead_code)]
527pub fn generate_workspace_aliases() -> Result<String> {
528 let navigator = WorkspaceNavigator::new()?;
529 let workspaces = navigator.get_all_workspaces();
530
531 let mut aliases = String::new();
532 aliases.push_str("# Sprite workspace aliases\n");
533 aliases.push_str("# Generated automatically - add to your shell config\n\n");
534
535 for workspace in workspaces {
536 if workspace.exists {
537 let alias_name = workspace.name.replace('-', "_");
538 aliases.push_str(&format!(
539 "alias sw{}='cd {}'\n",
540 alias_name,
541 workspace.path.display()
542 ));
543 }
544 }
545
546 Ok(aliases)
547}
548
549#[cfg(test)]
550mod tests {
551 use super::*;
552 use std::path::PathBuf;
553
554 #[test]
555 fn test_workspace_navigator_creation() {
556 }
560
561 #[test]
562 fn test_workspace_info_creation() {
563 let workspace = WorkspaceInfo {
564 name: "test".to_string(),
565 path: PathBuf::from("/test/path"),
566 workspace_type: WorkspaceType::Agent,
567 exists: true,
568 current: false,
569 relative_path: "../test".to_string(),
570 };
571
572 assert_eq!(workspace.name, "test");
573 assert_eq!(workspace.workspace_type, WorkspaceType::Agent);
574 assert!(workspace.exists);
575 assert!(!workspace.current);
576 }
577
578 #[test]
579 fn test_navigation_result() {
580 let workspace = WorkspaceInfo {
581 name: "test".to_string(),
582 path: PathBuf::from("/test/path"),
583 workspace_type: WorkspaceType::Agent,
584 exists: true,
585 current: false,
586 relative_path: "../test".to_string(),
587 };
588
589 let result = NavigationResult {
590 workspace: workspace.clone(),
591 current_workspace: None,
592 command: "cd /test/path".to_string(),
593 relative_command: "cd ../test".to_string(),
594 };
595
596 assert_eq!(result.workspace.name, "test");
597 assert_eq!(result.command, "cd /test/path");
598 assert_eq!(result.relative_command, "cd ../test");
599 }
600}