augent 0.6.6

Lean package manager for various AI coding platforms
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! Git operations for cloning and fetching bundles
//!
//! This module handles:
//! - Cloning repositories (HTTPS and SSH)
//! - Resolving refs (branches, tags) to exact SHAs
//! - Fetching updates for existing repositories
//! - Authentication via git's native credential system
//!
//! Authentication is delegated entirely to git's native system:
//! - SSH keys from ~/.ssh/
//! - Git credential helpers
//! - Environment variables (GIT_SSH_COMMAND, etc.)

#[cfg(windows)]
use std::fs;
use std::path::Path;
use std::process::Command;

use git2::{
    Cred, CredentialType, ErrorClass, FetchOptions, RemoteCallbacks, Repository, build::RepoBuilder,
};

use crate::error::{AugentError, Result};

/// Normalize SSH URLs from SCP-style (git@host:path) to ssh:// format.
///
/// libgit2 may have issues with SCP-style SSH URLs, so we convert them to
/// the explicit ssh:// format for better compatibility.
fn normalize_ssh_url_for_clone(url: &str) -> std::borrow::Cow<'_, str> {
    // Only process SCP-style URLs (git@host:path), not already-normalized ssh:// URLs
    if !url.starts_with("git@") || url.starts_with("ssh://") {
        return std::borrow::Cow::Borrowed(url);
    }

    // Parse git@host:path format
    // Find the colon that separates host from path
    if let Some(colon_pos) = url.find(':') {
        let host_part = &url[..colon_pos]; // git@host
        let path_part = &url[colon_pos + 1..]; // path/repo.git

        // Convert to ssh://git@host/path format
        // Note: colon becomes slash in the path part
        // If path already starts with /, use it directly; otherwise add /
        let normalized_path = if path_part.starts_with('/') {
            path_part.to_string()
        } else {
            format!("/{}", path_part)
        };
        return std::borrow::Cow::Owned(format!("ssh://{}{}", host_part, normalized_path));
    }

    // No colon found, return as-is (shouldn't happen for valid SSH URLs)
    std::borrow::Cow::Borrowed(url)
}

/// Normalize file:// URLs so libgit2 can resolve them on Unix.
///
/// On Windows, file:// is not used: clone() uses a local copy instead because
/// libgit2 mis-parses file://C:\path, file:///C:/path, and file:///C|/path.
fn normalize_file_url_for_clone(url: &str) -> std::borrow::Cow<'_, str> {
    if !url.starts_with("file://") {
        return std::borrow::Cow::Borrowed(url);
    }
    #[cfg(not(windows))]
    {
        let after = &url[7..]; // after "file://"
        if after.contains('\\') {
            let path = after.replace('\\', "/");
            return std::borrow::Cow::Owned(format!("file:///{}", path));
        }
        if !after.is_empty() && !after.starts_with('/') {
            return std::borrow::Cow::Owned(format!("file:///{}", after));
        }
    }
    std::borrow::Cow::Borrowed(url)
}

/// On Windows, libgit2 fails to parse file:// URLs (drive letters, path
/// resolution). Clone by copying the source directory and opening it.
#[cfg(windows)]
fn clone_local_file(url: &str, target: &Path) -> Result<Repository> {
    let path_str = url
        .strip_prefix("file:///")
        .or_else(|| url.strip_prefix("file://"))
        .unwrap_or(url)
        .replace('|', ":");
    let source = Path::new(&path_str);
    if !source.is_dir() {
        return Err(AugentError::GitCloneFailed {
            url: url.to_string(),
            reason: "local path is not a directory".to_string(),
        });
    }
    fs::create_dir_all(target).map_err(|e| AugentError::GitCloneFailed {
        url: url.to_string(),
        reason: format!("Failed to create target directory: {}", e),
    })?;
    copy_dir_recursive_for_clone(source, target, url)?;
    Repository::open(target).map_err(|e| AugentError::GitCloneFailed {
        url: url.to_string(),
        reason: e.message().to_string(),
    })
}

