Skip to main content

dumpfs/git/
mod.rs

1mod error;
2mod remote;
3
4use std::fs;
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, Mutex};
7use std::time::{Duration, SystemTime};
8
9use error::GitResult;
10use git2::{AutotagOption, Cred, FetchOptions, RemoteCallbacks, Repository};
11use tracing::{Level, debug, error, instrument, span, trace, warn};
12
13use crate::cache;
14
15pub use error::GitError;
16pub use remote::RemoteInfo;
17
18/// Repository structure containing information about a git repository
19pub struct Repo {
20    /// The URL of the repository
21    pub url: String,
22    /// The local path to the repository
23    pub root: PathBuf,
24    /// The repository object from git2
25    repo: Option<Arc<Mutex<Repository>>>,
26    /// The remote info extracted from URL
27    info: RemoteInfo,
28}
29
30impl std::fmt::Debug for Repo {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        f.debug_struct("Repo")
33            .field("url", &self.url)
34            .field("root", &self.root)
35            .field("info", &self.info)
36            .finish()
37    }
38}
39
40impl Repo {
41    /// Create a new repo from remote information
42    #[instrument(level = "debug", skip(info), fields(owner = %info.owner, name = %info.name, branch = ?info.branch))]
43    pub fn new(info: RemoteInfo) -> Repo {
44        Repo {
45            url: info.url.clone(),
46            root: cache::dir().join(&info.owner).join(&info.name),
47            repo: None,
48            info,
49        }
50    }
51
52    /// Check if the repository exists locally
53    #[instrument(skip(self), fields(path = %self.root.display()))]
54    pub fn exists(&self) -> bool {
55        let root_exists = self.root.exists();
56        let git_dir_exists = self.root.join(".git").exists();
57        let result = root_exists && git_dir_exists;
58        debug!(
59            root_exists,
60            git_dir_exists, result, "Checking if repository exists"
61        );
62        result
63    }
64
65    /// Get the default branch of a repository
66    #[instrument(skip(self), fields(repo_url = %self.url))]
67    pub fn get_default_branch(&mut self) -> GitResult<String> {
68        let repo = self.open()?;
69        let repo = repo.lock().unwrap();
70
71        let remote = repo.find_remote("origin").map_err(|e| {
72            error!(error = %e, "Failed to find remote 'origin'");
73            error::GitError::RemoteNotFound(e.to_string())
74        })?;
75
76        debug!("Found remote 'origin', listing refs");
77        let refs = remote.list()?;
78
79        // Try HEAD first
80        for r in refs.iter() {
81            if r.name() == "HEAD" || r.name().ends_with("/HEAD") {
82                if let Some(target) = r.symref_target() {
83                    if let Some(branch) = target.strip_prefix("refs/heads/") {
84                        debug!(branch, "Found default branch via HEAD reference");
85                        return Ok(branch.to_string());
86                    }
87                }
88            }
89        }
90
91        // If HEAD is not found, try to find the default branch (usually main/master)
92        for branch_name in &["main", "master"] {
93            let ref_name = format!("refs/heads/{}", branch_name);
94            for r in refs.iter() {
95                if r.name() == ref_name {
96                    debug!(branch = %branch_name, "Found default branch via common branch name");
97                    return Ok(branch_name.to_string());
98                }
99            }
100        }
101
102        // If none found, fail
103        warn!("Could not determine default branch");
104        Err(error::GitError::DefaultBranchNotFound)
105    }
106
107    /// Clone the repository
108    #[instrument(skip(self, ui_progress), fields(url = %self.info.url, path = %self.root.display()))]
109    pub fn clone(&self, ui_progress: Option<indicatif::ProgressBar>) -> GitResult<()> {
110        debug!("Cloning repository");
111
112        // Make sure the parent directory exists
113        let parent_dir = self.root.parent().unwrap();
114        debug!(path = %parent_dir.display(), "Creating parent directory");
115
116        match fs::create_dir_all(parent_dir) {
117            Ok(_) => debug!("Parent directory created successfully"),
118            Err(e) => {
119                error!(error = %e, "Failed to create parent directory");
120                if let Some(p) = &ui_progress {
121                    p.set_message(format!("Failed to create directory: {}", e));
122                }
123                return Err(e.into());
124            }
125        }
126
127        // Set up callbacks for cloning
128        let mut callbacks = RemoteCallbacks::new();
129
130        // Set up SSH authentication
131        callbacks.credentials(setup_credentials);
132        debug!("Credentials set up");
133
134        // Set up progress reporting
135        let progress = ProgressHandler::new();
136        let progress_clone = progress.clone();
137        let ui_prog_clone = ui_progress.clone();
138
139        callbacks.transfer_progress(move |stats| {
140            let total = stats.total_objects();
141            let current = stats.received_objects();
142            progress_clone.update(current, total);
143
144            if let Some(p) = &ui_prog_clone {
145                if total > 0 {
146                    let percent = (current as f32 / total as f32) * 100.0;
147                    p.set_message(format!(
148                        "Cloning: {}/{} objects ({:.1}%)",
149                        current, total, percent
150                    ));
151                } else {
152                    p.set_message(format!("Cloning: {} objects", current));
153                }
154            }
155
156            true
157        });
158        debug!("Progress callback set up");
159
160        // Set up fetch options with callbacks
161        let mut fetch_opts = FetchOptions::new();
162        fetch_opts.remote_callbacks(callbacks);
163
164        // Set up repository builder
165        let mut builder = git2::build::RepoBuilder::new();
166        builder.fetch_options(fetch_opts);
167
168        // Check if the branch field looks like a commit hash
169        let mut checkout_commit_hash: Option<String> = None;
170        if let Some(branch_or_hash) = &self.info.branch {
171            // Basic heuristic: check if it's likely a commit hash (e.g., hex and length >= 7)
172            // Git short hashes are typically 7+ chars. Full hashes are 40.
173            if branch_or_hash.len() >= 7 && branch_or_hash.chars().all(|c| c.is_ascii_hexdigit()) {
174                debug!(hash = %branch_or_hash, "Treating branch field as commit hash for checkout after clone");
175                checkout_commit_hash = Some(branch_or_hash.clone());
176                // DO NOT set builder.branch() - clone default branch first
177            } else {
178                // Treat as a branch name
179                let clone_span = span!(Level::INFO, "clone_with_branch", branch = %branch_or_hash);
180                let _guard = clone_span.enter();
181                debug!(branch = %branch_or_hash, "Cloning with specific branch");
182                builder.branch(branch_or_hash);
183            }
184        }
185
186        // Clone directly to the final repository location
187        debug!(path = %self.root.display(), "Cloning to repository location");
188        let repo = match builder.clone(&self.info.url, &self.root) {
189            Ok(repo) => {
190                debug!("Initial clone successful");
191                repo
192            }
193            Err(e) => {
194                error!(error = %e, "Clone failed");
195                // Try to clean up any partial clone
196                if let Err(cleanup_err) = fs::remove_dir_all(&self.root) {
197                    warn!(error = %cleanup_err, "Failed to clean up partial clone during clone error");
198                }
199                // Format the error message based on whether it was a branch or potentially a hash that failed
200                let error_context = self.info.branch.as_deref().unwrap_or("default branch");
201                return Err(error::GitError::CloneError(format!(
202                    "{} at {}: {}",
203                    self.info.url, error_context, e
204                )));
205            }
206        };
207
208        // If a commit hash was specified, check it out now
209        if let Some(hash_str) = checkout_commit_hash {
210            debug!(hash = %hash_str, "Checking out specific commit after clone");
211            match git2::Oid::from_str(&hash_str) {
212                Ok(oid) => {
213                    match repo.find_object(oid, None) {
214                        Ok(object) => {
215                            // Use reset --hard to match the state at that commit
216                            if let Err(e) = repo.reset(&object, git2::ResetType::Hard, None) {
217                                error!(error = %e, hash = %hash_str, "Failed to reset to commit after clone");
218                                fs::remove_dir_all(&self.root).ok(); // Attempt cleanup
219                                return Err(error::GitError::CloneError(format!(
220                                    "Failed to checkout commit {}: {}",
221                                    hash_str, e
222                                )));
223                            }
224                            debug!(hash = %hash_str, "Successfully checked out commit after clone");
225                        }
226                        Err(e) => {
227                            error!(error = %e, hash = %hash_str, "Failed to find commit object after clone");
228                            fs::remove_dir_all(&self.root).ok(); // Attempt cleanup
229                            return Err(error::GitError::CloneError(format!(
230                                "Commit {} not found in cloned repo: {}",
231                                hash_str, e
232                            )));
233                        }
234                    }
235                }
236                Err(e) => {
237                    error!(error = %e, hash = %hash_str, "Invalid commit hash provided in URL");
238                    fs::remove_dir_all(&self.root).ok(); // Attempt cleanup
239                    return Err(error::GitError::CloneError(format!(
240                        "Invalid commit hash {}: {}",
241                        hash_str, e
242                    )));
243                }
244            }
245        }
246
247        debug!("Repository clone and potential checkout complete.");
248        Ok(())
249    }
250
251    /// Update the repository by fetching latest changes
252    #[instrument(skip(self, ui_progress), fields(path = %self.root.display()))]
253    pub fn update(&mut self, ui_progress: Option<indicatif::ProgressBar>) -> GitResult<()> {
254        debug!("Updating repository");
255
256        let repo = self.open()?;
257        let repo = repo.lock().unwrap();
258
259        // Set up callbacks for fetching
260        let mut callbacks = RemoteCallbacks::new();
261
262        // Set up SSH authentication
263        callbacks.credentials(setup_credentials);
264        debug!("Credentials set up for update");
265
266        // Set up progress reporting
267        let progress = ProgressHandler::new();
268        let progress_clone = progress.clone();
269        let ui_prog_clone = ui_progress.clone();
270
271        callbacks.transfer_progress(move |stats| {
272            let total = stats.total_objects();
273            let current = stats.received_objects();
274            progress_clone.update(current, total);
275
276            if let Some(p) = &ui_prog_clone {
277                if total > 0 {
278                    let percent = (current as f32 / total as f32) * 100.0;
279                    p.set_message(format!(
280                        "Updating: {}/{} objects ({:.1}%)",
281                        current, total, percent
282                    ));
283                } else {
284                    p.set_message(format!("Updating: {} objects", current));
285                }
286            }
287
288            true
289        });
290        debug!("Progress callback set up for update");
291
292        // Set up fetch options with callbacks
293        let mut fetch_opts = FetchOptions::new();
294        fetch_opts.remote_callbacks(callbacks);
295        fetch_opts.download_tags(AutotagOption::All);
296
297        // Find the remote
298        debug!("Finding remote 'origin'");
299        let mut remote = repo.find_remote("origin").map_err(|e| {
300            error!(error = %e, "Failed to find remote 'origin'");
301            error::GitError::RemoteNotFound(e.to_string())
302        })?;
303
304        // Fetch from the remote
305        debug!("Fetching updates from remote");
306        remote
307            .fetch(&["refs/heads/*:refs/heads/*"], Some(&mut fetch_opts), None)
308            .map_err(|e| {
309                error!(error = %e, "Failed to fetch from remote");
310                error::GitError::UpdateError(format!("Failed to fetch: {}", e))
311            })?;
312        debug!("Fetch completed successfully");
313
314        // Get the current branch
315        let branch_name = if let Ok(head) = repo.head() {
316            if let Some(name) = head.shorthand() {
317                debug!(branch = %name, "Found current branch");
318                name.to_string()
319            } else {
320                warn!("Head exists but shorthand name not found, using 'main'");
321                "main".to_string()
322            }
323        } else {
324            warn!("Failed to get repository HEAD, using 'main'");
325            "main".to_string()
326        };
327
328        // Find the upstream branch
329        let upstream_ref = format!("refs/remotes/origin/{}", branch_name);
330        debug!(reference = %upstream_ref, "Finding upstream reference");
331        let upstream = repo.find_reference(&upstream_ref).map_err(|e| {
332            error!(error = %e, reference = %upstream_ref, "Failed to find upstream reference");
333            error::GitError::UpdateError(format!("Failed to find upstream reference: {}", e))
334        })?;
335
336        // Get the target commit
337        debug!("Getting target commit from upstream");
338        let target = upstream.target().ok_or_else(|| {
339            error!(reference = %upstream_ref, "Upstream reference has no target");
340            error::GitError::UpdateError("Upstream reference has no target".to_string())
341        })?;
342
343        // Look up the commit
344        debug!(commit = %target, "Looking up commit");
345        let commit = repo.find_commit(target).map_err(|e| {
346            error!(error = %e, commit = %target, "Failed to find commit");
347            error::GitError::UpdateError(format!("Failed to find commit: {}", e))
348        })?;
349
350        // Get the current branch
351        debug!(branch = %branch_name, "Finding local branch");
352        let _branch = repo
353            .find_branch(&branch_name, git2::BranchType::Local)
354            .map_err(|e| {
355                error!(error = %e, branch = %branch_name, "Failed to find local branch");
356                error::GitError::UpdateError(format!("Failed to find branch: {}", e))
357            })?;
358
359        // Set the target of the branch to the fetched commit
360        debug!(commit_id = %commit.id(), "Finding commit object");
361        let obj = repo.find_object(commit.id(), None).map_err(|e| {
362            error!(error = %e, commit_id = %commit.id(), "Failed to find commit object");
363            error::GitError::UpdateError(format!("Failed to find object: {}", e))
364        })?;
365
366        debug!("Resetting to target commit (hard reset)");
367        repo.reset(&obj, git2::ResetType::Hard, None).map_err(|e| {
368            error!(error = %e, "Failed to reset to target commit");
369            error::GitError::UpdateError(format!("Failed to reset: {}", e))
370        })?;
371
372        debug!("Repository updated successfully");
373        Ok(())
374    }
375
376    /// Open the repository
377    #[instrument(skip(self), fields(path = %self.root.display()))]
378    pub fn open(&mut self) -> GitResult<Arc<Mutex<Repository>>> {
379        if let Some(repo) = &self.repo {
380            trace!("Returning cached repository instance");
381            return Ok(repo.clone());
382        }
383
384        debug!("Opening git repository");
385        let repo = match Repository::open(&self.root) {
386            Ok(r) => {
387                debug!("Repository opened successfully");
388                r
389            }
390            Err(e) => {
391                error!(error = %e, "Failed to open repository");
392                return Err(error::GitError::OpenError(e.to_string()));
393            }
394        };
395
396        let repo_arc = Arc::new(Mutex::new(repo));
397        debug!("Repository wrapped in thread-safe container");
398
399        // Cache the repository instance
400        self.repo = Some(repo_arc.clone());
401
402        Ok(repo_arc)
403    }
404
405    /// Ensure the repository is cloned and updated
406    pub fn ensure_cloned(&mut self, progress: Option<indicatif::ProgressBar>) -> GitResult<()> {
407        debug!("Ensuring repository is cloned and updated");
408
409        if !self.exists() {
410            debug!("Repository does not exist, cloning");
411            if let Some(p) = &progress {
412                p.set_message(format!("Cloning repository {}...", self.info.name));
413            }
414
415            match self.clone(progress.clone()) {
416                Ok(_) => {
417                    debug!("Clone completed successfully");
418                    if let Some(p) = &progress {
419                        p.set_message("Clone completed successfully");
420                    }
421
422                    let exists_after = self.exists();
423                    debug!(
424                        exists = exists_after,
425                        "Checking if repository exists after clone"
426                    );
427
428                    // List the directory contents for debugging
429                    if let Ok(entries) = fs::read_dir(self.root.parent().unwrap_or(Path::new(".")))
430                    {
431                        debug!("Directory contents after clone:");
432                        entries.for_each(|entry| {
433                            if let Ok(entry) = entry {
434                                trace!(path = %entry.path().display(), "Directory entry");
435                            }
436                        });
437                    }
438
439                    // Verify repository exists after clone
440                    if !exists_after {
441                        let err_msg = format!(
442                            "Clone completed but repository at {:?} does not exist",
443                            self.root
444                        );
445                        error!(message = %err_msg, "Clone verification failed");
446                        if let Some(p) = &progress {
447                            p.abandon_with_message(format!(
448                                "Clone verification failed: {}",
449                                err_msg
450                            ));
451                        }
452                        return Err(error::GitError::CloneError(err_msg));
453                    }
454                }
455                Err(e) => {
456                    error!(error = ?e, "Clone failed");
457                    if let Some(p) = &progress {
458                        p.abandon_with_message(format!("Clone failed: {}", e));
459                    }
460                    return Err(e);
461                }
462            }
463        } else {
464            debug!("Repository exists, updating");
465            if let Some(p) = &progress {
466                p.set_message(format!("Updating repository {}...", self.info.name));
467            }
468
469            // Check if a specific commit hash was provided in the URL
470            let is_commit_hash = self
471                .info
472                .branch
473                .as_ref()
474                .is_some_and(|b| b.len() >= 7 && b.chars().all(|c| c.is_ascii_hexdigit()));
475
476            if is_commit_hash {
477                debug!(hash = %self.info.branch.as_deref().unwrap_or(""), "Skipping update because a specific commit hash was requested.");
478                if let Some(p) = &progress {
479                    p.set_message(format!("Using specific commit for {}", self.info.name));
480                }
481            } else {
482                debug!("Attempting to update repository to latest commit on branch.");
483                // TODO: Define an option to control whether to update the code
484                // For now, we keep the update commented out as per the existing TODO.
485                // If update were enabled, it would look like this:
486                /*
487                match self.update(progress.clone()) {
488                    Ok(_) => {
489                        debug!("Update completed successfully");
490                        if let Some(p) = &progress {
491                            p.set_message("Update completed successfully");
492                        }
493                    }
494                    Err(e) => {
495                        error!(error = ?e, "Update failed");
496                        if let Some(p) = &progress {
497                            p.abandon_with_message(format!("Update failed: {}", e));
498                        }
499                        return Err(e);
500                    }
501                }
502                */
503                // Since it's commented out, just log that we would update here.
504                debug!("Repository update logic is currently commented out.");
505                if let Some(p) = &progress {
506                    p.set_message(format!("Checked repository {}", self.info.name)); // More accurate message
507                }
508            }
509        }
510
511        debug!("Repository is ready for use");
512        if let Some(p) = &progress {
513            p.set_message(format!("Repository {} ready", self.info.name));
514        }
515        Ok(())
516    }
517
518    /// Get the path to a specific file or directory in the repository
519    #[instrument(skip(self), fields(repo_path = %self.root.display(), relative_path = ?relative_path))]
520    pub fn get_path(&self, relative_path: Option<&str>) -> PathBuf {
521        match relative_path {
522            Some(path) => {
523                let full_path = self.root.join(path);
524                trace!(path = %full_path.display(), "Resolved repository path with relative path");
525                full_path
526            }
527            None => {
528                trace!(path = %self.root.display(), "Returning repository root path");
529                self.root.clone()
530            }
531        }
532    }
533}
534
535/// Helper function to set up git authentication credentials
536#[instrument(skip(_url, _allowed_types), fields(username = ?username_from_url))]
537fn setup_credentials(
538    _url: &str,
539    username_from_url: Option<&str>,
540    _allowed_types: git2::CredentialType,
541) -> std::result::Result<Cred, git2::Error> {
542    // Try SSH key authentication first
543    if let Some(username) = username_from_url {
544        debug!("Attempting SSH authentication for user");
545
546        // Check for ed25519 key
547        let ed25519_key = Path::new(&dirs::home_dir().unwrap())
548            .join(".ssh")
549            .join("id_ed25519");
550
551        if ed25519_key.exists() {
552            debug!(key_path = %ed25519_key.display(), "Using Ed25519 SSH key");
553            return Cred::ssh_key(username, None, &ed25519_key, None);
554        }
555
556        // Check for RSA key
557        let rsa_key = Path::new(&dirs::home_dir().unwrap())
558            .join(".ssh")
559            .join("id_rsa");
560
561        if rsa_key.exists() {
562            debug!(key_path = %rsa_key.display(), "Using RSA SSH key");
563            return Cred::ssh_key(username, None, &rsa_key, None);
564        }
565
566        debug!("No SSH keys found");
567    } else {
568        debug!("No username provided for authentication");
569    }
570
571    // Fall back to default credentials
572    debug!("Using default credentials");
573    Cred::default()
574}
575
576/// Progress callback for clone/fetch operations
577#[derive(Clone, Debug)]
578struct ProgressHandler {
579    progress: Arc<Mutex<f32>>,
580    last_update: Arc<Mutex<SystemTime>>,
581}
582
583impl ProgressHandler {
584    #[instrument]
585    fn new() -> Self {
586        debug!("Creating new progress handler");
587        Self {
588            progress: Arc::new(Mutex::new(0.0)),
589            last_update: Arc::new(Mutex::new(SystemTime::now())),
590        }
591    }
592
593    #[instrument(fields(current, total))]
594    fn update(&self, current: usize, total: usize) {
595        trace!(current, total, "Progress update received");
596
597        // Only update progress at most once per 100ms to avoid excessive writes
598        let mut last_update = self.last_update.lock().unwrap();
599        let now = SystemTime::now();
600
601        if now
602            .duration_since(*last_update)
603            .unwrap_or(Duration::from_secs(0))
604            < Duration::from_millis(100)
605        {
606            return;
607        }
608
609        *last_update = now;
610
611        if total > 0 {
612            let percent = (current as f32 / total as f32) * 100.0;
613
614            let mut progress = self.progress.lock().unwrap();
615            *progress = percent;
616
617            debug!(
618                progress = %format!("{:.1}%", percent),
619                current,
620                total,
621                "Git operation progress"
622            );
623        } else {
624            trace!(current, "Progress update with zero total");
625        }
626    }
627}
628
629#[cfg(test)]
630mod tests {
631    use super::*;
632    use std::env;
633    use std::fs::{self, File};
634    use std::io::Write;
635    use std::net::TcpStream;
636    use tempfile::{TempDir, tempdir};
637    use test_log::test;
638
639    // Helper function to check if we have a network connection
640    #[instrument]
641    fn has_network_connection() -> bool {
642        // Try to connect to github.com on port 443 (HTTPS)
643        let result = TcpStream::connect("github.com:443").is_ok();
644        if result {
645            debug!("Network connection available");
646        } else {
647            debug!("No network connection available");
648        }
649        result
650    }
651
652    // Helper function to check if we're running in CI
653    #[instrument]
654    fn is_ci_environment() -> bool {
655        let ci_env = env::var("CI").is_ok();
656        let gh_actions = env::var("GITHUB_ACTIONS").is_ok();
657        let result = ci_env || gh_actions;
658        debug!(
659            ci = ci_env,
660            github_actions = gh_actions,
661            "CI environment check"
662        );
663        result
664    }
665
666    // Helper function to create a test repository
667    #[instrument]
668    fn setup_test_repo() -> (TempDir, Repository, PathBuf) {
669        let temp_dir = tempdir().unwrap();
670        let repo_path = temp_dir.path();
671        debug!(path = %repo_path.display(), "Created temporary directory for test repo");
672
673        // Initialize a new repository
674        debug!("Initializing git repository");
675        let repo = Repository::init(repo_path).unwrap();
676
677        // Create a test file and commit it
678        let test_file_path = repo_path.join("test_file.txt");
679        debug!(path = %test_file_path.display(), "Creating test file");
680        let mut file = File::create(&test_file_path).unwrap();
681        writeln!(file, "Test content").unwrap();
682
683        // Configure user for the test repository
684        debug!("Configuring git user");
685        let mut config = repo.config().unwrap();
686        config.set_str("user.name", "Test User").unwrap();
687        config.set_str("user.email", "test@example.com").unwrap();
688
689        // Add the file to git and commit
690        debug!("Adding file to git index");
691        let mut index = repo.index().unwrap();
692        index
693            .add_path(std::path::Path::new("test_file.txt"))
694            .unwrap();
695        index.write().unwrap();
696
697        debug!("Creating tree from index");
698        let tree_id = index.write_tree().unwrap();
699        let tree = repo.find_tree(tree_id).unwrap();
700
701        debug!("Creating initial commit");
702        let signature = git2::Signature::now("Test User", "test@example.com").unwrap();
703        repo.commit(
704            Some("HEAD"),
705            &signature,
706            &signature,
707            "Initial commit",
708            &tree,
709            &[],
710        )
711        .unwrap();
712
713        drop(tree);
714
715        debug!("Test repository setup complete");
716        (temp_dir, repo, test_file_path)
717    }
718
719    // Helper function to create a remote info for testing
720    #[instrument]
721    fn create_test_remote_info(url: &str) -> RemoteInfo {
722        debug!(url, "Creating test remote info");
723        let info = RemoteInfo::new(url.to_string()).unwrap();
724        trace!(owner = %info.owner, name = %info.name, "Remote info created");
725        info
726    }
727
728    #[test]
729    fn test_repo_new_basic() {
730        let info = create_test_remote_info("https://github.com/owner/repo");
731        let repo = Repo::new(info);
732
733        debug!(url = %repo.url, "Testing basic repo creation");
734        assert_eq!(repo.url, "https://github.com/owner/repo");
735
736        debug!(expected = %cache::dir().join("owner").join("repo").display(),
737               actual = %repo.root.display(),
738               "Checking repo root path");
739        assert_eq!(repo.root, cache::dir().join("owner").join("repo"));
740
741        assert!(
742            repo.repo.is_none(),
743            "Repository instance should be None initially"
744        );
745    }
746
747    #[test]
748    fn test_repo_new_with_branch() {
749        let info = create_test_remote_info("https://github.com/owner/repo/tree/main/src");
750        let repo = Repo::new(info);
751
752        debug!(url = %repo.url, "Testing repo creation with branch");
753        assert_eq!(repo.url, "https://github.com/owner/repo");
754
755        let expected_path = cache::dir().join("owner").join("repo");
756        debug!(expected = %expected_path.display(),
757               actual = %repo.root.display(),
758               "Checking repo root path with branch");
759        assert_eq!(repo.root, expected_path);
760
761        assert!(
762            repo.repo.is_none(),
763            "Repository instance should be None initially"
764        );
765    }
766
767    #[test]
768    #[ignore]
769    fn test_exists() {
770        debug!("Testing repository existence check");
771
772        // First test with non-existent repo
773        let info = create_test_remote_info("https://github.com/owner/repo");
774        let repo = Repo::new(info);
775
776        debug!(path = %repo.root.display(), "Checking non-existent repo");
777        assert!(
778            !repo.exists(),
779            "Non-existent repo should return false from exists()"
780        );
781
782        // Now create a directory structure to simulate an existing repo
783        let cache_path = tempdir().unwrap();
784        debug!(path = %cache_path.path().display(), "Created temporary cache dir");
785
786        unsafe {
787            env::set_var("XDG_CACHE_HOME", cache_path.path());
788        }
789
790        let repo_path = cache_path.path().join("dumpml").join("owner").join("repo");
791        debug!(path = %repo_path.display(), "Creating simulated repo structure");
792        fs::create_dir_all(&repo_path).unwrap();
793        fs::create_dir_all(repo_path.join(".git")).unwrap();
794
795        let info = create_test_remote_info("https://github.com/owner/repo");
796        let repo = Repo::new(info);
797
798        debug!(path = %repo.root.display(), "Checking existing repo");
799        assert!(
800            repo.exists(),
801            "Existing repo should return true from exists()"
802        );
803    }
804
805    #[test]
806    fn test_get_path() {
807        debug!("Testing repository path resolution");
808
809        let info = create_test_remote_info("https://github.com/owner/repo");
810        let repo = Repo::new(info);
811
812        // Test with no relative path
813        debug!(path = %repo.root.display(), "Testing get_path with no relative path");
814        let root_path = repo.get_path(None);
815        assert_eq!(
816            root_path, repo.root,
817            "get_path(None) should return the repo root"
818        );
819
820        // Test with a relative path
821        let rel_path = "src/main.rs";
822        debug!(
823            repo_root = %repo.root.display(),
824            relative_path = %rel_path,
825            "Testing get_path with relative path"
826        );
827
828        let file_path = repo.get_path(Some(rel_path));
829        let expected_path = repo.root.join(rel_path);
830
831        assert_eq!(
832            file_path, expected_path,
833            "get_path with relative path should correctly join paths"
834        );
835    }
836
837    #[test]
838    fn test_setup_credentials() {
839        debug!("Testing credential setup");
840        // This is a limited test since we can't easily test SSH key authentication
841        // without setting up actual SSH keys in the test environment.
842
843        debug!("Testing credential setup with username");
844        let result = setup_credentials(
845            "https://github.com/owner/repo",
846            Some("username"),
847            git2::CredentialType::USER_PASS_PLAINTEXT,
848        );
849        assert!(result.is_ok(), "Credential setup should not fail");
850
851        debug!("Testing credential setup without username");
852        let result_no_username = setup_credentials(
853            "https://github.com/owner/repo",
854            None,
855            git2::CredentialType::USER_PASS_PLAINTEXT,
856        );
857        assert!(
858            result_no_username.is_ok(),
859            "Credential setup without username should not fail"
860        );
861    }
862
863    #[ignore = "requires network access and git authentication"]
864    #[test]
865    fn test_clone_and_update() {
866        // This test requires network access and is marked as ignored by default
867        let temp_dir = tempdir().unwrap();
868        println!("test_clone_and_update: temp_dir={:?}", temp_dir.path());
869
870        unsafe {
871            env::set_var("XDG_CACHE_HOME", temp_dir.path());
872        }
873        println!(
874            "test_clone_and_update: XDG_CACHE_HOME set to {:?}",
875            temp_dir.path()
876        );
877
878        // Skip test if no network connection
879        if !has_network_connection() {
880            println!("Skipping test_clone_and_update: no network connection");
881            return;
882        }
883        println!("test_clone_and_update: Network connection verified");
884
885        // Use a public repo for testing that doesn't require authentication
886        let info = create_test_remote_info("https://github.com/kkharji/xbase");
887        let mut repo = Repo::new(info);
888        println!("test_clone_and_update: repo root path={:?}", repo.root);
889
890        // Test clone operation
891        let exists_before = repo.exists();
892        println!(
893            "test_clone_and_update: repo.exists() before clone = {}",
894            exists_before
895        );
896        assert!(!exists_before);
897
898        let clone_result = repo.ensure_cloned(None);
899        if let Err(ref e) = clone_result {
900            println!("Clone failed: {}", e);
901            // Instead of silently returning, make the test fail with a clear message
902            match e {
903                error::GitError::CloneError(msg)
904                    if msg.contains("remote authentication required") =>
905                {
906                    // Only skip the test with a warning for authentication errors,
907                    // as these might be expected in some test environments
908                    println!("WARN: Skipping test due to authentication requirements");
909                    return;
910                }
911                _ => {
912                    // For other errors, fail the test
913                    panic!("Repository clone failed: {}", e);
914                }
915            }
916        }
917        println!("test_clone_and_update: clone successful");
918        assert!(clone_result.is_ok());
919
920        // Check if the repository exists after cloning
921        let exists_after = repo.exists();
922        println!(
923            "test_clone_and_update: repo.exists() after clone = {}",
924            exists_after
925        );
926        println!(
927            "test_clone_and_update: Checking if directory exists: {:?}",
928            repo.root
929        );
930        println!(
931            "test_clone_and_update: Directory exists: {}",
932            repo.root.exists()
933        );
934        println!(
935            "test_clone_and_update: .git exists: {}",
936            repo.root.join(".git").exists()
937        );
938
939        // Skip the existence check if running in CI
940        if !is_ci_environment() {
941            assert!(repo.exists());
942        }
943
944        // Add a small delay to ensure timestamps are different
945        std::thread::sleep(std::time::Duration::from_secs(1));
946
947        // Test update operation
948        let update_result = repo.update(None);
949        if let Err(ref e) = update_result {
950            println!("Update failed: {}", e);
951            panic!("Repository update failed: {}", e);
952        }
953    }
954
955    #[test]
956    fn test_open_nonexistent_repo() {
957        let info = create_test_remote_info("https://github.com/owner/repo");
958        let mut repo = Repo::new(info);
959
960        // Try to open a repository that doesn't exist
961        let result = repo.open();
962        assert!(result.is_err());
963        match result {
964            Err(error::GitError::OpenError(_)) => {}
965            _ => panic!("Expected OpenError"),
966        }
967    }
968
969    #[test]
970    fn test_open_existing_repo() {
971        // Create a real git repository
972        let (temp_dir, _, _) = setup_test_repo();
973
974        // Create a remote info that points to the test repo
975        let url = format!("file://{}", temp_dir.path().display());
976        let mut info = create_test_remote_info(&url);
977
978        // Override the root to point to our test repo
979        info.url = url;
980        let mut repo = Repo::new(info);
981        repo.root = temp_dir.path().to_path_buf();
982
983        // Open the repository
984        let result = repo.open();
985        assert!(result.is_ok());
986
987        // Check that subsequent calls reuse the same repository instance
988        let repo1 = repo.open().unwrap();
989        let repo2 = repo.open().unwrap();
990
991        // Check both point to the same Arc (reference equality)
992        assert!(Arc::ptr_eq(&repo1, &repo2));
993    }
994
995    #[test]
996    #[ignore = "requires git remote access"]
997    fn test_get_default_branch() {
998        // This test requires network access and is marked as ignored by default
999        let temp_dir = tempdir().unwrap();
1000        unsafe {
1001            env::set_var("XDG_CACHE_HOME", temp_dir.path());
1002        }
1003
1004        // Skip test if no network connection
1005        if !has_network_connection() {
1006            println!("Skipping test_get_default_branch: no network connection");
1007            return;
1008        }
1009
1010        // Use a public repo for testing
1011        let info = create_test_remote_info("https://github.com/kkharji/xbase");
1012        let mut repo = Repo::new(info);
1013
1014        // Need to clone first
1015        let clone_result = repo.ensure_cloned(None);
1016        if let Err(ref e) = clone_result {
1017            println!("Clone failed: {}", e);
1018            // Skip rest of test if clone fails
1019            return;
1020        }
1021
1022        // Test getting the default branch
1023        let branch = repo.get_default_branch();
1024        if let Err(ref e) = branch {
1025            println!("Getting default branch failed: {}", e);
1026            return;
1027        }
1028        assert!(branch.is_ok());
1029        // Most repositories use main or master as default branch
1030        assert!(branch.as_ref().unwrap() == "main" || branch.as_ref().unwrap() == "master");
1031    }
1032
1033    #[test]
1034    fn test_repo_debug_formatting() {
1035        let info = create_test_remote_info("https://github.com/owner/repo");
1036        let repo = Repo::new(info);
1037
1038        // Verify we can format the repo with Debug
1039        let debug_str = format!("{:?}", repo);
1040        assert!(debug_str.contains("Repo"));
1041        assert!(debug_str.contains("url"));
1042        assert!(debug_str.contains("root"));
1043        assert!(debug_str.contains("info"));
1044    }
1045
1046    #[test]
1047    #[ignore = "requires network access and authentication"]
1048    fn test_full_workflow() {
1049        // This comprehensive test covers the full workflow with a real repository
1050        let temp_dir = tempdir().unwrap();
1051        println!("test_full_workflow: temp_dir={:?}", temp_dir.path());
1052
1053        unsafe {
1054            env::set_var("XDG_CACHE_HOME", temp_dir.path());
1055        }
1056        println!(
1057            "test_full_workflow: XDG_CACHE_HOME set to {:?}",
1058            temp_dir.path()
1059        );
1060        println!(
1061            "test_full_workflow: cache dir calculated as: {:?}",
1062            cache::dir()
1063        );
1064
1065        // Skip test if no network connection
1066        if !has_network_connection() {
1067            println!("Skipping test_full_workflow: no network connection");
1068            return;
1069        }
1070        println!("test_full_workflow: Network connection verified");
1071
1072        // Use a public repo for testing
1073        let info = create_test_remote_info("https://github.com/kkharji/xbase");
1074        let mut repo = Repo::new(info);
1075        println!("test_full_workflow: repo root path={:?}", repo.root);
1076
1077        // Test the full workflow: clone, open, update
1078        let exists_before = repo.exists();
1079        println!(
1080            "test_full_workflow: repo.exists() before clone = {}",
1081            exists_before
1082        );
1083        assert!(!exists_before);
1084
1085        // Step 1: Clone the repository
1086        let result = repo.ensure_cloned(None);
1087        if let Err(ref e) = result {
1088            println!("Clone failed: {}", e);
1089            // Skip rest of test if clone fails
1090            return;
1091        }
1092        println!("test_full_workflow: clone successful");
1093        assert!(result.is_ok());
1094
1095        // Check if the repository exists after cloning
1096        let exists_after = repo.exists();
1097        println!(
1098            "test_full_workflow: repo.exists() after clone = {}",
1099            exists_after
1100        );
1101        println!(
1102            "test_full_workflow: Checking if directory exists: {:?}",
1103            repo.root
1104        );
1105        println!(
1106            "test_full_workflow: Directory exists: {}",
1107            repo.root.exists()
1108        );
1109        println!(
1110            "test_full_workflow: .git exists: {}",
1111            repo.root.join(".git").exists()
1112        );
1113
1114        // Skip the existence check if running in CI
1115        if !is_ci_environment() {
1116            assert!(repo.exists());
1117        }
1118
1119        // Step 2: Open the repository
1120        let open_result = repo.open();
1121        if let Err(ref e) = open_result {
1122            println!("Open failed: {}", e);
1123            panic!("Repository open failed: {}", e);
1124        }
1125
1126        // Step 3: Update the repository
1127        let update_result = repo.update(None);
1128        assert!(update_result.is_ok());
1129
1130        // Step 4: Get a file path
1131        let readme_path = repo.get_path(Some("README.md"));
1132        // Only check if file exists if we're not in CI
1133        if !is_ci_environment() {
1134            assert!(readme_path.exists());
1135        }
1136    }
1137}