cargocrypt 0.2.0

Zero-config cryptographic operations for Rust projects with HIVE MIND collective intelligence
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
//! Git repository management for CargoCrypt
//! 
//! This module provides the GitRepo struct which handles all git repository
//! operations including initialization, file staging, and CargoCrypt configuration.

use git2::{Repository, Status, StatusOptions, Signature, Oid};
use std::path::{Path, PathBuf};
use tokio::fs;
use thiserror::Error;

/// Errors specific to GitRepo operations
#[derive(Error, Debug)]
pub enum GitRepoError {
    #[error("Repository operation failed: {0}")]
    Operation(#[from] git2::Error),
    
    #[error("File system operation failed: {0}")]
    FileSystem(#[from] std::io::Error),
    
    #[error("Path does not exist: {}", .0.display())]
    PathNotFound(PathBuf),
    
    #[error("Invalid repository state: {0}")]
    InvalidState(String),
}

pub type GitRepoResult<T> = Result<T, GitRepoError>;

/// Git repository wrapper with CargoCrypt-specific functionality
pub struct GitRepo {
    repo: Repository,
    workdir: PathBuf,
}

impl Clone for GitRepo {
    fn clone(&self) -> Self {
        // Re-open the repository from the working directory
        let repo = Repository::open(&self.workdir).expect("Failed to re-open repository");
        Self {
            repo,
            workdir: self.workdir.clone(),
        }
    }
}

impl std::fmt::Debug for GitRepo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GitRepo")
            .field("workdir", &self.workdir)
            .finish()
    }
}

impl GitRepo {
    /// Open an existing git repository
    pub fn open<P: AsRef<Path>>(path: P) -> GitRepoResult<Self> {
        let repo = Repository::open(path)?;
        let workdir = repo.workdir()
            .ok_or_else(|| GitRepoError::InvalidState("Bare repository not supported".to_string()))?
            .to_path_buf();
        
        Ok(Self { repo, workdir })
    }
    
    /// Create a new git repository
    pub fn init<P: AsRef<Path>>(path: P) -> GitRepoResult<Self> {
        let repo = Repository::init(path)?;
        let workdir = repo.workdir()
            .ok_or_else(|| GitRepoError::InvalidState("Failed to get workdir".to_string()))?
            .to_path_buf();
        
        Ok(Self { repo, workdir })
    }
    
    /// Find existing repository or create a new one
    pub async fn find_or_create() -> GitRepoResult<Self> {
        Self::find_or_create_in(".").await
    }
    
    /// Find existing repository or create a new one in the specified directory
    pub async fn find_or_create_in<P: AsRef<Path>>(path: P) -> GitRepoResult<Self> {
        let path = path.as_ref();
        
        // Try to discover existing repository
        match Repository::discover(path) {
            Ok(repo) => {
                let workdir = repo.workdir()
                    .ok_or_else(|| GitRepoError::InvalidState("Bare repository not supported".to_string()))?
                    .to_path_buf();
                Ok(Self { repo, workdir })
            }
            Err(_) => {
                // Create new repository
                Self::init(path)
            }
        }
    }
    
    /// Open existing repository or create new one
    pub async fn open_or_create<P: AsRef<Path>>(path: P) -> GitRepoResult<Self> {
        let path = path.as_ref();
        
        match Self::open(path) {
            Ok(repo) => Ok(repo),
            Err(_) => Self::init(path),
        }
    }
    
    /// Get the repository path
    pub fn path(&self) -> &Path {
        self.repo.path()
    }
    
    /// Get the working directory path
    pub fn workdir(&self) -> &Path {
        &self.workdir
    }
    
    /// Get the .git directory path
    pub fn git_dir(&self) -> &Path {
        self.repo.path()
    }
    
    /// Check if CargoCrypt configuration exists
    pub fn has_cargocrypt_config(&self) -> bool {
        self.workdir.join(".cargocrypt").exists() ||
        self.workdir.join("Cargo.toml").exists() // Check if it's a Rust project
    }
    
    /// Stage a file for commit
    pub async fn stage_file<P: AsRef<Path>>(&self, path: P) -> GitRepoResult<()> {
        let path = path.as_ref();
        let relative_path = self.make_relative_path(path)?;
        
        let mut index = self.repo.index()?;
        index.add_path(&relative_path)?;
        index.write()?;
        
        Ok(())
    }
    