#[cfg(windows)]
fn copy_dir_recursive_for_clone(src: &Path, dst: &Path, url: &str) -> Result<()> {
    for entry in fs::read_dir(src).map_err(|e| AugentError::GitCloneFailed {
        url: url.to_string(),
        reason: format!("Failed to read source directory: {}", e),
    })? {
        let entry = entry.map_err(|e| AugentError::GitCloneFailed {
            url: url.to_string(),
            reason: format!("Failed to read directory entry: {}", e),
        })?;
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());
        if src_path.is_dir() {
            fs::create_dir_all(&dst_path).map_err(|e| AugentError::GitCloneFailed {
                url: url.to_string(),
                reason: format!("Failed to create directory: {}", e),
            })?;
            copy_dir_recursive_for_clone(&src_path, &dst_path, url)?;
        } else {
            fs::copy(&src_path, &dst_path).map_err(|e| AugentError::GitCloneFailed {
                url: url.to_string(),
                reason: format!(
                    "Failed to copy {} to {}: {}",
                    src_path.display(),
                    dst_path.display(),
                    e
                ),
            })?;
        }
    }
    Ok(())
}

/// Interpret a git2 error and provide a more user-friendly message
fn interpret_git_error(err: &git2::Error) -> String {
    let class = err.class();
    let message = err.message().to_lowercase();

    // Check for specific error patterns in the message
    // Order matters - more specific patterns first
    if message.contains("not found") || message.contains("404") {
        "Repository not found".to_string()
    } else if message.contains("too many redirects") || message.contains("authentication replays") {
        // This often means repository doesn't exist but auth is being attempted
        "Repository not found".to_string()
    } else if message.contains("authentication") || message.contains("credentials") {
        "Authentication failed".to_string()
    } else if message.contains("permission denied") || message.contains("access denied") {
        "Permission denied".to_string()
    } else if message.contains("connection")
        || message.contains("network")
        || message.contains("timeout")
        || message.contains("timed out")
    {
        "Network error".to_string()
    } else if class == ErrorClass::Http {
        // Generic HTTP error - try to provide more context
        if message.contains("certificate") {
            "Certificate error".to_string()
        } else if message.contains("ssl") {
            "SSL error".to_string()
        } else {
            format!("HTTP error: {}", err.message())
        }
    } else if class == ErrorClass::Ssh {
        format!("SSH error: {}", err.message())
    } else {
        // Fall back to original message
        err.message().to_string()
    }
}

/// Clone a git repository to a target directory
///
/// Supports both HTTPS and SSH URLs. Authentication is delegated to git's
/// native credential system (SSH keys, credential helpers, etc.).
///
/// # Arguments
/// * `url` - The git URL to clone
/// * `target` - The target directory path
/// * `shallow` - Whether to do a shallow clone (depth=1). Default is true.
///   Set to false when you need to resolve specific refs like tags.
pub fn clone(url: &str, target: &Path, shallow: bool) -> Result<Repository> {
    // On Windows, libgit2 fails on file:// URLs (drive letters, path resolution).
    // Clone by copying the source directory instead.
    #[cfg(windows)]
    if url.starts_with("file://") {
        return clone_local_file(url, target);
    }

    let mut callbacks = RemoteCallbacks::new();
    setup_auth_callbacks(&mut callbacks);

    let mut fetch_options = FetchOptions::new();
    fetch_options.remote_callbacks(callbacks);

    // Shallow clone for remote URLs only if requested
    // (not supported for local file:// URLs or local paths)
    let is_local = url.starts_with("file://")
        || url.starts_with('/')
        || std::path::Path::new(url).is_absolute();
    if shallow && !is_local {
        fetch_options.depth(1);
    }

    let mut builder = RepoBuilder::new();
    builder.fetch_options(fetch_options);

    // Normalize URLs for libgit2 compatibility
    let url_to_clone = normalize_ssh_url_for_clone(url);
    let url_to_clone = normalize_file_url_for_clone(&url_to_clone);
    builder.clone(url_to_clone.as_ref(), target).map_err(|e| {
        let reason = interpret_git_error(&e);
        AugentError::GitCloneFailed {
            url: url.to_string(),
            reason,
        }
    })
}

