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