| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use std::{ |
| 8 | collections::{HashMap, HashSet}, |
| 9 | ffi::OsStr, |
| 10 | io, |
| 11 | path::PathBuf, |
| 12 | process::{Output, Stdio}, |
| 13 | sync::{Arc, Mutex}, |
| 14 | time::SystemTime, |
| 15 | }; |
| 16 | |
| 17 | use tokio::{ |
| 18 | io::{AsyncBufReadExt, AsyncReadExt, BufReader}, |
| 19 | process::{ChildStdout, Command}, |
| 20 | }; |
| 21 | |
| 22 | use crate::{ |
| 23 | application::port::{ |
| 24 | ArchiveRequest, Blob, ByteStream, GitArchive, GitArchiveError, GitMethod, GitProtocolError, |
| 25 | GitProtocolServer, GitQuery, GitQueryError, GitRequest, GitResponse, GitStorage, |
| 26 | GitStorageError, |
| 27 | }, |
| 28 | domain::{ |
| 29 | BranchRow, CommitSummary, GitRef, ObjectId, OrgName, RefKind, RefName, RepoName, RepoPath, |
| 30 | TagRow, TagSummary, TreeEntry, |
| 31 | }, |
| 32 | }; |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | const MAX_CGI_HEADERS: usize = 64; |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | const REDIRECTING_VARS: &[&str] = &[ |
| 47 | "GIT_ALTERNATE_OBJECT_DIRECTORIES", |
| 48 | "GIT_DIR", |
| 49 | "GIT_INDEX_FILE", |
| 50 | "GIT_OBJECT_DIRECTORY", |
| 51 | "GIT_WORK_TREE", |
| 52 | ]; |
| 53 | |
| 54 | |
| 55 | #[derive(Debug, Clone)] |
| 56 | pub struct DiskGitStorage { |
| 57 | data_dir: PathBuf, |
| 58 | } |
| 59 | |
| 60 | impl DiskGitStorage { |
| 61 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 62 | Self { |
| 63 | data_dir: data_dir.into(), |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | impl GitStorage for DiskGitStorage { |
| 69 | async fn init_bare(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> { |
| 70 | let path = self.repo_path(handle, name); |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | if path.exists() { |
| 77 | return Err(GitStorageError::AlreadyExists); |
| 78 | } |
| 79 | |
| 80 | |
| 81 | run_git([ |
| 82 | OsStr::new("init"), |
| 83 | OsStr::new("--bare"), |
| 84 | OsStr::new("--quiet"), |
| 85 | |
| 86 | |
| 87 | |
| 88 | OsStr::new("--template="), |
| 89 | |
| 90 | |
| 91 | OsStr::new("--initial-branch=main"), |
| 92 | |
| 93 | |
| 94 | OsStr::new("--"), |
| 95 | path.as_os_str(), |
| 96 | ]) |
| 97 | .await |
| 98 | .map(|_| ()) |
| 99 | } |
| 100 | |
| 101 | async fn remove(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> { |
| 102 | let path = self.repo_path(handle, name); |
| 103 | |
| 104 | |
| 105 | |
| 106 | match tokio::fs::remove_dir_all(&path).await { |
| 107 | Ok(()) => Ok(()), |
| 108 | |
| 109 | Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), |
| 110 | Err(error) => Err(GitStorageError::backend(error)), |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 115 | |
| 116 | |
| 117 | |
| 118 | self.data_dir |
| 119 | .join(handle.as_str()) |
| 120 | .join(format!("{name}.git")) |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | pub(crate) fn git_command() -> Command { |
| 131 | let mut command = Command::new("git"); |
| 132 | |
| 133 | |
| 134 | |
| 135 | command |
| 136 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 137 | .env("GIT_CONFIG_SYSTEM", "/dev/null"); |
| 138 | |
| 139 | for variable in REDIRECTING_VARS { |
| 140 | command.env_remove(variable); |
| 141 | } |
| 142 | |
| 143 | command |
| 144 | } |
| 145 | |
| 146 | |
| 147 | |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | async fn run_git<I, S>(args: I) -> Result<Output, GitStorageError> |
| 153 | where |
| 154 | I: IntoIterator<Item = S>, |
| 155 | S: AsRef<OsStr>, |
| 156 | { |
| 157 | let mut command = git_command(); |
| 158 | command.args(args).stdin(Stdio::null()); |
| 159 | |
| 160 | |
| 161 | let output = command |
| 162 | .output() |
| 163 | .await |
| 164 | .map_err(|error| GitStorageError::backend(format!("could not run git: {error}")))?; |
| 165 | |
| 166 | if !output.status.success() { |
| 167 | |
| 168 | |
| 169 | return Err(GitStorageError::backend(format!( |
| 170 | "git exited with {}: {}", |
| 171 | output.status, |
| 172 | String::from_utf8_lossy(&output.stderr).trim() |
| 173 | ))); |
| 174 | } |
| 175 | |
| 176 | Ok(output) |
| 177 | } |
| 178 | |
| 179 | |
| 180 | |
| 181 | |
| 182 | |
| 183 | |
| 184 | #[derive(Debug, Default, Clone)] |
| 185 | pub struct InMemoryGitStorage { |
| 186 | created: Arc<Mutex<HashSet<PathBuf>>>, |
| 187 | } |
| 188 | |
| 189 | impl InMemoryGitStorage { |
| 190 | pub fn new() -> Self { |
| 191 | Self::default() |
| 192 | } |
| 193 | |
| 194 | |
| 195 | pub fn contains(&self, handle: &OrgName, name: &RepoName) -> bool { |
| 196 | self.created |
| 197 | .lock() |
| 198 | .expect("lock poisoned") |
| 199 | .contains(&self.repo_path(handle, name)) |
| 200 | } |
| 201 | |
| 202 | |
| 203 | pub fn len(&self) -> usize { |
| 204 | self.created.lock().expect("lock poisoned").len() |
| 205 | } |
| 206 | |
| 207 | pub fn is_empty(&self) -> bool { |
| 208 | self.len() == 0 |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | impl GitStorage for InMemoryGitStorage { |
| 213 | async fn init_bare(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> { |
| 214 | let mut created = self.created.lock().expect("lock poisoned"); |
| 215 | |
| 216 | if !created.insert(self.repo_path(handle, name)) { |
| 217 | return Err(GitStorageError::AlreadyExists); |
| 218 | } |
| 219 | |
| 220 | Ok(()) |
| 221 | } |
| 222 | |
| 223 | async fn remove(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> { |
| 224 | self.created |
| 225 | .lock() |
| 226 | .expect("lock poisoned") |
| 227 | .remove(&self.repo_path(handle, name)); |
| 228 | |
| 229 | Ok(()) |
| 230 | } |
| 231 | |
| 232 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 233 | PathBuf::from("/in-memory") |
| 234 | .join(handle.as_str()) |
| 235 | .join(format!("{name}.git")) |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | #[derive(Debug, Clone)] |
| 245 | pub struct GitHttpBackend { |
| 246 | data_dir: PathBuf, |
| 247 | } |
| 248 | |
| 249 | impl GitHttpBackend { |
| 250 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 251 | Self { |
| 252 | data_dir: data_dir.into(), |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | impl GitProtocolServer for GitHttpBackend { |
| 258 | async fn serve(&self, request: GitRequest) -> Result<GitResponse, GitProtocolError> { |
| 259 | let mut command = git_command(); |
| 260 | |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | if request.allow_receive_pack { |
| 266 | command.arg("-c").arg("http.receivepack=true"); |
| 267 | } |
| 268 | |
| 269 | command |
| 270 | .arg("http-backend") |
| 271 | .env("GIT_PROJECT_ROOT", &self.data_dir) |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | .env("GIT_HTTP_EXPORT_ALL", "1") |
| 277 | .env("PATH_INFO", &request.path_info) |
| 278 | .env("QUERY_STRING", &request.query) |
| 279 | .env("REQUEST_METHOD", request.method.as_str()) |
| 280 | .stdin(Stdio::piped()) |
| 281 | .stdout(Stdio::piped()) |
| 282 | .stderr(Stdio::piped()); |
| 283 | |
| 284 | |
| 285 | |
| 286 | |
| 287 | |
| 288 | |
| 289 | for (variable, value) in [ |
| 290 | ("CONTENT_TYPE", &request.content_type), |
| 291 | ("CONTENT_LENGTH", &request.content_length), |
| 292 | ("HTTP_CONTENT_ENCODING", &request.content_encoding), |
| 293 | ("HTTP_GIT_PROTOCOL", &request.git_protocol), |
| 294 | ] { |
| 295 | if let Some(value) = value { |
| 296 | command.env(variable, value); |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | let mut child = command |
| 301 | .spawn() |
| 302 | .map_err(|error| GitProtocolError::new(format!("could not run git: {error}")))?; |
| 303 | |
| 304 | let mut stdin = child.stdin.take().expect("stdin was piped"); |
| 305 | let stdout = child.stdout.take().expect("stdout was piped"); |
| 306 | let mut stderr = child.stderr.take().expect("stderr was piped"); |
| 307 | let mut body = request.body; |
| 308 | |
| 309 | |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | tokio::spawn(async move { |
| 315 | let _ = tokio::io::copy(&mut body, &mut stdin).await; |
| 316 | }); |
| 317 | |
| 318 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | |
| 323 | tokio::spawn(async move { |
| 324 | let mut complaint = String::new(); |
| 325 | let _ = stderr.read_to_string(&mut complaint).await; |
| 326 | |
| 327 | match child.wait().await { |
| 328 | Ok(status) if status.success() => {} |
| 329 | Ok(status) => eprintln!( |
| 330 | "steid: git http-backend exited with {status}: {}", |
| 331 | complaint.trim() |
| 332 | ), |
| 333 | Err(error) => eprintln!("steid: could not wait for git http-backend: {error}"), |
| 334 | } |
| 335 | }); |
| 336 | |
| 337 | |
| 338 | |
| 339 | |
| 340 | let mut reader = BufReader::new(stdout); |
| 341 | let (status, headers) = read_cgi_headers(&mut reader).await?; |
| 342 | |
| 343 | Ok(GitResponse { |
| 344 | status, |
| 345 | headers, |
| 346 | body: Box::pin(reader), |
| 347 | }) |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | |
| 355 | |
| 356 | async fn read_cgi_headers( |
| 357 | reader: &mut BufReader<ChildStdout>, |
| 358 | ) -> Result<(u16, Vec<(String, String)>), GitProtocolError> { |
| 359 | let mut status = 200; |
| 360 | let mut headers = Vec::new(); |
| 361 | let mut line = Vec::new(); |
| 362 | |
| 363 | loop { |
| 364 | line.clear(); |
| 365 | |
| 366 | let read = reader |
| 367 | .read_until(b'\n', &mut line) |
| 368 | .await |
| 369 | .map_err(|error| GitProtocolError::new(format!("reading git's headers: {error}")))?; |
| 370 | |
| 371 | if read == 0 { |
| 372 | return Err(GitProtocolError::new( |
| 373 | "git http-backend produced no headers before closing", |
| 374 | )); |
| 375 | } |
| 376 | |
| 377 | |
| 378 | |
| 379 | let text = String::from_utf8_lossy(&line); |
| 380 | let text = text.trim_end_matches(['\r', '\n']); |
| 381 | |
| 382 | if text.is_empty() { |
| 383 | return Ok((status, headers)); |
| 384 | } |
| 385 | |
| 386 | let Some((name, value)) = text.split_once(": ") else { |
| 387 | return Err(GitProtocolError::new(format!( |
| 388 | "git http-backend wrote an unparseable header: {text:?}" |
| 389 | ))); |
| 390 | }; |
| 391 | |
| 392 | if name.eq_ignore_ascii_case("status") { |
| 393 | status = value |
| 394 | .split_whitespace() |
| 395 | .next() |
| 396 | .and_then(|code| code.parse().ok()) |
| 397 | .ok_or_else(|| { |
| 398 | GitProtocolError::new(format!("git http-backend wrote a bad status: {value:?}")) |
| 399 | })?; |
| 400 | } else { |
| 401 | headers.push((name.to_owned(), value.to_owned())); |
| 402 | } |
| 403 | |
| 404 | if headers.len() > MAX_CGI_HEADERS { |
| 405 | return Err(GitProtocolError::new( |
| 406 | "git http-backend wrote more headers than a CGI response can plausibly have", |
| 407 | )); |
| 408 | } |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | |
| 413 | |
| 414 | |
| 415 | |
| 416 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 417 | pub struct RecordedGitRequest { |
| 418 | pub method: GitMethod, |
| 419 | pub path_info: String, |
| 420 | pub query: String, |
| 421 | pub git_protocol: Option<String>, |
| 422 | pub content_encoding: Option<String>, |
| 423 | pub allow_receive_pack: bool, |
| 424 | } |
| 425 | |
| 426 | |
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | #[derive(Debug, Default, Clone)] |
| 432 | pub struct InMemoryGitProtocol { |
| 433 | requests: Arc<Mutex<Vec<RecordedGitRequest>>>, |
| 434 | } |
| 435 | |
| 436 | impl InMemoryGitProtocol { |
| 437 | pub fn new() -> Self { |
| 438 | Self::default() |
| 439 | } |
| 440 | |
| 441 | pub fn requests(&self) -> Vec<RecordedGitRequest> { |
| 442 | self.requests.lock().expect("lock poisoned").clone() |
| 443 | } |
| 444 | |
| 445 | |
| 446 | pub fn was_called(&self) -> bool { |
| 447 | !self.requests.lock().expect("lock poisoned").is_empty() |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | impl GitProtocolServer for InMemoryGitProtocol { |
| 452 | async fn serve(&self, request: GitRequest) -> Result<GitResponse, GitProtocolError> { |
| 453 | self.requests |
| 454 | .lock() |
| 455 | .expect("lock poisoned") |
| 456 | .push(RecordedGitRequest { |
| 457 | method: request.method, |
| 458 | path_info: request.path_info, |
| 459 | query: request.query, |
| 460 | git_protocol: request.git_protocol, |
| 461 | content_encoding: request.content_encoding, |
| 462 | allow_receive_pack: request.allow_receive_pack, |
| 463 | }); |
| 464 | |
| 465 | Ok(GitResponse { |
| 466 | status: 200, |
| 467 | headers: vec![( |
| 468 | "Content-Type".to_owned(), |
| 469 | "application/x-git-upload-pack-advertisement".to_owned(), |
| 470 | )], |
| 471 | body: Box::pin(std::io::Cursor::new(b"0000".to_vec())), |
| 472 | }) |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 481 | |
| 482 | #[derive(Debug, Clone)] |
| 483 | pub struct DiskGitArchive { |
| 484 | data_dir: PathBuf, |
| 485 | } |
| 486 | |
| 487 | impl DiskGitArchive { |
| 488 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 489 | Self { |
| 490 | data_dir: data_dir.into(), |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | |
| 495 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 496 | self.data_dir |
| 497 | .join(handle.as_str()) |
| 498 | .join(format!("{name}.git")) |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | impl GitArchive for DiskGitArchive { |
| 503 | async fn archive(&self, request: ArchiveRequest) -> Result<ByteStream, GitArchiveError> { |
| 504 | let repo = self.repo_path(&request.handle, &request.name); |
| 505 | |
| 506 | |
| 507 | |
| 508 | |
| 509 | |
| 510 | let mut command = git_command(); |
| 511 | command |
| 512 | .arg("-C") |
| 513 | .arg(&repo) |
| 514 | .arg("archive") |
| 515 | .arg(format!("--format={}", request.format.as_str())) |
| 516 | .arg(format!("--prefix={}", request.prefix)) |
| 517 | .arg(request.commit.as_str()) |
| 518 | .stdin(Stdio::null()) |
| 519 | .stdout(Stdio::piped()) |
| 520 | .stderr(Stdio::piped()) |
| 521 | |
| 522 | |
| 523 | .kill_on_drop(true); |
| 524 | |
| 525 | let mut child = command |
| 526 | .spawn() |
| 527 | .map_err(|error| GitArchiveError::new(format!("could not run git: {error}")))?; |
| 528 | |
| 529 | let stdout = child.stdout.take().expect("stdout was piped"); |
| 530 | let mut stderr = child.stderr.take().expect("stderr was piped"); |
| 531 | |
| 532 | |
| 533 | |
| 534 | |
| 535 | |
| 536 | |
| 537 | |
| 538 | tokio::spawn(async move { |
| 539 | let mut complaint = String::new(); |
| 540 | let _ = stderr.read_to_string(&mut complaint).await; |
| 541 | |
| 542 | match child.wait().await { |
| 543 | Ok(status) if status.success() => {} |
| 544 | Ok(status) => { |
| 545 | eprintln!( |
| 546 | "steid: git archive exited with {status}: {}", |
| 547 | complaint.trim() |
| 548 | ) |
| 549 | } |
| 550 | Err(error) => eprintln!("steid: could not wait for git archive: {error}"), |
| 551 | } |
| 552 | }); |
| 553 | |
| 554 | Ok(Box::pin(stdout)) |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | |
| 559 | |
| 560 | |
| 561 | |
| 562 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 563 | pub struct RecordedArchive { |
| 564 | pub handle: OrgName, |
| 565 | pub name: RepoName, |
| 566 | pub format: crate::application::port::ArchiveFormat, |
| 567 | pub commit: ObjectId, |
| 568 | pub prefix: String, |
| 569 | } |
| 570 | |
| 571 | |
| 572 | |
| 573 | |
| 574 | |
| 575 | #[derive(Debug, Default, Clone)] |
| 576 | pub struct InMemoryGitArchive { |
| 577 | requests: Arc<Mutex<Vec<RecordedArchive>>>, |
| 578 | } |
| 579 | |
| 580 | impl InMemoryGitArchive { |
| 581 | pub fn new() -> Self { |
| 582 | Self::default() |
| 583 | } |
| 584 | |
| 585 | pub fn requests(&self) -> Vec<RecordedArchive> { |
| 586 | self.requests.lock().expect("lock poisoned").clone() |
| 587 | } |
| 588 | |
| 589 | |
| 590 | pub fn was_called(&self) -> bool { |
| 591 | !self.requests.lock().expect("lock poisoned").is_empty() |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | impl GitArchive for InMemoryGitArchive { |
| 596 | async fn archive(&self, request: ArchiveRequest) -> Result<ByteStream, GitArchiveError> { |
| 597 | self.requests |
| 598 | .lock() |
| 599 | .expect("lock poisoned") |
| 600 | .push(RecordedArchive { |
| 601 | handle: request.handle, |
| 602 | name: request.name, |
| 603 | format: request.format, |
| 604 | commit: request.commit, |
| 605 | prefix: request.prefix, |
| 606 | }); |
| 607 | |
| 608 | Ok(Box::pin(std::io::Cursor::new(b"archive".to_vec()))) |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | |
| 613 | |
| 614 | |
| 615 | |
| 616 | |
| 617 | #[derive(Debug, Default, Clone)] |
| 618 | pub struct InMemoryGitQuery { |
| 619 | default_branch: Option<RefName>, |
| 620 | |
| 621 | trees: HashMap<String, Vec<TreeEntry>>, |
| 622 | blobs: HashMap<String, Vec<u8>>, |
| 623 | commits: Vec<CommitSummary>, |
| 624 | |
| 625 | |
| 626 | refs: Vec<GitRef>, |
| 627 | |
| 628 | |
| 629 | commit_count: Option<u64>, |
| 630 | latest_tag: Option<TagSummary>, |
| 631 | |
| 632 | |
| 633 | branch_rows: Vec<BranchRow>, |
| 634 | tag_rows: Vec<TagRow>, |
| 635 | } |
| 636 | |
| 637 | impl InMemoryGitQuery { |
| 638 | |
| 639 | pub fn empty() -> Self { |
| 640 | Self::default() |
| 641 | } |
| 642 | |
| 643 | |
| 644 | pub fn new() -> Self { |
| 645 | Self { |
| 646 | default_branch: Some(RefName::from_trusted("main")), |
| 647 | ..Self::default() |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | fn key(rev: &RefName, path: &RepoPath) -> String { |
| 652 | format!("{}\0{}", rev.as_str(), path.as_str()) |
| 653 | } |
| 654 | |
| 655 | pub fn with_tree(mut self, rev: &str, path: &str, entries: Vec<TreeEntry>) -> Self { |
| 656 | self.trees.insert( |
| 657 | Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)), |
| 658 | entries, |
| 659 | ); |
| 660 | self |
| 661 | } |
| 662 | |
| 663 | pub fn with_blob(mut self, rev: &str, path: &str, content: impl Into<Vec<u8>>) -> Self { |
| 664 | self.blobs.insert( |
| 665 | Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)), |
| 666 | content.into(), |
| 667 | ); |
| 668 | self |
| 669 | } |
| 670 | |
| 671 | pub fn with_log(mut self, commits: Vec<CommitSummary>) -> Self { |
| 672 | self.commits = commits; |
| 673 | self |
| 674 | } |
| 675 | |
| 676 | pub fn with_branch(self, name: &str) -> Self { |
| 677 | self.with_ref(name, RefKind::Branch) |
| 678 | } |
| 679 | |
| 680 | pub fn with_tag(self, name: &str) -> Self { |
| 681 | self.with_ref(name, RefKind::Tag) |
| 682 | } |
| 683 | |
| 684 | pub fn with_commit_count(mut self, count: u64) -> Self { |
| 685 | self.commit_count = Some(count); |
| 686 | self |
| 687 | } |
| 688 | |
| 689 | pub fn with_latest_tag(mut self, name: &str, created_at: SystemTime) -> Self { |
| 690 | self.latest_tag = Some(TagSummary { |
| 691 | name: RefName::from_trusted(name), |
| 692 | created_at, |
| 693 | }); |
| 694 | self |
| 695 | } |
| 696 | |
| 697 | |
| 698 | pub fn with_branch_row( |
| 699 | mut self, |
| 700 | name: &str, |
| 701 | is_default: bool, |
| 702 | committed_at: SystemTime, |
| 703 | ) -> Self { |
| 704 | self.branch_rows.push(BranchRow { |
| 705 | name: RefName::from_trusted(name), |
| 706 | is_default, |
| 707 | commit: ObjectId::from_trusted("2".repeat(40)), |
| 708 | summary: format!("work on {name}"), |
| 709 | committed_at, |
| 710 | }); |
| 711 | self |
| 712 | } |
| 713 | |
| 714 | |
| 715 | |
| 716 | pub fn with_tag_row(mut self, name: &str, annotated: bool, created_at: SystemTime) -> Self { |
| 717 | self.tag_rows.push(TagRow { |
| 718 | name: RefName::from_trusted(name), |
| 719 | commit: ObjectId::from_trusted("3".repeat(40)), |
| 720 | message: annotated.then(|| format!("release {name}")), |
| 721 | annotated, |
| 722 | created_at, |
| 723 | }); |
| 724 | self |
| 725 | } |
| 726 | |
| 727 | fn with_ref(mut self, name: &str, kind: RefKind) -> Self { |
| 728 | self.refs.push(GitRef { |
| 729 | name: RefName::from_trusted(name), |
| 730 | kind, |
| 731 | }); |
| 732 | self |
| 733 | } |
| 734 | } |
| 735 | |
| 736 | impl GitQuery for InMemoryGitQuery { |
| 737 | async fn default_branch( |
| 738 | &self, |
| 739 | _handle: &OrgName, |
| 740 | _name: &RepoName, |
| 741 | ) -> Result<Option<RefName>, GitQueryError> { |
| 742 | Ok(self.default_branch.clone()) |
| 743 | } |
| 744 | |
| 745 | async fn resolve( |
| 746 | &self, |
| 747 | _handle: &OrgName, |
| 748 | _name: &RepoName, |
| 749 | _rev: &RefName, |
| 750 | ) -> Result<Option<ObjectId>, GitQueryError> { |
| 751 | Ok(self |
| 752 | .default_branch |
| 753 | .as_ref() |
| 754 | .map(|_| ObjectId::from_trusted("0".repeat(40)))) |
| 755 | } |
| 756 | |
| 757 | async fn list_tree( |
| 758 | &self, |
| 759 | _handle: &OrgName, |
| 760 | _name: &RepoName, |
| 761 | rev: &RefName, |
| 762 | path: &RepoPath, |
| 763 | ) -> Result<Option<Vec<TreeEntry>>, GitQueryError> { |
| 764 | Ok(self.trees.get(&Self::key(rev, path)).cloned()) |
| 765 | } |
| 766 | |
| 767 | async fn read_blob( |
| 768 | &self, |
| 769 | _handle: &OrgName, |
| 770 | _name: &RepoName, |
| 771 | rev: &RefName, |
| 772 | path: &RepoPath, |
| 773 | max_bytes: u64, |
| 774 | ) -> Result<Option<Blob>, GitQueryError> { |
| 775 | Ok(self.blobs.get(&Self::key(rev, path)).map(|content| { |
| 776 | let size = content.len() as u64; |
| 777 | |
| 778 | Blob { |
| 779 | id: ObjectId::from_trusted("1".repeat(40)), |
| 780 | size, |
| 781 | |
| 782 | |
| 783 | content: (size <= max_bytes).then(|| content.clone()), |
| 784 | } |
| 785 | })) |
| 786 | } |
| 787 | |
| 788 | async fn log( |
| 789 | &self, |
| 790 | _handle: &OrgName, |
| 791 | _name: &RepoName, |
| 792 | _rev: &RefName, |
| 793 | limit: usize, |
| 794 | ) -> Result<Vec<CommitSummary>, GitQueryError> { |
| 795 | Ok(self.commits.iter().take(limit).cloned().collect()) |
| 796 | } |
| 797 | |
| 798 | async fn list_refs( |
| 799 | &self, |
| 800 | _handle: &OrgName, |
| 801 | _name: &RepoName, |
| 802 | ) -> Result<Vec<GitRef>, GitQueryError> { |
| 803 | Ok(self.refs.clone()) |
| 804 | } |
| 805 | |
| 806 | async fn count_commits( |
| 807 | &self, |
| 808 | _handle: &OrgName, |
| 809 | _name: &RepoName, |
| 810 | _rev: &RefName, |
| 811 | ) -> Result<u64, GitQueryError> { |
| 812 | Ok(self.commit_count.unwrap_or(self.commits.len() as u64)) |
| 813 | } |
| 814 | |
| 815 | async fn latest_tag( |
| 816 | &self, |
| 817 | _handle: &OrgName, |
| 818 | _name: &RepoName, |
| 819 | ) -> Result<Option<TagSummary>, GitQueryError> { |
| 820 | Ok(self.latest_tag.clone()) |
| 821 | } |
| 822 | |
| 823 | async fn branches( |
| 824 | &self, |
| 825 | _handle: &OrgName, |
| 826 | _name: &RepoName, |
| 827 | ) -> Result<Vec<BranchRow>, GitQueryError> { |
| 828 | Ok(self.branch_rows.clone()) |
| 829 | } |
| 830 | |
| 831 | async fn tags( |
| 832 | &self, |
| 833 | _handle: &OrgName, |
| 834 | _name: &RepoName, |
| 835 | ) -> Result<Vec<TagRow>, GitQueryError> { |
| 836 | Ok(self.tag_rows.clone()) |
| 837 | } |
| 838 | } |
| 839 | |
| 840 | #[cfg(test)] |
| 841 | mod tests { |
| 842 | use std::path::Path; |
| 843 | |
| 844 | use tempfile::TempDir; |
| 845 | |
| 846 | use tokio::io::AsyncReadExt; |
| 847 | |
| 848 | use super::*; |
| 849 | use crate::application::port::ArchiveFormat; |
| 850 | |
| 851 | |
| 852 | |
| 853 | fn storage() -> (TempDir, DiskGitStorage) { |
| 854 | let dir = TempDir::new().expect("temp dir"); |
| 855 | let storage = DiskGitStorage::new(dir.path()); |
| 856 | (dir, storage) |
| 857 | } |
| 858 | |
| 859 | fn handle() -> OrgName { |
| 860 | OrgName::new("jamesgill").expect("valid handle") |
| 861 | } |
| 862 | |
| 863 | fn repo_name(value: &str) -> RepoName { |
| 864 | RepoName::new(value).expect("valid repository name") |
| 865 | } |
| 866 | |
| 867 | |
| 868 | |
| 869 | fn git_says(path: &Path, args: &[&str]) -> String { |
| 870 | let output = std::process::Command::new("git") |
| 871 | .arg("-C") |
| 872 | .arg(path) |
| 873 | .args(args) |
| 874 | .output() |
| 875 | .expect("git should be on PATH"); |
| 876 | |
| 877 | assert!( |
| 878 | output.status.success(), |
| 879 | "git {args:?} failed: {}", |
| 880 | String::from_utf8_lossy(&output.stderr) |
| 881 | ); |
| 882 | |
| 883 | String::from_utf8_lossy(&output.stdout).trim().to_owned() |
| 884 | } |
| 885 | |
| 886 | #[tokio::test] |
| 887 | async fn init_bare_creates_a_bare_repository() { |
| 888 | let (_dir, storage) = storage(); |
| 889 | |
| 890 | storage |
| 891 | .init_bare(&handle(), &repo_name("steid")) |
| 892 | .await |
| 893 | .expect("should create"); |
| 894 | |
| 895 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 896 | assert!(path.is_dir(), "expected a repository at {path:?}"); |
| 897 | assert_eq!( |
| 898 | git_says(&path, &["rev-parse", "--is-bare-repository"]), |
| 899 | "true" |
| 900 | ); |
| 901 | } |
| 902 | |
| 903 | #[tokio::test] |
| 904 | async fn a_new_repository_is_empty() { |
| 905 | |
| 906 | let (_dir, storage) = storage(); |
| 907 | storage |
| 908 | .init_bare(&handle(), &repo_name("steid")) |
| 909 | .await |
| 910 | .expect("should create"); |
| 911 | |
| 912 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 913 | |
| 914 | assert_eq!(git_says(&path, &["for-each-ref"]), ""); |
| 915 | } |
| 916 | |
| 917 | #[tokio::test] |
| 918 | async fn a_new_repository_defaults_to_main() { |
| 919 | |
| 920 | |
| 921 | let (_dir, storage) = storage(); |
| 922 | storage |
| 923 | .init_bare(&handle(), &repo_name("steid")) |
| 924 | .await |
| 925 | .expect("should create"); |
| 926 | |
| 927 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 928 | |
| 929 | assert_eq!( |
| 930 | git_says(&path, &["symbolic-ref", "HEAD"]), |
| 931 | "refs/heads/main" |
| 932 | ); |
| 933 | } |
| 934 | |
| 935 | #[tokio::test] |
| 936 | async fn no_sample_hooks_are_installed() { |
| 937 | |
| 938 | let (_dir, storage) = storage(); |
| 939 | storage |
| 940 | .init_bare(&handle(), &repo_name("steid")) |
| 941 | .await |
| 942 | .expect("should create"); |
| 943 | |
| 944 | let hooks = storage |
| 945 | .repo_path(&handle(), &repo_name("steid")) |
| 946 | .join("hooks"); |
| 947 | |
| 948 | let samples = std::fs::read_dir(&hooks) |
| 949 | .map(|entries| entries.count()) |
| 950 | .unwrap_or(0); |
| 951 | assert_eq!(samples, 0, "expected no templated hooks in {hooks:?}"); |
| 952 | } |
| 953 | |
| 954 | #[tokio::test] |
| 955 | async fn init_bare_creates_the_handle_directory() { |
| 956 | let (dir, storage) = storage(); |
| 957 | assert!(!dir.path().join("jamesgill").exists()); |
| 958 | |
| 959 | storage |
| 960 | .init_bare(&handle(), &repo_name("steid")) |
| 961 | .await |
| 962 | .expect("should create"); |
| 963 | |
| 964 | assert!(dir.path().join("jamesgill").is_dir()); |
| 965 | } |
| 966 | |
| 967 | #[tokio::test] |
| 968 | async fn one_handle_can_own_several_repositories() { |
| 969 | let (_dir, storage) = storage(); |
| 970 | |
| 971 | for name in ["steid", "foo.js", ".github"] { |
| 972 | storage |
| 973 | .init_bare(&handle(), &repo_name(name)) |
| 974 | .await |
| 975 | .unwrap_or_else(|error| panic!("{name} should create: {error}")); |
| 976 | } |
| 977 | |
| 978 | for name in ["steid", "foo.js", ".github"] { |
| 979 | assert!(storage.repo_path(&handle(), &repo_name(name)).is_dir()); |
| 980 | } |
| 981 | } |
| 982 | |
| 983 | #[tokio::test] |
| 984 | async fn init_bare_refuses_a_repository_that_already_exists() { |
| 985 | let (_dir, storage) = storage(); |
| 986 | storage |
| 987 | .init_bare(&handle(), &repo_name("steid")) |
| 988 | .await |
| 989 | .expect("should create"); |
| 990 | |
| 991 | let error = storage |
| 992 | .init_bare(&handle(), &repo_name("steid")) |
| 993 | .await |
| 994 | .expect_err("should refuse"); |
| 995 | |
| 996 | assert!(matches!(error, GitStorageError::AlreadyExists)); |
| 997 | } |
| 998 | |
| 999 | #[tokio::test] |
| 1000 | async fn a_refused_init_leaves_the_existing_repository_alone() { |
| 1001 | |
| 1002 | |
| 1003 | let (_dir, storage) = storage(); |
| 1004 | storage |
| 1005 | .init_bare(&handle(), &repo_name("steid")) |
| 1006 | .await |
| 1007 | .expect("should create"); |
| 1008 | |
| 1009 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 1010 | let marker = path.join("objects").join("marker"); |
| 1011 | std::fs::write(&marker, b"existing data").expect("write marker"); |
| 1012 | |
| 1013 | let _ = storage.init_bare(&handle(), &repo_name("steid")).await; |
| 1014 | |
| 1015 | assert_eq!( |
| 1016 | std::fs::read(&marker).expect("marker should survive"), |
| 1017 | b"existing data" |
| 1018 | ); |
| 1019 | } |
| 1020 | |
| 1021 | #[tokio::test] |
| 1022 | async fn repo_path_creates_nothing() { |
| 1023 | let (dir, storage) = storage(); |
| 1024 | |
| 1025 | let path = storage.repo_path(&handle(), &repo_name("never-created")); |
| 1026 | |
| 1027 | assert!(!path.exists()); |
| 1028 | assert_eq!( |
| 1029 | std::fs::read_dir(dir.path()) |
| 1030 | .expect("data dir should exist") |
| 1031 | .count(), |
| 1032 | 0, |
| 1033 | "repo_path must be pure" |
| 1034 | ); |
| 1035 | } |
| 1036 | |
| 1037 | #[tokio::test] |
| 1038 | async fn repo_path_lands_under_the_data_directory() { |
| 1039 | let (dir, storage) = storage(); |
| 1040 | |
| 1041 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 1042 | |
| 1043 | assert_eq!(path, dir.path().join("jamesgill").join("steid.git")); |
| 1044 | } |
| 1045 | |
| 1046 | #[tokio::test] |
| 1047 | async fn remove_deletes_the_repository() { |
| 1048 | let (_dir, storage) = storage(); |
| 1049 | storage |
| 1050 | .init_bare(&handle(), &repo_name("steid")) |
| 1051 | .await |
| 1052 | .expect("should create"); |
| 1053 | |
| 1054 | storage |
| 1055 | .remove(&handle(), &repo_name("steid")) |
| 1056 | .await |
| 1057 | .expect("should remove"); |
| 1058 | |
| 1059 | assert!(!storage.repo_path(&handle(), &repo_name("steid")).exists()); |
| 1060 | } |
| 1061 | |
| 1062 | #[tokio::test] |
| 1063 | async fn removing_what_is_not_there_succeeds() { |
| 1064 | |
| 1065 | let (_dir, storage) = storage(); |
| 1066 | |
| 1067 | storage |
| 1068 | .remove(&handle(), &repo_name("never-created")) |
| 1069 | .await |
| 1070 | .expect("should succeed with nothing to do"); |
| 1071 | } |
| 1072 | |
| 1073 | #[tokio::test] |
| 1074 | async fn a_compensated_create_can_be_retried() { |
| 1075 | |
| 1076 | let (_dir, storage) = storage(); |
| 1077 | |
| 1078 | storage |
| 1079 | .init_bare(&handle(), &repo_name("steid")) |
| 1080 | .await |
| 1081 | .expect("should create"); |
| 1082 | storage |
| 1083 | .remove(&handle(), &repo_name("steid")) |
| 1084 | .await |
| 1085 | .expect("should remove"); |
| 1086 | storage |
| 1087 | .init_bare(&handle(), &repo_name("steid")) |
| 1088 | .await |
| 1089 | .expect("should create again"); |
| 1090 | } |
| 1091 | |
| 1092 | #[tokio::test] |
| 1093 | async fn removing_one_repository_leaves_its_neighbours() { |
| 1094 | let (_dir, storage) = storage(); |
| 1095 | storage |
| 1096 | .init_bare(&handle(), &repo_name("steid")) |
| 1097 | .await |
| 1098 | .expect("should create"); |
| 1099 | storage |
| 1100 | .init_bare(&handle(), &repo_name("keeper")) |
| 1101 | .await |
| 1102 | .expect("should create"); |
| 1103 | |
| 1104 | storage |
| 1105 | .remove(&handle(), &repo_name("steid")) |
| 1106 | .await |
| 1107 | .expect("should remove"); |
| 1108 | |
| 1109 | assert!(storage.repo_path(&handle(), &repo_name("keeper")).is_dir()); |
| 1110 | } |
| 1111 | |
| 1112 | #[tokio::test] |
| 1113 | async fn a_failing_git_invocation_carries_gits_own_message() { |
| 1114 | let error = run_git(["not-a-real-subcommand"]) |
| 1115 | .await |
| 1116 | .expect_err("should fail"); |
| 1117 | |
| 1118 | let message = error.to_string(); |
| 1119 | assert!( |
| 1120 | message.contains("not-a-real-subcommand"), |
| 1121 | "expected git's own words, got: {message}" |
| 1122 | ); |
| 1123 | } |
| 1124 | |
| 1125 | |
| 1126 | |
| 1127 | |
| 1128 | async fn backend() -> (TempDir, GitHttpBackend) { |
| 1129 | let dir = TempDir::new().expect("temp dir"); |
| 1130 | let storage = DiskGitStorage::new(dir.path()); |
| 1131 | |
| 1132 | let acme = OrgName::new("acme").expect("valid handle"); |
| 1133 | storage |
| 1134 | .init_bare(&acme, &repo_name("steid")) |
| 1135 | .await |
| 1136 | .expect("init bare"); |
| 1137 | |
| 1138 | let backend = GitHttpBackend::new(dir.path()); |
| 1139 | (dir, backend) |
| 1140 | } |
| 1141 | |
| 1142 | fn advertisement(path_info: &str) -> GitRequest { |
| 1143 | GitRequest { |
| 1144 | method: GitMethod::Get, |
| 1145 | path_info: path_info.to_owned(), |
| 1146 | query: "service=git-upload-pack".to_owned(), |
| 1147 | content_type: None, |
| 1148 | content_encoding: None, |
| 1149 | content_length: None, |
| 1150 | git_protocol: None, |
| 1151 | allow_receive_pack: false, |
| 1152 | body: Box::pin(tokio::io::empty()), |
| 1153 | } |
| 1154 | } |
| 1155 | |
| 1156 | async fn drain(response: GitResponse) -> Vec<u8> { |
| 1157 | let mut body = response.body; |
| 1158 | let mut bytes = Vec::new(); |
| 1159 | body.read_to_end(&mut bytes).await.expect("read body"); |
| 1160 | bytes |
| 1161 | } |
| 1162 | |
| 1163 | #[tokio::test] |
| 1164 | async fn the_backend_advertises_refs() { |
| 1165 | let (_dir, backend) = backend().await; |
| 1166 | |
| 1167 | let response = backend |
| 1168 | .serve(advertisement("/acme/steid.git/info/refs")) |
| 1169 | .await |
| 1170 | .expect("should serve"); |
| 1171 | |
| 1172 | assert_eq!(response.status, 200); |
| 1173 | assert!( |
| 1174 | response |
| 1175 | .headers |
| 1176 | .iter() |
| 1177 | .any(|(name, value)| name == "Content-Type" |
| 1178 | && value == "application/x-git-upload-pack-advertisement"), |
| 1179 | "git sets its own content type and we forward it: {:?}", |
| 1180 | response.headers |
| 1181 | ); |
| 1182 | |
| 1183 | |
| 1184 | |
| 1185 | let body = drain(response).await; |
| 1186 | assert!( |
| 1187 | body.starts_with(b"001e# service=git-upload-pack\n"), |
| 1188 | "unexpected advertisement: {:?}", |
| 1189 | String::from_utf8_lossy(&body[..body.len().min(40)]) |
| 1190 | ); |
| 1191 | } |
| 1192 | |
| 1193 | #[tokio::test] |
| 1194 | async fn a_missing_repository_is_reported_as_404_not_as_a_failure() { |
| 1195 | |
| 1196 | |
| 1197 | let (_dir, backend) = backend().await; |
| 1198 | |
| 1199 | let response = backend |
| 1200 | .serve(advertisement("/acme/nothing-here.git/info/refs")) |
| 1201 | .await |
| 1202 | .expect("serving should not itself fail"); |
| 1203 | |
| 1204 | assert_eq!(response.status, 404); |
| 1205 | } |
| 1206 | |
| 1207 | #[tokio::test] |
| 1208 | async fn the_status_header_is_translated_rather_than_forwarded() { |
| 1209 | let (_dir, backend) = backend().await; |
| 1210 | |
| 1211 | let response = backend |
| 1212 | .serve(advertisement("/acme/nothing-here.git/info/refs")) |
| 1213 | .await |
| 1214 | .expect("should serve"); |
| 1215 | |
| 1216 | assert!( |
| 1217 | !response |
| 1218 | .headers |
| 1219 | .iter() |
| 1220 | .any(|(name, _)| name.eq_ignore_ascii_case("status")), |
| 1221 | "Status: is CGI's, and means nothing to an HTTP client: {:?}", |
| 1222 | response.headers |
| 1223 | ); |
| 1224 | } |
| 1225 | |
| 1226 | #[tokio::test] |
| 1227 | async fn the_protocol_version_reaches_upload_pack() { |
| 1228 | |
| 1229 | |
| 1230 | |
| 1231 | let (_dir, backend) = backend().await; |
| 1232 | |
| 1233 | let mut request = advertisement("/acme/steid.git/info/refs"); |
| 1234 | request.git_protocol = Some("version=2".to_owned()); |
| 1235 | |
| 1236 | let body = drain(backend.serve(request).await.expect("should serve")).await; |
| 1237 | |
| 1238 | assert!( |
| 1239 | String::from_utf8_lossy(&body).contains("version 2"), |
| 1240 | "expected a v2 capability advertisement: {:?}", |
| 1241 | String::from_utf8_lossy(&body[..body.len().min(80)]) |
| 1242 | ); |
| 1243 | } |
| 1244 | |
| 1245 | #[tokio::test] |
| 1246 | async fn the_in_memory_protocol_records_what_it_was_asked() { |
| 1247 | let protocol = InMemoryGitProtocol::new(); |
| 1248 | |
| 1249 | protocol |
| 1250 | .serve(advertisement("/acme/steid.git/info/refs")) |
| 1251 | .await |
| 1252 | .expect("should serve"); |
| 1253 | |
| 1254 | assert_eq!( |
| 1255 | protocol.requests(), |
| 1256 | vec![RecordedGitRequest { |
| 1257 | method: GitMethod::Get, |
| 1258 | path_info: "/acme/steid.git/info/refs".to_owned(), |
| 1259 | query: "service=git-upload-pack".to_owned(), |
| 1260 | git_protocol: None, |
| 1261 | content_encoding: None, |
| 1262 | allow_receive_pack: false, |
| 1263 | }] |
| 1264 | ); |
| 1265 | assert!(protocol.was_called()); |
| 1266 | } |
| 1267 | |
| 1268 | |
| 1269 | |
| 1270 | |
| 1271 | |
| 1272 | |
| 1273 | |
| 1274 | fn archivable() -> (TempDir, DiskGitArchive, ObjectId) { |
| 1275 | let dir = TempDir::new().expect("temp dir"); |
| 1276 | let storage = DiskGitStorage::new(dir.path()); |
| 1277 | let repo = storage.repo_path(&handle(), &repo_name("steid")); |
| 1278 | let work = dir.path().join("work"); |
| 1279 | |
| 1280 | let git = |at: &Path, args: &[&str]| { |
| 1281 | let output = std::process::Command::new("git") |
| 1282 | .arg("-C") |
| 1283 | .arg(at) |
| 1284 | .args(args) |
| 1285 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 1286 | .env("GIT_CONFIG_SYSTEM", "/dev/null") |
| 1287 | .env("GIT_AUTHOR_NAME", "Ada Lovelace") |
| 1288 | .env("GIT_AUTHOR_EMAIL", "ada@example.com") |
| 1289 | .env("GIT_COMMITTER_NAME", "Ada Lovelace") |
| 1290 | .env("GIT_COMMITTER_EMAIL", "ada@example.com") |
| 1291 | .output() |
| 1292 | .expect("git should be on PATH"); |
| 1293 | |
| 1294 | assert!( |
| 1295 | output.status.success(), |
| 1296 | "git {args:?} failed: {}", |
| 1297 | String::from_utf8_lossy(&output.stderr) |
| 1298 | ); |
| 1299 | |
| 1300 | String::from_utf8_lossy(&output.stdout).trim().to_owned() |
| 1301 | }; |
| 1302 | |
| 1303 | std::fs::create_dir_all(&work).expect("create work tree"); |
| 1304 | git( |
| 1305 | dir.path(), |
| 1306 | &[ |
| 1307 | "init", |
| 1308 | "--bare", |
| 1309 | "--quiet", |
| 1310 | "--template=", |
| 1311 | "--initial-branch=main", |
| 1312 | "--", |
| 1313 | repo.to_str().expect("utf-8 fixture path"), |
| 1314 | ], |
| 1315 | ); |
| 1316 | git(&work, &["init", "--quiet", "-b", "main"]); |
| 1317 | std::fs::write(work.join("README.md"), b"hello\n").expect("write"); |
| 1318 | git(&work, &["add", "-A"]); |
| 1319 | git(&work, &["commit", "--quiet", "-m", "first"]); |
| 1320 | git( |
| 1321 | &work, |
| 1322 | &["push", "--quiet", repo.to_str().expect("utf-8"), "main"], |
| 1323 | ); |
| 1324 | |
| 1325 | let head = git(&repo, &["rev-parse", "main"]); |
| 1326 | let archives = DiskGitArchive::new(dir.path()); |
| 1327 | |
| 1328 | ( |
| 1329 | dir, |
| 1330 | archives, |
| 1331 | ObjectId::new(head).expect("a real object id"), |
| 1332 | ) |
| 1333 | } |
| 1334 | |
| 1335 | async fn packed(format: ArchiveFormat) -> Vec<u8> { |
| 1336 | let (dir, archives, commit) = archivable(); |
| 1337 | |
| 1338 | let mut stream = archives |
| 1339 | .archive(ArchiveRequest { |
| 1340 | handle: handle(), |
| 1341 | name: repo_name("steid"), |
| 1342 | format, |
| 1343 | commit, |
| 1344 | prefix: "steid-main/".to_owned(), |
| 1345 | }) |
| 1346 | .await |
| 1347 | .expect("should pack"); |
| 1348 | |
| 1349 | let mut bytes = Vec::new(); |
| 1350 | stream.read_to_end(&mut bytes).await.expect("should stream"); |
| 1351 | |
| 1352 | |
| 1353 | |
| 1354 | drop(dir); |
| 1355 | |
| 1356 | bytes |
| 1357 | } |
| 1358 | |
| 1359 | #[tokio::test] |
| 1360 | async fn a_tarball_carries_the_prefix_directory() { |
| 1361 | let bytes = packed(ArchiveFormat::TarGz).await; |
| 1362 | |
| 1363 | |
| 1364 | |
| 1365 | assert_eq!(&bytes[..2], &[0x1f, 0x8b], "expected gzip"); |
| 1366 | assert!(bytes.len() > 100, "expected a real archive"); |
| 1367 | } |
| 1368 | |
| 1369 | #[tokio::test] |
| 1370 | async fn a_zip_is_a_zip() { |
| 1371 | let bytes = packed(ArchiveFormat::Zip).await; |
| 1372 | |
| 1373 | assert_eq!(&bytes[..2], b"PK", "expected a zip"); |
| 1374 | |
| 1375 | |
| 1376 | assert!( |
| 1377 | bytes.windows(11).any(|window| window == b"steid-main/"), |
| 1378 | "expected the prefix directory in the archive" |
| 1379 | ); |
| 1380 | } |
| 1381 | } |