1use anyhow::*;
2use std::io::Write;
3use std::result::Result::Ok;
4
5use crate::repo;
6
7pub fn test_auth<W: Write>(
8 repo: &repo::Repo,
9 stdout: &mut W,
10) -> Result<()> {
11 writeln!(stdout, "Testing authentication for repository...")?;
12 writeln!(stdout, "Repository: {}", repo.work_dir.display())?;
13 writeln!(stdout)?;
14
15 let head_ref = repo.git_repo.head()?;
17 let branch_name = head_ref.shorthand()
18 .ok_or_else(|| anyhow!("Cannot get branch name"))?;
19
20 writeln!(stdout, "Current branch: {}", branch_name)?;
21
22 if let Some(tracking) = repo.tracking_branch(branch_name)? {
24 writeln!(stdout, "Remote: {}", tracking.remote)?;
25 writeln!(stdout, "Remote ref: {}", tracking.remote_ref)?;
26 writeln!(stdout)?;
27
28 match repo.git_repo.find_remote(&tracking.remote) {
30 Ok(mut remote) => {
31 writeln!(stdout, "Attempting to connect to remote...")?;
32 writeln!(stdout)?;
33
34 match remote.connect_auth(
36 git2::Direction::Fetch,
37 Some(repo.remote_callbacks_verbose()?),
38 None,
39 ) {
40 Ok(connection) => {
41 writeln!(stdout)?;
42 writeln!(stdout, "? Connection successful!")?;
43 writeln!(stdout)?;
44 writeln!(stdout, "Available remote heads:")?;
45 for head in connection.list()?.iter() {
46 writeln!(stdout, " - {}", head.name())?;
47 }
48 drop(connection);
49 }
50 Err(e) => {
51 writeln!(stdout)?;
52 writeln!(stdout, "? Connection failed: {}", e)?;
53 writeln!(stdout)?;
54 writeln!(stdout, "Troubleshooting steps:")?;
55 writeln!(stdout, "1. Check SSH agent is running: ssh-add -l")?;
56 writeln!(stdout, "2. Verify SSH_AUTH_SOCK is set: echo $SSH_AUTH_SOCK")?;
57 writeln!(stdout, "3. Test SSH connection: ssh -T git@<hostname>")?;
58 writeln!(stdout, "4. Check SSH keys exist: ls -la ~/.ssh/")?;
59 return Err(e.into());
60 }
61 }
62 }
63 Err(e) => {
64 writeln!(stdout, "? Remote '{}' not found: {}", tracking.remote, e)?;
65 return Err(e.into());
66 }
67 }
68 } else {
69 writeln!(stdout, "No tracking branch configured for '{}'", branch_name)?;
70 writeln!(stdout)?;
71 writeln!(stdout, "To set up tracking, run:")?;
72 writeln!(stdout, " git branch --set-upstream-to=<remote>/<branch> {}", branch_name)?;
73 }
74
75 Ok(())
76}