1#[derive(Debug)]
8#[allow(dead_code)]
9pub enum SpriteError {
10 Config {
12 message: String,
13 source: Option<Box<dyn std::error::Error + Send + Sync>>,
14 },
15
16 Git {
18 operation: String,
19 source: Option<Box<dyn std::error::Error + Send + Sync>>,
20 },
21
22 Tmux {
24 operation: String,
25 source: Option<Box<dyn std::error::Error + Send + Sync>>,
26 },
27
28 Agent {
30 message: String,
31 agent_id: Option<String>,
32 },
33
34 Session {
36 message: String,
37 session_name: Option<String>,
38 },
39
40 FileSystem {
42 operation: String,
43 path: String,
44 source: Option<Box<dyn std::error::Error + Send + Sync>>,
45 },
46
47 Validation {
49 message: String,
50 field: Option<String>,
51 value: Option<String>,
52 },
53
54 Process {
56 command: String,
57 exit_code: Option<i32>,
58 stdout: String,
59 stderr: String,
60 },
61
62 Io {
64 operation: String,
65 source: std::io::Error,
66 },
67
68 Yaml {
70 message: String,
71 line: Option<usize>,
72 column: Option<usize>,
73 },
74
75 Security {
77 message: String,
78 violation_type: SecurityViolationType,
79 },
80
81 Communication {
83 message: String,
84 target: Option<String>,
85 },
86}
87
88#[derive(Debug, Clone)]
90#[allow(dead_code)]
91pub enum SecurityViolationType {
92 PathTraversal,
93 InvalidPath,
94 UnauthorizedAccess,
95 CommandInjection,
96 UnsafeCommand,
97 InvalidInput,
98 MalformedSessionName,
99 WorkspaceValidation,
100 InsecurePermissions,
101 InsecureEnvironment,
102}
103
104#[allow(dead_code)]
105impl SpriteError {
106 pub fn config(message: impl Into<String>) -> Self {
108 Self::Config {
109 message: message.into(),
110 source: None,
111 }
112 }
113
114 pub fn config_with_source(
116 message: impl Into<String>,
117 source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
118 ) -> Self {
119 Self::Config {
120 message: message.into(),
121 source: Some(source.into()),
122 }
123 }
124
125 pub fn git(operation: impl Into<String>) -> Self {
127 Self::Git {
128 operation: operation.into(),
129 source: None,
130 }
131 }
132
133 pub fn git_with_source(
135 operation: impl Into<String>,
136 source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
137 ) -> Self {
138 Self::Git {
139 operation: operation.into(),
140 source: Some(source.into()),
141 }
142 }
143
144 pub fn tmux(operation: impl Into<String>) -> Self {
146 Self::Tmux {
147 operation: operation.into(),
148 source: None,
149 }
150 }
151
152 pub fn tmux_with_source(
154 operation: impl Into<String>,
155 source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
156 ) -> Self {
157 Self::Tmux {
158 operation: operation.into(),
159 source: Some(source.into()),
160 }
161 }
162
163 pub fn agent(message: impl Into<String>, agent_id: Option<impl Into<String>>) -> Self {
165 Self::Agent {
166 message: message.into(),
167 agent_id: agent_id.map(|id| id.into()),
168 }
169 }
170
171 pub fn session(message: impl Into<String>, session_name: Option<impl Into<String>>) -> Self {
173 Self::Session {
174 message: message.into(),
175 session_name: session_name.map(|name| name.into()),
176 }
177 }
178
179 pub fn filesystem(operation: impl Into<String>, path: impl Into<String>) -> Self {
181 Self::FileSystem {
182 operation: operation.into(),
183 path: path.into(),
184 source: None,
185 }
186 }
187
188 pub fn filesystem_with_source(
190 operation: impl Into<String>,
191 path: impl Into<String>,
192 source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
193 ) -> Self {
194 Self::FileSystem {
195 operation: operation.into(),
196 path: path.into(),
197 source: Some(source.into()),
198 }
199 }
200
201 pub fn validation(
203 message: impl Into<String>,
204 field: Option<impl Into<String>>,
205 value: Option<impl Into<String>>,
206 ) -> Self {
207 Self::Validation {
208 message: message.into(),
209 field: field.map(|f| f.into()),
210 value: value.map(|v| v.into()),
211 }
212 }
213
214 pub fn process(
216 command: impl Into<String>,
217 exit_code: Option<i32>,
218 stdout: impl Into<String>,
219 stderr: impl Into<String>,
220 ) -> Self {
221 Self::Process {
222 command: command.into(),
223 exit_code,
224 stdout: stdout.into(),
225 stderr: stderr.into(),
226 }
227 }
228
229 pub fn io(operation: impl Into<String>, source: std::io::Error) -> Self {
231 Self::Io {
232 operation: operation.into(),
233 source,
234 }
235 }
236
237 pub fn yaml(message: impl Into<String>, line: Option<usize>, column: Option<usize>) -> Self {
239 Self::Yaml {
240 message: message.into(),
241 line,
242 column,
243 }
244 }
245
246 pub fn security(message: impl Into<String>, violation_type: SecurityViolationType) -> Self {
248 Self::Security {
249 message: message.into(),
250 violation_type,
251 }
252 }
253
254 pub fn communication(message: impl Into<String>, target: Option<impl Into<String>>) -> Self {
256 Self::Communication {
257 message: message.into(),
258 target: target.map(|t| t.into()),
259 }
260 }
261
262 pub fn config_not_found(path: impl Into<String>) -> Self {
264 Self::Config {
265 message: format!("Configuration file not found: {}", path.into()),
266 source: None,
267 }
268 }
269
270 pub fn agent_not_found(agent_id: impl Into<String>) -> Self {
272 let id = agent_id.into();
273 Self::Agent {
274 message: format!("Agent '{}' not found", id),
275 agent_id: Some(id.clone()),
276 }
277 }
278
279 pub fn agent_not_active(agent_id: impl Into<String>) -> Self {
281 let id = agent_id.into();
282 Self::Agent {
283 message: format!("Agent '{}' is not active", id),
284 agent_id: Some(id.clone()),
285 }
286 }
287
288 pub fn session_not_found(message: impl Into<String>) -> Self {
290 Self::Session {
291 message: message.into(),
292 session_name: None,
293 }
294 }
295
296 pub fn sync(message: impl Into<String>) -> Self {
298 Self::Git {
299 operation: message.into(),
300 source: None,
301 }
302 }
303
304 pub fn pane_not_found(message: impl Into<String>) -> Self {
306 Self::Tmux {
307 operation: message.into(),
308 source: None,
309 }
310 }
311
312 pub fn suggestion(&self) -> Option<String> {
314 match self {
315 Self::Config { message, .. } => {
316 if message.contains("not found") {
317 Some("Run 'sprite init' to create a default configuration.".to_string())
318 } else if message.contains("invalid") {
319 Some("Check your configuration file syntax and required fields.".to_string())
320 } else {
321 None
322 }
323 }
324 Self::Git { operation, .. } => {
325 if operation.contains("worktree") {
326 Some("Make sure you're in a git repository and the branch exists.".to_string())
327 } else {
328 Some("Check your git repository status and permissions.".to_string())
329 }
330 }
331 Self::Tmux { operation, .. } => {
332 if operation.contains("session") {
333 Some("Use 'sprite start' to create a new session.".to_string())
334 } else {
335 Some("Make sure tmux is installed and running.".to_string())
336 }
337 }
338 Self::Agent { agent_id, .. } => {
339 if let Some(id) = agent_id {
340 Some(format!(
341 "Check if agent '{}' exists and is properly configured.",
342 id
343 ))
344 } else {
345 Some("Verify your agent configuration in agents.yaml.".to_string())
346 }
347 }
348 Self::Session { session_name, .. } => {
349 if let Some(name) = session_name {
350 Some(format!(
351 "Use 'sprite attach {}' to connect to the session.",
352 name
353 ))
354 } else {
355 Some("Use 'sprite start' to create a new session.".to_string())
356 }
357 }
358 Self::FileSystem {
359 operation, path, ..
360 } => {
361 if operation.contains("create") || operation.contains("write") {
362 Some(format!(
363 "Check permissions for path '{}' and parent directories.",
364 path
365 ))
366 } else {
367 Some(format!("Verify that '{}' exists and is accessible.", path))
368 }
369 }
370 Self::Validation { field, .. } => {
371 if let Some(f) = field {
372 Some(format!(
373 "Check the value of field '{}' in your configuration.",
374 f
375 ))
376 } else {
377 Some("Review your configuration for invalid values.".to_string())
378 }
379 }
380 Self::Process { command, .. } => Some(format!(
381 "Check if '{}' is installed and in your PATH.",
382 command
383 )),
384 Self::Security { violation_type, .. } => match violation_type {
385 SecurityViolationType::PathTraversal => {
386 Some("Use relative paths within the project directory only.".to_string())
387 }
388 SecurityViolationType::InvalidPath => {
389 Some("Check that the path is valid and within allowed boundaries.".to_string())
390 }
391 SecurityViolationType::UnauthorizedAccess => {
392 Some("Check file permissions and access rights.".to_string())
393 }
394 SecurityViolationType::CommandInjection => {
395 Some("Avoid special shell characters in agent names and commands.".to_string())
396 }
397 SecurityViolationType::UnsafeCommand => Some(
398 "Use only safe, approved commands. Avoid shell metacharacters.".to_string(),
399 ),
400 SecurityViolationType::InvalidInput => Some(
401 "Check that input contains only allowed characters and formats.".to_string(),
402 ),
403 SecurityViolationType::MalformedSessionName => {
404 Some("Use alphanumeric session names with hyphens only.".to_string())
405 }
406 SecurityViolationType::WorkspaceValidation => {
407 Some("Ensure all workspaces are within the agents/ directory.".to_string())
408 }
409 SecurityViolationType::InsecurePermissions => {
410 Some("Restrict file permissions to prevent unauthorized access.".to_string())
411 }
412 SecurityViolationType::InsecureEnvironment => Some(
413 "Run with appropriate user permissions and secure environment settings."
414 .to_string(),
415 ),
416 },
417 Self::Communication { target, .. } => {
418 if let Some(t) = target {
419 Some(format!("Check if agent '{}' is running and accessible.", t))
420 } else {
421 Some("Verify that all agents are running and responsive.".to_string())
422 }
423 }
424 Self::Io { operation, .. } => Some(format!(
425 "Check file permissions and disk space for operation: {}",
426 operation
427 )),
428 Self::Yaml { line, column, .. } => {
429 let mut suggestion = "Check your YAML syntax.".to_string();
430 if let Some(l) = line {
431 suggestion.push_str(&format!(" Error at line {}.", l));
432 if let Some(c) = column {
433 suggestion.push_str(&format!(" Column {}.", c));
434 }
435 }
436 Some(suggestion)
437 }
438 }
439 }
440
441 pub fn exit_code(&self) -> i32 {
443 match self {
444 Self::Config { .. } => 2,
445 Self::Git { .. } => 3,
446 Self::Tmux { .. } => 4,
447 Self::Agent { .. } => 5,
448 Self::Session { .. } => 6,
449 Self::FileSystem { .. } => 7,
450 Self::Validation { .. } => 8,
451 Self::Process { exit_code, .. } => exit_code.unwrap_or(9),
452 Self::Io { .. } => 10,
453 Self::Yaml { .. } => 11,
454 Self::Security { .. } => 12,
455 Self::Communication { .. } => 13,
456 }
457 }
458}
459
460#[allow(dead_code)]
462pub type Result<T> = anyhow::Result<T, SpriteError>;
463
464impl From<std::io::Error> for SpriteError {
466 fn from(err: std::io::Error) -> Self {
467 Self::io("I/O operation", err)
468 }
469}
470
471impl From<serde_yaml::Error> for SpriteError {
473 fn from(err: serde_yaml::Error) -> Self {
474 let location = err.location();
475 let line = location.as_ref().map(|loc| loc.line());
476 let column = location.as_ref().map(|loc| loc.column());
477 Self::yaml(err.to_string(), line, column)
478 }
479}
480
481impl std::fmt::Display for SpriteError {
483 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
484 match self {
485 Self::Config { message, .. } => write!(f, "Configuration error: {}", message),
486 Self::Git { operation, .. } => write!(f, "Git operation failed: {}", operation),
487 Self::Tmux { operation, .. } => write!(f, "Tmux operation failed: {}", operation),
488 Self::Agent { message, .. } => write!(f, "Agent error: {}", message),
489 Self::Session { message, .. } => write!(f, "Session error: {}", message),
490 Self::FileSystem {
491 operation, path, ..
492 } => {
493 write!(f, "File system error: {} on '{}' failed", operation, path)
494 }
495 Self::Validation { message, .. } => write!(f, "Validation error: {}", message),
496 Self::Process { command, .. } => write!(f, "Command execution failed: {}", command),
497 Self::Io { operation, .. } => write!(f, "I/O error: {}", operation),
498 Self::Yaml { message, .. } => write!(f, "YAML parsing error: {}", message),
499 Self::Security { message, .. } => write!(f, "Security error: {}", message),
500 Self::Communication { message, .. } => write!(f, "Communication error: {}", message),
501 }?;
502
503 if let Some(suggestion) = self.suggestion() {
504 write!(f, "\n\nSuggestion: {}", suggestion)?;
505 }
506 Ok(())
507 }
508}
509
510impl std::error::Error for SpriteError {
512 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
513 match self {
514 Self::Config { source, .. } => source
515 .as_ref()
516 .map(|e| e.as_ref() as &dyn std::error::Error),
517 Self::Git { source, .. } => source
518 .as_ref()
519 .map(|e| e.as_ref() as &dyn std::error::Error),
520 Self::Tmux { source, .. } => source
521 .as_ref()
522 .map(|e| e.as_ref() as &dyn std::error::Error),
523 Self::FileSystem { source, .. } => source
524 .as_ref()
525 .map(|e| e.as_ref() as &dyn std::error::Error),
526 Self::Io { source, .. } => Some(source),
527 _ => None,
528 }
529 }
530}
531
532#[cfg(test)]
533mod tests {
534 use super::*;
535
536 #[test]
537 fn test_error_creation() {
538 let err = SpriteError::config("Test config error");
539 assert!(matches!(err, SpriteError::Config { .. }));
540 assert_eq!(err.exit_code(), 2);
541 }
542
543 #[test]
544 fn test_error_with_agent_id() {
545 let err = SpriteError::agent("Agent not found", Some("agent-1"));
546 match err {
547 SpriteError::Agent { agent_id, .. } => {
548 assert_eq!(agent_id.as_deref(), Some("agent-1"));
549 }
550 _ => panic!("Expected Agent error"),
551 }
552 }
553
554 #[test]
555 fn test_error_suggestion() {
556 let err = SpriteError::config("Configuration file not found");
557 let suggestion = err.suggestion();
558 assert!(suggestion.is_some());
559 assert!(suggestion.unwrap().contains("sprite init"));
560 }
561
562 #[test]
563 fn test_error_display() {
564 let err = SpriteError::git("failed to create worktree");
565 let display = format!("{}", err);
566 assert!(display.contains("Git operation failed"));
567 assert!(display.contains("Suggestion:"));
568 }
569
570 #[test]
571 fn test_security_violation_types() {
572 let err = SpriteError::security("Path contains '..'", SecurityViolationType::PathTraversal);
573 assert!(matches!(err, SpriteError::Security { .. }));
574 assert_eq!(err.exit_code(), 12);
575
576 let suggestion = err.suggestion();
577 assert!(suggestion.is_some());
578 assert!(suggestion.unwrap().contains("relative paths"));
579 }
580
581 #[test]
582 fn test_yaml_error_with_location() {
583 let err = SpriteError::yaml("Invalid mapping", Some(10), Some(5));
584 assert!(matches!(
585 err,
586 SpriteError::Yaml {
587 line: Some(10),
588 column: Some(5),
589 ..
590 }
591 ));
592
593 let suggestion = err.suggestion();
594 assert!(suggestion.is_some());
595 assert!(suggestion.clone().unwrap().contains("line 10"));
596 assert!(suggestion.clone().unwrap().contains("Column 5"));
597 }
598}