sal-git 0.1.0

SAL Git - Git repository management and operations
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
use regex::Regex;
use std::error::Error;
use std::fmt;
use std::fs;
use std::path::Path;
use std::process::Command;

// Define a custom error type for git operations
#[derive(Debug)]
pub enum GitError {
    GitNotInstalled(std::io::Error),
    InvalidUrl(String),
    InvalidBasePath(String),
    HomeDirectoryNotFound(std::env::VarError),
    FileSystemError(std::io::Error),
    GitCommandFailed(String),
    CommandExecutionError(std::io::Error),
    NoRepositoriesFound,
    RepositoryNotFound(String),
    MultipleRepositoriesFound(String, usize),
    NotAGitRepository(String),
    LocalChangesExist(String),
}

// Implement Display for GitError
impl fmt::Display for GitError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GitError::GitNotInstalled(e) => write!(f, "Git is not installed: {}", e),
            GitError::InvalidUrl(url) => write!(f, "Could not parse git URL: {}", url),
            GitError::InvalidBasePath(path) => write!(f, "Invalid base path: {}", path),
            GitError::HomeDirectoryNotFound(e) => write!(f, "Could not determine home directory: {}", e),
            GitError::FileSystemError(e) => write!(f, "Error creating directory structure: {}", e),
            GitError::GitCommandFailed(e) => write!(f, "{}", e),
            GitError::CommandExecutionError(e) => write!(f, "Error executing command: {}", e),
            GitError::NoRepositoriesFound => write!(f, "No repositories found"),
            GitError::RepositoryNotFound(pattern) => write!(f, "No repositories found matching '{}'", pattern),
            GitError::MultipleRepositoriesFound(pattern, count) =>
                write!(f, "Multiple repositories ({}) found matching '{}'. Use '*' suffix for multiple matches.", count, pattern),
            GitError::NotAGitRepository(path) => write!(f, "Not a git repository at {}", path),
            GitError::LocalChangesExist(path) => write!(f, "Repository at {} has local changes", path),
        }
    }
}

// Implement Error trait for GitError
impl Error for GitError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            GitError::GitNotInstalled(e) => Some(e),
            GitError::HomeDirectoryNotFound(e) => Some(e),
            GitError::FileSystemError(e) => Some(e),
            GitError::CommandExecutionError(e) => Some(e),
            _ => None,
        }
    }
}

/// Parses a git URL to extract the server, account, and repository name.
///
/// # Arguments
///
/// * `url` - The URL of the git repository to parse. Can be in HTTPS format
///   (https://github.com/username/repo.git) or SSH format (git@github.com:username/repo.git).
///
/// # Returns
///
/// A tuple containing:
/// * `server` - The server name (e.g., "github.com")
/// * `account` - The account or organization name (e.g., "username")
/// * `repo` - The repository name (e.g., "repo")
///
/// If the URL cannot be parsed, all three values will be empty strings.
pub fn parse_git_url(url: &str) -> (String, String, String) {
    // HTTP(S) URL format: https://github.com/username/repo.git
    let https_re = Regex::new(r"https?://([^/]+)/([^/]+)/([^/\.]+)(?:\.git)?").unwrap();

    // SSH URL format: git@github.com:username/repo.git
    let ssh_re = Regex::new(r"git@([^:]+):([^/]+)/([^/\.]+)(?:\.git)?").unwrap();

    if let Some(caps) = https_re.captures(url) {
        let server = caps.get(1).map_or("", |m| m.as_str()).to_string();
        let account = caps.get(2).map_or("", |m| m.as_str()).to_string();
        let repo = caps.get(3).map_or("", |m| m.as_str()).to_string();

        return (server, account, repo);
    } else if let Some(caps) = ssh_re.captures(url) {
        let server = caps.get(1).map_or("", |m| m.as_str()).to_string();
        let account = caps.get(2).map_or("", |m| m.as_str()).to_string();
        let repo = caps.get(3).map_or("", |m| m.as_str()).to_string();

        return (server, account, repo);
    }

    (String::new(), String::new(), String::new())
}

