| 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::{ |
| 24 | blame::Blame, |
| 25 | port::{ |
| 26 | ArchiveRequest, Blob, ByteStream, GitArchive, GitArchiveError, GitImport, |
| 27 | GitImportError, GitMethod, GitProtocolError, GitProtocolServer, GitQuery, |
| 28 | GitQueryError, GitRequest, GitResponse, GitStorage, GitStorageError, RawDiff, |
| 29 | }, |
| 30 | }, |
| 31 | domain::{ |
| 32 | BranchRow, CommitDetail, CommitSummary, GitRef, GrepHit, ImportSource, ObjectId, OrgName, |
| 33 | RefKind, RefName, RepoName, RepoPath, TagRow, TagSummary, TreeEntry, is_public, |
| 34 | }, |
| 35 | }; |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | const MAX_CGI_HEADERS: usize = 64; |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | const REDIRECTING_VARS: &[&str] = &[ |
| 50 | "GIT_ALTERNATE_OBJECT_DIRECTORIES", |
| 51 | "GIT_DIR", |
| 52 | "GIT_INDEX_FILE", |
| 53 | "GIT_OBJECT_DIRECTORY", |
| 54 | "GIT_WORK_TREE", |
| 55 | ]; |
| 56 | |
| 57 | |
| 58 | #[derive(Debug, Clone)] |
| 59 | pub struct DiskGitStorage { |
| 60 | data_dir: PathBuf, |
| 61 | } |
| 62 | |
| 63 | impl DiskGitStorage { |
| 64 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 65 | Self { |
| 66 | data_dir: data_dir.into(), |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | impl GitStorage for DiskGitStorage { |
| 72 | async fn init_bare(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> { |
| 73 | let path = self.repo_path(handle, name); |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | if path.exists() { |
| 80 | return Err(GitStorageError::AlreadyExists); |
| 81 | } |
| 82 | |
| 83 | |
| 84 | run_git([ |
| 85 | OsStr::new("init"), |
| 86 | OsStr::new("--bare"), |
| 87 | OsStr::new("--quiet"), |
| 88 | |
| 89 | |
| 90 | |
| 91 | OsStr::new("--template="), |
| 92 | |
| 93 | |
| 94 | OsStr::new("--initial-branch=main"), |
| 95 | |
| 96 | |
| 97 | OsStr::new("--"), |
| 98 | path.as_os_str(), |
| 99 | ]) |
| 100 | .await?; |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | run_git([ |
| 114 | OsStr::new("--git-dir"), |
| 115 | path.as_os_str(), |
| 116 | OsStr::new("config"), |
| 117 | OsStr::new("core.logAllRefUpdates"), |
| 118 | OsStr::new("true"), |
| 119 | ]) |
| 120 | .await |
| 121 | .map(|_| ()) |
| 122 | } |
| 123 | |
| 124 | async fn remove(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> { |
| 125 | let path = self.repo_path(handle, name); |
| 126 | |
| 127 | |
| 128 | |
| 129 | match tokio::fs::remove_dir_all(&path).await { |
| 130 | Ok(()) => Ok(()), |
| 131 | |
| 132 | Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), |
| 133 | Err(error) => Err(GitStorageError::backend(error)), |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | async fn rename( |
| 138 | &self, |
| 139 | handle: &OrgName, |
| 140 | from: &RepoName, |
| 141 | to: &RepoName, |
| 142 | ) -> Result<(), GitStorageError> { |
| 143 | let source = self.repo_path(handle, from); |
| 144 | let destination = self.repo_path(handle, to); |
| 145 | |
| 146 | |
| 147 | |
| 148 | |
| 149 | if destination.exists() { |
| 150 | return Err(GitStorageError::AlreadyExists); |
| 151 | } |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | tokio::fs::rename(&source, &destination) |
| 157 | .await |
| 158 | .map_err(GitStorageError::backend) |
| 159 | } |
| 160 | |
| 161 | async fn set_default_branch( |
| 162 | &self, |
| 163 | handle: &OrgName, |
| 164 | name: &RepoName, |
| 165 | branch: &RefName, |
| 166 | ) -> Result<(), GitStorageError> { |
| 167 | let path = self.repo_path(handle, name); |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | run_git([ |
| 174 | OsStr::new("--git-dir"), |
| 175 | path.as_os_str(), |
| 176 | OsStr::new("symbolic-ref"), |
| 177 | OsStr::new("HEAD"), |
| 178 | OsStr::new(&format!("refs/heads/{branch}")), |
| 179 | ]) |
| 180 | .await |
| 181 | .map(|_| ()) |
| 182 | } |
| 183 | |
| 184 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 185 | |
| 186 | |
| 187 | |
| 188 | self.data_dir |
| 189 | .join(handle.as_str()) |
| 190 | .join(format!("{name}.git")) |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | |
| 199 | |
| 200 | pub(crate) fn git_command() -> Command { |
| 201 | let mut command = Command::new("git"); |
| 202 | |
| 203 | |
| 204 | |
| 205 | command |
| 206 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 207 | .env("GIT_CONFIG_SYSTEM", "/dev/null"); |
| 208 | |
| 209 | for variable in REDIRECTING_VARS { |
| 210 | command.env_remove(variable); |
| 211 | } |
| 212 | |
| 213 | command |
| 214 | } |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | async fn run_git<I, S>(args: I) -> Result<Output, GitStorageError> |
| 223 | where |
| 224 | I: IntoIterator<Item = S>, |
| 225 | S: AsRef<OsStr>, |
| 226 | { |
| 227 | let mut command = git_command(); |
| 228 | command.args(args).stdin(Stdio::null()); |
| 229 | |
| 230 | |
| 231 | let output = command |
| 232 | .output() |
| 233 | .await |
| 234 | .map_err(|error| GitStorageError::backend(format!("could not run git: {error}")))?; |
| 235 | |
| 236 | if !output.status.success() { |
| 237 | |
| 238 | |
| 239 | return Err(GitStorageError::backend(format!( |
| 240 | "git exited with {}: {}", |
| 241 | output.status, |
| 242 | String::from_utf8_lossy(&output.stderr).trim() |
| 243 | ))); |
| 244 | } |
| 245 | |
| 246 | Ok(output) |
| 247 | } |
| 248 | |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 254 | #[derive(Debug, Default, Clone)] |
| 255 | pub struct InMemoryGitStorage { |
| 256 | created: Arc<Mutex<HashSet<PathBuf>>>, |
| 257 | |
| 258 | heads: Arc<Mutex<HashMap<PathBuf, RefName>>>, |
| 259 | } |
| 260 | |
| 261 | impl InMemoryGitStorage { |
| 262 | pub fn new() -> Self { |
| 263 | Self::default() |
| 264 | } |
| 265 | |
| 266 | |
| 267 | pub fn contains(&self, handle: &OrgName, name: &RepoName) -> bool { |
| 268 | self.created |
| 269 | .lock() |
| 270 | .expect("lock poisoned") |
| 271 | .contains(&self.repo_path(handle, name)) |
| 272 | } |
| 273 | |
| 274 | |
| 275 | pub fn head(&self, handle: &OrgName, name: &RepoName) -> Option<RefName> { |
| 276 | self.heads |
| 277 | .lock() |
| 278 | .expect("lock poisoned") |
| 279 | .get(&self.repo_path(handle, name)) |
| 280 | .cloned() |
| 281 | } |
| 282 | |
| 283 | |
| 284 | pub fn len(&self) -> usize { |
| 285 | self.created.lock().expect("lock poisoned").len() |
| 286 | } |
| 287 | |
| 288 | pub fn is_empty(&self) -> bool { |
| 289 | self.len() == 0 |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | impl GitStorage for InMemoryGitStorage { |
| 294 | async fn init_bare(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> { |
| 295 | let mut created = self.created.lock().expect("lock poisoned"); |
| 296 | |
| 297 | if !created.insert(self.repo_path(handle, name)) { |
| 298 | return Err(GitStorageError::AlreadyExists); |
| 299 | } |
| 300 | |
| 301 | Ok(()) |
| 302 | } |
| 303 | |
| 304 | async fn remove(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> { |
| 305 | self.created |
| 306 | .lock() |
| 307 | .expect("lock poisoned") |
| 308 | .remove(&self.repo_path(handle, name)); |
| 309 | |
| 310 | Ok(()) |
| 311 | } |
| 312 | |
| 313 | async fn rename( |
| 314 | &self, |
| 315 | handle: &OrgName, |
| 316 | from: &RepoName, |
| 317 | to: &RepoName, |
| 318 | ) -> Result<(), GitStorageError> { |
| 319 | let mut created = self.created.lock().expect("lock poisoned"); |
| 320 | let destination = self.repo_path(handle, to); |
| 321 | |
| 322 | |
| 323 | |
| 324 | if created.contains(&destination) { |
| 325 | return Err(GitStorageError::AlreadyExists); |
| 326 | } |
| 327 | |
| 328 | let source = self.repo_path(handle, from); |
| 329 | created.remove(&source); |
| 330 | created.insert(destination.clone()); |
| 331 | |
| 332 | |
| 333 | let mut heads = self.heads.lock().expect("lock poisoned"); |
| 334 | if let Some(head) = heads.remove(&source) { |
| 335 | heads.insert(destination, head); |
| 336 | } |
| 337 | |
| 338 | Ok(()) |
| 339 | } |
| 340 | |
| 341 | async fn set_default_branch( |
| 342 | &self, |
| 343 | handle: &OrgName, |
| 344 | name: &RepoName, |
| 345 | branch: &RefName, |
| 346 | ) -> Result<(), GitStorageError> { |
| 347 | self.heads |
| 348 | .lock() |
| 349 | .expect("lock poisoned") |
| 350 | .insert(self.repo_path(handle, name), branch.clone()); |
| 351 | |
| 352 | Ok(()) |
| 353 | } |
| 354 | |
| 355 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 356 | PathBuf::from("/in-memory") |
| 357 | .join(handle.as_str()) |
| 358 | .join(format!("{name}.git")) |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | |
| 363 | |
| 364 | |
| 365 | |
| 366 | |
| 367 | #[derive(Debug, Clone)] |
| 368 | pub struct GitHttpBackend { |
| 369 | data_dir: PathBuf, |
| 370 | } |
| 371 | |
| 372 | impl GitHttpBackend { |
| 373 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 374 | Self { |
| 375 | data_dir: data_dir.into(), |
| 376 | } |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | impl GitProtocolServer for GitHttpBackend { |
| 381 | async fn serve(&self, request: GitRequest) -> Result<GitResponse, GitProtocolError> { |
| 382 | let mut command = git_command(); |
| 383 | |
| 384 | |
| 385 | |
| 386 | |
| 387 | |
| 388 | if request.allow_receive_pack { |
| 389 | command.arg("-c").arg("http.receivepack=true"); |
| 390 | } |
| 391 | |
| 392 | command |
| 393 | .arg("http-backend") |
| 394 | .env("GIT_PROJECT_ROOT", &self.data_dir) |
| 395 | |
| 396 | |
| 397 | |
| 398 | |
| 399 | .env("GIT_HTTP_EXPORT_ALL", "1") |
| 400 | .env("PATH_INFO", &request.path_info) |
| 401 | .env("QUERY_STRING", &request.query) |
| 402 | .env("REQUEST_METHOD", request.method.as_str()) |
| 403 | .stdin(Stdio::piped()) |
| 404 | .stdout(Stdio::piped()) |
| 405 | .stderr(Stdio::piped()); |
| 406 | |
| 407 | |
| 408 | |
| 409 | |
| 410 | |
| 411 | |
| 412 | |
| 413 | |
| 414 | |
| 415 | |
| 416 | for (variable, value) in [ |
| 417 | ("CONTENT_TYPE", &request.content_type), |
| 418 | ("CONTENT_LENGTH", &request.content_length), |
| 419 | ("HTTP_CONTENT_ENCODING", &request.content_encoding), |
| 420 | ("HTTP_GIT_PROTOCOL", &request.git_protocol), |
| 421 | ("REMOTE_USER", &request.remote_user), |
| 422 | ] { |
| 423 | if let Some(value) = value { |
| 424 | command.env(variable, value); |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | let mut child = command |
| 429 | .spawn() |
| 430 | .map_err(|error| GitProtocolError::new(format!("could not run git: {error}")))?; |
| 431 | |
| 432 | let mut stdin = child.stdin.take().expect("stdin was piped"); |
| 433 | let stdout = child.stdout.take().expect("stdout was piped"); |
| 434 | let mut stderr = child.stderr.take().expect("stderr was piped"); |
| 435 | let mut body = request.body; |
| 436 | |
| 437 | |
| 438 | |
| 439 | |
| 440 | |
| 441 | |
| 442 | tokio::spawn(async move { |
| 443 | let _ = tokio::io::copy(&mut body, &mut stdin).await; |
| 444 | }); |
| 445 | |
| 446 | |
| 447 | |
| 448 | |
| 449 | |
| 450 | |
| 451 | tokio::spawn(async move { |
| 452 | let mut complaint = String::new(); |
| 453 | let _ = stderr.read_to_string(&mut complaint).await; |
| 454 | |
| 455 | match child.wait().await { |
| 456 | Ok(status) if status.success() => {} |
| 457 | Ok(status) => eprintln!( |
| 458 | "steid: git http-backend exited with {status}: {}", |
| 459 | complaint.trim() |
| 460 | ), |
| 461 | Err(error) => eprintln!("steid: could not wait for git http-backend: {error}"), |
| 462 | } |
| 463 | }); |
| 464 | |
| 465 | |
| 466 | |
| 467 | |
| 468 | let mut reader = BufReader::new(stdout); |
| 469 | let (status, headers) = read_cgi_headers(&mut reader).await?; |
| 470 | |
| 471 | Ok(GitResponse { |
| 472 | status, |
| 473 | headers, |
| 474 | body: Box::pin(reader), |
| 475 | }) |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | |
| 480 | |
| 481 | |
| 482 | |
| 483 | |
| 484 | async fn read_cgi_headers( |
| 485 | reader: &mut BufReader<ChildStdout>, |
| 486 | ) -> Result<(u16, Vec<(String, String)>), GitProtocolError> { |
| 487 | let mut status = 200; |
| 488 | let mut headers = Vec::new(); |
| 489 | let mut line = Vec::new(); |
| 490 | |
| 491 | loop { |
| 492 | line.clear(); |
| 493 | |
| 494 | let read = reader |
| 495 | .read_until(b'\n', &mut line) |
| 496 | .await |
| 497 | .map_err(|error| GitProtocolError::new(format!("reading git's headers: {error}")))?; |
| 498 | |
| 499 | if read == 0 { |
| 500 | return Err(GitProtocolError::new( |
| 501 | "git http-backend produced no headers before closing", |
| 502 | )); |
| 503 | } |
| 504 | |
| 505 | |
| 506 | |
| 507 | let text = String::from_utf8_lossy(&line); |
| 508 | let text = text.trim_end_matches(['\r', '\n']); |
| 509 | |
| 510 | if text.is_empty() { |
| 511 | return Ok((status, headers)); |
| 512 | } |
| 513 | |
| 514 | let Some((name, value)) = text.split_once(": ") else { |
| 515 | return Err(GitProtocolError::new(format!( |
| 516 | "git http-backend wrote an unparseable header: {text:?}" |
| 517 | ))); |
| 518 | }; |
| 519 | |
| 520 | if name.eq_ignore_ascii_case("status") { |
| 521 | status = value |
| 522 | .split_whitespace() |
| 523 | .next() |
| 524 | .and_then(|code| code.parse().ok()) |
| 525 | .ok_or_else(|| { |
| 526 | GitProtocolError::new(format!("git http-backend wrote a bad status: {value:?}")) |
| 527 | })?; |
| 528 | } else { |
| 529 | headers.push((name.to_owned(), value.to_owned())); |
| 530 | } |
| 531 | |
| 532 | if headers.len() > MAX_CGI_HEADERS { |
| 533 | return Err(GitProtocolError::new( |
| 534 | "git http-backend wrote more headers than a CGI response can plausibly have", |
| 535 | )); |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | |
| 541 | |
| 542 | |
| 543 | |
| 544 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 545 | pub struct RecordedGitRequest { |
| 546 | pub method: GitMethod, |
| 547 | pub path_info: String, |
| 548 | pub query: String, |
| 549 | pub git_protocol: Option<String>, |
| 550 | pub content_encoding: Option<String>, |
| 551 | pub allow_receive_pack: bool, |
| 552 | pub remote_user: Option<String>, |
| 553 | } |
| 554 | |
| 555 | |
| 556 | |
| 557 | |
| 558 | |
| 559 | |
| 560 | #[derive(Debug, Default, Clone)] |
| 561 | pub struct InMemoryGitProtocol { |
| 562 | requests: Arc<Mutex<Vec<RecordedGitRequest>>>, |
| 563 | } |
| 564 | |
| 565 | impl InMemoryGitProtocol { |
| 566 | pub fn new() -> Self { |
| 567 | Self::default() |
| 568 | } |
| 569 | |
| 570 | pub fn requests(&self) -> Vec<RecordedGitRequest> { |
| 571 | self.requests.lock().expect("lock poisoned").clone() |
| 572 | } |
| 573 | |
| 574 | |
| 575 | pub fn was_called(&self) -> bool { |
| 576 | !self.requests.lock().expect("lock poisoned").is_empty() |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | impl GitProtocolServer for InMemoryGitProtocol { |
| 581 | async fn serve(&self, request: GitRequest) -> Result<GitResponse, GitProtocolError> { |
| 582 | self.requests |
| 583 | .lock() |
| 584 | .expect("lock poisoned") |
| 585 | .push(RecordedGitRequest { |
| 586 | method: request.method, |
| 587 | path_info: request.path_info, |
| 588 | query: request.query, |
| 589 | git_protocol: request.git_protocol, |
| 590 | content_encoding: request.content_encoding, |
| 591 | allow_receive_pack: request.allow_receive_pack, |
| 592 | remote_user: request.remote_user, |
| 593 | }); |
| 594 | |
| 595 | Ok(GitResponse { |
| 596 | status: 200, |
| 597 | headers: vec![( |
| 598 | "Content-Type".to_owned(), |
| 599 | "application/x-git-upload-pack-advertisement".to_owned(), |
| 600 | )], |
| 601 | body: Box::pin(std::io::Cursor::new(b"0000".to_vec())), |
| 602 | }) |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | |
| 607 | |
| 608 | |
| 609 | |
| 610 | |
| 611 | |
| 612 | #[derive(Debug, Clone)] |
| 613 | pub struct DiskGitArchive { |
| 614 | data_dir: PathBuf, |
| 615 | } |
| 616 | |
| 617 | impl DiskGitArchive { |
| 618 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 619 | Self { |
| 620 | data_dir: data_dir.into(), |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | |
| 625 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 626 | self.data_dir |
| 627 | .join(handle.as_str()) |
| 628 | .join(format!("{name}.git")) |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | impl GitArchive for DiskGitArchive { |
| 633 | async fn archive(&self, request: ArchiveRequest) -> Result<ByteStream, GitArchiveError> { |
| 634 | let repo = self.repo_path(&request.handle, &request.name); |
| 635 | |
| 636 | |
| 637 | |
| 638 | |
| 639 | |
| 640 | let mut command = git_command(); |
| 641 | command |
| 642 | .arg("-C") |
| 643 | .arg(&repo) |
| 644 | .arg("archive") |
| 645 | .arg(format!("--format={}", request.format.as_str())) |
| 646 | .arg(format!("--prefix={}", request.prefix)) |
| 647 | .arg(request.commit.as_str()) |
| 648 | .stdin(Stdio::null()) |
| 649 | .stdout(Stdio::piped()) |
| 650 | .stderr(Stdio::piped()) |
| 651 | |
| 652 | |
| 653 | .kill_on_drop(true); |
| 654 | |
| 655 | let mut child = command |
| 656 | .spawn() |
| 657 | .map_err(|error| GitArchiveError::new(format!("could not run git: {error}")))?; |
| 658 | |
| 659 | let stdout = child.stdout.take().expect("stdout was piped"); |
| 660 | let mut stderr = child.stderr.take().expect("stderr was piped"); |
| 661 | |
| 662 | |
| 663 | |
| 664 | |
| 665 | |
| 666 | |
| 667 | |
| 668 | tokio::spawn(async move { |
| 669 | let mut complaint = String::new(); |
| 670 | let _ = stderr.read_to_string(&mut complaint).await; |
| 671 | |
| 672 | match child.wait().await { |
| 673 | Ok(status) if status.success() => {} |
| 674 | Ok(status) => { |
| 675 | eprintln!( |
| 676 | "steid: git archive exited with {status}: {}", |
| 677 | complaint.trim() |
| 678 | ) |
| 679 | } |
| 680 | Err(error) => eprintln!("steid: could not wait for git archive: {error}"), |
| 681 | } |
| 682 | }); |
| 683 | |
| 684 | Ok(Box::pin(stdout)) |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | |
| 689 | |
| 690 | |
| 691 | |
| 692 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 693 | pub struct RecordedArchive { |
| 694 | pub handle: OrgName, |
| 695 | pub name: RepoName, |
| 696 | pub format: crate::application::port::ArchiveFormat, |
| 697 | pub commit: ObjectId, |
| 698 | pub prefix: String, |
| 699 | } |
| 700 | |
| 701 | |
| 702 | |
| 703 | |
| 704 | |
| 705 | #[derive(Debug, Default, Clone)] |
| 706 | pub struct InMemoryGitArchive { |
| 707 | requests: Arc<Mutex<Vec<RecordedArchive>>>, |
| 708 | } |
| 709 | |
| 710 | impl InMemoryGitArchive { |
| 711 | pub fn new() -> Self { |
| 712 | Self::default() |
| 713 | } |
| 714 | |
| 715 | pub fn requests(&self) -> Vec<RecordedArchive> { |
| 716 | self.requests.lock().expect("lock poisoned").clone() |
| 717 | } |
| 718 | |
| 719 | |
| 720 | pub fn was_called(&self) -> bool { |
| 721 | !self.requests.lock().expect("lock poisoned").is_empty() |
| 722 | } |
| 723 | } |
| 724 | |
| 725 | impl GitArchive for InMemoryGitArchive { |
| 726 | async fn archive(&self, request: ArchiveRequest) -> Result<ByteStream, GitArchiveError> { |
| 727 | self.requests |
| 728 | .lock() |
| 729 | .expect("lock poisoned") |
| 730 | .push(RecordedArchive { |
| 731 | handle: request.handle, |
| 732 | name: request.name, |
| 733 | format: request.format, |
| 734 | commit: request.commit, |
| 735 | prefix: request.prefix, |
| 736 | }); |
| 737 | |
| 738 | Ok(Box::pin(std::io::Cursor::new(b"archive".to_vec()))) |
| 739 | } |
| 740 | } |
| 741 | |
| 742 | |
| 743 | |
| 744 | |
| 745 | |
| 746 | |
| 747 | #[derive(Debug, Default, Clone)] |
| 748 | pub struct InMemoryGitQuery { |
| 749 | default_branch: Option<RefName>, |
| 750 | |
| 751 | trees: HashMap<String, Vec<TreeEntry>>, |
| 752 | blobs: HashMap<String, Vec<u8>>, |
| 753 | commits: Vec<CommitSummary>, |
| 754 | |
| 755 | |
| 756 | refs: Vec<GitRef>, |
| 757 | |
| 758 | |
| 759 | commit_count: Option<u64>, |
| 760 | latest_tag: Option<TagSummary>, |
| 761 | |
| 762 | |
| 763 | branch_rows: Vec<BranchRow>, |
| 764 | tag_rows: Vec<TagRow>, |
| 765 | |
| 766 | |
| 767 | grep_hits: Vec<GrepHit>, |
| 768 | |
| 769 | |
| 770 | slow_grep: bool, |
| 771 | |
| 772 | |
| 773 | detail: Option<CommitDetail>, |
| 774 | |
| 775 | diff: Option<RawDiff>, |
| 776 | |
| 777 | merge_base: Option<ObjectId>, |
| 778 | |
| 779 | |
| 780 | |
| 781 | snapshot: Arc<Mutex<Vec<(RefName, ObjectId)>>>, |
| 782 | |
| 783 | |
| 784 | |
| 785 | blames: HashMap<String, Blame>, |
| 786 | } |
| 787 | |
| 788 | impl InMemoryGitQuery { |
| 789 | |
| 790 | pub fn empty() -> Self { |
| 791 | Self::default() |
| 792 | } |
| 793 | |
| 794 | |
| 795 | pub fn new() -> Self { |
| 796 | Self { |
| 797 | default_branch: Some(RefName::from_trusted("main")), |
| 798 | ..Self::default() |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | fn key(rev: &RefName, path: &RepoPath) -> String { |
| 803 | format!("{}\0{}", rev.as_str(), path.as_str()) |
| 804 | } |
| 805 | |
| 806 | pub fn with_tree(mut self, rev: &str, path: &str, entries: Vec<TreeEntry>) -> Self { |
| 807 | self.trees.insert( |
| 808 | Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)), |
| 809 | entries, |
| 810 | ); |
| 811 | self |
| 812 | } |
| 813 | |
| 814 | pub fn with_blob(mut self, rev: &str, path: &str, content: impl Into<Vec<u8>>) -> Self { |
| 815 | self.blobs.insert( |
| 816 | Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)), |
| 817 | content.into(), |
| 818 | ); |
| 819 | self |
| 820 | } |
| 821 | |
| 822 | pub fn with_log(mut self, commits: Vec<CommitSummary>) -> Self { |
| 823 | self.commits = commits; |
| 824 | self |
| 825 | } |
| 826 | |
| 827 | pub fn with_branch(self, name: &str) -> Self { |
| 828 | self.with_ref(name, RefKind::Branch) |
| 829 | } |
| 830 | |
| 831 | pub fn with_tag(self, name: &str) -> Self { |
| 832 | self.with_ref(name, RefKind::Tag) |
| 833 | } |
| 834 | |
| 835 | pub fn with_commit_count(mut self, count: u64) -> Self { |
| 836 | self.commit_count = Some(count); |
| 837 | self |
| 838 | } |
| 839 | |
| 840 | pub fn with_latest_tag(mut self, name: &str, created_at: SystemTime) -> Self { |
| 841 | self.latest_tag = Some(TagSummary { |
| 842 | name: RefName::from_trusted(name), |
| 843 | created_at, |
| 844 | }); |
| 845 | self |
| 846 | } |
| 847 | |
| 848 | |
| 849 | pub fn with_branch_row( |
| 850 | mut self, |
| 851 | name: &str, |
| 852 | is_default: bool, |
| 853 | committed_at: SystemTime, |
| 854 | ) -> Self { |
| 855 | self.branch_rows.push(BranchRow { |
| 856 | name: RefName::from_trusted(name), |
| 857 | is_default, |
| 858 | commit: ObjectId::from_trusted("2".repeat(40)), |
| 859 | summary: format!("work on {name}"), |
| 860 | committed_at, |
| 861 | }); |
| 862 | self |
| 863 | } |
| 864 | |
| 865 | |
| 866 | |
| 867 | pub fn with_tag_row(mut self, name: &str, annotated: bool, created_at: SystemTime) -> Self { |
| 868 | self.tag_rows.push(TagRow { |
| 869 | name: RefName::from_trusted(name), |
| 870 | commit: ObjectId::from_trusted("3".repeat(40)), |
| 871 | message: annotated.then(|| format!("release {name}")), |
| 872 | annotated, |
| 873 | created_at, |
| 874 | }); |
| 875 | self |
| 876 | } |
| 877 | |
| 878 | |
| 879 | |
| 880 | pub fn with_grep_hits(mut self, hits: Vec<GrepHit>) -> Self { |
| 881 | self.grep_hits = hits; |
| 882 | self |
| 883 | } |
| 884 | |
| 885 | |
| 886 | pub fn with_slow_grep(mut self) -> Self { |
| 887 | self.slow_grep = true; |
| 888 | self |
| 889 | } |
| 890 | |
| 891 | pub fn with_commit(mut self, detail: CommitDetail) -> Self { |
| 892 | self.detail = Some(detail); |
| 893 | self |
| 894 | } |
| 895 | |
| 896 | pub fn with_diff(mut self, patch: impl Into<Vec<u8>>, numstat: impl Into<Vec<u8>>) -> Self { |
| 897 | self.diff = Some(RawDiff { |
| 898 | numstat: numstat.into(), |
| 899 | patch: patch.into(), |
| 900 | truncated: false, |
| 901 | }); |
| 902 | self |
| 903 | } |
| 904 | |
| 905 | pub fn with_merge_base(mut self, id: &str) -> Self { |
| 906 | self.merge_base = Some(ObjectId::from_trusted(id)); |
| 907 | self |
| 908 | } |
| 909 | |
| 910 | pub fn with_blame(mut self, rev: &str, path: &str, blame: Blame) -> Self { |
| 911 | self.blames.insert( |
| 912 | Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)), |
| 913 | blame, |
| 914 | ); |
| 915 | self |
| 916 | } |
| 917 | |
| 918 | |
| 919 | pub fn with_ref_snapshot(self, refs: &[(&str, &str)]) -> Self { |
| 920 | self.set_ref_snapshot(refs); |
| 921 | self |
| 922 | } |
| 923 | |
| 924 | |
| 925 | |
| 926 | |
| 927 | |
| 928 | pub fn set_ref_snapshot(&self, refs: &[(&str, &str)]) { |
| 929 | *self.snapshot.lock().expect("lock poisoned") = refs |
| 930 | .iter() |
| 931 | .map(|(name, id)| { |
| 932 | ( |
| 933 | RefName::from_trusted(*name), |
| 934 | ObjectId::from_trusted(format!("{id:0>40}")), |
| 935 | ) |
| 936 | }) |
| 937 | .collect(); |
| 938 | } |
| 939 | |
| 940 | fn with_ref(mut self, name: &str, kind: RefKind) -> Self { |
| 941 | self.refs.push(GitRef { |
| 942 | name: RefName::from_trusted(name), |
| 943 | kind, |
| 944 | }); |
| 945 | self |
| 946 | } |
| 947 | } |
| 948 | |
| 949 | impl GitQuery for InMemoryGitQuery { |
| 950 | async fn default_branch( |
| 951 | &self, |
| 952 | _handle: &OrgName, |
| 953 | _name: &RepoName, |
| 954 | ) -> Result<Option<RefName>, GitQueryError> { |
| 955 | Ok(self.default_branch.clone()) |
| 956 | } |
| 957 | |
| 958 | async fn resolve( |
| 959 | &self, |
| 960 | _handle: &OrgName, |
| 961 | _name: &RepoName, |
| 962 | _rev: &RefName, |
| 963 | ) -> Result<Option<ObjectId>, GitQueryError> { |
| 964 | Ok(self |
| 965 | .default_branch |
| 966 | .as_ref() |
| 967 | .map(|_| ObjectId::from_trusted("0".repeat(40)))) |
| 968 | } |
| 969 | |
| 970 | async fn list_tree( |
| 971 | &self, |
| 972 | _handle: &OrgName, |
| 973 | _name: &RepoName, |
| 974 | rev: &RefName, |
| 975 | path: &RepoPath, |
| 976 | ) -> Result<Option<Vec<TreeEntry>>, GitQueryError> { |
| 977 | Ok(self.trees.get(&Self::key(rev, path)).cloned()) |
| 978 | } |
| 979 | |
| 980 | async fn read_blob( |
| 981 | &self, |
| 982 | _handle: &OrgName, |
| 983 | _name: &RepoName, |
| 984 | rev: &RefName, |
| 985 | path: &RepoPath, |
| 986 | max_bytes: u64, |
| 987 | ) -> Result<Option<Blob>, GitQueryError> { |
| 988 | Ok(self.blobs.get(&Self::key(rev, path)).map(|content| { |
| 989 | let size = content.len() as u64; |
| 990 | |
| 991 | Blob { |
| 992 | id: ObjectId::from_trusted("1".repeat(40)), |
| 993 | size, |
| 994 | |
| 995 | |
| 996 | content: (size <= max_bytes).then(|| content.clone()), |
| 997 | } |
| 998 | })) |
| 999 | } |
| 1000 | |
| 1001 | async fn log( |
| 1002 | &self, |
| 1003 | _handle: &OrgName, |
| 1004 | _name: &RepoName, |
| 1005 | _rev: &RefName, |
| 1006 | limit: usize, |
| 1007 | ) -> Result<Vec<CommitSummary>, GitQueryError> { |
| 1008 | Ok(self.commits.iter().take(limit).cloned().collect()) |
| 1009 | } |
| 1010 | |
| 1011 | async fn list_refs( |
| 1012 | &self, |
| 1013 | _handle: &OrgName, |
| 1014 | _name: &RepoName, |
| 1015 | ) -> Result<Vec<GitRef>, GitQueryError> { |
| 1016 | Ok(self.refs.clone()) |
| 1017 | } |
| 1018 | |
| 1019 | async fn count_commits( |
| 1020 | &self, |
| 1021 | _handle: &OrgName, |
| 1022 | _name: &RepoName, |
| 1023 | _rev: &RefName, |
| 1024 | ) -> Result<u64, GitQueryError> { |
| 1025 | Ok(self.commit_count.unwrap_or(self.commits.len() as u64)) |
| 1026 | } |
| 1027 | |
| 1028 | async fn latest_tag( |
| 1029 | &self, |
| 1030 | _handle: &OrgName, |
| 1031 | _name: &RepoName, |
| 1032 | ) -> Result<Option<TagSummary>, GitQueryError> { |
| 1033 | Ok(self.latest_tag.clone()) |
| 1034 | } |
| 1035 | |
| 1036 | async fn branches( |
| 1037 | &self, |
| 1038 | _handle: &OrgName, |
| 1039 | _name: &RepoName, |
| 1040 | ) -> Result<Vec<BranchRow>, GitQueryError> { |
| 1041 | Ok(self.branch_rows.clone()) |
| 1042 | } |
| 1043 | |
| 1044 | async fn tags( |
| 1045 | &self, |
| 1046 | _handle: &OrgName, |
| 1047 | _name: &RepoName, |
| 1048 | ) -> Result<Vec<TagRow>, GitQueryError> { |
| 1049 | Ok(self.tag_rows.clone()) |
| 1050 | } |
| 1051 | |
| 1052 | async fn grep( |
| 1053 | &self, |
| 1054 | _handle: &OrgName, |
| 1055 | _name: &RepoName, |
| 1056 | _commit: &ObjectId, |
| 1057 | _query: &str, |
| 1058 | limit: usize, |
| 1059 | ) -> Result<Vec<GrepHit>, GitQueryError> { |
| 1060 | if self.slow_grep { |
| 1061 | return Err(GitQueryError::timed_out(std::time::Duration::from_secs(20))); |
| 1062 | } |
| 1063 | |
| 1064 | Ok(self.grep_hits.iter().take(limit).cloned().collect()) |
| 1065 | } |
| 1066 | |
| 1067 | async fn commit( |
| 1068 | &self, |
| 1069 | _handle: &OrgName, |
| 1070 | _name: &RepoName, |
| 1071 | _rev: &RefName, |
| 1072 | ) -> Result<Option<CommitDetail>, GitQueryError> { |
| 1073 | Ok(self.detail.clone()) |
| 1074 | } |
| 1075 | |
| 1076 | async fn diff( |
| 1077 | &self, |
| 1078 | _handle: &OrgName, |
| 1079 | _name: &RepoName, |
| 1080 | _base: Option<&ObjectId>, |
| 1081 | _head: &ObjectId, |
| 1082 | _max_bytes: u64, |
| 1083 | ) -> Result<RawDiff, GitQueryError> { |
| 1084 | Ok(self.diff.clone().unwrap_or_default()) |
| 1085 | } |
| 1086 | |
| 1087 | async fn merge_base( |
| 1088 | &self, |
| 1089 | _handle: &OrgName, |
| 1090 | _name: &RepoName, |
| 1091 | _base: &ObjectId, |
| 1092 | _head: &ObjectId, |
| 1093 | ) -> Result<Option<ObjectId>, GitQueryError> { |
| 1094 | Ok(self.merge_base.clone()) |
| 1095 | } |
| 1096 | |
| 1097 | async fn log_between( |
| 1098 | &self, |
| 1099 | _handle: &OrgName, |
| 1100 | _name: &RepoName, |
| 1101 | _base: Option<&ObjectId>, |
| 1102 | _head: &ObjectId, |
| 1103 | limit: usize, |
| 1104 | ) -> Result<Vec<CommitSummary>, GitQueryError> { |
| 1105 | Ok(self.commits.iter().take(limit).cloned().collect()) |
| 1106 | } |
| 1107 | |
| 1108 | async fn blame( |
| 1109 | &self, |
| 1110 | _handle: &OrgName, |
| 1111 | _name: &RepoName, |
| 1112 | rev: &RefName, |
| 1113 | path: &RepoPath, |
| 1114 | ) -> Result<Option<Blame>, GitQueryError> { |
| 1115 | Ok(self.blames.get(&Self::key(rev, path)).cloned()) |
| 1116 | } |
| 1117 | |
| 1118 | async fn ref_snapshot( |
| 1119 | &self, |
| 1120 | _handle: &OrgName, |
| 1121 | _name: &RepoName, |
| 1122 | ) -> Result<Vec<(RefName, ObjectId)>, GitQueryError> { |
| 1123 | Ok(self.snapshot.lock().expect("lock poisoned").clone()) |
| 1124 | } |
| 1125 | } |
| 1126 | |
| 1127 | |
| 1128 | |
| 1129 | |
| 1130 | |
| 1131 | |
| 1132 | |
| 1133 | |
| 1134 | |
| 1135 | |
| 1136 | const IMPORT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600); |
| 1137 | |
| 1138 | |
| 1139 | |
| 1140 | const HTTPS_PORT: u16 = 443; |
| 1141 | |
| 1142 | |
| 1143 | |
| 1144 | |
| 1145 | |
| 1146 | |
| 1147 | |
| 1148 | |
| 1149 | #[derive(Debug, Clone)] |
| 1150 | pub struct DiskGitImport { |
| 1151 | data_dir: PathBuf, |
| 1152 | } |
| 1153 | |
| 1154 | impl DiskGitImport { |
| 1155 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 1156 | Self { |
| 1157 | data_dir: data_dir.into(), |
| 1158 | } |
| 1159 | } |
| 1160 | |
| 1161 | |
| 1162 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 1163 | self.data_dir |
| 1164 | .join(handle.as_str()) |
| 1165 | .join(format!("{name}.git")) |
| 1166 | } |
| 1167 | } |
| 1168 | |
| 1169 | impl GitImport for DiskGitImport { |
| 1170 | async fn mirror( |
| 1171 | &self, |
| 1172 | handle: &OrgName, |
| 1173 | name: &RepoName, |
| 1174 | source: &ImportSource, |
| 1175 | ) -> Result<(), GitImportError> { |
| 1176 | resolve_public_host(source.host()).await?; |
| 1177 | |
| 1178 | let path = self.repo_path(handle, name); |
| 1179 | |
| 1180 | |
| 1181 | |
| 1182 | |
| 1183 | if path.exists() { |
| 1184 | return Err(GitImportError::new( |
| 1185 | "something is already on disk at this repository's path", |
| 1186 | )); |
| 1187 | } |
| 1188 | |
| 1189 | |
| 1190 | |
| 1191 | |
| 1192 | |
| 1193 | run_import( |
| 1194 | [ |
| 1195 | OsStr::new("clone"), |
| 1196 | OsStr::new("--mirror"), |
| 1197 | OsStr::new("--quiet"), |
| 1198 | |
| 1199 | |
| 1200 | |
| 1201 | |
| 1202 | OsStr::new("--"), |
| 1203 | OsStr::new(source.as_str()), |
| 1204 | path.as_os_str(), |
| 1205 | ], |
| 1206 | None, |
| 1207 | ) |
| 1208 | .await?; |
| 1209 | |
| 1210 | finish_mirror(&path).await |
| 1211 | } |
| 1212 | } |
| 1213 | |
| 1214 | |
| 1215 | |
| 1216 | |
| 1217 | |
| 1218 | |
| 1219 | async fn finish_mirror(path: &std::path::Path) -> Result<(), GitImportError> { |
| 1220 | |
| 1221 | |
| 1222 | |
| 1223 | |
| 1224 | run_import( |
| 1225 | [ |
| 1226 | OsStr::new("remote"), |
| 1227 | OsStr::new("remove"), |
| 1228 | OsStr::new("origin"), |
| 1229 | ], |
| 1230 | Some(path), |
| 1231 | ) |
| 1232 | .await?; |
| 1233 | |
| 1234 | |
| 1235 | |
| 1236 | |
| 1237 | |
| 1238 | promote_remote_refs(path).await |
| 1239 | } |
| 1240 | |
| 1241 | |
| 1242 | |
| 1243 | |
| 1244 | |
| 1245 | |
| 1246 | |
| 1247 | |
| 1248 | |
| 1249 | |
| 1250 | async fn promote_remote_refs(path: &std::path::Path) -> Result<(), GitImportError> { |
| 1251 | let listed = run_import( |
| 1252 | [ |
| 1253 | OsStr::new("for-each-ref"), |
| 1254 | OsStr::new("--format=%(objectname) %(refname)"), |
| 1255 | OsStr::new("refs/remotes/"), |
| 1256 | ], |
| 1257 | Some(path), |
| 1258 | ) |
| 1259 | .await?; |
| 1260 | |
| 1261 | let listed = String::from_utf8_lossy(&listed.stdout); |
| 1262 | |
| 1263 | for line in listed.lines() { |
| 1264 | let Some((id, reference)) = line.trim().split_once(' ') else { |
| 1265 | continue; |
| 1266 | }; |
| 1267 | |
| 1268 | |
| 1269 | |
| 1270 | |
| 1271 | if let Some(branch) = reference |
| 1272 | .strip_prefix("refs/remotes/origin/") |
| 1273 | .filter(|branch| *branch != "HEAD") |
| 1274 | { |
| 1275 | run_import( |
| 1276 | [ |
| 1277 | OsStr::new("update-ref"), |
| 1278 | OsStr::new(&format!("refs/heads/{branch}")), |
| 1279 | OsStr::new(id), |
| 1280 | ], |
| 1281 | Some(path), |
| 1282 | ) |
| 1283 | .await?; |
| 1284 | } |
| 1285 | |
| 1286 | run_import( |
| 1287 | [ |
| 1288 | OsStr::new("update-ref"), |
| 1289 | OsStr::new("-d"), |
| 1290 | OsStr::new(reference), |
| 1291 | ], |
| 1292 | Some(path), |
| 1293 | ) |
| 1294 | .await?; |
| 1295 | } |
| 1296 | |
| 1297 | Ok(()) |
| 1298 | } |
| 1299 | |
| 1300 | |
| 1301 | |
| 1302 | |
| 1303 | |
| 1304 | |
| 1305 | |
| 1306 | |
| 1307 | |
| 1308 | |
| 1309 | |
| 1310 | |
| 1311 | |
| 1312 | async fn resolve_public_host(host: &str) -> Result<(), GitImportError> { |
| 1313 | let refused = || { |
| 1314 | GitImportError::new(format!( |
| 1315 | "{host} resolves to an address that is not on the public internet" |
| 1316 | )) |
| 1317 | }; |
| 1318 | |
| 1319 | let addresses = tokio::net::lookup_host((host, HTTPS_PORT)) |
| 1320 | .await |
| 1321 | .map_err(|error| GitImportError::new(format!("could not resolve {host}: {error}")))?; |
| 1322 | |
| 1323 | let mut any = false; |
| 1324 | |
| 1325 | for address in addresses { |
| 1326 | any = true; |
| 1327 | |
| 1328 | if !is_public(address.ip()) { |
| 1329 | return Err(refused()); |
| 1330 | } |
| 1331 | } |
| 1332 | |
| 1333 | if !any { |
| 1334 | return Err(GitImportError::new(format!("{host} resolves to nothing"))); |
| 1335 | } |
| 1336 | |
| 1337 | Ok(()) |
| 1338 | } |
| 1339 | |
| 1340 | |
| 1341 | |
| 1342 | |
| 1343 | |
| 1344 | |
| 1345 | |
| 1346 | async fn run_import<I, S>(args: I, repo: Option<&std::path::Path>) -> Result<Output, GitImportError> |
| 1347 | where |
| 1348 | I: IntoIterator<Item = S>, |
| 1349 | S: AsRef<OsStr>, |
| 1350 | { |
| 1351 | let mut command = git_command(); |
| 1352 | |
| 1353 | if let Some(repo) = repo { |
| 1354 | command.arg("-C").arg(repo); |
| 1355 | } |
| 1356 | |
| 1357 | command |
| 1358 | .args(args) |
| 1359 | .stdin(Stdio::null()) |
| 1360 | |
| 1361 | |
| 1362 | |
| 1363 | .env("GIT_TERMINAL_PROMPT", "0") |
| 1364 | |
| 1365 | |
| 1366 | .kill_on_drop(true); |
| 1367 | |
| 1368 | let output = match tokio::time::timeout(IMPORT_TIMEOUT, command.output()).await { |
| 1369 | Ok(result) => { |
| 1370 | result.map_err(|error| GitImportError::new(format!("could not run git: {error}")))? |
| 1371 | } |
| 1372 | Err(_elapsed) => { |
| 1373 | return Err(GitImportError::new(format!( |
| 1374 | "the import did not finish within {IMPORT_TIMEOUT:?}" |
| 1375 | ))); |
| 1376 | } |
| 1377 | }; |
| 1378 | |
| 1379 | if !output.status.success() { |
| 1380 | |
| 1381 | |
| 1382 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 1383 | let reason = stderr.lines().rev().find(|line| !line.trim().is_empty()); |
| 1384 | |
| 1385 | return Err(GitImportError::new(match reason { |
| 1386 | Some(reason) => reason.trim().to_owned(), |
| 1387 | None => format!("git exited with {}", output.status), |
| 1388 | })); |
| 1389 | } |
| 1390 | |
| 1391 | Ok(output) |
| 1392 | } |
| 1393 | |
| 1394 | |
| 1395 | |
| 1396 | |
| 1397 | |
| 1398 | |
| 1399 | #[derive(Debug, Default, Clone)] |
| 1400 | pub struct InMemoryGitImport { |
| 1401 | requests: Arc<Mutex<Vec<(String, String, String)>>>, |
| 1402 | failure: Option<String>, |
| 1403 | } |
| 1404 | |
| 1405 | impl InMemoryGitImport { |
| 1406 | pub fn new() -> Self { |
| 1407 | Self::default() |
| 1408 | } |
| 1409 | |
| 1410 | |
| 1411 | pub fn failing(reason: impl Into<String>) -> Self { |
| 1412 | Self { |
| 1413 | requests: Arc::default(), |
| 1414 | failure: Some(reason.into()), |
| 1415 | } |
| 1416 | } |
| 1417 | |
| 1418 | |
| 1419 | pub fn requests(&self) -> Vec<(String, String, String)> { |
| 1420 | self.requests.lock().expect("lock poisoned").clone() |
| 1421 | } |
| 1422 | } |
| 1423 | |
| 1424 | impl GitImport for InMemoryGitImport { |
| 1425 | async fn mirror( |
| 1426 | &self, |
| 1427 | handle: &OrgName, |
| 1428 | name: &RepoName, |
| 1429 | source: &ImportSource, |
| 1430 | ) -> Result<(), GitImportError> { |
| 1431 | self.requests.lock().expect("lock poisoned").push(( |
| 1432 | handle.to_string(), |
| 1433 | name.to_string(), |
| 1434 | source.as_str().to_owned(), |
| 1435 | )); |
| 1436 | |
| 1437 | match &self.failure { |
| 1438 | Some(reason) => Err(GitImportError::new(reason.clone())), |
| 1439 | None => Ok(()), |
| 1440 | } |
| 1441 | } |
| 1442 | } |
| 1443 | |
| 1444 | #[cfg(test)] |
| 1445 | mod tests { |
| 1446 | use std::path::Path; |
| 1447 | |
| 1448 | use tempfile::TempDir; |
| 1449 | |
| 1450 | use tokio::io::AsyncReadExt; |
| 1451 | |
| 1452 | use super::*; |
| 1453 | use crate::application::port::ArchiveFormat; |
| 1454 | |
| 1455 | |
| 1456 | |
| 1457 | fn storage() -> (TempDir, DiskGitStorage) { |
| 1458 | let dir = TempDir::new().expect("temp dir"); |
| 1459 | let storage = DiskGitStorage::new(dir.path()); |
| 1460 | (dir, storage) |
| 1461 | } |
| 1462 | |
| 1463 | fn handle() -> OrgName { |
| 1464 | OrgName::new("jamesgill").expect("valid handle") |
| 1465 | } |
| 1466 | |
| 1467 | fn repo_name(value: &str) -> RepoName { |
| 1468 | RepoName::new(value).expect("valid repository name") |
| 1469 | } |
| 1470 | |
| 1471 | |
| 1472 | |
| 1473 | fn git_says(path: &Path, args: &[&str]) -> String { |
| 1474 | let output = std::process::Command::new("git") |
| 1475 | .arg("-C") |
| 1476 | .arg(path) |
| 1477 | .args(args) |
| 1478 | .output() |
| 1479 | .expect("git should be on PATH"); |
| 1480 | |
| 1481 | assert!( |
| 1482 | output.status.success(), |
| 1483 | "git {args:?} failed: {}", |
| 1484 | String::from_utf8_lossy(&output.stderr) |
| 1485 | ); |
| 1486 | |
| 1487 | String::from_utf8_lossy(&output.stdout).trim().to_owned() |
| 1488 | } |
| 1489 | |
| 1490 | |
| 1491 | |
| 1492 | |
| 1493 | |
| 1494 | fn source_repo() -> (TempDir, PathBuf) { |
| 1495 | let dir = TempDir::new().expect("temp dir"); |
| 1496 | let path = dir.path().join("source"); |
| 1497 | |
| 1498 | std::fs::create_dir(&path).expect("create"); |
| 1499 | |
| 1500 | let run = |args: &[&str]| { |
| 1501 | let output = std::process::Command::new("git") |
| 1502 | .arg("-C") |
| 1503 | .arg(&path) |
| 1504 | .args(args) |
| 1505 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 1506 | .env("GIT_CONFIG_SYSTEM", "/dev/null") |
| 1507 | .env("GIT_AUTHOR_NAME", "Ada") |
| 1508 | .env("GIT_AUTHOR_EMAIL", "ada@example.com") |
| 1509 | .env("GIT_COMMITTER_NAME", "Ada") |
| 1510 | .env("GIT_COMMITTER_EMAIL", "ada@example.com") |
| 1511 | .output() |
| 1512 | .expect("git should be on PATH"); |
| 1513 | assert!( |
| 1514 | output.status.success(), |
| 1515 | "git {args:?} failed: {}", |
| 1516 | String::from_utf8_lossy(&output.stderr) |
| 1517 | ); |
| 1518 | }; |
| 1519 | |
| 1520 | run(&["init", "--quiet", "--initial-branch=main"]); |
| 1521 | std::fs::write(path.join("README.md"), "# source\n").expect("write"); |
| 1522 | run(&["add", "README.md"]); |
| 1523 | run(&["commit", "--quiet", "-m", "first"]); |
| 1524 | run(&["tag", "-a", "v0.1.0", "-m", "first"]); |
| 1525 | run(&["checkout", "--quiet", "-b", "side"]); |
| 1526 | std::fs::write(path.join("more.md"), "more\n").expect("write"); |
| 1527 | run(&["add", "more.md"]); |
| 1528 | run(&["commit", "--quiet", "-m", "second"]); |
| 1529 | run(&["checkout", "--quiet", "main"]); |
| 1530 | |
| 1531 | (dir, path) |
| 1532 | } |
| 1533 | |
| 1534 | |
| 1535 | |
| 1536 | |
| 1537 | |
| 1538 | |
| 1539 | |
| 1540 | #[tokio::test] |
| 1541 | async fn a_mirror_lands_as_an_ordinary_bare_repository() { |
| 1542 | let (_source_dir, source) = source_repo(); |
| 1543 | let (dest_dir, _storage) = storage(); |
| 1544 | let destination = dest_dir.path().join("mirrored.git"); |
| 1545 | |
| 1546 | run_import( |
| 1547 | [ |
| 1548 | OsStr::new("clone"), |
| 1549 | OsStr::new("--mirror"), |
| 1550 | OsStr::new("--quiet"), |
| 1551 | OsStr::new("--"), |
| 1552 | source.as_os_str(), |
| 1553 | destination.as_os_str(), |
| 1554 | ], |
| 1555 | None, |
| 1556 | ) |
| 1557 | .await |
| 1558 | .expect("the clone should succeed"); |
| 1559 | |
| 1560 | finish_mirror(&destination) |
| 1561 | .await |
| 1562 | .expect("the mirror should finish"); |
| 1563 | |
| 1564 | |
| 1565 | let branches = git_says( |
| 1566 | &destination, |
| 1567 | &["for-each-ref", "--format=%(refname)", "refs/heads/"], |
| 1568 | ); |
| 1569 | assert_eq!(branches, "refs/heads/main\nrefs/heads/side"); |
| 1570 | |
| 1571 | |
| 1572 | assert_eq!( |
| 1573 | git_says( |
| 1574 | &destination, |
| 1575 | &["for-each-ref", "--format=%(refname)", "refs/tags/"] |
| 1576 | ), |
| 1577 | "refs/tags/v0.1.0" |
| 1578 | ); |
| 1579 | |
| 1580 | |
| 1581 | assert_eq!( |
| 1582 | git_says( |
| 1583 | &destination, |
| 1584 | &["for-each-ref", "--format=%(refname)", "refs/remotes/"] |
| 1585 | ), |
| 1586 | "" |
| 1587 | ); |
| 1588 | assert_eq!(git_says(&destination, &["remote"]), ""); |
| 1589 | |
| 1590 | |
| 1591 | assert_eq!( |
| 1592 | git_says(&destination, &["symbolic-ref", "HEAD"]), |
| 1593 | "refs/heads/main" |
| 1594 | ); |
| 1595 | assert_eq!( |
| 1596 | git_says(&destination, &["rev-parse", "--is-bare-repository"]), |
| 1597 | "true" |
| 1598 | ); |
| 1599 | } |
| 1600 | |
| 1601 | |
| 1602 | |
| 1603 | #[tokio::test] |
| 1604 | async fn branches_left_under_refs_remotes_are_moved_to_refs_heads() { |
| 1605 | let (_source_dir, source) = source_repo(); |
| 1606 | let (dest_dir, _storage) = storage(); |
| 1607 | let destination = dest_dir.path().join("remotes.git"); |
| 1608 | |
| 1609 | |
| 1610 | |
| 1611 | run_import( |
| 1612 | [ |
| 1613 | OsStr::new("clone"), |
| 1614 | OsStr::new("--bare"), |
| 1615 | OsStr::new("--quiet"), |
| 1616 | OsStr::new("--"), |
| 1617 | source.as_os_str(), |
| 1618 | destination.as_os_str(), |
| 1619 | ], |
| 1620 | None, |
| 1621 | ) |
| 1622 | .await |
| 1623 | .expect("clone"); |
| 1624 | |
| 1625 | |
| 1626 | run_import( |
| 1627 | [ |
| 1628 | OsStr::new("update-ref"), |
| 1629 | OsStr::new("refs/remotes/origin/side"), |
| 1630 | OsStr::new("refs/heads/main"), |
| 1631 | ], |
| 1632 | Some(&destination), |
| 1633 | ) |
| 1634 | .await |
| 1635 | .expect("stage a remote-tracking ref"); |
| 1636 | run_import( |
| 1637 | [ |
| 1638 | OsStr::new("symbolic-ref"), |
| 1639 | OsStr::new("refs/remotes/origin/HEAD"), |
| 1640 | OsStr::new("refs/remotes/origin/side"), |
| 1641 | ], |
| 1642 | Some(&destination), |
| 1643 | ) |
| 1644 | .await |
| 1645 | .expect("stage origin/HEAD"); |
| 1646 | |
| 1647 | finish_mirror(&destination).await.expect("finish"); |
| 1648 | |
| 1649 | let branches = git_says( |
| 1650 | &destination, |
| 1651 | &["for-each-ref", "--format=%(refname)", "refs/heads/"], |
| 1652 | ); |
| 1653 | assert!( |
| 1654 | branches.contains("refs/heads/side"), |
| 1655 | "expected the remote-tracking branch to become a branch, got {branches:?}" |
| 1656 | ); |
| 1657 | assert_eq!( |
| 1658 | git_says( |
| 1659 | &destination, |
| 1660 | &["for-each-ref", "--format=%(refname)", "refs/remotes/"] |
| 1661 | ), |
| 1662 | "", |
| 1663 | "origin/HEAD is a pointer, not a branch, and must not survive either" |
| 1664 | ); |
| 1665 | } |
| 1666 | |
| 1667 | |
| 1668 | |
| 1669 | #[tokio::test] |
| 1670 | async fn a_host_that_resolves_to_loopback_is_refused() { |
| 1671 | let error = resolve_public_host("localhost") |
| 1672 | .await |
| 1673 | .expect_err("localhost must never be dialled"); |
| 1674 | |
| 1675 | assert!( |
| 1676 | error.message().contains("not on the public internet"), |
| 1677 | "{error}" |
| 1678 | ); |
| 1679 | } |
| 1680 | |
| 1681 | #[tokio::test] |
| 1682 | async fn a_host_that_does_not_resolve_is_a_failed_import_not_a_panic() { |
| 1683 | let error = resolve_public_host("no-such-host.invalid") |
| 1684 | .await |
| 1685 | .expect_err("`.invalid` never resolves"); |
| 1686 | |
| 1687 | assert!(error.message().contains("no-such-host.invalid"), "{error}"); |
| 1688 | } |
| 1689 | |
| 1690 | |
| 1691 | #[tokio::test] |
| 1692 | async fn a_failed_git_command_carries_gits_own_last_word() { |
| 1693 | let (dir, _storage) = storage(); |
| 1694 | |
| 1695 | let error = run_import( |
| 1696 | [OsStr::new("rev-parse"), OsStr::new("HEAD")], |
| 1697 | Some(dir.path()), |
| 1698 | ) |
| 1699 | .await |
| 1700 | .expect_err("an empty directory is not a repository"); |
| 1701 | |
| 1702 | assert!( |
| 1703 | error.message().contains("not a git repository"), |
| 1704 | "expected git's own words, got {error}" |
| 1705 | ); |
| 1706 | } |
| 1707 | |
| 1708 | #[tokio::test] |
| 1709 | async fn an_import_refuses_a_path_that_is_already_occupied() { |
| 1710 | let (dir, storage) = storage(); |
| 1711 | let importer = DiskGitImport::new(dir.path()); |
| 1712 | |
| 1713 | storage |
| 1714 | .init_bare(&handle(), &repo_name("taken")) |
| 1715 | .await |
| 1716 | .expect("seed"); |
| 1717 | |
| 1718 | let error = importer |
| 1719 | .mirror( |
| 1720 | &handle(), |
| 1721 | &repo_name("taken"), |
| 1722 | &ImportSource::new("https://example.com/taken.git").expect("valid"), |
| 1723 | ) |
| 1724 | .await |
| 1725 | .expect_err("must not adopt what is already there"); |
| 1726 | |
| 1727 | assert!(error.message().contains("already on disk"), "{error}"); |
| 1728 | } |
| 1729 | |
| 1730 | #[tokio::test] |
| 1731 | async fn the_in_memory_importer_records_what_it_was_asked_for() { |
| 1732 | let importer = InMemoryGitImport::new(); |
| 1733 | let source = ImportSource::new("https://example.com/thing.git").expect("valid"); |
| 1734 | |
| 1735 | importer |
| 1736 | .mirror(&handle(), &repo_name("thing"), &source) |
| 1737 | .await |
| 1738 | .expect("succeeds"); |
| 1739 | |
| 1740 | assert_eq!( |
| 1741 | importer.requests(), |
| 1742 | vec![( |
| 1743 | "jamesgill".to_owned(), |
| 1744 | "thing".to_owned(), |
| 1745 | "https://example.com/thing.git".to_owned() |
| 1746 | )] |
| 1747 | ); |
| 1748 | } |
| 1749 | |
| 1750 | #[tokio::test] |
| 1751 | async fn a_created_repository_keeps_a_reflog() { |
| 1752 | |
| 1753 | |
| 1754 | let dir = TempDir::new().expect("temp dir"); |
| 1755 | let storage = DiskGitStorage::new(dir.path()); |
| 1756 | |
| 1757 | storage |
| 1758 | .init_bare(&handle(), &repo_name("steid")) |
| 1759 | .await |
| 1760 | .expect("should create"); |
| 1761 | |
| 1762 | let config = std::fs::read_to_string( |
| 1763 | storage |
| 1764 | .repo_path(&handle(), &repo_name("steid")) |
| 1765 | .join("config"), |
| 1766 | ) |
| 1767 | .expect("read config"); |
| 1768 | |
| 1769 | assert!( |
| 1770 | config.to_lowercase().contains("logallrefupdates = true"), |
| 1771 | "a bare repository needs reflogs turned on: {config}" |
| 1772 | ); |
| 1773 | } |
| 1774 | |
| 1775 | #[tokio::test] |
| 1776 | async fn init_bare_creates_a_bare_repository() { |
| 1777 | let (_dir, storage) = storage(); |
| 1778 | |
| 1779 | storage |
| 1780 | .init_bare(&handle(), &repo_name("steid")) |
| 1781 | .await |
| 1782 | .expect("should create"); |
| 1783 | |
| 1784 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 1785 | assert!(path.is_dir(), "expected a repository at {path:?}"); |
| 1786 | assert_eq!( |
| 1787 | git_says(&path, &["rev-parse", "--is-bare-repository"]), |
| 1788 | "true" |
| 1789 | ); |
| 1790 | } |
| 1791 | |
| 1792 | #[tokio::test] |
| 1793 | async fn a_new_repository_is_empty() { |
| 1794 | |
| 1795 | let (_dir, storage) = storage(); |
| 1796 | storage |
| 1797 | .init_bare(&handle(), &repo_name("steid")) |
| 1798 | .await |
| 1799 | .expect("should create"); |
| 1800 | |
| 1801 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 1802 | |
| 1803 | assert_eq!(git_says(&path, &["for-each-ref"]), ""); |
| 1804 | } |
| 1805 | |
| 1806 | #[tokio::test] |
| 1807 | async fn a_new_repository_defaults_to_main() { |
| 1808 | |
| 1809 | |
| 1810 | let (_dir, storage) = storage(); |
| 1811 | storage |
| 1812 | .init_bare(&handle(), &repo_name("steid")) |
| 1813 | .await |
| 1814 | .expect("should create"); |
| 1815 | |
| 1816 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 1817 | |
| 1818 | assert_eq!( |
| 1819 | git_says(&path, &["symbolic-ref", "HEAD"]), |
| 1820 | "refs/heads/main" |
| 1821 | ); |
| 1822 | } |
| 1823 | |
| 1824 | #[tokio::test] |
| 1825 | async fn no_sample_hooks_are_installed() { |
| 1826 | |
| 1827 | let (_dir, storage) = storage(); |
| 1828 | storage |
| 1829 | .init_bare(&handle(), &repo_name("steid")) |
| 1830 | .await |
| 1831 | .expect("should create"); |
| 1832 | |
| 1833 | let hooks = storage |
| 1834 | .repo_path(&handle(), &repo_name("steid")) |
| 1835 | .join("hooks"); |
| 1836 | |
| 1837 | let samples = std::fs::read_dir(&hooks) |
| 1838 | .map(|entries| entries.count()) |
| 1839 | .unwrap_or(0); |
| 1840 | assert_eq!(samples, 0, "expected no templated hooks in {hooks:?}"); |
| 1841 | } |
| 1842 | |
| 1843 | #[tokio::test] |
| 1844 | async fn init_bare_creates_the_handle_directory() { |
| 1845 | let (dir, storage) = storage(); |
| 1846 | assert!(!dir.path().join("jamesgill").exists()); |
| 1847 | |
| 1848 | storage |
| 1849 | .init_bare(&handle(), &repo_name("steid")) |
| 1850 | .await |
| 1851 | .expect("should create"); |
| 1852 | |
| 1853 | assert!(dir.path().join("jamesgill").is_dir()); |
| 1854 | } |
| 1855 | |
| 1856 | #[tokio::test] |
| 1857 | async fn one_handle_can_own_several_repositories() { |
| 1858 | let (_dir, storage) = storage(); |
| 1859 | |
| 1860 | for name in ["steid", "foo.js", ".github"] { |
| 1861 | storage |
| 1862 | .init_bare(&handle(), &repo_name(name)) |
| 1863 | .await |
| 1864 | .unwrap_or_else(|error| panic!("{name} should create: {error}")); |
| 1865 | } |
| 1866 | |
| 1867 | for name in ["steid", "foo.js", ".github"] { |
| 1868 | assert!(storage.repo_path(&handle(), &repo_name(name)).is_dir()); |
| 1869 | } |
| 1870 | } |
| 1871 | |
| 1872 | #[tokio::test] |
| 1873 | async fn init_bare_refuses_a_repository_that_already_exists() { |
| 1874 | let (_dir, storage) = storage(); |
| 1875 | storage |
| 1876 | .init_bare(&handle(), &repo_name("steid")) |
| 1877 | .await |
| 1878 | .expect("should create"); |
| 1879 | |
| 1880 | let error = storage |
| 1881 | .init_bare(&handle(), &repo_name("steid")) |
| 1882 | .await |
| 1883 | .expect_err("should refuse"); |
| 1884 | |
| 1885 | assert!(matches!(error, GitStorageError::AlreadyExists)); |
| 1886 | } |
| 1887 | |
| 1888 | #[tokio::test] |
| 1889 | async fn a_refused_init_leaves_the_existing_repository_alone() { |
| 1890 | |
| 1891 | |
| 1892 | let (_dir, storage) = storage(); |
| 1893 | storage |
| 1894 | .init_bare(&handle(), &repo_name("steid")) |
| 1895 | .await |
| 1896 | .expect("should create"); |
| 1897 | |
| 1898 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 1899 | let marker = path.join("objects").join("marker"); |
| 1900 | std::fs::write(&marker, b"existing data").expect("write marker"); |
| 1901 | |
| 1902 | let _ = storage.init_bare(&handle(), &repo_name("steid")).await; |
| 1903 | |
| 1904 | assert_eq!( |
| 1905 | std::fs::read(&marker).expect("marker should survive"), |
| 1906 | b"existing data" |
| 1907 | ); |
| 1908 | } |
| 1909 | |
| 1910 | #[tokio::test] |
| 1911 | async fn repo_path_creates_nothing() { |
| 1912 | let (dir, storage) = storage(); |
| 1913 | |
| 1914 | let path = storage.repo_path(&handle(), &repo_name("never-created")); |
| 1915 | |
| 1916 | assert!(!path.exists()); |
| 1917 | assert_eq!( |
| 1918 | std::fs::read_dir(dir.path()) |
| 1919 | .expect("data dir should exist") |
| 1920 | .count(), |
| 1921 | 0, |
| 1922 | "repo_path must be pure" |
| 1923 | ); |
| 1924 | } |
| 1925 | |
| 1926 | #[tokio::test] |
| 1927 | async fn repo_path_lands_under_the_data_directory() { |
| 1928 | let (dir, storage) = storage(); |
| 1929 | |
| 1930 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 1931 | |
| 1932 | assert_eq!(path, dir.path().join("jamesgill").join("steid.git")); |
| 1933 | } |
| 1934 | |
| 1935 | #[tokio::test] |
| 1936 | async fn remove_deletes_the_repository() { |
| 1937 | let (_dir, storage) = storage(); |
| 1938 | storage |
| 1939 | .init_bare(&handle(), &repo_name("steid")) |
| 1940 | .await |
| 1941 | .expect("should create"); |
| 1942 | |
| 1943 | storage |
| 1944 | .remove(&handle(), &repo_name("steid")) |
| 1945 | .await |
| 1946 | .expect("should remove"); |
| 1947 | |
| 1948 | assert!(!storage.repo_path(&handle(), &repo_name("steid")).exists()); |
| 1949 | } |
| 1950 | |
| 1951 | #[tokio::test] |
| 1952 | async fn removing_what_is_not_there_succeeds() { |
| 1953 | |
| 1954 | let (_dir, storage) = storage(); |
| 1955 | |
| 1956 | storage |
| 1957 | .remove(&handle(), &repo_name("never-created")) |
| 1958 | .await |
| 1959 | .expect("should succeed with nothing to do"); |
| 1960 | } |
| 1961 | |
| 1962 | #[tokio::test] |
| 1963 | async fn a_compensated_create_can_be_retried() { |
| 1964 | |
| 1965 | let (_dir, storage) = storage(); |
| 1966 | |
| 1967 | storage |
| 1968 | .init_bare(&handle(), &repo_name("steid")) |
| 1969 | .await |
| 1970 | .expect("should create"); |
| 1971 | storage |
| 1972 | .remove(&handle(), &repo_name("steid")) |
| 1973 | .await |
| 1974 | .expect("should remove"); |
| 1975 | storage |
| 1976 | .init_bare(&handle(), &repo_name("steid")) |
| 1977 | .await |
| 1978 | .expect("should create again"); |
| 1979 | } |
| 1980 | |
| 1981 | #[tokio::test] |
| 1982 | async fn removing_one_repository_leaves_its_neighbours() { |
| 1983 | let (_dir, storage) = storage(); |
| 1984 | storage |
| 1985 | .init_bare(&handle(), &repo_name("steid")) |
| 1986 | .await |
| 1987 | .expect("should create"); |
| 1988 | storage |
| 1989 | .init_bare(&handle(), &repo_name("keeper")) |
| 1990 | .await |
| 1991 | .expect("should create"); |
| 1992 | |
| 1993 | storage |
| 1994 | .remove(&handle(), &repo_name("steid")) |
| 1995 | .await |
| 1996 | .expect("should remove"); |
| 1997 | |
| 1998 | assert!(storage.repo_path(&handle(), &repo_name("keeper")).is_dir()); |
| 1999 | } |
| 2000 | |
| 2001 | #[tokio::test] |
| 2002 | async fn a_failing_git_invocation_carries_gits_own_message() { |
| 2003 | let error = run_git(["not-a-real-subcommand"]) |
| 2004 | .await |
| 2005 | .expect_err("should fail"); |
| 2006 | |
| 2007 | let message = error.to_string(); |
| 2008 | assert!( |
| 2009 | message.contains("not-a-real-subcommand"), |
| 2010 | "expected git's own words, got: {message}" |
| 2011 | ); |
| 2012 | } |
| 2013 | |
| 2014 | |
| 2015 | |
| 2016 | |
| 2017 | async fn backend() -> (TempDir, GitHttpBackend) { |
| 2018 | let dir = TempDir::new().expect("temp dir"); |
| 2019 | let storage = DiskGitStorage::new(dir.path()); |
| 2020 | |
| 2021 | let acme = OrgName::new("acme").expect("valid handle"); |
| 2022 | storage |
| 2023 | .init_bare(&acme, &repo_name("steid")) |
| 2024 | .await |
| 2025 | .expect("init bare"); |
| 2026 | |
| 2027 | let backend = GitHttpBackend::new(dir.path()); |
| 2028 | (dir, backend) |
| 2029 | } |
| 2030 | |
| 2031 | fn advertisement(path_info: &str) -> GitRequest { |
| 2032 | GitRequest { |
| 2033 | method: GitMethod::Get, |
| 2034 | path_info: path_info.to_owned(), |
| 2035 | query: "service=git-upload-pack".to_owned(), |
| 2036 | content_type: None, |
| 2037 | content_encoding: None, |
| 2038 | content_length: None, |
| 2039 | git_protocol: None, |
| 2040 | allow_receive_pack: false, |
| 2041 | remote_user: None, |
| 2042 | body: Box::pin(tokio::io::empty()), |
| 2043 | } |
| 2044 | } |
| 2045 | |
| 2046 | async fn drain(response: GitResponse) -> Vec<u8> { |
| 2047 | let mut body = response.body; |
| 2048 | let mut bytes = Vec::new(); |
| 2049 | body.read_to_end(&mut bytes).await.expect("read body"); |
| 2050 | bytes |
| 2051 | } |
| 2052 | |
| 2053 | #[tokio::test] |
| 2054 | async fn the_backend_advertises_refs() { |
| 2055 | let (_dir, backend) = backend().await; |
| 2056 | |
| 2057 | let response = backend |
| 2058 | .serve(advertisement("/acme/steid.git/info/refs")) |
| 2059 | .await |
| 2060 | .expect("should serve"); |
| 2061 | |
| 2062 | assert_eq!(response.status, 200); |
| 2063 | assert!( |
| 2064 | response |
| 2065 | .headers |
| 2066 | .iter() |
| 2067 | .any(|(name, value)| name == "Content-Type" |
| 2068 | && value == "application/x-git-upload-pack-advertisement"), |
| 2069 | "git sets its own content type and we forward it: {:?}", |
| 2070 | response.headers |
| 2071 | ); |
| 2072 | |
| 2073 | |
| 2074 | |
| 2075 | let body = drain(response).await; |
| 2076 | assert!( |
| 2077 | body.starts_with(b"001e# service=git-upload-pack\n"), |
| 2078 | "unexpected advertisement: {:?}", |
| 2079 | String::from_utf8_lossy(&body[..body.len().min(40)]) |
| 2080 | ); |
| 2081 | } |
| 2082 | |
| 2083 | #[tokio::test] |
| 2084 | async fn a_missing_repository_is_reported_as_404_not_as_a_failure() { |
| 2085 | |
| 2086 | |
| 2087 | let (_dir, backend) = backend().await; |
| 2088 | |
| 2089 | let response = backend |
| 2090 | .serve(advertisement("/acme/nothing-here.git/info/refs")) |
| 2091 | .await |
| 2092 | .expect("serving should not itself fail"); |
| 2093 | |
| 2094 | assert_eq!(response.status, 404); |
| 2095 | } |
| 2096 | |
| 2097 | #[tokio::test] |
| 2098 | async fn the_status_header_is_translated_rather_than_forwarded() { |
| 2099 | let (_dir, backend) = backend().await; |
| 2100 | |
| 2101 | let response = backend |
| 2102 | .serve(advertisement("/acme/nothing-here.git/info/refs")) |
| 2103 | .await |
| 2104 | .expect("should serve"); |
| 2105 | |
| 2106 | assert!( |
| 2107 | !response |
| 2108 | .headers |
| 2109 | .iter() |
| 2110 | .any(|(name, _)| name.eq_ignore_ascii_case("status")), |
| 2111 | "Status: is CGI's, and means nothing to an HTTP client: {:?}", |
| 2112 | response.headers |
| 2113 | ); |
| 2114 | } |
| 2115 | |
| 2116 | #[tokio::test] |
| 2117 | async fn the_protocol_version_reaches_upload_pack() { |
| 2118 | |
| 2119 | |
| 2120 | |
| 2121 | let (_dir, backend) = backend().await; |
| 2122 | |
| 2123 | let mut request = advertisement("/acme/steid.git/info/refs"); |
| 2124 | request.git_protocol = Some("version=2".to_owned()); |
| 2125 | |
| 2126 | let body = drain(backend.serve(request).await.expect("should serve")).await; |
| 2127 | |
| 2128 | assert!( |
| 2129 | String::from_utf8_lossy(&body).contains("version 2"), |
| 2130 | "expected a v2 capability advertisement: {:?}", |
| 2131 | String::from_utf8_lossy(&body[..body.len().min(80)]) |
| 2132 | ); |
| 2133 | } |
| 2134 | |
| 2135 | #[tokio::test] |
| 2136 | async fn the_in_memory_protocol_records_what_it_was_asked() { |
| 2137 | let protocol = InMemoryGitProtocol::new(); |
| 2138 | |
| 2139 | protocol |
| 2140 | .serve(advertisement("/acme/steid.git/info/refs")) |
| 2141 | .await |
| 2142 | .expect("should serve"); |
| 2143 | |
| 2144 | assert_eq!( |
| 2145 | protocol.requests(), |
| 2146 | vec![RecordedGitRequest { |
| 2147 | method: GitMethod::Get, |
| 2148 | path_info: "/acme/steid.git/info/refs".to_owned(), |
| 2149 | query: "service=git-upload-pack".to_owned(), |
| 2150 | git_protocol: None, |
| 2151 | content_encoding: None, |
| 2152 | allow_receive_pack: false, |
| 2153 | remote_user: None, |
| 2154 | }] |
| 2155 | ); |
| 2156 | assert!(protocol.was_called()); |
| 2157 | } |
| 2158 | |
| 2159 | |
| 2160 | |
| 2161 | |
| 2162 | |
| 2163 | |
| 2164 | |
| 2165 | fn archivable() -> (TempDir, DiskGitArchive, ObjectId) { |
| 2166 | let dir = TempDir::new().expect("temp dir"); |
| 2167 | let storage = DiskGitStorage::new(dir.path()); |
| 2168 | let repo = storage.repo_path(&handle(), &repo_name("steid")); |
| 2169 | let work = dir.path().join("work"); |
| 2170 | |
| 2171 | let git = |at: &Path, args: &[&str]| { |
| 2172 | let output = std::process::Command::new("git") |
| 2173 | .arg("-C") |
| 2174 | .arg(at) |
| 2175 | .args(args) |
| 2176 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 2177 | .env("GIT_CONFIG_SYSTEM", "/dev/null") |
| 2178 | .env("GIT_AUTHOR_NAME", "Ada Lovelace") |
| 2179 | .env("GIT_AUTHOR_EMAIL", "ada@example.com") |
| 2180 | .env("GIT_COMMITTER_NAME", "Ada Lovelace") |
| 2181 | .env("GIT_COMMITTER_EMAIL", "ada@example.com") |
| 2182 | .output() |
| 2183 | .expect("git should be on PATH"); |
| 2184 | |
| 2185 | assert!( |
| 2186 | output.status.success(), |
| 2187 | "git {args:?} failed: {}", |
| 2188 | String::from_utf8_lossy(&output.stderr) |
| 2189 | ); |
| 2190 | |
| 2191 | String::from_utf8_lossy(&output.stdout).trim().to_owned() |
| 2192 | }; |
| 2193 | |
| 2194 | std::fs::create_dir_all(&work).expect("create work tree"); |
| 2195 | git( |
| 2196 | dir.path(), |
| 2197 | &[ |
| 2198 | "init", |
| 2199 | "--bare", |
| 2200 | "--quiet", |
| 2201 | "--template=", |
| 2202 | "--initial-branch=main", |
| 2203 | "--", |
| 2204 | repo.to_str().expect("utf-8 fixture path"), |
| 2205 | ], |
| 2206 | ); |
| 2207 | git(&work, &["init", "--quiet", "-b", "main"]); |
| 2208 | std::fs::write(work.join("README.md"), b"hello\n").expect("write"); |
| 2209 | git(&work, &["add", "-A"]); |
| 2210 | git(&work, &["commit", "--quiet", "-m", "first"]); |
| 2211 | git( |
| 2212 | &work, |
| 2213 | &["push", "--quiet", repo.to_str().expect("utf-8"), "main"], |
| 2214 | ); |
| 2215 | |
| 2216 | let head = git(&repo, &["rev-parse", "main"]); |
| 2217 | let archives = DiskGitArchive::new(dir.path()); |
| 2218 | |
| 2219 | ( |
| 2220 | dir, |
| 2221 | archives, |
| 2222 | ObjectId::new(head).expect("a real object id"), |
| 2223 | ) |
| 2224 | } |
| 2225 | |
| 2226 | async fn packed(format: ArchiveFormat) -> Vec<u8> { |
| 2227 | let (dir, archives, commit) = archivable(); |
| 2228 | |
| 2229 | let mut stream = archives |
| 2230 | .archive(ArchiveRequest { |
| 2231 | handle: handle(), |
| 2232 | name: repo_name("steid"), |
| 2233 | format, |
| 2234 | commit, |
| 2235 | prefix: "steid-main/".to_owned(), |
| 2236 | }) |
| 2237 | .await |
| 2238 | .expect("should pack"); |
| 2239 | |
| 2240 | let mut bytes = Vec::new(); |
| 2241 | stream.read_to_end(&mut bytes).await.expect("should stream"); |
| 2242 | |
| 2243 | |
| 2244 | |
| 2245 | drop(dir); |
| 2246 | |
| 2247 | bytes |
| 2248 | } |
| 2249 | |
| 2250 | #[tokio::test] |
| 2251 | async fn a_tarball_carries_the_prefix_directory() { |
| 2252 | let bytes = packed(ArchiveFormat::TarGz).await; |
| 2253 | |
| 2254 | |
| 2255 | |
| 2256 | assert_eq!(&bytes[..2], &[0x1f, 0x8b], "expected gzip"); |
| 2257 | assert!(bytes.len() > 100, "expected a real archive"); |
| 2258 | } |
| 2259 | |
| 2260 | #[tokio::test] |
| 2261 | async fn a_zip_is_a_zip() { |
| 2262 | let bytes = packed(ArchiveFormat::Zip).await; |
| 2263 | |
| 2264 | assert_eq!(&bytes[..2], b"PK", "expected a zip"); |
| 2265 | |
| 2266 | |
| 2267 | assert!( |
| 2268 | bytes.windows(11).any(|window| window == b"steid-main/"), |
| 2269 | "expected the prefix directory in the archive" |
| 2270 | ); |
| 2271 | } |
| 2272 | } |