codeberg_cli/actions/repo/
fork.rs

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
use crate::actions::GeneralArgs;
use crate::render::spinner::{spin_and_try_every_second_for, spin_until_ready};
use crate::render::ui::confirm_with_prompt;
use crate::types::context::BergContext;
use anyhow::Context;
use forgejo_api::structs::CreateForkOption;
use url::Url;

use super::parse_owner_and_repo;

use clap::Parser;

/// Fork a repository
#[derive(Parser, Debug)]
pub struct RepoForkArgs {
    /// Repository to be forked
    #[arg(value_name = "OWNER/REPO")]
    pub owner_and_repo: String,
}

impl RepoForkArgs {
    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 ssh_url =
            spin_until_ready(start_fork_repo(&ctx, owner.as_str(), repo.as_str())).await?;
        ask_confirm_clone(repo.as_str())?;
        start_clone_repo(ssh_url)?;
        Ok(())
    }
}

async fn start_fork_repo(
    ctx: &BergContext<RepoForkArgs>,
    owner: &str,
    repo: &str,
) -> anyhow::Result<Url> {
    // just to check if the repo exists
    let _ssh_url_original = get_ssh_url(ctx, owner, repo).await?;

    ctx.client
        .create_fork(
            owner,
            repo,
            CreateForkOption {
                name: None,
                organization: None,
            },
        )
        .await?;
    let user = ctx.client.user_get_current().await?;
    let username = user
        .login
        .as_ref()
        .cloned()
        .context("Current user has no username")?;
    let new_url = spin_and_try_every_second_for(|| get_ssh_url(ctx, &username, repo), 10).await?;
    tracing::debug!("Forked Repo SSH URL: {new_url:?}");
    Ok(new_url)
}

async fn get_ssh_url(
    ctx: &BergContext<RepoForkArgs>,
    owner: &str,
    repo: &str,
) -> anyhow::Result<Url> {
    ctx.client
        .repo_get(owner, repo)
        .await
        .map_err(anyhow::Error::from)
        .and_then(|repo| repo.ssh_url.context("No SSH url on repo"))
        .context("User doesn't own the repo that was specified.")
}

fn ask_confirm_clone(repo: &str) -> anyhow::Result<()> {
    let current_path = std::env::current_dir()?;
    if !confirm_with_prompt(
        format!("Do you really to fork {repo} into the directory {current_path:?}").as_str(),
    )? {
        anyhow::bail!("Abort cloning the repository.")
    }
    Ok(())
}

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