/// Checks if git is installed on the system.
///
/// # Returns
///
/// * `Ok(())` - If git is installed
/// * `Err(GitError)` - If git is not installed
fn check_git_installed() -> Result<(), GitError> {
    Command::new("git")
        .arg("--version")
        .output()
        .map_err(GitError::GitNotInstalled)?;
    Ok(())
}

/// Represents a collection of git repositories under a base path.
#[derive(Clone)]
pub struct GitTree {
    base_path: String,
}

impl GitTree {
    /// Creates a new GitTree with the specified base path.
    ///
    /// # Arguments
    ///
    /// * `base_path` - The base path where all git repositories are located
    ///
    /// # Returns
    ///
    /// * `Ok(GitTree)` - A new GitTree instance
    /// * `Err(GitError)` - If the base path is invalid or cannot be created
    pub fn new(base_path: &str) -> Result<Self, GitError> {
        // Check if git is installed
        check_git_installed()?;

        // Validate the base path
        let path = Path::new(base_path);
        if !path.exists() {
            fs::create_dir_all(path).map_err(|e| GitError::FileSystemError(e))?;
        } else if !path.is_dir() {
            return Err(GitError::InvalidBasePath(base_path.to_string()));
        }

        Ok(GitTree {
            base_path: base_path.to_string(),
        })
    }

    /// Lists all git repositories under the base path.
    ///
    /// # Returns
    ///
    /// * `Ok(Vec<String>)` - A vector of paths to git repositories
    /// * `Err(GitError)` - If the operation failed
    pub fn list(&self) -> Result<Vec<String>, GitError> {
        let base_path = Path::new(&self.base_path);

        if !base_path.exists() || !base_path.is_dir() {
            return Ok(Vec::new());
        }

        let mut repos = Vec::new();

        // Find all directories with .git subdirectories
        let output = Command::new("find")
            .args(&[&self.base_path, "-type", "d", "-name", ".git"])
            .output()
            .map_err(GitError::CommandExecutionError)?;

        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines() {
                // Get the parent directory of .git which is the repo root
                if let Some(parent) = Path::new(line).parent() {
                    if let Some(path_str) = parent.to_str() {
                        repos.push(path_str.to_string());
                    }
                }
            }
        } else {
            let error = String::from_utf8_lossy(&output.stderr);
            return Err(GitError::GitCommandFailed(format!(
                "Failed to find git repositories: {}",
                error
            )));
        }

