tsk-ai 0.10.8

tsk-tsk: keeping your agents out of trouble with sandboxed coding agent automation
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
use anyhow::{Context, Result};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use tempfile::TempDir;

/// A test utility that creates and manages a temporary git repository for testing.
///
/// This struct provides methods for common git operations needed in tests,
/// automatically cleans up on drop, and ensures tests have isolated git repositories.
pub struct TestGitRepository {
    /// The temporary directory that contains the repository.
    /// This field is not accessed directly but must be kept to ensure the
    /// directory isn't deleted while the TestGitRepository is still in use.
    /// When this struct is dropped, the TempDir will be dropped and cleaned up.
    #[allow(dead_code)]
    temp_dir: TempDir,
    repo_path: PathBuf,
}

/// A wrapper for an existing git repository path that doesn't manage its lifecycle.
/// Used for working with submodules or copies of repositories within tests.
pub struct ExistingGitRepository {
    repo_path: PathBuf,
}

impl ExistingGitRepository {
    /// Wraps an existing git repository path.
    pub fn new(path: &Path) -> Result<Self> {
        if !path.exists() {
            anyhow::bail!("Repository path does not exist: {}", path.display());
        }
        Ok(Self {
            repo_path: path.to_path_buf(),
        })
    }

    /// Configures git user identity for testing.
    /// This is needed in CI environments where global git config is not set.
    pub fn configure_test_user(&self) -> Result<()> {
        self.run_git_command(&["config", "user.email", "test@example.com"])?;
        self.run_git_command(&["config", "user.name", "Test User"])?;
        Ok(())
    }

    /// Stages all changes in the repository.
    pub fn stage_all(&self) -> Result<()> {
        self.run_git_command(&["add", "-A"])
            .context("Failed to stage files")?;
        Ok(())
    }

    /// Creates a commit with the given message.
    /// Returns the commit SHA.
    pub fn commit(&self, message: &str) -> Result<String> {
        self.run_git_command(&["commit", "-m", message])
            .context("Failed to create commit")?;

        self.get_current_commit()
    }

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

        Ok(output.trim().to_string())
    }

    /// Runs a git command in the repository directory.
    pub fn run_git_command(&self, args: &[&str]) -> Result<String> {
        let output = Command::new("git")
            .args(args)
            .current_dir(&self.repo_path)
            .output()
            .context("Failed to execute git command")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("Git command failed: {}", stderr);
        }

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

impl TestGitRepository {
    /// Creates a new temporary directory for testing.
    /// Does not initialize git repository - call `init()` or `init_with_commit()` for that.
    pub fn new() -> Result<Self> {
        let temp_dir = TempDir::new().context("Failed to create temp dir")?;
        let repo_path = temp_dir.path().to_path_buf();

        Ok(Self {
            temp_dir,
            repo_path,
        })
    }

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

    /// Initializes a new git repository without any commits.
    pub fn init(&self) -> Result<()> {
        self.run_git_command(&["init"])
            .context("Failed to initialize git repository")?;

        // Set local git config to avoid using global config
        self.run_git_command(&["config", "user.email", "test@example.com"])?;
        self.run_git_command(&["config", "user.name", "Test User"])?;

        Ok(())
    }

    /// Initializes a new git repository with an initial commit.
    /// Returns the commit SHA of the initial commit.
    pub fn init_with_commit(&self) -> Result<String> {
        self.init()?;

        // Create an initial file
        self.create_file("README.md", "# Test Repository\n")?;
        self.stage_all()?;
        self.commit("Initial commit")
    }

    /// Creates a file in the repository with the given content.
    pub fn create_file(&self, path: &str, content: &str) -> Result<()> {
        let file_path = self.repo_path.join(path);

        // Create parent directories if needed
        if let Some(parent) = file_path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create parent directories for {path}"))?;
        }

        fs::write(&file_path, content).with_context(|| format!("Failed to write file {path}"))?;

