codeberg_cli/actions/repo/
fork.rs

1use crate::actions::GlobalArgs;
2use crate::render::spinner::{spin_and_try_every_second_for, spin_until_ready};
3use crate::render::ui::confirm_with_prompt;
4use crate::types::context::BergContext;
5use crate::types::git::OwnerRepo;
6use anyhow::Context;
7use forgejo_api::structs::CreateForkOption;
8use url::Url;
9
10use clap::Parser;
11
12/// Fork a repository
13#[derive(Parser, Debug)]
14pub struct RepoForkArgs {
15    /// Repository to be forked
16    #[arg(value_name = "OWNER/REPO")]
17    pub owner_and_repo: OwnerRepo,
18}
19
20impl RepoForkArgs {
21    pub async fn run(self, global_args: GlobalArgs) -> anyhow::Result<()> {
22        let _ = global_args;
23        let ctx = BergContext::new(self, global_args).await?;
24
25        let OwnerRepo { owner, repo } = ctx.args.owner_and_repo.clone();
26        let ssh_url =
27            spin_until_ready(start_fork_repo(&ctx, owner.as_str(), repo.as_str())).await?;
28        ask_confirm_clone(repo.as_str())?;
29        start_clone_repo(ssh_url)?;
30        Ok(())
31    }
32}
33
34async fn start_fork_repo(
35    ctx: &BergContext<RepoForkArgs>,
36    owner: &str,
37    repo: &str,
38) -> anyhow::Result<Url> {
39    // just to check if the repo exists
40    let _ssh_url_original = get_ssh_url(ctx, owner, repo).await?;
41
42    ctx.client
43        .create_fork(
44            owner,
45            repo,
46            CreateForkOption {
47                name: None,
48                organization: None,
49            },
50        )
51        .await?;
52    let user = ctx.client.user_get_current().await?;
53    let username = user
54        .login
55        .as_ref()
56        .cloned()
57        .context("Current user has no username")?;
58    let new_url = spin_and_try_every_second_for(|| get_ssh_url(ctx, &username, repo), 10).await?;
59    tracing::debug!("Forked Repo SSH URL: {new_url:?}");
60    Ok(new_url)
61}
62
63async fn get_ssh_url(
64    ctx: &BergContext<RepoForkArgs>,
65    owner: &str,
66    repo: &str,
67) -> anyhow::Result<Url> {
68    ctx.client
69        .repo_get(owner, repo)
70        .await
71        .map_err(anyhow::Error::from)
72        .and_then(|repo| repo.ssh_url.context("No SSH url on repo"))
73        .context("User doesn't own the repo that was specified.")
74}
75
76fn ask_confirm_clone(repo: &str) -> anyhow::Result<()> {
77    let current_path = std::env::current_dir()?;
78    if !confirm_with_prompt(
79        format!("Do you really to fork {repo} into the directory {current_path:?}").as_str(),
80    )? {
81        anyhow::bail!("Abort cloning the repository.")
82    }
83    Ok(())
84}
85
86fn start_clone_repo(ssh_url: Url) -> anyhow::Result<()> {
87    let mut cmd = std::process::Command::new("git");
88    cmd.arg("clone").arg(ssh_url.to_string());
89    tracing::debug!("cmd: {cmd:?}");
90    let mut child = cmd.stdout(std::process::Stdio::inherit()).spawn()?;
91    child.wait()?;
92    Ok(())
93}