agpm-cli 0.4.14

AGent Package Manager - A Git-based package manager for coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Error context builders for consistent error reporting
//!
//! This module provides utilities for creating consistent error contexts
//! throughout the application, reducing boilerplate and ensuring uniform
//! error messages for users.

use crate::core::error::ErrorContext;
use anyhow::{Context, Result};
use std::path::Path;

/// Create an error context for file operations
///
/// # Arguments
///
/// * `operation` - The operation being performed (e.g., "read", "write", "delete")
/// * `path` - The path being operated on
///
/// # Example
///
/// ```no_run
/// # use anyhow::{Context, Result};
/// # fn example() -> Result<()> {
/// use agpm_cli::core::error_builders::file_error_context;
/// use std::fs;
/// use std::path::Path;
///
/// let path = Path::new("config.toml");
/// let contents = fs::read_to_string(&path)
///     .with_context(|| file_error_context("read", path))?;
/// # Ok(())
/// # }
/// ```
pub fn file_error_context(operation: &str, path: &Path) -> ErrorContext {
    use crate::core::AgpmError;

    ErrorContext {
        error: AgpmError::FileSystemError {
            operation: operation.to_string(),
            path: path.display().to_string(),
        },
        suggestion: match operation {
            "read" => Some("Check that the file exists and you have read permissions".to_string()),
            "write" => Some("Check that you have write permissions for this location".to_string()),
            "create" => Some(
                "Check that the parent directory exists and you have write permissions".to_string(),
            ),
            "delete" => {
                Some("Check that the file exists and you have delete permissions".to_string())
            }
            _ => None,
        },
        details: Some(format!("File path: {}", path.display())),
    }
}

/// Create an error context for git operations
///
/// # Arguments
///
/// * `command` - The git command that failed (e.g., "clone", "fetch", "pull")
/// * `repo` - Optional repository URL or path
///
/// # Example
///
/// ```no_run
/// use agpm_cli::core::error_builders::git_error_context;
///
/// let context = git_error_context("clone", Some("https://github.com/user/repo.git"));
/// ```
pub fn git_error_context(command: &str, repo: Option<&str>) -> ErrorContext {
    use crate::core::AgpmError;

    ErrorContext {
        error: AgpmError::GitCommandError {
            operation: command.to_string(),
            stderr: format!("Git {command} operation failed"),
        },
        suggestion: match command {
            "clone" => {
                Some("Check your network connection and that the repository exists".to_string())
            }
            "fetch" | "pull" => {
                Some("Check your network connection and repository access".to_string())
            }
            "checkout" => Some("Ensure the branch or tag exists in the repository".to_string()),
            "status" => Some("Ensure you're in a valid git repository".to_string()),
            _ => Some("Check that git is installed and accessible".to_string()),
        },
        details: repo.map(|r| format!("Repository: {r}")),
    }
}

/// Create an error context for manifest operations
///
/// # Arguments
///
/// * `operation` - The operation being performed (e.g., "load", "parse", "validate")
/// * `details` - Optional additional details
///
/// # Example
///
/// ```no_run
/// use agpm_cli::core::error_builders::manifest_error_context;
///
/// let context = manifest_error_context("parse", Some("Invalid TOML syntax at line 5"));
/// ```
pub fn manifest_error_context(operation: &str, details: Option<&str>) -> ErrorContext {
    use crate::core::AgpmError;

    let error = match operation {
        "load" => AgpmError::ManifestNotFound,
        "parse" => AgpmError::ManifestParseError {
            file: "agpm.toml".to_string(),
            reason: details.unwrap_or("Invalid TOML syntax").to_string(),
        },
        "validate" => AgpmError::ManifestValidationError {
            reason: details.unwrap_or("Validation failed").to_string(),
        },
        _ => AgpmError::Other {
            message: format!("Manifest operation '{operation}' failed"),
        },
    };

    ErrorContext {
        error,
        suggestion: match operation {
            "load" => Some("Check that agpm.toml exists in the project directory".to_string()),
            "parse" => Some("Check that agpm.toml contains valid TOML syntax".to_string()),
            "validate" => {
                Some("Ensure all required fields are present in the manifest".to_string())
            }
            _ => None,
        },
        details: details.map(std::string::ToString::to_string),
    }
}

