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
use anyhow::Context;
use url::Url;

use crate::actions::repo::parse_owner_and_repo;
use crate::actions::GeneralArgs;
use crate::render::spinner::spin_until_ready;
use crate::types::context::BergContext;

use clap::Parser;

/// Clone a repository
#[derive(Parser, Debug)]
pub struct RepoCloneArgs {
    /// Repository to be cloned
    #[arg(value_name = "OWNER/REPO")]
    pub owner_and_repo: String,
    /// Whether or not to clone via ssh
    #[arg(long, default_value_t = false)]
    pub use_ssh: bool,
    /// Where to clone into
    #[arg(value_name = "DESTINATION")]
    pub destination: Option<String>,
}

impl RepoCloneArgs {
    pub async fn run(self, general_args: GeneralArgs) -> anyhow::Result<()> {
        let _ = general_args;
        let ctx = BergContext::new(self).await?;

        let (owner, repo) = parse_owner_and_repo(ctx.args.owner_and_repo.as_str())?;
        let url = if ctx.args.use_ssh {
            anyhow::bail!("SSH Cloning under maintenance");
            #[allow(unreachable_code)]
            spin_until_ready(get_ssh_url(&ctx, owner.as_str(), repo.as_str())).await?
        } else {
            ctx.config
                .url()?
                .join(format!("/{owner}/{repo}.git").as_str())?
        };

        // TODO: Add back ***opt in*** ask confirm to clone

        start_clone_repo(url, ctx.args.destination.unwrap_or(repo))?;
        Ok(())
    }
}

async fn get_ssh_url(
    ctx: &BergContext<RepoCloneArgs>,
    ownername: &str,
    reponame: &str,
) -> anyhow::Result<Url> {
    ctx.client
        .repo_get(ownername, reponame)
        .await
        .map_err(anyhow::Error::from)
        .inspect(|x| tracing::debug!("{x:#?}"))
        .and_then(|repo| repo.ssh_url.context("No SSH url on repo"))
        .and_then(|url| Url::parse(url.as_str()).context("Url wasn't a valid SSH Url"))
        .context("User doesn't own the repo that was specified.")
}

fn start_clone_repo(ssh_url: Url, destination: String) -> anyhow::Result<()> {
    let mut cmd = std::process::Command::new("git");
    cmd.arg("clone")
        .arg(ssh_url.as_str())
        .arg(destination.as_str());
    tracing::debug!("cmd: {cmd:?}");
    let mut child = cmd.stdout(std::process::Stdio::inherit()).spawn()?;
    child.wait()?;
    Ok(())
}