/// Resolve a ref to SHA via `git ls-remote` without cloning.
///
/// Use this to check the cache before cloning. For file:// URLs or when the
/// git CLI is unavailable, returns an error (caller should fall back to clone).
/// Ref defaults to "HEAD" when None.
pub fn ls_remote(url: &str, git_ref: Option<&str>) -> Result<String> {
    // file:// and local paths don't support ls-remote in a useful way
    let is_local =
        url.starts_with("file://") || url.starts_with('/') || Path::new(url).is_absolute();
    if is_local {
        return Err(AugentError::GitRefResolveFailed {
            git_ref: git_ref.unwrap_or("HEAD").to_string(),
            reason: "ls-remote not used for local URLs".to_string(),
        });
    }

    let ref_arg = git_ref.unwrap_or("HEAD");
    let output = Command::new("git")
        .args(["ls-remote", "--exit-code", url, ref_arg])
        .output()
        .map_err(|e| AugentError::GitRefResolveFailed {
            git_ref: ref_arg.to_string(),
            reason: format!("git ls-remote failed: {}", e),
        })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(AugentError::GitRefResolveFailed {
            git_ref: ref_arg.to_string(),
            reason: stderr.trim().to_string(),
        });
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let line = stdout
        .lines()
        .next()
        .ok_or_else(|| AugentError::GitRefResolveFailed {
            git_ref: ref_arg.to_string(),
            reason: "git ls-remote returned no output".to_string(),
        })?;
    let sha = line
        .split_whitespace()
        .next()
        .ok_or_else(|| AugentError::GitRefResolveFailed {
            git_ref: ref_arg.to_string(),
            reason: "could not parse ls-remote output".to_string(),
        })?;
    if sha.len() != 40 || !sha.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(AugentError::GitRefResolveFailed {
            git_ref: ref_arg.to_string(),
            reason: format!("invalid SHA from ls-remote: {}", sha),
        });
    }
    Ok(sha.to_string())
}

/// Resolve a git ref (branch, tag, or partial SHA) to a full SHA
///
/// If no ref is provided, defaults to HEAD.
pub fn resolve_ref(repo: &Repository, git_ref: Option<&str>) -> Result<String> {
    let reference = match git_ref {
        Some(r) => {
            // Try to resolve as a reference
            resolve_reference(repo, r)?
        }
        None => {
            // Default to HEAD
            repo.head()
                .map_err(|e| AugentError::GitRefResolveFailed {
                    git_ref: "HEAD".to_string(),
                    reason: e.message().to_string(),
                })?
                .peel_to_commit()
                .map_err(|e| AugentError::GitRefResolveFailed {
                    git_ref: "HEAD".to_string(),
                    reason: e.message().to_string(),
                })?
        }
    };

    Ok(reference.id().to_string())
}

/// Resolve a reference name to a commit
fn resolve_reference<'a>(repo: &'a Repository, refname: &str) -> Result<git2::Commit<'a>> {
    // Try different reference formats in order
    let ref_candidates = [
        refname.to_string(),
        format!("refs/heads/{}", refname),
        format!("refs/tags/{}", refname),
        format!("refs/remotes/origin/{}", refname),
    ];

    for candidate in &ref_candidates {
        if let Ok(reference) = repo.find_reference(candidate) {
            if let Ok(commit) = reference.peel_to_commit() {
                return Ok(commit);
            }
        }
    }

    // Try as a SHA prefix
    if let Ok(oid) = git2::Oid::from_str(refname) {
        if let Ok(commit) = repo.find_commit(oid) {
            return Ok(commit);
        }
    }

    // Try revparse as last resort
    if let Ok(obj) = repo.revparse_single(refname) {
        if let Ok(commit) = obj.peel_to_commit() {
            return Ok(commit);
        }
    }

    Err(AugentError::GitRefResolveFailed {
        git_ref: refname.to_string(),
        reason: "Could not resolve reference".to_string(),
    })
}

/// Checkout a specific commit in the repository
pub fn checkout_commit(repo: &Repository, sha: &str) -> Result<()> {
    let oid = git2::Oid::from_str(sha).map_err(|e| AugentError::GitCheckoutFailed {
        sha: sha.to_string(),
        reason: e.message().to_string(),
    })?;

    let commit = repo
        .find_commit(oid)
        .map_err(|e| AugentError::GitCheckoutFailed {
            sha: sha.to_string(),
            reason: e.message().to_string(),
        })?;

    // Create a detached HEAD at the commit
    repo.set_head_detached(commit.id())
        .map_err(|e| AugentError::GitCheckoutFailed {
            sha: sha.to_string(),
            reason: e.message().to_string(),
        })?;

    // Checkout the working tree
    let mut checkout_builder = git2::build::CheckoutBuilder::new();
    checkout_builder.force();

    repo.checkout_head(Some(&mut checkout_builder))
        .map_err(|e| AugentError::GitCheckoutFailed {
            sha: sha.to_string(),
            reason: e.message().to_string(),
        })?;

    Ok(())
}