/// Create an error context for dependency resolution
///
/// # Arguments
///
/// * `dependency` - The dependency that caused the error
/// * `reason` - The reason for the failure
///
/// # Example
///
/// ```no_run
/// use agpm_cli::core::error_builders::dependency_error_context;
///
/// let context = dependency_error_context("my-agent", "Version conflict with existing dependency");
/// ```
pub fn dependency_error_context(dependency: &str, reason: &str) -> ErrorContext {
    use crate::core::AgpmError;

    ErrorContext {
        error: AgpmError::InvalidDependency {
            name: dependency.to_string(),
            reason: reason.to_string(),
        },
        suggestion: Some("Try running 'agpm update' to update dependencies".to_string()),
        details: Some(reason.to_string()),
    }
}

/// Create an error context for network operations
///
/// # Arguments
///
/// * `operation` - The network operation (e.g., "download", "fetch", "connect")
/// * `url` - Optional URL being accessed
///
/// # Example
///
/// ```no_run
/// use agpm_cli::core::error_builders::network_error_context;
///
/// let context = network_error_context("fetch", Some("https://api.example.com"));
/// ```
pub fn network_error_context(operation: &str, url: Option<&str>) -> ErrorContext {
    use crate::core::AgpmError;

    ErrorContext {
        error: AgpmError::NetworkError {
            operation: operation.to_string(),
            reason: format!("Network {operation} failed"),
        },
        suggestion: Some("Check your internet connection and try again".to_string()),
        details: url.map(|u| format!("URL: {u}")),
    }
}

/// Create an error context for configuration issues
///
/// # Arguments
///
/// * `config_type` - The type of configuration (e.g., "global", "project", "mcp")
/// * `issue` - Description of the issue
///
/// # Example
///
/// ```no_run
/// use agpm_cli::core::error_builders::config_error_context;
///
/// let context = config_error_context("global", "Missing authentication token");
/// ```
pub fn config_error_context(config_type: &str, issue: &str) -> ErrorContext {
    use crate::core::AgpmError;

    ErrorContext {
        error: AgpmError::ConfigError {
            message: format!("Configuration error in {config_type} config: {issue}"),
        },
        suggestion: match config_type {
            "global" => Some("Check ~/.agpm/config.toml for correct settings".to_string()),
            "project" => Some("Check agpm.toml in your project directory".to_string()),
            "mcp" => Some("Check .mcp.json for valid MCP server configurations".to_string()),
            _ => None,
        },
        details: Some(issue.to_string()),
    }
}

/// Create an error context for permission issues
///
/// # Arguments
///
/// * `resource` - The resource that requires permissions
/// * `operation` - The operation that failed
///
/// # Example
///
/// ```no_run
/// use agpm_cli::core::error_builders::permission_error_context;
///
/// let context = permission_error_context("/usr/local/bin", "write");
/// ```
pub fn permission_error_context(resource: &str, operation: &str) -> ErrorContext {
    use crate::core::AgpmError;

    ErrorContext {
        error: AgpmError::PermissionDenied {
            operation: operation.to_string(),
            path: resource.to_string(),
        },
        suggestion: Some(format!("Check that you have {operation} permissions for: {resource}")),
        details: if cfg!(windows) {
            Some("On Windows, you may need to run as Administrator".to_string())
        } else {
            Some("On Unix systems, you may need to use sudo or change file permissions".to_string())
        },
    }
}

/// Helper trait to easily attach error contexts
pub trait ErrorContextExt<T> {
    /// Attach a file error context
    fn file_context(self, operation: &str, path: &Path) -> Result<T>;

    /// Attach a git error context
    fn git_context(self, command: &str, repo: Option<&str>) -> Result<T>;

    /// Attach a manifest error context
    fn manifest_context(self, operation: &str, details: Option<&str>) -> Result<T>;

    /// Attach a dependency error context
    fn dependency_context(self, dependency: &str, reason: &str) -> Result<T>;

    /// Attach a network error context
    fn network_context(self, operation: &str, url: Option<&str>) -> Result<T>;
}

impl<T, E> ErrorContextExt<T> for std::result::Result<T, E>
where
    E: std::error::Error + Send + Sync + 'static,
{
    fn file_context(self, operation: &str, path: &Path) -> Result<T> {
        self.with_context(|| file_error_context(operation, path))
    }

    fn git_context(self, command: &str, repo: Option<&str>) -> Result<T> {
        self.with_context(|| git_error_context(command, repo))
    }

    fn manifest_context(self, operation: &str, details: Option<&str>) -> Result<T> {
        self.with_context(|| manifest_error_context(operation, details))
    }

    fn dependency_context(self, dependency: &str, reason: &str) -> Result<T> {
        self.with_context(|| dependency_error_context(dependency, reason))
    }

    fn network_context(self, operation: &str, url: Option<&str>) -> Result<T> {
        self.with_context(|| network_error_context(operation, url))
    }
}

