agpm-cli 0.4.3

AGent Package Manager - A Git-based package manager for Claude 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
//! Initialize a new AGPM project with a manifest file.
//!
//! This module provides the `init` command which creates a new `agpm.toml` manifest file
//! in the specified directory (or current directory). The manifest file is the main
//! configuration file for a AGPM project that defines dependencies on Claude Code resources.
//!
//! # Examples
//!
//! Initialize a manifest in the current directory:
//! ```bash
//! agpm init
//! ```
//!
//! Initialize a manifest in a specific directory:
//! ```bash
//! agpm init --path ./my-project
//! ```
//!
//! Force overwrite an existing manifest:
//! ```bash
//! agpm init --force
//! ```
//!
//! # Manifest Structure
//!
//! The generated manifest contains empty sections for all resource types:
//!
//! ```toml
//! [sources]
//!
//! [agents]
//!
//! [snippets]
//!
//! [commands]
//!
//! [scripts]
//!
//! [hooks]
//!
//! [mcp-servers]
//! ```
//!
//! # Error Conditions
//!
//! - Returns error if manifest already exists and `--force` is not used
//! - Returns error if unable to create the target directory
//! - Returns error if unable to write the manifest file (permissions, disk space, etc.)
//!
//! # Safety
//!
//! This command is safe to run and will not overwrite existing files unless `--force` is specified.

use anyhow::{Result, anyhow};
use clap::Args;
use colored::Colorize;
use std::fs;
use std::path::PathBuf;

/// Command to initialize a new AGPM project with a manifest file.
///
/// This command creates a `agpm.toml` manifest file in the specified directory
/// (or current directory if no path is provided). The manifest serves as the
/// main configuration file for defining Claude Code resource dependencies.
///
/// # Examples
///
/// ```rust,ignore
/// use agpm_cli::cli::init::InitCommand;
/// use std::path::PathBuf;
///
/// // Initialize in current directory
/// let cmd = InitCommand {
///     path: None,
///     force: false,
/// };
///
/// // Initialize in specific directory with force overwrite
/// let cmd = InitCommand {
///     path: Some(PathBuf::from("./my-project")),
///     force: true,
/// };
/// ```
#[derive(Args)]
pub struct InitCommand {
    /// Path to create the manifest (defaults to current directory)
    ///
    /// If not provided, the manifest will be created in the current working directory.
    /// If the specified directory doesn't exist, it will be created.
    #[arg(short, long)]
    path: Option<PathBuf>,

    /// Force overwrite if manifest already exists
    ///
    /// By default, the command will fail if a `agpm.toml` file already exists
    /// in the target directory. Use this flag to overwrite an existing file.
    #[arg(short, long)]
    force: bool,
}

impl InitCommand {
    /// Execute the init command with an optional manifest path (for API compatibility)
    pub async fn execute_with_manifest_path(
        self,
        _manifest_path: Option<std::path::PathBuf>,
    ) -> Result<()> {
        // Init command doesn't use manifest_path since it creates a new manifest
        // The path is already part of the InitCommand struct
        self.execute().await
    }