    /// Unstage a file
    pub async fn unstage_file<P: AsRef<Path>>(&self, path: P) -> GitRepoResult<()> {
        let path = path.as_ref();
        let relative_path = self.make_relative_path(path)?;
        
        // Reset the file to HEAD
        let head = self.repo.head()?.target().unwrap();
        let head_commit = self.repo.find_commit(head)?;
        let head_tree = head_commit.tree()?;
        
        let mut index = self.repo.index()?;
        
        // Check if file exists in HEAD
        match head_tree.get_path(&relative_path) {
            Ok(_) => {
                // File exists in HEAD, reset to that version
                // We'll just remove it from index and re-add from working directory
                index.remove_path(&relative_path)?;
                // Check if file exists in working directory
                let workdir = self.repo.workdir().ok_or_else(|| 
                    GitRepoError::InvalidState("No working directory found".to_string()))?;
                let full_path = workdir.join(&relative_path);
                if full_path.exists() {
                    index.add_path(&relative_path)?;
                }
            }
            Err(_) => {
                // File doesn't exist in HEAD, remove from index
                index.remove_path(&relative_path)?;
            }
        }
        
        index.write()?;
        Ok(())
    }
    
    /// Check if a file is staged
    pub async fn is_staged<P: AsRef<Path>>(&self, path: P) -> GitRepoResult<bool> {
        let path = path.as_ref();
        let relative_path = self.make_relative_path(path)?;
        
        let statuses = self.repo.statuses(None)?;
        
        for entry in statuses.iter() {
            if entry.path() == Some(relative_path.to_str().unwrap()) {
                return Ok(entry.status().intersects(
                    Status::INDEX_NEW | Status::INDEX_MODIFIED | Status::INDEX_DELETED
                ));
            }
        }
        
        Ok(false)
    }
    
    /// Get file status
    pub async fn file_status<P: AsRef<Path>>(&self, path: P) -> GitRepoResult<Status> {
        let path = path.as_ref();
        let relative_path = self.make_relative_path(path)?;
        
        Ok(self.repo.status_file(&relative_path)?)
    }
    
    /// Check if the repository is clean (no uncommitted changes)
    pub fn is_clean(&self) -> GitRepoResult<bool> {
        let statuses = self.repo.statuses(None)?;
        Ok(statuses.is_empty())
    }
    
    /// Get list of modified files
    pub fn get_modified_files(&self) -> GitRepoResult<Vec<PathBuf>> {
        let mut modified = Vec::new();
        let statuses = self.repo.statuses(None)?;
        
        for entry in statuses.iter() {
            if let Some(path) = entry.path() {
                if entry.status().intersects(
                    Status::WT_MODIFIED | Status::WT_NEW | Status::WT_DELETED |
                    Status::INDEX_MODIFIED | Status::INDEX_NEW | Status::INDEX_DELETED
                ) {
                    modified.push(PathBuf::from(path));
                }
            }
        }
        
        Ok(modified)
    }
    
    /// Create a commit with the staged changes
    pub async fn commit(&self, message: &str) -> GitRepoResult<Oid> {
        let signature = self.get_signature()?;
        let mut index = self.repo.index()?;
        let tree_id = index.write_tree()?;
        let tree = self.repo.find_tree(tree_id)?;
        
        // Get parent commit if it exists
        let parent_commit = match self.repo.head() {
            Ok(head) => Some(self.repo.find_commit(head.target().unwrap())?),
            Err(_) => None, // First commit
        };
        
        let parents: Vec<&git2::Commit> = parent_commit.iter().collect();
        
        let commit_id = self.repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            message,
            &tree,
            &parents,
        )?;
        
