From e2a1952f2e2c291166aa86774682cfafe16a5553 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 05:32:18 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix:=20fork=20works=20in=20dev?= =?UTF-8?q?=20and=20test=20builds;=20its=20route=20lived=20alone=20in=20a?= =?UTF-8?q?=20module=20nothing=20referenced,=20so=20the=20linker=20dropped?= =?UTF-8?q?=20it=20and=20POST=20/fork=20answered=20404?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-web-repo/src/pages/compare.rs | 139 ++++- crates/forge-web-repo/src/pages/fork.rs | 483 ------------------ crates/forge-web-repo/src/pages/fork_tests.rs | 340 ++++++++++++ crates/forge-web-repo/src/pages/mod.rs | 1 - 4 files changed, 474 insertions(+), 489 deletions(-) delete mode 100644 crates/forge-web-repo/src/pages/fork.rs create mode 100644 crates/forge-web-repo/src/pages/fork_tests.rs diff --git a/crates/forge-web-repo/src/pages/compare.rs b/crates/forge-web-repo/src/pages/compare.rs index 8d0192d..e9f5e59 100644 --- a/crates/forge-web-repo/src/pages/compare.rs +++ b/crates/forge-web-repo/src/pages/compare.rs @@ -1,20 +1,23 @@ use std::path::PathBuf; -use forge_core::{Action, NewPull, Repo as RepoRecord, authorize, validate_body, validate_title}; +use forge_core::{ + Action, AuditAction, NewPull, Repo as RepoRecord, authorize, validate_body, validate_title, +}; use forge_git::browse::{self, CommitInfo, RefKind}; use forge_git::command::ObjectSource; use forge_git::history; use forge_git::pulls; -use forge_git::repo::repo_path; +use forge_git::repo::{fork_bare, repo_path}; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, context}; use topcoat::router::content::Form; -use topcoat::router::error::{bad_request, not_found, see_other}; -use topcoat::router::{page, path_param, query_params}; +use topcoat::router::error::{SeeOther, bad_request, not_found, see_other}; +use topcoat::router::{page, path_param, query_params, route}; use topcoat::view::{View, view}; -use crate::auth::require_user; +use crate::audit::{self, Actor, Target}; +use crate::auth::{require_csrf, require_user}; use crate::i18n; use crate::i18n::pulls::{self as g, K}; use crate::notify::{self, Activity}; @@ -612,6 +615,132 @@ async fn pull_create(cx: &Cx, Form(form): Form) -> Result { Err(see_other(pull_href(&ctx, number)).into()) } +#[derive(Deserialize)] +struct ForkForm { + #[serde(default)] + csrf: String, +} + +#[route(POST "/{owner}/{repo}/fork")] +async fn fork_post(cx: &Cx, Form(form): Form) -> Result { + let owner = owner(cx); + let name = repo(cx); + let source = load_repo(cx, owner, name).await?; + let (viewer, _) = require_csrf(cx, &form.csrf).await?; + let state = context::(cx); + let source_repo = &source.repo; + + if source_repo.owner_id == viewer.id { + return Ok(see_other(repo_href( + &source_repo.owner_name, + &source_repo.name, + "", + "", + ))); + } + + if let Some(existing) = viewer_fork(state, &source_repo.id, &viewer.id).await? { + return Ok(see_other(repo_href( + &existing.owner_name, + &existing.name, + "", + "", + ))); + } + + let fork_name = free_name(state, &viewer.username, &source_repo.name).await?; + let fork = match state + .store + .create_fork(source_repo, &viewer.id, &fork_name) + .await + { + Ok(fork) => fork, + Err(e @ forge_core::Error::Conflict(_)) => { + let Some(existing) = viewer_fork(state, &source_repo.id, &viewer.id).await? else { + return Err(e.into()); + }; + return Ok(see_other(repo_href( + &existing.owner_name, + &existing.name, + "", + "", + ))); + } + Err(e) => return Err(e.into()), + }; + let dst = repo_path(&state.config.data_dir, &fork.id)?; + if let Err(e) = fork_bare(&state.git, &source.path, &dst).await { + let _ = state.store.delete_repo(&fork.id).await; + return Err(e.into()); + } + state.live.bump_repo(&fork.owner_id, &fork.id); + state.live.bump_repo(&source_repo.owner_id, &source_repo.id); + match state.store.list_labels(&source_repo.id).await { + Ok(labels) => { + for label in labels { + if let Err(e) = state + .store + .create_label(&fork.id, &label.name, &label.color, &label.description) + .await + { + tracing::warn!(error = %e, repo_id = %fork.id, label = %label.name, "fork: could not copy label"); + } + } + } + Err(e) => { + tracing::warn!(error = %e, repo_id = %fork.id, "fork: could not list source labels"); + } + } + let full_name = format!("{}/{}", fork.owner_name, fork.name); + let source_name = format!("{}/{}", source_repo.owner_name, source_repo.name); + audit::record( + &state.store, + Some(cx), + Actor::User(&viewer), + AuditAction::RepoCreated, + Target { + kind: "repo", + id: &fork.id, + name: &full_name, + }, + serde_json::json!({ "fork_of": source_name }), + ) + .await; + Ok(see_other(repo_href(&fork.owner_name, &fork.name, "", ""))) +} + +async fn viewer_fork( + state: &AppState, + source_id: &str, + viewer_id: &str, +) -> Result> { + Ok(state + .store + .list_forks(source_id) + .await? + .into_iter() + .find(|fork| fork.owner_id == viewer_id)) +} + +async fn free_name(state: &AppState, owner: &str, base: &str) -> Result { + let mut candidate = base.to_owned(); + let mut suffix = 1u32; + while state + .store + .repo_by_owner_and_name(owner, &candidate) + .await? + .is_some() + { + candidate = format!("{base}-{suffix}"); + suffix += 1; + } + Ok(candidate) +} + +#[cfg(test)] +#[path = "fork_tests.rs"] +mod fork_tests; + #[cfg(test)] mod tests { use std::path::{Path, PathBuf}; diff --git a/crates/forge-web-repo/src/pages/fork.rs b/crates/forge-web-repo/src/pages/fork.rs deleted file mode 100644 index f22a994..0000000 --- a/crates/forge-web-repo/src/pages/fork.rs +++ /dev/null @@ -1,483 +0,0 @@ -use forge_core::AuditAction; -use forge_git::repo::{fork_bare, repo_path}; -use serde::Deserialize; -use topcoat::Result; -use topcoat::context::{Cx, context}; -use topcoat::router::content::Form; -use topcoat::router::error::{SeeOther, see_other}; -use topcoat::router::{path_param, route}; - -use crate::audit::{self, Actor, Target}; -use crate::auth::require_csrf; -use crate::pages::repo_ctx::load_repo; -use crate::state::AppState; -use crate::views::repo_href; - -path_param!(owner); -path_param!(repo); - -#[derive(Deserialize)] -struct ForkForm { - #[serde(default)] - csrf: String, -} - -#[route(POST "/{owner}/{repo}/fork")] -async fn fork_post(cx: &Cx, Form(form): Form) -> Result { - let owner = owner(cx); - let name = repo(cx); - let source = load_repo(cx, owner, name).await?; - let (viewer, _) = require_csrf(cx, &form.csrf).await?; - let state = context::(cx); - let source_repo = &source.repo; - - if source_repo.owner_id == viewer.id { - return Ok(see_other(repo_href( - &source_repo.owner_name, - &source_repo.name, - "", - "", - ))); - } - - if let Some(existing) = viewer_fork(state, &source_repo.id, &viewer.id).await? { - return Ok(see_other(repo_href( - &existing.owner_name, - &existing.name, - "", - "", - ))); - } - - let fork_name = free_name(state, &viewer.username, &source_repo.name).await?; - let fork = match state - .store - .create_fork(source_repo, &viewer.id, &fork_name) - .await - { - Ok(fork) => fork, - Err(e @ forge_core::Error::Conflict(_)) => { - let Some(existing) = viewer_fork(state, &source_repo.id, &viewer.id).await? else { - return Err(e.into()); - }; - return Ok(see_other(repo_href( - &existing.owner_name, - &existing.name, - "", - "", - ))); - } - Err(e) => return Err(e.into()), - }; - let dst = repo_path(&state.config.data_dir, &fork.id)?; - if let Err(e) = fork_bare(&state.git, &source.path, &dst).await { - let _ = state.store.delete_repo(&fork.id).await; - return Err(e.into()); - } - state.live.bump_repo(&fork.owner_id, &fork.id); - state.live.bump_repo(&source_repo.owner_id, &source_repo.id); - match state.store.list_labels(&source_repo.id).await { - Ok(labels) => { - for label in labels { - if let Err(e) = state - .store - .create_label(&fork.id, &label.name, &label.color, &label.description) - .await - { - tracing::warn!(error = %e, repo_id = %fork.id, label = %label.name, "fork: could not copy label"); - } - } - } - Err(e) => { - tracing::warn!(error = %e, repo_id = %fork.id, "fork: could not list source labels"); - } - } - let full_name = format!("{}/{}", fork.owner_name, fork.name); - let source_name = format!("{}/{}", source_repo.owner_name, source_repo.name); - audit::record( - &state.store, - Some(cx), - Actor::User(&viewer), - AuditAction::RepoCreated, - Target { - kind: "repo", - id: &fork.id, - name: &full_name, - }, - serde_json::json!({ "fork_of": source_name }), - ) - .await; - Ok(see_other(repo_href(&fork.owner_name, &fork.name, "", ""))) -} - -async fn viewer_fork( - state: &AppState, - source_id: &str, - viewer_id: &str, -) -> Result> { - Ok(state - .store - .list_forks(source_id) - .await? - .into_iter() - .find(|fork| fork.owner_id == viewer_id)) -} - -async fn free_name(state: &AppState, owner: &str, base: &str) -> Result { - let mut candidate = base.to_owned(); - let mut suffix = 1u32; - while state - .store - .repo_by_owner_and_name(owner, &candidate) - .await? - .is_some() - { - candidate = format!("{base}-{suffix}"); - suffix += 1; - } - Ok(candidate) -} - -#[cfg(test)] -mod tests { - use std::path::Path; - use std::process::Command; - - use crate::test_support::fixture::{Reply, send_form}; - use forge_core::{AuditAction, Store, Visibility}; - use forge_git::repo::{init_bare, repo_path}; - use topcoat::router::Router; - - use crate::auth::SESSION_COOKIE; - - const CSRF: &str = "fork-test-csrf"; - - struct Site { - router: Router, - store: Store, - dir: tempfile::TempDir, - } - - async fn site() -> (Site, [String; 3]) { - let dir = tempfile::tempdir().expect("tempdir"); - let state = crate::test_support::test_state(dir.path()).await; - let store = state.store.clone(); - let router = crate::test_support::app_router(state.clone()); - - let tahinli = store - .create_user("tahinli", None, "x", false) - .await - .expect("tahinli"); - let bob = store - .create_user("bob", None, "x", false) - .await - .expect("bob"); - let carol = store - .create_user("carol", None, "x", false) - .await - .expect("carol"); - let demo = store - .create_repo( - &tahinli.id, - "demo", - "A demo repo", - Visibility::Public, - "main", - ) - .await - .expect("demo"); - let secret = store - .create_repo(&tahinli.id, "secret", "", Visibility::Private, "main") - .await - .expect("secret"); - for repo in [&demo, &secret] { - let path = repo_path(dir.path(), &repo.id).expect("path"); - init_bare(&state.git, &path, "main").await.expect("init"); - } - - let work = dir.path().join("work"); - std::fs::create_dir_all(&work).expect("work dir"); - std::fs::write(work.join("README.md"), "# Demo\n").expect("write"); - git(&work, &["init", "-q", "-b", "main"]); - git(&work, &["add", "-A"]); - git(&work, &["commit", "-q", "-m", "first commit"]); - git(&work, &["tag", "v1"]); - let demo_path = repo_path(dir.path(), &demo.id).expect("path"); - git( - &work, - &[ - "push", - "-q", - demo_path.to_str().expect("utf8"), - "main:main", - "v1", - ], - ); - - let cookies = [ - sign_in(&store, &tahinli.id, "tahinli-token").await, - sign_in(&store, &bob.id, "bob-token").await, - sign_in(&store, &carol.id, "carol-token").await, - ]; - (Site { router, store, dir }, cookies) - } - - async fn sign_in(store: &Store, user_id: &str, token: &str) -> String { - crate::test_support::create_session(store, user_id, token, CSRF).await; - format!("__Host-{SESSION_COOKIE}={token}") - } - - fn git(dir: &Path, args: &[&str]) { - let status = Command::new("git") - .current_dir(dir) - .env("GIT_CONFIG_NOSYSTEM", "1") - .args([ - "-c", - "user.name=Test", - "-c", - "user.email=test@example.com", - "-c", - "commit.gpgsign=false", - ]) - .args(args) - .status() - .expect("git runs"); - assert!(status.success(), "git {args:?} failed"); - } - - async fn send( - site: &Site, - method: &str, - uri: &str, - cookie: Option<&str>, - form: Option, - ) -> Reply { - send_form(&site.router, method, uri, cookie, form).await - } - - async fn fork(site: &Site, cookie: Option<&str>) -> Reply { - send( - site, - "POST", - "/tahinli/demo/fork", - cookie, - Some(format!("csrf={CSRF}")), - ) - .await - } - - async fn scenario_refusals(site: &Site, tahinli: &str, bob: &str, carol: &str) { - let reply = send( - site, - "POST", - "/tahinli/demo/fork", - Some(bob), - Some(String::new()), - ) - .await; - assert_eq!(reply.status, 403); - let reply = send( - site, - "POST", - "/tahinli/demo/fork", - Some(bob), - Some("csrf=wrong".into()), - ) - .await; - assert_eq!(reply.status, 403); - assert!( - site.store - .repo_by_owner_and_name("bob", "demo") - .await - .expect("q") - .is_none(), - "nothing was created" - ); - - let reply = fork(site, None).await; - assert_eq!(reply.status, 303); - assert!( - reply - .location - .as_deref() - .is_some_and(|l| l.starts_with("/login")), - "{:?}", - reply.location - ); - - let reply = send( - site, - "POST", - "/tahinli/secret/fork", - Some(carol), - Some(format!("csrf={CSRF}")), - ) - .await; - assert_eq!(reply.status, 404); - let reply = send( - site, - "POST", - "/tahinli/secret/fork", - None, - Some(format!("csrf={CSRF}")), - ) - .await; - assert_eq!(reply.status, 404, "anonymous viewers also get 404"); - - let reply = fork(site, Some(tahinli)).await; - assert_eq!(reply.status, 303); - assert_eq!(reply.location.as_deref(), Some("/tahinli/demo")); - assert!( - site.store - .repo_by_owner_and_name("tahinli", "demo-1") - .await - .expect("q") - .is_none() - ); - - let reply = send(site, "GET", "/tahinli/demo", Some(carol), None).await; - assert_eq!(reply.status, 200); - assert!( - reply.body.contains("href=\"/tahinli/demo/pulls\""), - "pulls tab" - ); - assert!(reply.body.contains("Pull requests")); - assert!( - reply.body.contains("action=\"/tahinli/demo/fork\""), - "fork button" - ); - let reply = send(site, "GET", "/tahinli/demo", None, None).await; - assert!( - !reply.body.contains("action=\"/tahinli/demo/fork\""), - "no fork button when anonymous" - ); - } - - async fn scenario_fork_copies(site: &Site, bob: &str) { - let demo = site - .store - .repo_by_owner_and_name("tahinli", "demo") - .await - .expect("query") - .expect("demo"); - site.store - .create_label(&demo.id, "triage-me", "#123456", "only here") - .await - .expect("label"); - let reply = fork(site, Some(bob)).await; - assert_eq!(reply.status, 303); - assert_eq!(reply.location.as_deref(), Some("/bob/demo")); - - let bob_id = site - .store - .user_by_username("bob") - .await - .expect("q") - .expect("bob") - .id; - let fork = site - .store - .repo_by_owner_and_name("bob", "demo") - .await - .expect("q") - .expect("fork row"); - assert_eq!(fork.fork_of.as_deref(), Some(demo.id.as_str())); - assert_eq!(fork.visibility, Visibility::Public); - assert_eq!(fork.owner_id, bob_id); - let labels: Vec<(String, String, String)> = site - .store - .list_labels(&fork.id) - .await - .expect("labels") - .into_iter() - .map(|l| (l.name, l.color, l.description)) - .collect(); - assert_eq!( - labels, - vec![( - "triage-me".to_string(), - "#123456".to_string(), - "only here".to_string() - )] - ); - - let forked = site - .store - .list_audit( - &forge_core::AuditFilter { - action: Some(AuditAction::RepoCreated), - ..Default::default() - }, - None, - 10, - ) - .await - .expect("audit"); - assert_eq!(forked.len(), 1, "one audit entry for the fork"); - assert_eq!(forked[0].target_id, fork.id); - assert_eq!(forked[0].target_name, "bob/demo"); - assert_eq!(forked[0].actor_id.as_deref(), Some(bob_id.as_str())); - let data: serde_json::Value = serde_json::from_str(&forked[0].data).expect("json"); - assert_eq!(data, serde_json::json!({ "fork_of": "tahinli/demo" })); - - let path = repo_path(site.dir.path(), &fork.id).expect("path"); - let refs = Command::new("git") - .arg("--git-dir") - .arg(&path) - .args(["for-each-ref", "--format=%(refname)"]) - .output() - .expect("git runs"); - let refs = String::from_utf8_lossy(&refs.stdout).into_owned(); - assert_eq!( - refs.lines().collect::>(), - vec!["refs/heads/main", "refs/tags/v1"] - ); - - let page = send(site, "GET", "/bob/demo", Some(bob), None).await; - assert_eq!(page.status, 200); - assert!(page.body.contains("forked from"), "fork line shown"); - assert!( - page.body.contains("href=\"/tahinli/demo\""), - "fork line links the source" - ); - } - - async fn scenario_fork_again(site: &Site, bob: &str) { - assert_eq!(fork(site, Some(bob)).await.status, 303); - let again = fork(site, Some(bob)).await; - assert_eq!(again.status, 303); - assert_eq!(again.location.as_deref(), Some("/bob/demo")); - assert!( - site.store - .repo_by_owner_and_name("bob", "demo-1") - .await - .expect("q") - .is_none(), - "no second fork was created" - ); - } - - async fn scenario_suffix(site: &Site) { - let erin = site - .store - .create_user("erin", None, "x", false) - .await - .expect("erin"); - let erin_cookie = sign_in(&site.store, &erin.id, "erin-token").await; - site.store - .create_repo(&erin.id, "demo", "", Visibility::Private, "main") - .await - .expect("erin's own demo"); - let reply = fork(site, Some(&erin_cookie)).await; - assert_eq!(reply.location.as_deref(), Some("/erin/demo-1")); - } - - #[tokio::test] - async fn fork_flows() { - let (site, [tahinli, bob, carol]) = site().await; - scenario_refusals(&site, &tahinli, &bob, &carol).await; - scenario_fork_copies(&site, &bob).await; - scenario_fork_again(&site, &bob).await; - scenario_suffix(&site).await; - } -} diff --git a/crates/forge-web-repo/src/pages/fork_tests.rs b/crates/forge-web-repo/src/pages/fork_tests.rs new file mode 100644 index 0000000..44b71a2 --- /dev/null +++ b/crates/forge-web-repo/src/pages/fork_tests.rs @@ -0,0 +1,340 @@ +use std::path::Path; +use std::process::Command; + +use crate::test_support::fixture::{Reply, send_form}; +use forge_core::{AuditAction, Store, Visibility}; +use forge_git::repo::{init_bare, repo_path}; +use topcoat::router::Router; + +use crate::auth::SESSION_COOKIE; + +const CSRF: &str = "fork-test-csrf"; + +struct Site { + router: Router, + store: Store, + dir: tempfile::TempDir, +} + +async fn site() -> (Site, [String; 3]) { + let dir = tempfile::tempdir().expect("tempdir"); + let state = crate::test_support::test_state(dir.path()).await; + let store = state.store.clone(); + let router = crate::test_support::app_router(state.clone()); + + let tahinli = store + .create_user("tahinli", None, "x", false) + .await + .expect("tahinli"); + let bob = store + .create_user("bob", None, "x", false) + .await + .expect("bob"); + let carol = store + .create_user("carol", None, "x", false) + .await + .expect("carol"); + let demo = store + .create_repo( + &tahinli.id, + "demo", + "A demo repo", + Visibility::Public, + "main", + ) + .await + .expect("demo"); + let secret = store + .create_repo(&tahinli.id, "secret", "", Visibility::Private, "main") + .await + .expect("secret"); + for repo in [&demo, &secret] { + let path = repo_path(dir.path(), &repo.id).expect("path"); + init_bare(&state.git, &path, "main").await.expect("init"); + } + + let work = dir.path().join("work"); + std::fs::create_dir_all(&work).expect("work dir"); + std::fs::write(work.join("README.md"), "# Demo\n").expect("write"); + git(&work, &["init", "-q", "-b", "main"]); + git(&work, &["add", "-A"]); + git(&work, &["commit", "-q", "-m", "first commit"]); + git(&work, &["tag", "v1"]); + let demo_path = repo_path(dir.path(), &demo.id).expect("path"); + git( + &work, + &[ + "push", + "-q", + demo_path.to_str().expect("utf8"), + "main:main", + "v1", + ], + ); + + let cookies = [ + sign_in(&store, &tahinli.id, "tahinli-token").await, + sign_in(&store, &bob.id, "bob-token").await, + sign_in(&store, &carol.id, "carol-token").await, + ]; + (Site { router, store, dir }, cookies) +} + +async fn sign_in(store: &Store, user_id: &str, token: &str) -> String { + crate::test_support::create_session(store, user_id, token, CSRF).await; + format!("__Host-{SESSION_COOKIE}={token}") +} + +fn git(dir: &Path, args: &[&str]) { + let status = Command::new("git") + .current_dir(dir) + .env("GIT_CONFIG_NOSYSTEM", "1") + .args([ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + ]) + .args(args) + .status() + .expect("git runs"); + assert!(status.success(), "git {args:?} failed"); +} + +async fn send( + site: &Site, + method: &str, + uri: &str, + cookie: Option<&str>, + form: Option, +) -> Reply { + send_form(&site.router, method, uri, cookie, form).await +} + +async fn fork(site: &Site, cookie: Option<&str>) -> Reply { + send( + site, + "POST", + "/tahinli/demo/fork", + cookie, + Some(format!("csrf={CSRF}")), + ) + .await +} + +async fn scenario_refusals(site: &Site, tahinli: &str, bob: &str, carol: &str) { + let reply = send( + site, + "POST", + "/tahinli/demo/fork", + Some(bob), + Some(String::new()), + ) + .await; + assert_eq!(reply.status, 403); + let reply = send( + site, + "POST", + "/tahinli/demo/fork", + Some(bob), + Some("csrf=wrong".into()), + ) + .await; + assert_eq!(reply.status, 403); + assert!( + site.store + .repo_by_owner_and_name("bob", "demo") + .await + .expect("q") + .is_none(), + "nothing was created" + ); + + let reply = fork(site, None).await; + assert_eq!(reply.status, 303); + assert!( + reply + .location + .as_deref() + .is_some_and(|l| l.starts_with("/login")), + "{:?}", + reply.location + ); + + let reply = send( + site, + "POST", + "/tahinli/secret/fork", + Some(carol), + Some(format!("csrf={CSRF}")), + ) + .await; + assert_eq!(reply.status, 404); + let reply = send( + site, + "POST", + "/tahinli/secret/fork", + None, + Some(format!("csrf={CSRF}")), + ) + .await; + assert_eq!(reply.status, 404, "anonymous viewers also get 404"); + + let reply = fork(site, Some(tahinli)).await; + assert_eq!(reply.status, 303); + assert_eq!(reply.location.as_deref(), Some("/tahinli/demo")); + assert!( + site.store + .repo_by_owner_and_name("tahinli", "demo-1") + .await + .expect("q") + .is_none() + ); + + let reply = send(site, "GET", "/tahinli/demo", Some(carol), None).await; + assert_eq!(reply.status, 200); + assert!( + reply.body.contains("href=\"/tahinli/demo/pulls\""), + "pulls tab" + ); + assert!(reply.body.contains("Pull requests")); + assert!( + reply.body.contains("action=\"/tahinli/demo/fork\""), + "fork button" + ); + let reply = send(site, "GET", "/tahinli/demo", None, None).await; + assert!( + !reply.body.contains("action=\"/tahinli/demo/fork\""), + "no fork button when anonymous" + ); +} + +async fn scenario_fork_copies(site: &Site, bob: &str) { + let demo = site + .store + .repo_by_owner_and_name("tahinli", "demo") + .await + .expect("query") + .expect("demo"); + site.store + .create_label(&demo.id, "triage-me", "#123456", "only here") + .await + .expect("label"); + let reply = fork(site, Some(bob)).await; + assert_eq!(reply.status, 303); + assert_eq!(reply.location.as_deref(), Some("/bob/demo")); + + let bob_id = site + .store + .user_by_username("bob") + .await + .expect("q") + .expect("bob") + .id; + let fork = site + .store + .repo_by_owner_and_name("bob", "demo") + .await + .expect("q") + .expect("fork row"); + assert_eq!(fork.fork_of.as_deref(), Some(demo.id.as_str())); + assert_eq!(fork.visibility, Visibility::Public); + assert_eq!(fork.owner_id, bob_id); + let labels: Vec<(String, String, String)> = site + .store + .list_labels(&fork.id) + .await + .expect("labels") + .into_iter() + .map(|l| (l.name, l.color, l.description)) + .collect(); + assert_eq!( + labels, + vec![( + "triage-me".to_string(), + "#123456".to_string(), + "only here".to_string() + )] + ); + + let forked = site + .store + .list_audit( + &forge_core::AuditFilter { + action: Some(AuditAction::RepoCreated), + ..Default::default() + }, + None, + 10, + ) + .await + .expect("audit"); + assert_eq!(forked.len(), 1, "one audit entry for the fork"); + assert_eq!(forked[0].target_id, fork.id); + assert_eq!(forked[0].target_name, "bob/demo"); + assert_eq!(forked[0].actor_id.as_deref(), Some(bob_id.as_str())); + let data: serde_json::Value = serde_json::from_str(&forked[0].data).expect("json"); + assert_eq!(data, serde_json::json!({ "fork_of": "tahinli/demo" })); + + let path = repo_path(site.dir.path(), &fork.id).expect("path"); + let refs = Command::new("git") + .arg("--git-dir") + .arg(&path) + .args(["for-each-ref", "--format=%(refname)"]) + .output() + .expect("git runs"); + let refs = String::from_utf8_lossy(&refs.stdout).into_owned(); + assert_eq!( + refs.lines().collect::>(), + vec!["refs/heads/main", "refs/tags/v1"] + ); + + let page = send(site, "GET", "/bob/demo", Some(bob), None).await; + assert_eq!(page.status, 200); + assert!(page.body.contains("forked from"), "fork line shown"); + assert!( + page.body.contains("href=\"/tahinli/demo\""), + "fork line links the source" + ); +} + +async fn scenario_fork_again(site: &Site, bob: &str) { + assert_eq!(fork(site, Some(bob)).await.status, 303); + let again = fork(site, Some(bob)).await; + assert_eq!(again.status, 303); + assert_eq!(again.location.as_deref(), Some("/bob/demo")); + assert!( + site.store + .repo_by_owner_and_name("bob", "demo-1") + .await + .expect("q") + .is_none(), + "no second fork was created" + ); +} + +async fn scenario_suffix(site: &Site) { + let erin = site + .store + .create_user("erin", None, "x", false) + .await + .expect("erin"); + let erin_cookie = sign_in(&site.store, &erin.id, "erin-token").await; + site.store + .create_repo(&erin.id, "demo", "", Visibility::Private, "main") + .await + .expect("erin's own demo"); + let reply = fork(site, Some(&erin_cookie)).await; + assert_eq!(reply.location.as_deref(), Some("/erin/demo-1")); +} + +#[tokio::test] +async fn fork_flows() { + let (site, [tahinli, bob, carol]) = site().await; + scenario_refusals(&site, &tahinli, &bob, &carol).await; + scenario_fork_copies(&site, &bob).await; + scenario_fork_again(&site, &bob).await; + scenario_suffix(&site).await; +} diff --git a/crates/forge-web-repo/src/pages/mod.rs b/crates/forge-web-repo/src/pages/mod.rs index 599ac46..868ffb6 100644 --- a/crates/forge-web-repo/src/pages/mod.rs +++ b/crates/forge-web-repo/src/pages/mod.rs @@ -17,7 +17,6 @@ pub mod commit; pub mod commits; pub mod compare; #[cfg(test)] -pub mod fork; #[cfg(test)] mod issue_meta_tests; pub mod issue_pin;