use crate::actions::GlobalArgs;
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 crate::types::git::{Git, OwnerRepo};
use forgejo_api::structs::CreateForkOption;
use miette::{Context, IntoDiagnostic};
use url::Url;
use clap::Parser;
#[derive(Parser, Debug)]
pub struct RepoForkArgs {
#[arg(value_name = "OWNER/REPO")]
pub owner_and_repo: OwnerRepo,
}
impl RepoForkArgs {
pub async fn run(self, global_args: GlobalArgs) -> miette::Result<()> {
let _ = global_args;
let ctx = BergContext::new(self, global_args).await?;
let OwnerRepo { owner, repo } = ctx.args.owner_and_repo.clone();
let url = spin_until_ready(start_fork_repo(&ctx, owner.as_str(), repo.as_str())).await?;
ask_confirm_clone(repo.as_str())?;
Git::clone(url, repo)?;
Ok(())
}
}
async fn start_fork_repo(
ctx: &BergContext<RepoForkArgs>,
owner: &str,
repo: &str,
) -> miette::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
.into_diagnostic()?;
let user = ctx.client.user_get_current().await.into_diagnostic()?;
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,
) -> miette::Result<Url> {
ctx.client
.repo_get(owner, repo)
.await
.into_diagnostic()
.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) -> miette::Result<()> {
let current_path = std::env::current_dir().into_diagnostic()?;
if !confirm_with_prompt(
format!("Do you really to fork {repo} into the directory {current_path:?}").as_str(),
)? {
miette::bail!("Abort cloning the repository.")
}
Ok(())
}