agpm-cli 0.4.4

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
508
509
510
511
512
513
514
515
//! Common test utilities and fixtures for AGPM integration tests
//!
//! This module consolidates frequently used test patterns to reduce duplication
//! and improve test maintainability.

// Allow dead code because these utilities are used across different test files
// and not all utilities are used in every test file
#![allow(dead_code)]

use anyhow::{Context, Result, bail};
use std::path::{Path, PathBuf};
use std::process::Command;
use tempfile::TempDir;
use tokio::fs;

/// Git command builder for tests
pub struct TestGit {
    repo_path: PathBuf,
}

impl TestGit {
    fn run_git_command(&self, args: &[&str], action: &str) -> Result<std::process::Output> {
        let output = Command::new("git")
            .args(args)
            .current_dir(&self.repo_path)
            .output()
            .with_context(|| action.to_string())?;

        if !output.status.success() {
            bail!("{} failed: {}", action, String::from_utf8_lossy(&output.stderr));
        }

        Ok(output)
    }

    /// Create a new TestGit instance for the given repository path
    pub fn new(repo_path: impl Into<PathBuf>) -> Self {
        Self {
            repo_path: repo_path.into(),
        }
    }

    /// Initialize a new git repository
    pub fn init(&self) -> Result<()> {
        self.run_git_command(&["init"], "Failed to initialize git repository")?;
        Ok(())
    }

    /// Configure git user for tests
    pub fn config_user(&self) -> Result<()> {
        self.run_git_command(
            &["config", "user.email", "test@agpm.example"],
            "Failed to configure git user email",
        )?;

        self.run_git_command(
            &["config", "user.name", "Test User"],
            "Failed to configure git user name",
        )?;
        Ok(())
    }

    /// Add all files to staging
    pub fn add_all(&self) -> Result<()> {
        self.run_git_command(&["add", "."], "Failed to add files to git")?;
        Ok(())
    }

    /// Create a commit with the given message
    pub fn commit(&self, message: &str) -> Result<()> {
        self.run_git_command(&["commit", "-m", message], "Failed to create git commit")?;
        Ok(())
    }

    /// Create a tag
    pub fn tag(&self, tag_name: &str) -> Result<()> {
        self.run_git_command(&["tag", tag_name], &format!("Failed to create tag: {}", tag_name))?;
        Ok(())
    }

    /// Create and checkout a branch
    pub fn create_branch(&self, branch_name: &str) -> Result<()> {
        self.run_git_command(
            &["checkout", "-b", branch_name],
            &format!("Failed to create branch: {}", branch_name),
        )?;
        Ok(())
    }

    /// Checkout an existing branch
    pub fn checkout(&self, branch_name: &str) -> Result<()> {
        self.run_git_command(
            &["checkout", branch_name],
            &format!("Failed to checkout branch: {}", branch_name),
        )?;
        Ok(())
    }

    /// Ensure we're on a specific branch, creating it if it doesn't exist
    /// This is useful when the default branch name is unknown (master vs main)
    pub fn ensure_branch(&self, branch_name: &str) -> Result<()> {
        // Try to checkout the branch first
        if self.checkout(branch_name).is_ok() {
            return Ok(());
        }

        // Branch doesn't exist, create it from current HEAD
        self.create_branch(branch_name)?;
        Ok(())
    }

    /// Set the HEAD to point to a branch (making it the default branch)
    pub fn set_head(&self, branch_name: &str) -> Result<()> {
        self.run_git_command(
            &["symbolic-ref", "HEAD", &format!("refs/heads/{}", branch_name)],
            &format!("Failed to set HEAD to branch: {}", branch_name),
        )?;
        Ok(())
    }