/// Open an existing repository
#[allow(dead_code)] // used when reading ref from cached repo; kept for future use
pub fn open(path: &Path) -> Result<Repository> {
    Repository::open(path).map_err(|e| AugentError::GitOpenFailed {
        path: path.display().to_string(),
        reason: e.message().to_string(),
    })
}

/// Set up authentication callbacks for git operations
///
/// This delegates authentication to git's native credential system:
/// - SSH keys from ~/.ssh/
/// - SSH agent
/// - Git credential helpers
/// - Username/password from environment
fn setup_auth_callbacks(callbacks: &mut RemoteCallbacks) {
    callbacks.credentials(|url, username_from_url, allowed_types| {
        // Default credentials (for public repos) - try this first
        if allowed_types.contains(CredentialType::DEFAULT) {
            return Cred::default();
        }

        // For SSH authentication
        if allowed_types.contains(CredentialType::SSH_KEY) {
            // Try SSH agent first
            if let Some(username) = username_from_url {
                if let Ok(cred) = Cred::ssh_key_from_agent(username) {
                    return Ok(cred);
                }

                // Fall back to default SSH key locations
                let home = dirs::home_dir().unwrap_or_default();
                let ssh_dir = home.join(".ssh");

                // Try common key names
                for key_name in &["id_ed25519", "id_rsa", "id_ecdsa"] {
                    let private_key = ssh_dir.join(key_name);
                    let public_key = ssh_dir.join(format!("{}.pub", key_name));

                    if private_key.exists() {
                        let public_key_path = if public_key.exists() {
                            Some(public_key.as_path())
                        } else {
                            None
                        };

                        if let Ok(cred) =
                            Cred::ssh_key(username, public_key_path, &private_key, None)
                        {
                            return Ok(cred);
                        }
                    }
                }
            }
        }

        // For username/password authentication
        if allowed_types.contains(CredentialType::USER_PASS_PLAINTEXT) {
            // Try git credential helper first
            if let Ok(cred) = Cred::credential_helper(
                &git2::Config::open_default().unwrap_or_else(|_| git2::Config::new().unwrap()),
                url,
                username_from_url,
            ) {
                return Ok(cred);
            }

            // For public HTTPS repos, try empty username/password
            // This allows git2 to make request and get real error from server
            if let Ok(cred) = Cred::userpass_plaintext("", "") {
                return Ok(cred);
            }

            // If that fails, try a default username with empty password
            if let Some(username) = username_from_url {
                if let Ok(cred) = Cred::userpass_plaintext(username, "") {
                    return Ok(cred);
                }
            }

            // Try common git usernames (git, anonymous)
            for username in &["git", "anonymous"] {
                if let Ok(cred) = Cred::userpass_plaintext(username, "") {
                    return Ok(cred);
                }
            }
        }

        // If we get here, we couldn't provide any credentials
        // Return a generic error to let git2 handle it
        Err(git2::Error::new(
            git2::ErrorCode::Auth,
            git2::ErrorClass::Http,
            "authentication failed",
        ))
    });
}