        Ok(repos)
    }

    /// Finds repositories matching a pattern or partial path.
    ///
    /// # Arguments
    ///
    /// * `pattern` - The pattern to match against repository paths
    ///   - If the pattern ends with '*', all matching repositories are returned
    ///   - Otherwise, exactly one matching repository must be found
    ///
    /// # Returns
    ///
    /// * `Ok(Vec<String>)` - A vector of paths to matching repositories
    /// * `Err(GitError)` - If no matching repositories are found,
    ///   or if multiple repositories match a non-wildcard pattern
    pub fn find(&self, pattern: &str) -> Result<Vec<GitRepo>, GitError> {
        let repo_names = self.list()?; // list() already ensures these are git repo names

        if repo_names.is_empty() {
            return Ok(Vec::new()); // If no repos listed, find results in an empty list
        }

        let mut matched_repos: Vec<GitRepo> = Vec::new();

        if pattern == "*" {
            for name in repo_names {
                let full_path = format!("{}/{}", self.base_path, name);
                matched_repos.push(GitRepo::new(full_path));
            }
        } else if pattern.ends_with('*') {
            let prefix = &pattern[0..pattern.len() - 1];
            for name in repo_names {
                if name.starts_with(prefix) {
                    let full_path = format!("{}/{}", self.base_path, name);
                    matched_repos.push(GitRepo::new(full_path));
                }
            }
        } else {
            // Exact match for the name
            for name in repo_names {
                if name == pattern {
                    let full_path = format!("{}/{}", self.base_path, name);
                    matched_repos.push(GitRepo::new(full_path));
                    // `find` returns all exact matches. If names aren't unique (unlikely from `list`),
                    // it could return more than one. For an exact name, typically one is expected.
                }
            }
        }

        Ok(matched_repos)
    }

    /// Gets one or more GitRepo objects based on a path pattern or URL.
    ///
    /// # Arguments
    ///
    /// * `path_or_url` - The path pattern to match against repository paths or a git URL
    ///   - If it's a URL, the repository will be cloned if it doesn't exist
    ///   - If it's a path pattern, it will find matching repositories
    ///
    /// # Returns
    ///
    /// * `Ok(Vec<GitRepo>)` - A vector of GitRepo objects
    /// * `Err(GitError)` - If no matching repositories are found or the clone operation failed
    pub fn get(&self, path_or_url: &str) -> Result<Vec<GitRepo>, GitError> {
        // Check if it's a URL
        if path_or_url.starts_with("http") || path_or_url.starts_with("git@") {
            // Parse the URL
            let (server, account, repo) = parse_git_url(path_or_url);
            if server.is_empty() || account.is_empty() || repo.is_empty() {
                return Err(GitError::InvalidUrl(path_or_url.to_string()));
            }

            // Create the target directory
            let clone_path = format!("{}/{}/{}/{}", self.base_path, server, account, repo);
            let clone_dir = Path::new(&clone_path);

            // Check if repo already exists
            if clone_dir.exists() {
                return Ok(vec![GitRepo::new(clone_path)]);
            }

            // Create parent directory
            if let Some(parent) = clone_dir.parent() {
                fs::create_dir_all(parent).map_err(GitError::FileSystemError)?;
            }

            // Clone the repository
            let output = Command::new("git")
                .args(&["clone", "--depth", "1", path_or_url, &clone_path])
                .output()
                .map_err(GitError::CommandExecutionError)?;

            if output.status.success() {
                Ok(vec![GitRepo::new(clone_path)])
            } else {
                let error = String::from_utf8_lossy(&output.stderr);
                Err(GitError::GitCommandFailed(format!(
                    "Git clone error: {}",
                    error
                )))
            }
        } else {
            // It's a path pattern, find matching repositories using the updated self.find()
            // which now directly returns Result<Vec<GitRepo>, GitError>.
            let repos = self.find(path_or_url)?;
            Ok(repos)
        }
    }
}

/// Represents a git repository.
pub struct GitRepo {
    path: String,
}

impl GitRepo {
    /// Creates a new GitRepo with the specified path.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to the git repository
    pub fn new(path: String) -> Self {
        GitRepo { path }
    }

    /// Gets the path of the repository.
    ///
    /// # Returns
    ///
    /// * The path to the git repository
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Checks if the repository has uncommitted changes.
    ///
    /// # Returns
    ///
    /// * `Ok(bool)` - True if the repository has uncommitted changes, false otherwise
    /// * `Err(GitError)` - If the operation failed
    pub fn has_changes(&self) -> Result<bool, GitError> {
        let output = Command::new("git")
            .args(&["-C", &self.path, "status", "--porcelain"])
            .output()
            .map_err(GitError::CommandExecutionError)?;

        Ok(!output.stdout.is_empty())
    }

    /// Pulls the latest changes from the remote repository.
    ///
    /// # Returns
    ///
    /// * `Ok(Self)` - The GitRepo object for method chaining
    /// * `Err(GitError)` - If the pull operation failed
    pub fn pull(&self) -> Result<Self, GitError> {
        // Check if repository exists and is a git repository
        let git_dir = Path::new(&self.path).join(".git");
        if !git_dir.exists() || !git_dir.is_dir() {
            return Err(GitError::NotAGitRepository(self.path.clone()));
        }

        // Check for local changes
        if self.has_changes()? {
            return Err(GitError::LocalChangesExist(self.path.clone()));
        }

        // Pull the latest changes
        let output = Command::new("git")
            .args(&["-C", &self.path, "pull"])
            .output()
            .map_err(GitError::CommandExecutionError)?;

        if output.status.success() {
            Ok(self.clone())
        } else {
            let error = String::from_utf8_lossy(&output.stderr);
            Err(GitError::GitCommandFailed(format!(
                "Git pull error: {}",
                error
            )))
        }
    }