        Ok(commit_id)
    }
    
    /// Add all CargoCrypt-related files and commit
    pub async fn commit_cargocrypt_setup(&self) -> GitRepoResult<Oid> {
        // Stage CargoCrypt configuration files
        let config_files = [
            ".gitignore",
            ".gitattributes",
            ".cargocrypt/config.toml",
            ".githooks/pre-commit",
            ".githooks/pre-push",
        ];
        
        for file in &config_files {
            let path = self.workdir.join(file);
            if path.exists() {
                self.stage_file(&path).await?;
            }
        }
        
        self.commit("feat: Initialize CargoCrypt git integration\n\n- Add .gitignore patterns for encrypted files\n- Configure git attributes for automatic encryption\n- Install git hooks for secret detection\n- Set up encrypted storage and team key sharing").await
    }
    
    /// Get git signature for commits
    fn get_signature(&self) -> GitRepoResult<Signature> {
        // Try to get from git config first
        self.repo.signature()
            .or_else(|_| {
                // Fallback to CargoCrypt defaults
                Signature::now("CargoCrypt", "cargocrypt@localhost")
            })
            .map_err(GitRepoError::Operation)
    }
    
    /// Convert absolute path to relative path from repository root
    fn make_relative_path<P: AsRef<Path>>(&self, path: P) -> GitRepoResult<PathBuf> {
        let path = path.as_ref();
        
        if path.is_absolute() {
            path.strip_prefix(&self.workdir)
                .map(|p| p.to_path_buf())
                .map_err(|_| GitRepoError::InvalidState(
                    format!("Path {} is not within repository", path.display())
                ))
        } else {
            Ok(path.to_path_buf())
        }
    }
    
    /// Create a branch for CargoCrypt operations
    pub async fn create_cargocrypt_branch(&self, branch_name: &str) -> GitRepoResult<()> {
        let head = self.repo.head()?;
        let head_commit = self.repo.find_commit(head.target().unwrap())?;
        
        self.repo.branch(branch_name, &head_commit, false)?;
        Ok(())
    }
    
    /// Switch to a branch
    pub async fn checkout_branch(&self, branch_name: &str) -> GitRepoResult<()> {
        let (object, reference) = self.repo.revparse_ext(branch_name)?;
        
        self.repo.checkout_tree(&object, None)?;
        
        match reference {
            Some(gref) => self.repo.set_head(gref.name().unwrap()),
            None => self.repo.set_head_detached(object.id()),
        }?;
        
        Ok(())
    }
    
    /// Get current branch name
    pub fn current_branch(&self) -> GitRepoResult<String> {
        let head = self.repo.head()?;
        
        if let Some(name) = head.shorthand() {
            Ok(name.to_string())
        } else {
            Ok("HEAD".to_string()) // Detached HEAD
        }
    }
    
    /// Check if working directory is dirty
    pub fn is_dirty(&self) -> GitRepoResult<bool> {
        let mut opts = StatusOptions::new();
        opts.include_untracked(true);
        
        let statuses = self.repo.statuses(Some(&mut opts))?;
        Ok(!statuses.is_empty())
    }
    
    /// Get the underlying git2::Repository
    pub fn inner(&self) -> &Repository {
        &self.repo
    }
    
    /// Initialize .cargocrypt directory structure
    pub async fn init_cargocrypt_structure(&self) -> GitRepoResult<()> {
        let base_dir = self.workdir.join(".cargocrypt");
        
        // Create directory structure
        fs::create_dir_all(&base_dir).await?;
        fs::create_dir_all(base_dir.join("keys")).await?;
        fs::create_dir_all(base_dir.join("team")).await?;
        fs::create_dir_all(base_dir.join("hooks")).await?;
        
        // Create basic config file
        let config_content = r#"# CargoCrypt Configuration
[encryption]
algorithm = "ChaCha20-Poly1305"
key_derivation = "Argon2id"

[git]
auto_encrypt_patterns = ["*.secret", "*.key", "secrets/*"]
ignore_patterns = ["*.cargocrypt", "*.enc"]

[team]
key_sharing_enabled = true
require_signature = true

[hooks]
pre_commit_secret_detection = true
pre_push_validation = true
"#;
        
        fs::write(base_dir.join("config.toml"), config_content).await?;
        
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;
    use std::fs::File;
    use std::io::Write;
    
    #[tokio::test]
    async fn test_git_repo_creation() {
        let temp_dir = TempDir::new().unwrap();
        let repo = GitRepo::init(temp_dir.path()).unwrap();
        
        assert!(repo.path().exists());
        assert!(repo.workdir().exists());
    }
    
    #[tokio::test]
    async fn test_find_or_create() {
        let temp_dir = TempDir::new().unwrap();
        
        // Should create new repo
        let repo1 = GitRepo::find_or_create_in(temp_dir.path()).await.unwrap();
        assert!(repo1.path().exists());
        
        // Should find existing repo
        let repo2 = GitRepo::find_or_create_in(temp_dir.path()).await.unwrap();
        assert_eq!(repo1.path(), repo2.path());
    }
    
    #[tokio::test]
    async fn test_file_staging() {
        let temp_dir = TempDir::new().unwrap();
        let repo = GitRepo::init(temp_dir.path()).unwrap();
        
        // Create a test file
        let test_file = temp_dir.path().join("test.txt");
        let mut file = File::create(&test_file).unwrap();
        writeln!(file, "test content").unwrap();
        
        // Stage the file
        repo.stage_file(&test_file).await.unwrap();
        
        // Check if staged
        assert!(repo.is_staged(&test_file).await.unwrap());
    }
    
    #[tokio::test]
    async fn test_cargocrypt_structure_init() {
        let temp_dir = TempDir::new().unwrap();
        let repo = GitRepo::init(temp_dir.path()).unwrap();
        
        repo.init_cargocrypt_structure().await.unwrap();
        
        let cargocrypt_dir = temp_dir.path().join(".cargocrypt");
        assert!(cargocrypt_dir.exists());
        assert!(cargocrypt_dir.join("config.toml").exists());
        assert!(cargocrypt_dir.join("keys").exists());
        assert!(cargocrypt_dir.join("team").exists());
    }
    
    #[tokio::test]
    async fn test_commit_creation() {
        let temp_dir = TempDir::new().unwrap();
        let repo = GitRepo::init(temp_dir.path()).unwrap();
        
        // Create and stage a file
        let test_file = temp_dir.path().join("test.txt");
        let mut file = File::create(&test_file).unwrap();
        writeln!(file, "test content").unwrap();
        
        repo.stage_file(&test_file).await.unwrap();
        
        // Create commit
        let commit_id = repo.commit("Initial commit").await.unwrap();
        assert!(!commit_id.is_zero());
    }
}