/// Get the symbolic name of HEAD (e.g., "main", "master")
///
/// Returns the branch name if HEAD is not detached, None if HEAD is detached
pub fn get_head_ref_name(repo: &Repository) -> Result<Option<String>> {
    let head = repo.head().map_err(|e| AugentError::GitRefResolveFailed {
        git_ref: "HEAD".to_string(),
        reason: e.message().to_string(),
    })?;

    // Check if HEAD is symbolic (i.e., not detached)
    // is_branch() returns true only for normal branch references
    if head.is_branch() {
        if let Some(refname) = head.shorthand() {
            Ok(Some(refname.to_string()))
        } else {
            Ok(None)
        }
    } else {
        Ok(None)
    }
}

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

    #[test]
    fn test_ls_remote_rejects_file_url() {
        // ls-remote is not used for local URLs; we should get a clear error
        let result = ls_remote("file:///tmp/repo", None);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("ls-remote not used"));
    }

    #[test]
    fn test_clone_public_repo() {
        // This test requires network access, so we mark it as ignored by default
        // Run with: cargo test -- --ignored
        let temp = TempDir::new_in(crate::temp::temp_dir_base()).unwrap();
        let result = clone(
            "https://github.com/octocat/Hello-World.git",
            temp.path(),
            true,
        );

        // This may fail in CI without network, so we don't assert success
        if let Ok(repo) = result {
            assert!(repo.head().is_ok());
        }
    }

    #[test]
    fn test_resolve_ref_head() {
        // Create a test repository
        let temp = TempDir::new_in(crate::temp::temp_dir_base()).unwrap();
        let repo = Repository::init(temp.path()).unwrap();

        // Create an initial commit
        let sig = git2::Signature::now("Test", "test@test.com").unwrap();
        let tree_id = {
            let mut index = repo.index().unwrap();
            index.write_tree().unwrap()
        };
        let tree = repo.find_tree(tree_id).unwrap();
        repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .unwrap();

        // Resolve HEAD
        let sha = resolve_ref(&repo, None).unwrap();
        assert!(!sha.is_empty());
        assert_eq!(sha.len(), 40); // Full SHA
    }

    #[test]
    fn test_resolve_ref_by_name() {
        // Create a test repository with a branch
        let temp = TempDir::new_in(crate::temp::temp_dir_base()).unwrap();
        let repo = Repository::init(temp.path()).unwrap();

        // Create an initial commit
        let sig = git2::Signature::now("Test", "test@test.com").unwrap();
        let tree_id = {
            let mut index = repo.index().unwrap();
            index.write_tree().unwrap()
        };
        let tree = repo.find_tree(tree_id).unwrap();
        let commit_oid = repo
            .commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .unwrap();

        // Resolve by branch name (master/main is the default)
        let sha = resolve_ref(&repo, Some("master")).or_else(|_| resolve_ref(&repo, Some("main")));

        if let Ok(sha) = sha {
            assert_eq!(sha, commit_oid.to_string());
        }
    }

    #[test]
    fn test_get_head_ref_name() {
        // Create a test repository
        let temp = TempDir::new_in(crate::temp::temp_dir_base()).unwrap();
        let repo = Repository::init(temp.path()).unwrap();

        // Create an initial commit
        let sig = git2::Signature::now("Test", "test@test.com").unwrap();
        let tree_id = {
            let mut index = repo.index().unwrap();
            index.write_tree().unwrap()
        };
        let tree = repo.find_tree(tree_id).unwrap();
        repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .unwrap();

        // Get HEAD ref name (should be "master" or "main" depending on git version)
        let ref_name = get_head_ref_name(&repo).unwrap();
        assert!(ref_name.is_some());
        assert!(ref_name == Some("master".to_string()) || ref_name == Some("main".to_string()));
    }

    #[test]
    fn test_get_head_ref_name_detached() {
        // Create a test repository
        let temp = TempDir::new_in(crate::temp::temp_dir_base()).unwrap();
        let repo = Repository::init(temp.path()).unwrap();

        // Create an initial commit
        let sig = git2::Signature::now("Test", "test@test.com").unwrap();
        let tree_id = {
            let mut index = repo.index().unwrap();
            index.write_tree().unwrap()
        };
        let tree = repo.find_tree(tree_id).unwrap();
        let commit_oid = repo
            .commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .unwrap();

        // Checkout the commit to detach HEAD
        let oid = git2::Oid::from_str(&commit_oid.to_string()).unwrap();
        let commit = repo.find_commit(oid).unwrap();
        repo.set_head_detached(commit.id()).unwrap();

        // Get HEAD ref name (should be None when detached)
        let ref_name = get_head_ref_name(&repo).unwrap();
        assert!(ref_name.is_none());
    }

    #[test]
    fn test_checkout_commit() {
        // Create a test repository
        let temp = TempDir::new_in(crate::temp::temp_dir_base()).unwrap();
        let repo = Repository::init(temp.path()).unwrap();

        // Create an initial commit
        let sig = git2::Signature::now("Test", "test@test.com").unwrap();
        let tree_id = {
            let mut index = repo.index().unwrap();
            index.write_tree().unwrap()
        };
        let tree = repo.find_tree(tree_id).unwrap();
        let commit_oid = repo
            .commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .unwrap();

        // Checkout the commit
        let result = checkout_commit(&repo, &commit_oid.to_string());
        assert!(result.is_ok());
    }

    #[test]
    fn test_resolve_ref_invalid() {
        // Create a test repository
        let temp = TempDir::new_in(crate::temp::temp_dir_base()).unwrap();
        let repo = Repository::init(temp.path()).unwrap();

        // Create an initial commit
        let sig = git2::Signature::now("Test", "test@test.com").unwrap();
        let tree_id = {
            let mut index = repo.index().unwrap();
            index.write_tree().unwrap()
        };
        let tree = repo.find_tree(tree_id).unwrap();
        repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .unwrap();

        // Try to resolve invalid ref
        let result = resolve_ref(&repo, Some("nonexistent"));
        assert!(result.is_err());
    }

    #[test]
    fn test_checkout_invalid_sha() {
        // Create a test repository
        let temp = TempDir::new_in(crate::temp::temp_dir_base()).unwrap();
        let repo = Repository::init(temp.path()).unwrap();

        // Try to checkout invalid SHA
        let result = checkout_commit(&repo, "0000000000000000000000000000000000000000");
        assert!(result.is_err());
    }

    #[test]
    fn test_open_nonexistent_repo() {
        let temp = TempDir::new_in(crate::temp::temp_dir_base()).unwrap();
        let result = open(temp.path().join("nonexistent").as_path());
        assert!(result.is_err());
    }

    #[test]
    fn test_resolve_reference_full_sha() {
        let temp = TempDir::new_in(crate::temp::temp_dir_base()).unwrap();
        let repo = Repository::init(temp.path()).unwrap();

        let sig = git2::Signature::now("Test", "test@test.com").unwrap();
        let tree_id = {
            let mut index = repo.index().unwrap();
            index.write_tree().unwrap()
        };
        let tree = repo.find_tree(tree_id).unwrap();
        let commit_oid = repo
            .commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .unwrap();

        let commit = repo.find_commit(commit_oid).unwrap();
        let full_sha = commit.id().to_string();

        let result = resolve_reference(&repo, &full_sha);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap().id(),
            git2::Oid::from_str(&full_sha).unwrap()
        );
    }

    #[test]
    fn test_normalize_ssh_url() {
        // Test SCP-style SSH URL normalization
        let scp_url = "git@github.com:user/repo.git";
        let normalized = normalize_ssh_url_for_clone(scp_url);
        assert_eq!(normalized, "ssh://git@github.com/user/repo.git");

        // Test already-normalized ssh:// URL (should not change)
        let ssh_url = "ssh://git@github.com/user/repo.git";
        let normalized = normalize_ssh_url_for_clone(ssh_url);
        assert_eq!(normalized, "ssh://git@github.com/user/repo.git");

        // Test HTTPS URL (should not change)
        let https_url = "https://github.com/user/repo.git";
        let normalized = normalize_ssh_url_for_clone(https_url);
        assert_eq!(normalized, "https://github.com/user/repo.git");

        // Test SSH URL with custom port
        let scp_url_port = "git@github.com:22:user/repo.git";
        let normalized = normalize_ssh_url_for_clone(scp_url_port);
        // Note: This will normalize to ssh://git@github.com/22:user/repo.git
        // which is not ideal, but libgit2 should handle the port in the host part
        assert!(normalized.starts_with("ssh://git@github.com/"));

        // Test SSH URL without .git suffix
        let scp_url_no_git = "git@github.com:user/repo";
        let normalized = normalize_ssh_url_for_clone(scp_url_no_git);
        assert_eq!(normalized, "ssh://git@github.com/user/repo");

        // Test SSH URL with absolute path
        let scp_url_absolute = "git@github.com:/absolute/path/repo.git";
        let normalized = normalize_ssh_url_for_clone(scp_url_absolute);
        assert_eq!(normalized, "ssh://git@github.com/absolute/path/repo.git");
    }
}