    /// Resets any local changes in the repository.
    ///
    /// # Returns
    ///
    /// * `Ok(Self)` - The GitRepo object for method chaining
    /// * `Err(GitError)` - If the reset operation failed
    pub fn reset(&self) -> Result<Self, GitError> {
        // Check if repository exists and is a git repository
        let git_dir = Path::new(&self.path).join(".git");
        if !git_dir.exists() || !git_dir.is_dir() {
            return Err(GitError::NotAGitRepository(self.path.clone()));
        }

        // Reset any local changes
        let reset_output = Command::new("git")
            .args(&["-C", &self.path, "reset", "--hard", "HEAD"])
            .output()
            .map_err(GitError::CommandExecutionError)?;

        if !reset_output.status.success() {
            let error = String::from_utf8_lossy(&reset_output.stderr);
            return Err(GitError::GitCommandFailed(format!(
                "Git reset error: {}",
                error
            )));
        }

        // Clean untracked files
        let clean_output = Command::new("git")
            .args(&["-C", &self.path, "clean", "-fd"])
            .output()
            .map_err(GitError::CommandExecutionError)?;

        if !clean_output.status.success() {
            let error = String::from_utf8_lossy(&clean_output.stderr);
            return Err(GitError::GitCommandFailed(format!(
                "Git clean error: {}",
                error
            )));
        }

        Ok(self.clone())
    }

    /// Commits changes in the repository.
    ///
    /// # Arguments
    ///
    /// * `message` - The commit message
    ///
    /// # Returns
    ///
    /// * `Ok(Self)` - The GitRepo object for method chaining
    /// * `Err(GitError)` - If the commit operation failed
    pub fn commit(&self, message: &str) -> Result<Self, GitError> {
        // Check if repository exists and is a git repository
        let git_dir = Path::new(&self.path).join(".git");
        if !git_dir.exists() || !git_dir.is_dir() {
            return Err(GitError::NotAGitRepository(self.path.clone()));
        }

        // Check for local changes
        if !self.has_changes()? {
            return Ok(self.clone());
        }

        // Add all changes
        let add_output = Command::new("git")
            .args(&["-C", &self.path, "add", "."])
            .output()
            .map_err(GitError::CommandExecutionError)?;

        if !add_output.status.success() {
            let error = String::from_utf8_lossy(&add_output.stderr);
            return Err(GitError::GitCommandFailed(format!(
                "Git add error: {}",
                error
            )));
        }

        // Commit the changes
        let commit_output = Command::new("git")
            .args(&["-C", &self.path, "commit", "-m", message])
            .output()
            .map_err(GitError::CommandExecutionError)?;

        if !commit_output.status.success() {
            let error = String::from_utf8_lossy(&commit_output.stderr);
            return Err(GitError::GitCommandFailed(format!(
                "Git commit error: {}",
                error
            )));
        }

        Ok(self.clone())
    }

    /// Pushes changes to the remote repository.
    ///
    /// # Returns
    ///
    /// * `Ok(Self)` - The GitRepo object for method chaining
    /// * `Err(GitError)` - If the push operation failed
    pub fn push(&self) -> Result<Self, GitError> {
        // Check if repository exists and is a git repository
        let git_dir = Path::new(&self.path).join(".git");
        if !git_dir.exists() || !git_dir.is_dir() {
            return Err(GitError::NotAGitRepository(self.path.clone()));
        }

        // Push the changes
        let push_output = Command::new("git")
            .args(&["-C", &self.path, "push"])
            .output()
            .map_err(GitError::CommandExecutionError)?;

        if push_output.status.success() {
            Ok(self.clone())
        } else {
            let error = String::from_utf8_lossy(&push_output.stderr);
            Err(GitError::GitCommandFailed(format!(
                "Git push error: {}",
                error
            )))
        }
    }
}

// Implement Clone for GitRepo to allow for method chaining
impl Clone for GitRepo {
    fn clone(&self) -> Self {
        GitRepo {
            path: self.path.clone(),
        }
    }
}