    /// Get the current commit hash
    pub fn get_commit_hash(&self) -> Result<String> {
        let output = self.run_git_command(&["rev-parse", "HEAD"], "Failed to get commit hash")?;

        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    /// Get the HEAD SHA (alias for get_commit_hash for compatibility)
    pub fn get_head_sha(&self) -> Result<String> {
        self.get_commit_hash()
    }

    /// Clone current repository to a bare repository
    pub fn clone_to_bare(&self, target_path: &Path) -> Result<()> {
        let output = Command::new("git")
            .args([
                "clone",
                "--bare",
                self.repo_path.to_str().unwrap(),
                target_path.to_str().unwrap(),
            ])
            .output()
            .context("Failed to create bare repository")?;
        if !output.status.success() {
            bail!("Failed to create bare repository: {}", String::from_utf8_lossy(&output.stderr));
        }
        Ok(())
    }

    /// Return the repository path
    pub fn repo_path(&self) -> &Path {
        &self.repo_path
    }

    /// Get porcelain status output
    pub fn status_porcelain(&self) -> Result<String> {
        let output =
            self.run_git_command(&["status", "--porcelain"], "Failed to get git status")?;
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Check if path is ignored by git
    pub fn check_ignore(&self, path: &str) -> Result<bool> {
        let output = Command::new("git")
            .args(["check-ignore", path])
            .current_dir(&self.repo_path)
            .output()
            .with_context(|| format!("Failed to run git check-ignore for {}", path))?;

        Ok(output.status.success())
    }
}

/// Test project builder for creating test environments
pub struct TestProject {
    _temp_dir: TempDir, // Keep alive for RAII cleanup
    project_dir: PathBuf,
    cache_dir: PathBuf,
    sources_dir: PathBuf,
}

impl TestProject {
    /// Create a new test project with default structure
    pub async fn new() -> Result<Self> {
        let temp_dir = TempDir::new()?;
        let project_dir = temp_dir.path().join("project");
        let cache_dir = temp_dir.path().join(".agpm").join("cache");
        let sources_dir = temp_dir.path().join("sources");

        fs::create_dir_all(&project_dir).await?;
        fs::create_dir_all(&cache_dir).await?;
        fs::create_dir_all(&sources_dir).await?;

        Ok(Self {
            _temp_dir: temp_dir,
            project_dir,
            cache_dir,
            sources_dir,
        })
    }

    /// Get the project directory path
    pub fn project_path(&self) -> &Path {
        &self.project_dir
    }

    /// Get the cache directory path
    pub fn cache_path(&self) -> &Path {
        &self.cache_dir
    }

    /// Get the sources directory path
    pub fn sources_path(&self) -> &Path {
        &self.sources_dir
    }

    /// Write a manifest file to the project directory
    pub async fn write_manifest(&self, content: &str) -> Result<()> {
        let manifest_path = self.project_dir.join("agpm.toml");
        fs::write(&manifest_path, content)
            .await
            .with_context(|| format!("Failed to write manifest to {:?}", manifest_path))?;
        Ok(())
    }

    /// Write a lockfile to the project directory
    pub async fn write_lockfile(&self, content: &str) -> Result<()> {
        let lockfile_path = self.project_dir.join("agpm.lock");
        fs::write(&lockfile_path, content)
            .await
            .with_context(|| format!("Failed to write lockfile to {:?}", lockfile_path))?;
        Ok(())
    }

    /// Read the lockfile from the project directory
    pub async fn read_lockfile(&self) -> Result<String> {
        let lockfile_path = self.project_dir.join("agpm.lock");
        fs::read_to_string(&lockfile_path)
            .await
            .with_context(|| format!("Failed to read lockfile from {:?}", lockfile_path))
    }

    /// Create a local resource file
    pub async fn create_local_resource(&self, path: &str, content: &str) -> Result<()> {
        let resource_path = self.project_dir.join(path);
        if let Some(parent) = resource_path.parent() {
            fs::create_dir_all(parent).await?;
        }
        fs::write(&resource_path, content).await?;
        Ok(())
    }

    /// Initialize a git repository inside the project directory
    pub fn init_git_repo(&self) -> Result<TestGit> {
        let git = TestGit::new(self.project_dir.clone());
        git.init()?;
        git.config_user()?;
        Ok(git)
    }

    /// Create a source repository with the given name
    pub async fn create_source_repo(&self, name: &str) -> Result<TestSourceRepo> {
        let source_dir = self.sources_dir.join(name);
        fs::create_dir_all(&source_dir).await?;

        let git = TestGit::new(&source_dir);
        git.init()?;
        git.config_user()?;

        Ok(TestSourceRepo {
            path: source_dir,
            git,
        })
    }

    /// Run a AGPM command in the project directory
    pub fn run_agpm(&self, args: &[&str]) -> Result<CommandOutput> {
        self.run_agpm_with_env(args, &[])
    }

    /// Run a AGPM command with custom environment variables
    pub fn run_agpm_with_env(
        &self,
        args: &[&str],
        env_vars: &[(&str, &str)],
    ) -> Result<CommandOutput> {
        let agpm_binary = env!("CARGO_BIN_EXE_agpm");
        let mut cmd = Command::new(agpm_binary);

        cmd.args(args)
            .current_dir(&self.project_dir)
            .env("AGPM_CACHE_DIR", &self.cache_dir)
            .env("AGPM_TEST_MODE", "true")
            .env("NO_COLOR", "1");

        // Add custom environment variables
        for (key, value) in env_vars {
            cmd.env(key, value);
        }

        let output = cmd.output().context("Failed to run agpm command")?;

        Ok(CommandOutput {
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            success: output.status.success(),
            code: output.status.code(),
        })
    }
}

/// Test source repository helper
pub struct TestSourceRepo {
    pub path: PathBuf,
    pub git: TestGit,
}

impl TestSourceRepo {
    /// Add a resource file to the repository
    pub async fn add_resource(&self, resource_type: &str, name: &str, content: &str) -> Result<()> {
        let resource_dir = self.path.join(resource_type);
        fs::create_dir_all(&resource_dir).await?;

        let file_path = resource_dir.join(format!("{}.md", name));
        fs::write(&file_path, content).await?;
        Ok(())
    }

    /// Create standard test resources
    pub async fn create_standard_resources(&self) -> Result<()> {
        self.add_resource("agents", "test-agent", "# Test Agent\n\nA test agent").await?;
        self.add_resource("snippets", "test-snippet", "# Test Snippet\n\nA test snippet").await?;
        self.add_resource("commands", "test-command", "# Test Command\n\nA test command").await?;
        Ok(())
    }

    /// Commit all changes with a message
    pub fn commit_all(&self, message: &str) -> Result<()> {
        self.git.add_all()?;
        self.git.commit(message)?;
        Ok(())
    }

    /// Create a version tag
    pub fn tag_version(&self, version: &str) -> Result<()> {
        self.git.tag(version)?;
        Ok(())
    }

    /// Get the file:// URL for this repository
    pub fn file_url(&self) -> String {
        let path_str = self.path.display().to_string().replace('\\', "/");
        format!("file://{}", path_str)
    }

    /// Clone this repository to a bare repository for reliable serving
    /// Returns the path to the new bare repository
    pub fn to_bare_repo(&self, target_path: &Path) -> Result<PathBuf> {
        let output = Command::new("git")
            .args(["clone", "--bare", self.path.to_str().unwrap(), target_path.to_str().unwrap()])
            .output()
            .context("Failed to create bare repository")?;

        if !output.status.success() {
            return Err(anyhow::anyhow!(
                "Failed to create bare repository: {}",
                String::from_utf8_lossy(&output.stderr)
            ));
        }

        // Verify the bare repository is ready by listing tags
        // This ensures git has finished writing all references
        let verify_output = Command::new("git")
            .args(["tag", "-l"])
            .current_dir(target_path)
            .output()
            .context("Failed to verify bare repository")?;

        if !verify_output.status.success() {
            return Err(anyhow::anyhow!(
                "Bare repository verification failed: {}",
                String::from_utf8_lossy(&verify_output.stderr)
            ));
        }

        Ok(target_path.to_path_buf())
    }

    /// Get a file:// URL for a bare clone of this repository
    /// Creates the bare repo in the parent's sources directory
    pub fn bare_file_url(&self, sources_dir: &Path) -> Result<String> {
        let bare_name =
            format!("{}.git", self.path.file_name().and_then(|n| n.to_str()).unwrap_or("repo"));
        let bare_path = sources_dir.join(bare_name);
        self.to_bare_repo(&bare_path)?;
        let path_str = bare_path.display().to_string().replace('\\', "/");
        Ok(format!("file://{}", path_str))
    }
}

/// Command output helper
pub struct CommandOutput {
    pub stdout: String,
    pub stderr: String,
    pub success: bool,
    pub code: Option<i32>,
}

impl CommandOutput {
    /// Assert the command succeeded
    pub fn assert_success(&self) -> &Self {
        assert!(self.success, "Command failed with code {:?}\nStderr: {}", self.code, self.stderr);
        self
    }

    /// Assert stdout contains the given text
    pub fn assert_stdout_contains(&self, text: &str) -> &Self {
        assert!(
            self.stdout.contains(text),
            "Expected stdout to contain '{}'\nActual stdout: {}",
            text,
            self.stdout
        );
        self
    }
}

/// File assertion helpers
pub struct FileAssert;

impl FileAssert {
    /// Assert a file exists
    pub async fn exists(path: impl AsRef<Path>) {
        let path = path.as_ref();
        let exists = fs::metadata(path).await.is_ok();
        assert!(exists, "Expected file to exist: {}", path.display());
    }

    /// Assert a file does not exist
    pub async fn not_exists(path: impl AsRef<Path>) {
        let path = path.as_ref();
        let exists = fs::metadata(path).await.is_ok();
        assert!(!exists, "Expected file to not exist: {}", path.display());
    }

    /// Assert a file contains specific content
    pub async fn contains(path: impl AsRef<Path>, expected: &str) {
        let path = path.as_ref();
        let content = fs::read_to_string(path)
            .await
            .unwrap_or_else(|e| panic!("Failed to read file {}: {}", path.display(), e));
        assert!(
            content.contains(expected),
            "Expected file {} to contain '{}'\nActual content: {}",
            path.display(),
            expected,
            content
        );
    }

    /// Assert a file has exact content
    pub async fn equals(path: impl AsRef<Path>, expected: &str) {
        let path = path.as_ref();
        let content = fs::read_to_string(path)
            .await
            .unwrap_or_else(|e| panic!("Failed to read file {}: {}", path.display(), e));
        assert_eq!(content, expected, "File {} content mismatch", path.display());
    }
}

/// Directory assertion helpers
pub struct DirAssert;

impl DirAssert {
    /// Assert a directory exists
    pub async fn exists(path: impl AsRef<Path>) {
        let path = path.as_ref();
        let metadata = fs::metadata(path).await;
        let is_dir = metadata.map(|m| m.is_dir()).unwrap_or(false);
        assert!(is_dir, "Expected directory to exist: {}", path.display());
    }

    /// Assert a directory contains a file
    pub async fn contains_file(dir: impl AsRef<Path>, file_name: &str) {
        let path = dir.as_ref().join(file_name);
        let exists = fs::metadata(&path).await.is_ok();
        assert!(
            exists,
            "Expected directory {} to contain file '{}'",
            dir.as_ref().display(),
            file_name
        );
    }

    /// Assert a directory is empty
    pub async fn is_empty(path: impl AsRef<Path>) {
        let path = path.as_ref();
        let mut read_dir = fs::read_dir(path)
            .await
            .unwrap_or_else(|e| panic!("Failed to read directory {}: {}", path.display(), e));

        let mut count = 0;
        while read_dir.next_entry().await.unwrap().is_some() {
            count += 1;
        }

        assert_eq!(
            count,
            0,
            "Expected directory {} to be empty, but it contains {} entries",
            path.display(),
            count
        );
    }
}