    /// Execute the init command to create a new AGPM manifest file.
    ///
    /// This method creates a `agpm.toml` manifest file with a minimal template structure
    /// that includes empty sections for all resource types. The file is
    /// created in the specified directory or current directory if no path is provided.
    ///
    /// # Behavior
    ///
    /// 1. Determines the target directory (from `path` option or current directory)
    /// 2. Checks if a manifest already exists and handles the `force` flag
    /// 3. Creates the target directory if it doesn't exist
    /// 4. Writes the manifest template to `agpm.toml`
    /// 5. Displays success message and next steps to the user
    ///
    /// # Returns
    ///
    /// - `Ok(())` if the manifest was created successfully
    /// - `Err(anyhow::Error)` if:
    ///   - A manifest already exists and `force` is false
    ///   - Unable to create the target directory
    ///   - Unable to write the manifest file
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use agpm_cli::cli::init::InitCommand;
    /// use std::path::PathBuf;
    ///
    /// # tokio_test::block_on(async {
    /// let cmd = InitCommand {
    ///     path: Some(PathBuf::from("./test-project")),
    ///     force: false,
    /// };
    ///
    /// // This would create ./test-project/agpm.toml
    /// // cmd.execute().await?;
    /// # Ok::<(), anyhow::Error>(())
    /// # });
    /// ```
    pub async fn execute(self) -> Result<()> {
        let target_dir = self.path.unwrap_or_else(|| PathBuf::from("."));
        let manifest_path = target_dir.join("agpm.toml");
        let gitignore_path = target_dir.join(".gitignore");

        // Check if manifest already exists
        if manifest_path.exists() && !self.force {
            return Err(anyhow!(
                "Manifest already exists at {}. Use --force to overwrite",
                manifest_path.display()
            ));
        }

        // Create directory if it doesn't exist
        if !target_dir.exists() {
            fs::create_dir_all(&target_dir)?;
        }

        // Write a minimal template with empty sections
        let template = r#"# AGPM Manifest
# This file defines your Claude Code resource dependencies

[sources]
# Add your Git repository sources here
# Example: official = "https://github.com/aig787/agpm-community.git"

# Tool type configurations (multi-tool support)
[tools.claude-code]
path = ".claude"
resources = { agents = { path = "agents" }, snippets = { path = "agpm/snippets" }, commands = { path = "commands" }, scripts = { path = "scripts" }, hooks = { path = "hooks" }, mcp-servers = { path = "mcp-servers" } }

[tools.opencode]
path = ".opencode"
resources = { agents = { path = "agent" }, commands = { path = "command" } }
# Note: OpenCode MCP servers merge into opencode.json (no file installation)

[tools.agpm]
path = ".agpm"
resources = { snippets = { path = "snippets" } }

[agents]
# Add your agent dependencies here
# Example: my-agent = { source = "official", path = "agents/my-agent.md", version = "v1.0.0" }
# For OpenCode: my-agent = { source = "official", path = "agents/my-agent.md", version = "v1.0.0", tool = "opencode" }

[snippets]
# Add your snippet dependencies here (AGPM-specific resources)
# Example: utils = { source = "official", path = "snippets/utils.md", tool = "agpm" }

[commands]
# Add your command dependencies here
# Example: deploy = { source = "official", path = "commands/deploy.md" }

[scripts]
# Add your script dependencies here
# Example: build = { source = "official", path = "scripts/build.sh" }

[hooks]
# Add your hook dependencies here
# Example: pre-commit = { source = "official", path = "hooks/pre-commit.json" }

[mcp-servers]
# Add your MCP server dependencies here
# Example: filesystem = { source = "official", path = "mcp-servers/filesystem.json" }
"#;
        fs::write(&manifest_path, template)?;

        // Update or create .gitignore with AGPM entries
        let gitignore_entries = vec![".claude/agpm/"];

        let mut gitignore_content = if gitignore_path.exists() {
            fs::read_to_string(&gitignore_path)?
        } else {
            String::new()
        };

        // Check if AGPM section exists
        if !gitignore_content.contains("# AGPM managed directories") {
            // Add AGPM entries
            if !gitignore_content.is_empty() && !gitignore_content.ends_with('\n') {
                gitignore_content.push('\n');
            }
            if !gitignore_content.is_empty() {
                gitignore_content.push('\n');
            }
            gitignore_content.push_str("# AGPM managed directories\n");

            for entry in gitignore_entries {
                // Check if entry doesn't already exist
                if !gitignore_content.lines().any(|line| line.trim() == entry) {
                    gitignore_content.push_str(entry);
                    gitignore_content.push('\n');
                }
            }

            fs::write(&gitignore_path, gitignore_content)?;
            println!("{} Updated .gitignore with AGPM entries", "✓".green());
        }

        println!("{} Initialized agpm.toml at {}", "✓".green(), manifest_path.display());

        println!("\n{}", "Next steps:".cyan());
        println!("  Add dependencies with {}:", "agpm add".bright_white());
        println!(
            "    agpm add agent my-agent --source https://github.com/org/repo.git --path agents/my-agent.md"
        );
        println!("    agpm add snippet utils --path ../local/snippets/utils.md");
        println!("\n  Then run {} to install", "agpm install".bright_white());

        Ok(())
    }
}

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

    #[tokio::test]
    async fn test_init_creates_manifest() {
        let temp_dir = TempDir::new().unwrap();
        let cmd = InitCommand {
            path: Some(temp_dir.path().to_path_buf()),
            force: false,
        };

        let result = cmd.execute().await;
        assert!(result.is_ok());

        let manifest_path = temp_dir.path().join("agpm.toml");
        assert!(manifest_path.exists());

        let content = fs::read_to_string(&manifest_path).unwrap();
        assert!(content.contains("[sources]"));
        assert!(content.contains("[agents]"));
        assert!(content.contains("[snippets]"));
    }

    #[tokio::test]
    async fn test_init_creates_directory_if_not_exists() {
        let temp_dir = TempDir::new().unwrap();
        let new_dir = temp_dir.path().join("new_project");

        let cmd = InitCommand {
            path: Some(new_dir.clone()),
            force: false,
        };

        let result = cmd.execute().await;
        assert!(result.is_ok());

        assert!(new_dir.exists());
        assert!(new_dir.join("agpm.toml").exists());
    }

    #[tokio::test]
    async fn test_init_fails_if_manifest_exists() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");
        fs::write(&manifest_path, "existing content").unwrap();

        let cmd = InitCommand {
            path: Some(temp_dir.path().to_path_buf()),
            force: false,
        };

        let result = cmd.execute().await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("already exists"));
    }

    #[tokio::test]
    async fn test_init_force_overwrites_existing() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");
        fs::write(&manifest_path, "old content").unwrap();

        let cmd = InitCommand {
            path: Some(temp_dir.path().to_path_buf()),
            force: true,
        };

        let result = cmd.execute().await;
        assert!(result.is_ok());

        let content = fs::read_to_string(&manifest_path).unwrap();
        assert!(content.contains("[sources]"));
        assert!(!content.contains("old content"));
    }

    #[tokio::test]
    async fn test_init_uses_current_dir_by_default() {
        let temp_dir = TempDir::new().unwrap();

        // Use explicit path instead of changing directory
        let cmd = InitCommand {
            path: Some(temp_dir.path().to_path_buf()),
            force: false,
        };

        let result = cmd.execute().await;
        assert!(result.is_ok());
        assert!(temp_dir.path().join("agpm.toml").exists());
    }

    #[tokio::test]
    async fn test_init_template_content() {
        let temp_dir = TempDir::new().unwrap();
        let cmd = InitCommand {
            path: Some(temp_dir.path().to_path_buf()),
            force: false,
        };

        let result = cmd.execute().await;
        assert!(result.is_ok());

        let manifest_path = temp_dir.path().join("agpm.toml");
        let content = fs::read_to_string(&manifest_path).unwrap();

        // Verify template content
        assert!(content.contains("# AGPM Manifest"));
        assert!(content.contains("# This file defines your Claude Code resource dependencies"));
        assert!(content.contains("# Add your Git repository sources here"));
        assert!(content.contains("# Example: official ="));
        assert!(content.contains("# Add your agent dependencies here"));
        assert!(content.contains("# Example: my-agent ="));
        assert!(content.contains("# Add your snippet dependencies here"));
        assert!(content.contains("# Example: utils ="));
    }

    #[tokio::test]
    async fn test_init_nested_directory_creation() {
        let temp_dir = TempDir::new().unwrap();
        let nested_path = temp_dir.path().join("a").join("b").join("c");

        let cmd = InitCommand {
            path: Some(nested_path.clone()),
            force: false,
        };

        let result = cmd.execute().await;
        assert!(result.is_ok());
        assert!(nested_path.exists());
        assert!(nested_path.join("agpm.toml").exists());
    }

    #[tokio::test]
    async fn test_init_force_flag_behavior() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");

        // Write initial content
        let initial_content = "# Old manifest\n[sources]\n";
        fs::write(&manifest_path, initial_content).unwrap();

        // Try without force - should fail
        let cmd = InitCommand {
            path: Some(temp_dir.path().to_path_buf()),
            force: false,
        };
        let result = cmd.execute().await;
        assert!(result.is_err());

        // Verify old content still exists
        let content = fs::read_to_string(&manifest_path).unwrap();
        assert_eq!(content, initial_content);

        // Try with force - should succeed
        let cmd = InitCommand {
            path: Some(temp_dir.path().to_path_buf()),
            force: true,
        };
        let result = cmd.execute().await;
        assert!(result.is_ok());

        // Verify new template content
        let new_content = fs::read_to_string(&manifest_path).unwrap();
        assert!(new_content.contains("# AGPM Manifest"));
        assert!(!new_content.contains("# Old manifest"));
    }

    #[tokio::test]
    async fn test_init_creates_gitignore() {
        let temp_dir = TempDir::new().unwrap();
        let cmd = InitCommand {
            path: Some(temp_dir.path().to_path_buf()),
            force: false,
        };

        let result = cmd.execute().await;
        assert!(result.is_ok());

        let gitignore_path = temp_dir.path().join(".gitignore");
        assert!(gitignore_path.exists());

        let content = fs::read_to_string(&gitignore_path).unwrap();
        assert!(content.contains("# AGPM managed directories"));
        assert!(content.contains(".claude/agpm/"));
    }

    #[tokio::test]
    async fn test_init_updates_existing_gitignore() {
        let temp_dir = TempDir::new().unwrap();
        let gitignore_path = temp_dir.path().join(".gitignore");

        // Create existing .gitignore with some content
        fs::write(&gitignore_path, "node_modules/\n*.log\n").unwrap();

        let cmd = InitCommand {
            path: Some(temp_dir.path().to_path_buf()),
            force: false,
        };

        let result = cmd.execute().await;
        assert!(result.is_ok());

        let content = fs::read_to_string(&gitignore_path).unwrap();
        // Should preserve existing content
        assert!(content.contains("node_modules/"));
        assert!(content.contains("*.log"));
        // Should add AGPM entries
        assert!(content.contains("# AGPM managed directories"));
        assert!(content.contains(".claude/agpm/"));
    }

    #[tokio::test]
    async fn test_init_does_not_duplicate_gitignore_entries() {
        let temp_dir = TempDir::new().unwrap();

        // First init
        let cmd = InitCommand {
            path: Some(temp_dir.path().to_path_buf()),
            force: false,
        };
        let result = cmd.execute().await;
        assert!(result.is_ok());

        let gitignore_path = temp_dir.path().join(".gitignore");
        let first_content = fs::read_to_string(&gitignore_path).unwrap();

        // Second init with force
        let cmd = InitCommand {
            path: Some(temp_dir.path().to_path_buf()),
            force: true,
        };
        let result = cmd.execute().await;
        assert!(result.is_ok());

        let second_content = fs::read_to_string(&gitignore_path).unwrap();

        // Should not have duplicated the AGPM section
        assert_eq!(
            first_content.matches("# AGPM managed directories").count(),
            second_content.matches("# AGPM managed directories").count()
        );
    }
}