codeberg_cli/actions/repo/
fork.rsuse 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;
#[derive(Parser, Debug)]
pub struct RepoForkArgs {
#[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> {
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(())
}