use std::fmt::Debug; use std::path::{Path, PathBuf}; use std::process::Command; use std::time::Duration; use bytes::Bytes; use futures_util::{Stream, StreamExt}; use forge_core::{Store, Visibility}; use topcoat::router::request::Request; use topcoat::router::{Body, Router, to_bytes}; pub const OWNER: &str = "tahinli"; pub const REPO: &str = "demo"; pub struct Fixture { pub router: Router, pub store: Store, pub live: std::sync::Arc, pub root: String, pub modified: String, pub work: PathBuf, pub bare: PathBuf, _dir: tempfile::TempDir, } pub fn git(dir: &Path, args: &[&str]) -> String { let out = Command::new("git") .args([ "-c", "user.name=Tester", "-c", "user.email=tester@example.com", "-c", "commit.gpgsign=false", ]) .args(args) .current_dir(dir) .output() .expect("git runs"); assert!( out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr) ); String::from_utf8_lossy(&out.stdout).trim().to_owned() } impl Fixture { pub async fn new(visibility: Visibility) -> Self { let tmp = tempfile::tempdir().expect("tempdir"); let dir = tmp.path().to_path_buf(); let state = crate::test_support::test_state(&dir).await; let store = state.store.clone(); let live = state.live.clone(); let router = crate::test_support::app_router(state); let owner = store .create_user(OWNER, None, "not-a-real-hash", false) .await .unwrap(); let repo = store .create_repo(&owner.id, REPO, "", visibility, "main") .await .unwrap(); let bare = forge_git::repo::repo_path(&dir, &repo.id).unwrap(); std::fs::create_dir_all(bare.parent().unwrap()).unwrap(); git( &dir, &[ "init", "-q", "--bare", "-b", "main", &bare.to_string_lossy(), ], ); let work = dir.join("work"); std::fs::create_dir_all(&work).unwrap(); git(&work, &["init", "-q", "-b", "main"]); std::fs::write(work.join("a.txt"), "one\ntwo\nthree\n").unwrap(); std::fs::create_dir_all(work.join("dir")).unwrap(); std::fs::write(work.join("dir/b.txt"), "b\n").unwrap(); git(&work, &["add", "-A"]); git(&work, &["commit", "-q", "-m", "root commit"]); let root = git(&work, &["rev-parse", "HEAD"]); std::fs::write(work.join("a.txt"), "one\nTWO\nthree\nfour\n").unwrap(); std::fs::write(work.join("new.txt"), "new file\n").unwrap(); git(&work, &["add", "-A"]); git( &work, &[ "commit", "-q", "-m", "Modify a.txt and add new.txt", "-m", "Body line one.\n\nSecond paragraph.", ], ); let modified = git(&work, &["rev-parse", "HEAD"]); for n in 1..=53 { git( &work, &[ "commit", "-q", "--allow-empty", "-m", &format!("filler {n}"), ], ); } git( &work, &[ "push", "-q", &bare.to_string_lossy(), "HEAD:refs/heads/main", ], ); Self { router, store, live, root, modified, work, bare, _dir: tmp, } } } pub async fn get(router: &Router, uri: &str) -> (u16, http::HeaderMap, Vec) { let req = Request::builder() .method("GET") .uri(uri) .body(Body::empty()) .unwrap(); let res = router.handle(req).await; let status = res.status().as_u16(); let headers = res.headers().clone(); let body = to_bytes(res.into_body(), usize::MAX) .await .unwrap() .to_vec(); (status, headers, body) } pub struct Reply { pub status: u16, pub location: Option, pub body: String, } pub async fn send( router: &Router, method: &str, uri: &str, cookie: Option<&str>, fields: Option<&[(&str, &str)]>, ) -> Reply { let form = fields.map(|fields| { form_urlencoded::Serializer::new(String::new()) .extend_pairs(fields) .finish() }); send_form(router, method, uri, cookie, form).await } pub async fn send_form( router: &Router, method: &str, uri: &str, cookie: Option<&str>, form: Option, ) -> Reply { let mut builder = Request::builder().method(method).uri(uri); if let Some(cookie) = cookie { builder = builder.header("cookie", cookie); } let body = match form { Some(form) => { builder = builder.header("content-type", "application/x-www-form-urlencoded"); Body::from(form) } None => Body::empty(), }; let res = router.handle(builder.body(body).expect("request")).await; let status = res.status().as_u16(); let location = res .headers() .get("location") .and_then(|v| v.to_str().ok()) .map(str::to_owned); let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); Reply { status, location, body: String::from_utf8_lossy(&bytes).into_owned(), } } pub async fn next_frame(frames: &mut S) -> Option> where S: Stream> + Unpin, E: Debug, { let frame = tokio::time::timeout(Duration::from_secs(5), frames.next()) .await .expect("a frame within five seconds")?; Some(frame.expect("data").to_vec()) } pub async fn next_event(frames: &mut S) -> Option> where S: Stream> + Unpin, E: Debug, { loop { let bytes = next_frame(frames).await?; if !bytes.starts_with(b"retry: ") { return Some(seq_free(&bytes)); } } } pub fn seq_free(frame: &[u8]) -> Vec { let text = String::from_utf8_lossy(frame); let Some(data) = text .strip_prefix("event: changed\ndata: ") .and_then(|rest| rest.strip_suffix("\n\n")) else { return frame.to_vec(); }; let seq = data.strip_suffix(" head").unwrap_or(data); if seq.is_empty() || !seq.bytes().all(|b| b.is_ascii_digit()) { return frame.to_vec(); } format!("event: changed\ndata: 1{}\n\n", &data[seq.len()..]).into_bytes() }