/// Macro for creating custom error contexts quickly
///
/// # Example
///
/// ```
/// use agpm_cli::{error_context, core::AgpmError};
///
/// let context = error_context! {
///     error: AgpmError::Other { message: "Operation failed".to_string() },
///     suggestion: "Try again later",
///     details: "Additional information"
/// };
/// ```
#[macro_export]
macro_rules! error_context {
    (error: $err:expr) => {
        $crate::core::error::ErrorContext {
            error: $err,
            suggestion: None,
            details: None,
        }
    };
    (error: $err:expr, suggestion: $sug:expr) => {
        $crate::core::error::ErrorContext {
            error: $err,
            suggestion: Some($sug.to_string()),
            details: None,
        }
    };
    (error: $err:expr, suggestion: $sug:expr, details: $det:expr) => {
        $crate::core::error::ErrorContext {
            error: $err,
            suggestion: Some($sug.to_string()),
            details: Some($det.to_string()),
        }
    };
    (error: $err:expr, details: $det:expr) => {
        $crate::core::error::ErrorContext {
            error: $err,
            suggestion: None,
            details: Some($det.to_string()),
        }
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_file_error_context() {
        let context = file_error_context("read", Path::new("/tmp/test.txt"));
        assert!(matches!(context.error, crate::core::AgpmError::FileSystemError { .. }));
        assert!(context.suggestion.is_some());
        assert!(context.details.unwrap().contains("/tmp/test.txt"));
    }

    #[test]
    fn test_git_error_context() {
        let context = git_error_context("clone", Some("https://github.com/test/repo"));
        assert!(matches!(context.error, crate::core::AgpmError::GitCommandError { .. }));
        assert!(context.suggestion.unwrap().contains("network"));
        assert!(context.details.unwrap().contains("github.com"));
    }

    #[test]
    fn test_error_context_macro() {
        use crate::core::AgpmError;

        let context = error_context! {
            error: AgpmError::Other { message: "Test error".to_string() },
            suggestion: "Test suggestion",
            details: "Test details"
        };
        assert!(matches!(context.error, AgpmError::Other { .. }));
        assert_eq!(context.suggestion.unwrap(), "Test suggestion");
        assert_eq!(context.details.unwrap(), "Test details");
    }

    #[test]
    fn test_permission_error_context() {
        let context = permission_error_context("/usr/local", "write");
        assert!(matches!(context.error, crate::core::AgpmError::PermissionDenied { .. }));
        assert!(context.suggestion.unwrap().contains("write permissions"));
        assert!(context.details.is_some());
    }

    #[test]
    fn test_manifest_error_context_all_operations() {
        // Test load operation
        let context = manifest_error_context("load", None);
        assert!(matches!(context.error, crate::core::AgpmError::ManifestNotFound));
        assert!(context.suggestion.unwrap().contains("agpm.toml exists"));

        // Test parse operation with details
        let context = manifest_error_context("parse", Some("Syntax error at line 10"));
        assert!(matches!(context.error, crate::core::AgpmError::ManifestParseError { .. }));
        assert!(context.suggestion.unwrap().contains("valid TOML syntax"));
        assert_eq!(context.details.unwrap(), "Syntax error at line 10");

        // Test validate operation
        let context = manifest_error_context("validate", Some("Missing required field"));
        assert!(matches!(context.error, crate::core::AgpmError::ManifestValidationError { .. }));
        assert!(context.suggestion.unwrap().contains("required fields"));
        assert_eq!(context.details.unwrap(), "Missing required field");

        // Test unknown operation
        let context = manifest_error_context("unknown", None);
        assert!(matches!(context.error, crate::core::AgpmError::Other { .. }));
        assert!(context.suggestion.is_none());
    }

    #[test]
    fn test_dependency_error_context() {
        let context = dependency_error_context("test-agent", "Version not found");
        assert!(matches!(context.error, crate::core::AgpmError::InvalidDependency { .. }));
        assert!(context.suggestion.unwrap().contains("agpm update"));
        assert_eq!(context.details.unwrap(), "Version not found");
    }

    #[test]
    fn test_network_error_context() {
        let context = network_error_context("download", Some("https://example.com/file"));
        assert!(matches!(context.error, crate::core::AgpmError::NetworkError { .. }));
        assert!(context.suggestion.unwrap().contains("internet connection"));
        assert!(context.details.unwrap().contains("example.com"));
    }

    #[test]
    fn test_config_error_context_types() {
        // Test global config
        let context = config_error_context("global", "Invalid format");
        assert!(matches!(context.error, crate::core::AgpmError::ConfigError { .. }));
        assert!(context.suggestion.unwrap().contains("~/.agpm/config.toml"));

        // Test project config
        let context = config_error_context("project", "Missing dependency");
        assert!(context.suggestion.unwrap().contains("agpm.toml"));

        // Test MCP config
        let context = config_error_context("mcp", "Invalid server");
        assert!(context.suggestion.unwrap().contains(".mcp.json"));

        // Test unknown config type
        let context = config_error_context("unknown", "Some issue");
        assert!(context.suggestion.is_none());
    }

    #[test]
    fn test_file_error_context_operations() {
        // Test read operation
        let context = file_error_context("read", Path::new("/test/file.txt"));
        assert!(context.suggestion.unwrap().contains("read permissions"));

        // Test write operation
        let context = file_error_context("write", Path::new("/test/file.txt"));
        assert!(context.suggestion.unwrap().contains("write permissions"));

        // Test create operation
        let context = file_error_context("create", Path::new("/test/file.txt"));
        assert!(context.suggestion.unwrap().contains("parent directory"));

        // Test delete operation
        let context = file_error_context("delete", Path::new("/test/file.txt"));
        assert!(context.suggestion.unwrap().contains("delete permissions"));

        // Test unknown operation
        let context = file_error_context("unknown", Path::new("/test/file.txt"));
        assert!(context.suggestion.is_none());
    }

    #[test]
    fn test_git_error_context_commands() {
        // Test clone command
        let context = git_error_context("clone", Some("repo.git"));
        assert!(context.suggestion.unwrap().contains("repository exists"));

        // Test fetch command
        let context = git_error_context("fetch", None);
        assert!(context.suggestion.unwrap().contains("repository access"));

        // Test pull command
        let context = git_error_context("pull", Some("origin"));
        assert!(context.suggestion.unwrap().contains("repository access"));

        // Test checkout command
        let context = git_error_context("checkout", Some("branch"));
        assert!(context.suggestion.unwrap().contains("branch or tag exists"));

        // Test status command
        let context = git_error_context("status", None);
        assert!(context.suggestion.unwrap().contains("valid git repository"));

        // Test unknown command
        let context = git_error_context("unknown", None);
        assert!(context.suggestion.unwrap().contains("git is installed"));
    }

    #[test]
    fn test_error_context_ext_trait() {
        use std::io;

        // Test file_context
        let result: Result<(), io::Error> = Err(io::Error::new(io::ErrorKind::NotFound, "test"));
        let result = result.file_context("read", Path::new("/test.txt"));
        assert!(result.is_err());

        // Test git_context
        let result: Result<(), io::Error> = Err(io::Error::other("test"));
        let result = result.git_context("clone", Some("repo"));
        assert!(result.is_err());

        // Test manifest_context
        let result: Result<(), io::Error> = Err(io::Error::new(io::ErrorKind::InvalidData, "test"));
        let result = result.manifest_context("parse", Some("details"));
        assert!(result.is_err());

        // Test dependency_context
        let result: Result<(), io::Error> = Err(io::Error::other("test"));
        let result = result.dependency_context("dep", "reason");
        assert!(result.is_err());

        // Test network_context
        let result: Result<(), io::Error> = Err(io::Error::new(io::ErrorKind::TimedOut, "test"));
        let result = result.network_context("fetch", Some("url"));
        assert!(result.is_err());
    }

    #[test]
    fn test_permission_error_context_platforms() {
        let context = permission_error_context("/path", "execute");
        assert!(context.details.is_some());

        #[cfg(windows)]
        assert!(context.details.unwrap().contains("Administrator"));

        #[cfg(not(windows))]
        assert!(context.details.unwrap().contains("sudo"));
    }

    #[test]
    fn test_error_context_macro_variants() {
        use crate::core::AgpmError;

        // Test with error only
        let context = error_context! {
            error: AgpmError::Other { message: "Error only".to_string() }
        };
        assert!(context.suggestion.is_none());
        assert!(context.details.is_none());

        // Test with error and suggestion
        let context = error_context! {
            error: AgpmError::Other { message: "Error".to_string() },
            suggestion: "Do this"
        };
        assert_eq!(context.suggestion.unwrap(), "Do this");
        assert!(context.details.is_none());

        // Test with error and details
        let context = error_context! {
            error: AgpmError::Other { message: "Error".to_string() },
            details: "More info"
        };
        assert!(context.suggestion.is_none());
        assert_eq!(context.details.unwrap(), "More info");
    }
}