        Ok(())
    }

    /// Reads a file from the repository.
    pub fn read_file(&self, path: &str) -> Result<String> {
        let file_path = self.repo_path.join(path);
        fs::read_to_string(&file_path).with_context(|| format!("Failed to read file {path}"))
    }

    /// Stages all changes in the repository.
    pub fn stage_all(&self) -> Result<()> {
        self.run_git_command(&["add", "-A"])
            .context("Failed to stage files")?;
        Ok(())
    }

    /// Creates a commit with the given message.
    /// Returns the commit SHA.
    pub fn commit(&self, message: &str) -> Result<String> {
        self.run_git_command(&["commit", "-m", message])
            .context("Failed to create commit")?;

        self.get_current_commit()
    }

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

        Ok(output.trim().to_string())
    }

    /// Gets the SHA of the HEAD commit (alias for get_current_commit).
    pub fn get_head_commit(&self) -> Result<String> {
        self.get_current_commit()
    }

    /// Gets the name of the current branch.
    pub fn current_branch(&self) -> Result<String> {
        let output = self
            .run_git_command(&["branch", "--show-current"])
            .context("Failed to get current branch")?;

        Ok(output.trim().to_string())
    }

    /// Creates and checks out a new branch.
    pub fn checkout_new_branch(&self, branch_name: &str) -> Result<()> {
        self.run_git_command(&["checkout", "-b", branch_name])
            .context("Failed to create and checkout new branch")?;
        Ok(())
    }

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

    /// Gets the git status output.
    pub fn status(&self) -> Result<String> {
        self.run_git_command(&["status", "--porcelain"])
            .context("Failed to get git status")
    }

    /// Gets list of all branches.
    pub fn branches(&self) -> Result<Vec<String>> {
        let output = self
            .run_git_command(&["branch", "--format=%(refname:short)"])
            .context("Failed to list branches")?;

        Ok(output
            .lines()
            .map(|line| line.trim().to_string())
            .filter(|line| !line.is_empty())
            .collect())
    }

    /// Sets up a repository with uncommitted changes.
    /// Creates both staged and unstaged files.
    pub fn setup_with_uncommitted_changes(&self) -> Result<()> {
        self.init_with_commit()?;

        // Create an unstaged file
        self.create_file("unstaged.txt", "This file is not staged\n")?;

        // Create and stage a file
        self.create_file("staged.txt", "This file is staged\n")?;
        self.run_git_command(&["add", "staged.txt"])?;

        // Modify the README (which was committed earlier)
        self.create_file("README.md", "# Test Repository\n\nModified content\n")?;

        Ok(())
    }

    /// Sets up a repository with multiple branches.
    pub fn setup_with_branches(&self, branches: Vec<&str>) -> Result<()> {
        self.init_with_commit()?;

        let main_branch = self.current_branch()?;

        for branch in branches {
            self.checkout_new_branch(branch)?;
            self.create_file(&format!("{branch}.txt"), &format!("Content for {branch}\n"))?;
            self.stage_all()?;
            self.commit(&format!("Add {branch}.txt"))?;
            self.checkout_branch(&main_branch)?;
        }

        Ok(())
    }

    /// Creates a regular directory without git initialization.
    pub fn setup_non_git_directory(&self) -> Result<()> {
        // Just create a file to ensure the directory exists
        self.create_file("file.txt", "Not a git repository\n")?;
        Ok(())
    }

    /// Initialize repo with "main" as default branch, a README, and an initial commit.
    /// Combines init() + defaultBranch config + checkout -b main + README + commit.
    /// Returns the initial commit SHA.
    pub fn init_with_main_branch(&self) -> Result<String> {
        self.init()?;
        self.run_git_command(&["config", "init.defaultBranch", "main"])?;
        self.run_git_command(&["checkout", "-b", "main"])?;
        self.create_file("README.md", "# Test Repository\n")?;
        self.stage_all()?;
        self.commit("Initial commit")
    }

    /// Set up this repo as a task clone of another repo, tracking its current branch.
    /// Initializes, adds the source as origin, fetches, and checks out its current branch.
    /// Returns the current commit SHA.
    pub fn clone_from(&self, source: &TestGitRepository) -> Result<String> {
        self.init()?;
        self.run_git_command(&[
            "remote",
            "add",
            "origin",
            source
                .path()
                .to_str()
                .ok_or_else(|| anyhow::anyhow!("Invalid source path"))?,
        ])?;
        self.run_git_command(&["fetch", "origin"])?;
        let branch = source.current_branch()?;
        self.run_git_command(&["checkout", "-b", &branch, &format!("origin/{branch}")])?;
        self.get_current_commit()
    }

    /// Add another repository as a git submodule at the given path.
    pub fn add_submodule(&self, source: &TestGitRepository, path: &str) -> Result<()> {
        self.run_git_command(&[
            "-c",
            "protocol.file.allow=always",
            "submodule",
            "add",
            source
                .path()
                .to_str()
                .ok_or_else(|| anyhow::anyhow!("Invalid source path"))?,
            path,
        ])?;
        Ok(())
    }

    /// Runs a git command in the repository directory.
    pub fn run_git_command(&self, args: &[&str]) -> Result<String> {
        let output = Command::new("git")
            .args(args)
            .current_dir(&self.repo_path)
            .output()
            .context("Failed to execute git command")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("Git command failed: {}", stderr);
        }

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

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

    #[test]
    fn test_create_repository() -> Result<()> {
        let repo = TestGitRepository::new()?;
        repo.init()?;

        assert!(repo.path().exists());
        assert!(repo.path().join(".git").exists());

        Ok(())
    }

    #[test]
    fn test_init_with_commit() -> Result<()> {
        let repo = TestGitRepository::new()?;
        let commit_sha = repo.init_with_commit()?;

        assert!(!commit_sha.is_empty());
        assert_eq!(commit_sha.len(), 40); // Git SHA-1 is 40 characters

        let readme_content = repo.read_file("README.md")?;
        assert_eq!(readme_content, "# Test Repository\n");

        Ok(())
    }

    #[test]
    fn test_create_and_commit_file() -> Result<()> {
        let repo = TestGitRepository::new()?;
        repo.init()?;

        repo.create_file("test.txt", "Hello, World!")?;
        repo.stage_all()?;
        let commit_sha = repo.commit("Add test file")?;

        assert!(!commit_sha.is_empty());

        let content = repo.read_file("test.txt")?;
        assert_eq!(content, "Hello, World!");

        Ok(())
    }

    #[test]
    fn test_branch_operations() -> Result<()> {
        let repo = TestGitRepository::new()?;
        repo.init_with_commit()?;

        let initial_branch = repo.current_branch()?;
        assert!(initial_branch == "main" || initial_branch == "master");

        repo.checkout_new_branch("feature")?;
        assert_eq!(repo.current_branch()?, "feature");

        repo.checkout_branch(&initial_branch)?;
        assert_eq!(repo.current_branch()?, initial_branch);

        Ok(())
    }

    #[test]
    fn test_setup_with_uncommitted_changes() -> Result<()> {
        let repo = TestGitRepository::new()?;
        repo.setup_with_uncommitted_changes()?;

        let status = repo.status()?;
        assert!(status.contains("unstaged.txt"));
        assert!(status.contains("staged.txt"));
        assert!(status.contains("README.md"));

        Ok(())
    }

    #[test]
    fn test_setup_with_branches() -> Result<()> {
        let repo = TestGitRepository::new()?;
        repo.setup_with_branches(vec!["feature", "bugfix", "develop"])?;

        let branches = repo.branches()?;
        assert!(branches.iter().any(|b| b == "feature"));
        assert!(branches.iter().any(|b| b == "bugfix"));
        assert!(branches.iter().any(|b| b == "develop"));

        Ok(())
    }
}