| 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, CommitCount, CommitTreeRequest, GitArchive, |
| 28 | GitArchiveError, GitImport, GitImportError, GitMerge, GitMergeError, GitMethod, |
| 29 | GitProtocolError, GitProtocolServer, GitQuery, GitQueryError, GitRequest, GitResponse, |
| 30 | GitStorage, GitStorageError, MergePreview, RawDiff, RepoDir, |
| 31 | }, |
| 32 | }, |
| 33 | domain::{ |
| 34 | BranchRow, CommitDetail, CommitEntry, CommitSummary, EntryCommit, GitRef, GrepHit, |
| 35 | ImportSource, ObjectId, OrgName, RefKind, RefName, RepoName, RepoPath, TagRow, TagSummary, |
| 36 | TreeEntry, is_public, |
| 37 | }, |
| 38 | infrastructure::git_query::FOLLOWED_LOG_SCAN, |
| 39 | }; |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | const MAX_CGI_HEADERS: usize = 64; |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | const REDIRECTING_VARS: &[&str] = &[ |
| 54 | "GIT_ALTERNATE_OBJECT_DIRECTORIES", |
| 55 | "GIT_DIR", |
| 56 | "GIT_INDEX_FILE", |
| 57 | "GIT_OBJECT_DIRECTORY", |
| 58 | "GIT_WORK_TREE", |
| 59 | ]; |
| 60 | |
| 61 | |
| 62 | #[derive(Debug, Clone)] |
| 63 | pub struct DiskGitStorage { |
| 64 | data_dir: PathBuf, |
| 65 | } |
| 66 | |
| 67 | impl DiskGitStorage { |
| 68 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 69 | Self { |
| 70 | data_dir: data_dir.into(), |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | impl GitStorage for DiskGitStorage { |
| 76 | async fn init_bare(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> { |
| 77 | let path = self.repo_path(handle, name); |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | if path.exists() { |
| 84 | return Err(GitStorageError::AlreadyExists); |
| 85 | } |
| 86 | |
| 87 | |
| 88 | run_git([ |
| 89 | OsStr::new("init"), |
| 90 | OsStr::new("--bare"), |
| 91 | OsStr::new("--quiet"), |
| 92 | |
| 93 | |
| 94 | |
| 95 | OsStr::new("--template="), |
| 96 | |
| 97 | |
| 98 | OsStr::new("--initial-branch=main"), |
| 99 | |
| 100 | |
| 101 | OsStr::new("--"), |
| 102 | path.as_os_str(), |
| 103 | ]) |
| 104 | .await?; |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | run_git([ |
| 118 | OsStr::new("--git-dir"), |
| 119 | path.as_os_str(), |
| 120 | OsStr::new("config"), |
| 121 | OsStr::new("core.logAllRefUpdates"), |
| 122 | OsStr::new("true"), |
| 123 | ]) |
| 124 | .await |
| 125 | .map(|_| ()) |
| 126 | } |
| 127 | |
| 128 | async fn remove(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> { |
| 129 | let path = self.repo_path(handle, name); |
| 130 | |
| 131 | |
| 132 | |
| 133 | match tokio::fs::remove_dir_all(&path).await { |
| 134 | Ok(()) => Ok(()), |
| 135 | |
| 136 | Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), |
| 137 | Err(error) => Err(GitStorageError::backend(error)), |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | async fn rename( |
| 142 | &self, |
| 143 | handle: &OrgName, |
| 144 | from: &RepoName, |
| 145 | to: &RepoName, |
| 146 | ) -> Result<(), GitStorageError> { |
| 147 | let source = self.repo_path(handle, from); |
| 148 | let destination = self.repo_path(handle, to); |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | if destination.exists() { |
| 154 | return Err(GitStorageError::AlreadyExists); |
| 155 | } |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | tokio::fs::rename(&source, &destination) |
| 161 | .await |
| 162 | .map_err(GitStorageError::backend) |
| 163 | } |
| 164 | |
| 165 | async fn set_default_branch( |
| 166 | &self, |
| 167 | handle: &OrgName, |
| 168 | name: &RepoName, |
| 169 | branch: &RefName, |
| 170 | ) -> Result<(), GitStorageError> { |
| 171 | let path = self.repo_path(handle, name); |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | run_git([ |
| 178 | OsStr::new("--git-dir"), |
| 179 | path.as_os_str(), |
| 180 | OsStr::new("symbolic-ref"), |
| 181 | OsStr::new("HEAD"), |
| 182 | OsStr::new(&format!("refs/heads/{branch}")), |
| 183 | ]) |
| 184 | .await |
| 185 | .map(|_| ()) |
| 186 | } |
| 187 | |
| 188 | async fn enable_reflogs(&self) -> Result<u64, GitStorageError> { |
| 189 | let mut fixed = 0; |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | let Ok(mut handles) = fs::read_dir(&self.data_dir).await else { |
| 197 | return Ok(0); |
| 198 | }; |
| 199 | |
| 200 | while let Some(handle) = handles.next_entry().await.map_err(|error| { |
| 201 | GitStorageError::backend(format!("could not read data dir: {error}")) |
| 202 | })? { |
| 203 | let Ok(mut repos) = fs::read_dir(handle.path()).await else { |
| 204 | continue; |
| 205 | }; |
| 206 | |
| 207 | while let Some(repo) = repos.next_entry().await.map_err(|error| { |
| 208 | GitStorageError::backend(format!("could not read data dir: {error}")) |
| 209 | })? { |
| 210 | let path = repo.path(); |
| 211 | |
| 212 | if path.extension() != Some(OsStr::new("git")) { |
| 213 | continue; |
| 214 | } |
| 215 | |
| 216 | if enable_reflog(&path).await? { |
| 217 | fixed += 1; |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | Ok(fixed) |
| 223 | } |
| 224 | |
| 225 | async fn list_repo_dirs(&self) -> Result<Vec<RepoDir>, GitStorageError> { |
| 226 | let mut found = Vec::new(); |
| 227 | |
| 228 | |
| 229 | |
| 230 | |
| 231 | let Ok(mut handles) = fs::read_dir(&self.data_dir).await else { |
| 232 | return Ok(found); |
| 233 | }; |
| 234 | |
| 235 | while let Some(handle) = handles.next_entry().await.map_err(|error| { |
| 236 | GitStorageError::backend(format!("could not read data dir: {error}")) |
| 237 | })? { |
| 238 | let handle_path = handle.path(); |
| 239 | |
| 240 | let Some(handle_name) = file_name_of(&handle_path) else { |
| 241 | continue; |
| 242 | }; |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | if handle_name == QUARANTINE { |
| 249 | continue; |
| 250 | } |
| 251 | |
| 252 | let Ok(mut repos) = fs::read_dir(&handle_path).await else { |
| 253 | continue; |
| 254 | }; |
| 255 | |
| 256 | while let Some(repo) = repos.next_entry().await.map_err(|error| { |
| 257 | GitStorageError::backend(format!("could not read data dir: {error}")) |
| 258 | })? { |
| 259 | let path = repo.path(); |
| 260 | |
| 261 | if path.extension() != Some(OsStr::new("git")) { |
| 262 | continue; |
| 263 | } |
| 264 | |
| 265 | let Some(name) = path.file_stem().and_then(OsStr::to_str) else { |
| 266 | continue; |
| 267 | }; |
| 268 | |
| 269 | found.push(RepoDir { |
| 270 | handle: handle_name.to_owned(), |
| 271 | name: name.to_owned(), |
| 272 | path, |
| 273 | }); |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | Ok(found) |
| 278 | } |
| 279 | |
| 280 | async fn quarantine(&self, dir: &RepoDir, label: &str) -> Result<PathBuf, GitStorageError> { |
| 281 | let into = self.data_dir.join(QUARANTINE); |
| 282 | |
| 283 | fs::create_dir_all(&into) |
| 284 | .await |
| 285 | .map_err(GitStorageError::backend)?; |
| 286 | |
| 287 | let destination = into.join(label); |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | if fs::metadata(&destination).await.is_ok() { |
| 293 | return Err(GitStorageError::AlreadyExists); |
| 294 | } |
| 295 | |
| 296 | |
| 297 | |
| 298 | fs::rename(&dir.path, &destination) |
| 299 | .await |
| 300 | .map_err(GitStorageError::backend)?; |
| 301 | |
| 302 | Ok(destination) |
| 303 | } |
| 304 | |
| 305 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 306 | |
| 307 | |
| 308 | |
| 309 | self.data_dir |
| 310 | .join(handle.as_str()) |
| 311 | .join(format!("{name}.git")) |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | const QUARANTINE: &str = "orphaned"; |
| 321 | |
| 322 | |
| 323 | fn file_name_of(path: &Path) -> Option<&str> { |
| 324 | path.file_name().and_then(OsStr::to_str) |
| 325 | } |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | |
| 336 | |
| 337 | async fn enable_reflog(path: &Path) -> Result<bool, GitStorageError> { |
| 338 | let existing = git_command() |
| 339 | .args([ |
| 340 | OsStr::new("--git-dir"), |
| 341 | path.as_os_str(), |
| 342 | OsStr::new("config"), |
| 343 | OsStr::new("--get"), |
| 344 | OsStr::new("core.logAllRefUpdates"), |
| 345 | ]) |
| 346 | .stdin(Stdio::null()) |
| 347 | .output() |
| 348 | .await |
| 349 | .map_err(|error| GitStorageError::backend(format!("could not run git: {error}")))?; |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | match existing.status.code() { |
| 355 | Some(0) => return Ok(false), |
| 356 | Some(1) => {} |
| 357 | _ => { |
| 358 | return Err(GitStorageError::backend(format!( |
| 359 | "git config --get exited with {} in {}: {}", |
| 360 | existing.status, |
| 361 | path.display(), |
| 362 | String::from_utf8_lossy(&existing.stderr).trim() |
| 363 | ))); |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | run_git([ |
| 368 | OsStr::new("--git-dir"), |
| 369 | path.as_os_str(), |
| 370 | OsStr::new("config"), |
| 371 | OsStr::new("core.logAllRefUpdates"), |
| 372 | OsStr::new("true"), |
| 373 | ]) |
| 374 | .await?; |
| 375 | |
| 376 | Ok(true) |
| 377 | } |
| 378 | |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 384 | |
| 385 | pub(crate) fn git_command() -> Command { |
| 386 | let mut command = Command::new("git"); |
| 387 | |
| 388 | |
| 389 | |
| 390 | command |
| 391 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 392 | .env("GIT_CONFIG_SYSTEM", "/dev/null"); |
| 393 | |
| 394 | for variable in REDIRECTING_VARS { |
| 395 | command.env_remove(variable); |
| 396 | } |
| 397 | |
| 398 | command |
| 399 | } |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | async fn run_git<I, S>(args: I) -> Result<Output, GitStorageError> |
| 408 | where |
| 409 | I: IntoIterator<Item = S>, |
| 410 | S: AsRef<OsStr>, |
| 411 | { |
| 412 | let mut command = git_command(); |
| 413 | command.args(args).stdin(Stdio::null()); |
| 414 | |
| 415 | |
| 416 | let output = command |
| 417 | .output() |
| 418 | .await |
| 419 | .map_err(|error| GitStorageError::backend(format!("could not run git: {error}")))?; |
| 420 | |
| 421 | if !output.status.success() { |
| 422 | |
| 423 | |
| 424 | return Err(GitStorageError::backend(format!( |
| 425 | "git exited with {}: {}", |
| 426 | output.status, |
| 427 | String::from_utf8_lossy(&output.stderr).trim() |
| 428 | ))); |
| 429 | } |
| 430 | |
| 431 | Ok(output) |
| 432 | } |
| 433 | |
| 434 | |
| 435 | |
| 436 | |
| 437 | |
| 438 | |
| 439 | #[derive(Debug, Default, Clone)] |
| 440 | pub struct InMemoryGitStorage { |
| 441 | created: Arc<Mutex<HashSet<PathBuf>>>, |
| 442 | |
| 443 | heads: Arc<Mutex<HashMap<PathBuf, RefName>>>, |
| 444 | } |
| 445 | |
| 446 | impl InMemoryGitStorage { |
| 447 | pub fn new() -> Self { |
| 448 | Self::default() |
| 449 | } |
| 450 | |
| 451 | |
| 452 | pub fn contains(&self, handle: &OrgName, name: &RepoName) -> bool { |
| 453 | self.created |
| 454 | .lock() |
| 455 | .expect("lock poisoned") |
| 456 | .contains(&self.repo_path(handle, name)) |
| 457 | } |
| 458 | |
| 459 | |
| 460 | pub fn head(&self, handle: &OrgName, name: &RepoName) -> Option<RefName> { |
| 461 | self.heads |
| 462 | .lock() |
| 463 | .expect("lock poisoned") |
| 464 | .get(&self.repo_path(handle, name)) |
| 465 | .cloned() |
| 466 | } |
| 467 | |
| 468 | |
| 469 | pub fn len(&self) -> usize { |
| 470 | self.created.lock().expect("lock poisoned").len() |
| 471 | } |
| 472 | |
| 473 | pub fn is_empty(&self) -> bool { |
| 474 | self.len() == 0 |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | impl GitStorage for InMemoryGitStorage { |
| 479 | async fn init_bare(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> { |
| 480 | let mut created = self.created.lock().expect("lock poisoned"); |
| 481 | |
| 482 | if !created.insert(self.repo_path(handle, name)) { |
| 483 | return Err(GitStorageError::AlreadyExists); |
| 484 | } |
| 485 | |
| 486 | Ok(()) |
| 487 | } |
| 488 | |
| 489 | async fn remove(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> { |
| 490 | self.created |
| 491 | .lock() |
| 492 | .expect("lock poisoned") |
| 493 | .remove(&self.repo_path(handle, name)); |
| 494 | |
| 495 | Ok(()) |
| 496 | } |
| 497 | |
| 498 | async fn rename( |
| 499 | &self, |
| 500 | handle: &OrgName, |
| 501 | from: &RepoName, |
| 502 | to: &RepoName, |
| 503 | ) -> Result<(), GitStorageError> { |
| 504 | let mut created = self.created.lock().expect("lock poisoned"); |
| 505 | let destination = self.repo_path(handle, to); |
| 506 | |
| 507 | |
| 508 | |
| 509 | if created.contains(&destination) { |
| 510 | return Err(GitStorageError::AlreadyExists); |
| 511 | } |
| 512 | |
| 513 | let source = self.repo_path(handle, from); |
| 514 | created.remove(&source); |
| 515 | created.insert(destination.clone()); |
| 516 | |
| 517 | |
| 518 | let mut heads = self.heads.lock().expect("lock poisoned"); |
| 519 | if let Some(head) = heads.remove(&source) { |
| 520 | heads.insert(destination, head); |
| 521 | } |
| 522 | |
| 523 | Ok(()) |
| 524 | } |
| 525 | |
| 526 | async fn set_default_branch( |
| 527 | &self, |
| 528 | handle: &OrgName, |
| 529 | name: &RepoName, |
| 530 | branch: &RefName, |
| 531 | ) -> Result<(), GitStorageError> { |
| 532 | self.heads |
| 533 | .lock() |
| 534 | .expect("lock poisoned") |
| 535 | .insert(self.repo_path(handle, name), branch.clone()); |
| 536 | |
| 537 | Ok(()) |
| 538 | } |
| 539 | |
| 540 | |
| 541 | |
| 542 | |
| 543 | async fn enable_reflogs(&self) -> Result<u64, GitStorageError> { |
| 544 | Ok(0) |
| 545 | } |
| 546 | |
| 547 | async fn list_repo_dirs(&self) -> Result<Vec<RepoDir>, GitStorageError> { |
| 548 | let created = self.created.lock().expect("lock poisoned"); |
| 549 | |
| 550 | let mut found: Vec<RepoDir> = created |
| 551 | .iter() |
| 552 | .filter_map(|path| { |
| 553 | let name = path.file_stem().and_then(OsStr::to_str)?; |
| 554 | let handle = path.parent().and_then(|parent| file_name_of(parent))?; |
| 555 | |
| 556 | Some(RepoDir { |
| 557 | handle: handle.to_owned(), |
| 558 | name: name.to_owned(), |
| 559 | path: path.clone(), |
| 560 | }) |
| 561 | }) |
| 562 | .collect(); |
| 563 | |
| 564 | |
| 565 | |
| 566 | found.sort_by(|a, b| (&a.handle, &a.name).cmp(&(&b.handle, &b.name))); |
| 567 | |
| 568 | Ok(found) |
| 569 | } |
| 570 | |
| 571 | |
| 572 | |
| 573 | |
| 574 | async fn quarantine(&self, dir: &RepoDir, label: &str) -> Result<PathBuf, GitStorageError> { |
| 575 | let destination = PathBuf::from("/in-memory").join(QUARANTINE).join(label); |
| 576 | |
| 577 | let mut created = self.created.lock().expect("lock poisoned"); |
| 578 | |
| 579 | if created.contains(&destination) { |
| 580 | return Err(GitStorageError::AlreadyExists); |
| 581 | } |
| 582 | |
| 583 | created.remove(&dir.path); |
| 584 | created.insert(destination.clone()); |
| 585 | |
| 586 | Ok(destination) |
| 587 | } |
| 588 | |
| 589 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 590 | PathBuf::from("/in-memory") |
| 591 | .join(handle.as_str()) |
| 592 | .join(format!("{name}.git")) |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | |
| 597 | |
| 598 | |
| 599 | |
| 600 | |
| 601 | #[derive(Debug, Clone)] |
| 602 | pub struct GitHttpBackend { |
| 603 | data_dir: PathBuf, |
| 604 | } |
| 605 | |
| 606 | impl GitHttpBackend { |
| 607 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 608 | Self { |
| 609 | data_dir: data_dir.into(), |
| 610 | } |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | impl GitProtocolServer for GitHttpBackend { |
| 615 | async fn serve(&self, request: GitRequest) -> Result<GitResponse, GitProtocolError> { |
| 616 | let mut command = git_command(); |
| 617 | |
| 618 | |
| 619 | |
| 620 | |
| 621 | |
| 622 | if request.allow_receive_pack { |
| 623 | command.arg("-c").arg("http.receivepack=true"); |
| 624 | } |
| 625 | |
| 626 | command |
| 627 | .arg("http-backend") |
| 628 | .env("GIT_PROJECT_ROOT", &self.data_dir) |
| 629 | |
| 630 | |
| 631 | |
| 632 | |
| 633 | .env("GIT_HTTP_EXPORT_ALL", "1") |
| 634 | .env("PATH_INFO", &request.path_info) |
| 635 | .env("QUERY_STRING", &request.query) |
| 636 | .env("REQUEST_METHOD", request.method.as_str()) |
| 637 | .stdin(Stdio::piped()) |
| 638 | .stdout(Stdio::piped()) |
| 639 | .stderr(Stdio::piped()); |
| 640 | |
| 641 | |
| 642 | |
| 643 | |
| 644 | |
| 645 | |
| 646 | |
| 647 | |
| 648 | |
| 649 | |
| 650 | for (variable, value) in [ |
| 651 | ("CONTENT_TYPE", &request.content_type), |
| 652 | ("CONTENT_LENGTH", &request.content_length), |
| 653 | ("HTTP_CONTENT_ENCODING", &request.content_encoding), |
| 654 | ("HTTP_GIT_PROTOCOL", &request.git_protocol), |
| 655 | ("REMOTE_USER", &request.remote_user), |
| 656 | ] { |
| 657 | if let Some(value) = value { |
| 658 | command.env(variable, value); |
| 659 | } |
| 660 | } |
| 661 | |
| 662 | let mut child = command |
| 663 | .spawn() |
| 664 | .map_err(|error| GitProtocolError::new(format!("could not run git: {error}")))?; |
| 665 | |
| 666 | let mut stdin = child.stdin.take().expect("stdin was piped"); |
| 667 | let stdout = child.stdout.take().expect("stdout was piped"); |
| 668 | let mut stderr = child.stderr.take().expect("stderr was piped"); |
| 669 | let mut body = request.body; |
| 670 | |
| 671 | |
| 672 | |
| 673 | |
| 674 | |
| 675 | |
| 676 | tokio::spawn(async move { |
| 677 | let _ = tokio::io::copy(&mut body, &mut stdin).await; |
| 678 | }); |
| 679 | |
| 680 | |
| 681 | |
| 682 | |
| 683 | |
| 684 | |
| 685 | tokio::spawn(async move { |
| 686 | let mut complaint = String::new(); |
| 687 | let _ = stderr.read_to_string(&mut complaint).await; |
| 688 | |
| 689 | match child.wait().await { |
| 690 | Ok(status) if status.success() => {} |
| 691 | Ok(status) => eprintln!( |
| 692 | "steid: git http-backend exited with {status}: {}", |
| 693 | complaint.trim() |
| 694 | ), |
| 695 | Err(error) => eprintln!("steid: could not wait for git http-backend: {error}"), |
| 696 | } |
| 697 | }); |
| 698 | |
| 699 | |
| 700 | |
| 701 | |
| 702 | let mut reader = BufReader::new(stdout); |
| 703 | let (status, headers) = read_cgi_headers(&mut reader).await?; |
| 704 | |
| 705 | Ok(GitResponse { |
| 706 | status, |
| 707 | headers, |
| 708 | body: Box::pin(reader), |
| 709 | }) |
| 710 | } |
| 711 | } |
| 712 | |
| 713 | |
| 714 | |
| 715 | |
| 716 | |
| 717 | |
| 718 | async fn read_cgi_headers( |
| 719 | reader: &mut BufReader<ChildStdout>, |
| 720 | ) -> Result<(u16, Vec<(String, String)>), GitProtocolError> { |
| 721 | let mut status = 200; |
| 722 | let mut headers = Vec::new(); |
| 723 | let mut line = Vec::new(); |
| 724 | |
| 725 | loop { |
| 726 | line.clear(); |
| 727 | |
| 728 | let read = reader |
| 729 | .read_until(b'\n', &mut line) |
| 730 | .await |
| 731 | .map_err(|error| GitProtocolError::new(format!("reading git's headers: {error}")))?; |
| 732 | |
| 733 | if read == 0 { |
| 734 | return Err(GitProtocolError::new( |
| 735 | "git http-backend produced no headers before closing", |
| 736 | )); |
| 737 | } |
| 738 | |
| 739 | |
| 740 | |
| 741 | let text = String::from_utf8_lossy(&line); |
| 742 | let text = text.trim_end_matches(['\r', '\n']); |
| 743 | |
| 744 | if text.is_empty() { |
| 745 | return Ok((status, headers)); |
| 746 | } |
| 747 | |
| 748 | let Some((name, value)) = text.split_once(": ") else { |
| 749 | return Err(GitProtocolError::new(format!( |
| 750 | "git http-backend wrote an unparseable header: {text:?}" |
| 751 | ))); |
| 752 | }; |
| 753 | |
| 754 | if name.eq_ignore_ascii_case("status") { |
| 755 | status = value |
| 756 | .split_whitespace() |
| 757 | .next() |
| 758 | .and_then(|code| code.parse().ok()) |
| 759 | .ok_or_else(|| { |
| 760 | GitProtocolError::new(format!("git http-backend wrote a bad status: {value:?}")) |
| 761 | })?; |
| 762 | } else { |
| 763 | headers.push((name.to_owned(), value.to_owned())); |
| 764 | } |
| 765 | |
| 766 | if headers.len() > MAX_CGI_HEADERS { |
| 767 | return Err(GitProtocolError::new( |
| 768 | "git http-backend wrote more headers than a CGI response can plausibly have", |
| 769 | )); |
| 770 | } |
| 771 | } |
| 772 | } |
| 773 | |
| 774 | |
| 775 | |
| 776 | |
| 777 | |
| 778 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 779 | pub struct RecordedGitRequest { |
| 780 | pub method: GitMethod, |
| 781 | pub path_info: String, |
| 782 | pub query: String, |
| 783 | pub git_protocol: Option<String>, |
| 784 | pub content_encoding: Option<String>, |
| 785 | pub allow_receive_pack: bool, |
| 786 | pub remote_user: Option<String>, |
| 787 | } |
| 788 | |
| 789 | |
| 790 | |
| 791 | |
| 792 | |
| 793 | |
| 794 | #[derive(Debug, Default, Clone)] |
| 795 | pub struct InMemoryGitProtocol { |
| 796 | requests: Arc<Mutex<Vec<RecordedGitRequest>>>, |
| 797 | } |
| 798 | |
| 799 | impl InMemoryGitProtocol { |
| 800 | pub fn new() -> Self { |
| 801 | Self::default() |
| 802 | } |
| 803 | |
| 804 | pub fn requests(&self) -> Vec<RecordedGitRequest> { |
| 805 | self.requests.lock().expect("lock poisoned").clone() |
| 806 | } |
| 807 | |
| 808 | |
| 809 | pub fn was_called(&self) -> bool { |
| 810 | !self.requests.lock().expect("lock poisoned").is_empty() |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | impl GitProtocolServer for InMemoryGitProtocol { |
| 815 | async fn serve(&self, request: GitRequest) -> Result<GitResponse, GitProtocolError> { |
| 816 | self.requests |
| 817 | .lock() |
| 818 | .expect("lock poisoned") |
| 819 | .push(RecordedGitRequest { |
| 820 | method: request.method, |
| 821 | path_info: request.path_info, |
| 822 | query: request.query, |
| 823 | git_protocol: request.git_protocol, |
| 824 | content_encoding: request.content_encoding, |
| 825 | allow_receive_pack: request.allow_receive_pack, |
| 826 | remote_user: request.remote_user, |
| 827 | }); |
| 828 | |
| 829 | Ok(GitResponse { |
| 830 | status: 200, |
| 831 | headers: vec![( |
| 832 | "Content-Type".to_owned(), |
| 833 | "application/x-git-upload-pack-advertisement".to_owned(), |
| 834 | )], |
| 835 | body: Box::pin(std::io::Cursor::new(b"0000".to_vec())), |
| 836 | }) |
| 837 | } |
| 838 | } |
| 839 | |
| 840 | |
| 841 | |
| 842 | |
| 843 | |
| 844 | |
| 845 | |
| 846 | #[derive(Debug, Clone)] |
| 847 | pub struct DiskGitArchive { |
| 848 | data_dir: PathBuf, |
| 849 | } |
| 850 | |
| 851 | impl DiskGitArchive { |
| 852 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 853 | Self { |
| 854 | data_dir: data_dir.into(), |
| 855 | } |
| 856 | } |
| 857 | |
| 858 | |
| 859 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 860 | self.data_dir |
| 861 | .join(handle.as_str()) |
| 862 | .join(format!("{name}.git")) |
| 863 | } |
| 864 | } |
| 865 | |
| 866 | impl GitArchive for DiskGitArchive { |
| 867 | async fn archive(&self, request: ArchiveRequest) -> Result<ByteStream, GitArchiveError> { |
| 868 | let repo = self.repo_path(&request.handle, &request.name); |
| 869 | |
| 870 | |
| 871 | |
| 872 | |
| 873 | |
| 874 | let mut command = git_command(); |
| 875 | command |
| 876 | .arg("-C") |
| 877 | .arg(&repo) |
| 878 | .arg("archive") |
| 879 | .arg(format!("--format={}", request.format.as_str())) |
| 880 | .arg(format!("--prefix={}", request.prefix)) |
| 881 | .arg(request.commit.as_str()) |
| 882 | .stdin(Stdio::null()) |
| 883 | .stdout(Stdio::piped()) |
| 884 | .stderr(Stdio::piped()) |
| 885 | |
| 886 | |
| 887 | .kill_on_drop(true); |
| 888 | |
| 889 | let mut child = command |
| 890 | .spawn() |
| 891 | .map_err(|error| GitArchiveError::new(format!("could not run git: {error}")))?; |
| 892 | |
| 893 | let stdout = child.stdout.take().expect("stdout was piped"); |
| 894 | let mut stderr = child.stderr.take().expect("stderr was piped"); |
| 895 | |
| 896 | |
| 897 | |
| 898 | |
| 899 | |
| 900 | |
| 901 | |
| 902 | tokio::spawn(async move { |
| 903 | let mut complaint = String::new(); |
| 904 | let _ = stderr.read_to_string(&mut complaint).await; |
| 905 | |
| 906 | match child.wait().await { |
| 907 | Ok(status) if status.success() => {} |
| 908 | Ok(status) => { |
| 909 | eprintln!( |
| 910 | "steid: git archive exited with {status}: {}", |
| 911 | complaint.trim() |
| 912 | ) |
| 913 | } |
| 914 | Err(error) => eprintln!("steid: could not wait for git archive: {error}"), |
| 915 | } |
| 916 | }); |
| 917 | |
| 918 | Ok(Box::pin(stdout)) |
| 919 | } |
| 920 | } |
| 921 | |
| 922 | |
| 923 | |
| 924 | |
| 925 | |
| 926 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 927 | pub struct RecordedArchive { |
| 928 | pub handle: OrgName, |
| 929 | pub name: RepoName, |
| 930 | pub format: crate::application::port::ArchiveFormat, |
| 931 | pub commit: ObjectId, |
| 932 | pub prefix: String, |
| 933 | } |
| 934 | |
| 935 | |
| 936 | |
| 937 | |
| 938 | |
| 939 | #[derive(Debug, Default, Clone)] |
| 940 | pub struct InMemoryGitArchive { |
| 941 | requests: Arc<Mutex<Vec<RecordedArchive>>>, |
| 942 | } |
| 943 | |
| 944 | impl InMemoryGitArchive { |
| 945 | pub fn new() -> Self { |
| 946 | Self::default() |
| 947 | } |
| 948 | |
| 949 | pub fn requests(&self) -> Vec<RecordedArchive> { |
| 950 | self.requests.lock().expect("lock poisoned").clone() |
| 951 | } |
| 952 | |
| 953 | |
| 954 | pub fn was_called(&self) -> bool { |
| 955 | !self.requests.lock().expect("lock poisoned").is_empty() |
| 956 | } |
| 957 | } |
| 958 | |
| 959 | impl GitArchive for InMemoryGitArchive { |
| 960 | async fn archive(&self, request: ArchiveRequest) -> Result<ByteStream, GitArchiveError> { |
| 961 | self.requests |
| 962 | .lock() |
| 963 | .expect("lock poisoned") |
| 964 | .push(RecordedArchive { |
| 965 | handle: request.handle, |
| 966 | name: request.name, |
| 967 | format: request.format, |
| 968 | commit: request.commit, |
| 969 | prefix: request.prefix, |
| 970 | }); |
| 971 | |
| 972 | Ok(Box::pin(std::io::Cursor::new(b"archive".to_vec()))) |
| 973 | } |
| 974 | } |
| 975 | |
| 976 | |
| 977 | |
| 978 | |
| 979 | |
| 980 | |
| 981 | #[derive(Debug, Default, Clone)] |
| 982 | pub struct InMemoryGitQuery { |
| 983 | default_branch: Option<RefName>, |
| 984 | |
| 985 | trees: HashMap<String, Vec<TreeEntry>>, |
| 986 | blobs: HashMap<String, Vec<u8>>, |
| 987 | commits: Vec<CommitSummary>, |
| 988 | |
| 989 | |
| 990 | refs: Vec<GitRef>, |
| 991 | |
| 992 | |
| 993 | commit_count: Option<u64>, |
| 994 | latest_tag: Option<TagSummary>, |
| 995 | |
| 996 | |
| 997 | branch_rows: Vec<BranchRow>, |
| 998 | tag_rows: Vec<TagRow>, |
| 999 | |
| 1000 | |
| 1001 | grep_hits: Vec<GrepHit>, |
| 1002 | |
| 1003 | |
| 1004 | slow_grep: bool, |
| 1005 | |
| 1006 | |
| 1007 | detail: Option<CommitDetail>, |
| 1008 | |
| 1009 | diff: Option<RawDiff>, |
| 1010 | |
| 1011 | merge_base: Option<ObjectId>, |
| 1012 | |
| 1013 | |
| 1014 | |
| 1015 | merge_preview: Option<MergePreview>, |
| 1016 | |
| 1017 | |
| 1018 | |
| 1019 | snapshot: Arc<Mutex<Vec<(RefName, ObjectId)>>>, |
| 1020 | |
| 1021 | |
| 1022 | |
| 1023 | blames: HashMap<String, Blame>, |
| 1024 | |
| 1025 | |
| 1026 | |
| 1027 | |
| 1028 | bodies: HashMap<String, String>, |
| 1029 | |
| 1030 | |
| 1031 | last_commits: HashMap<String, HashMap<String, EntryCommit>>, |
| 1032 | |
| 1033 | |
| 1034 | |
| 1035 | |
| 1036 | |
| 1037 | |
| 1038 | path_logs: HashMap<String, Vec<CommitSummary>>, |
| 1039 | |
| 1040 | |
| 1041 | symlink_targets: HashMap<ObjectId, String>, |
| 1042 | |
| 1043 | |
| 1044 | |
| 1045 | |
| 1046 | |
| 1047 | |
| 1048 | resolved: HashMap<String, ObjectId>, |
| 1049 | } |
| 1050 | |
| 1051 | impl InMemoryGitQuery { |
| 1052 | |
| 1053 | pub fn empty() -> Self { |
| 1054 | Self::default() |
| 1055 | } |
| 1056 | |
| 1057 | |
| 1058 | pub fn new() -> Self { |
| 1059 | Self { |
| 1060 | default_branch: Some(RefName::from_trusted("main")), |
| 1061 | ..Self::default() |
| 1062 | } |
| 1063 | } |
| 1064 | |
| 1065 | fn key(rev: &RefName, path: &RepoPath) -> String { |
| 1066 | format!("{}\0{}", rev.as_str(), path.as_str()) |
| 1067 | } |
| 1068 | |
| 1069 | pub fn with_tree(mut self, rev: &str, path: &str, entries: Vec<TreeEntry>) -> Self { |
| 1070 | self.trees.insert( |
| 1071 | Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)), |
| 1072 | entries, |
| 1073 | ); |
| 1074 | self |
| 1075 | } |
| 1076 | |
| 1077 | pub fn with_blob(mut self, rev: &str, path: &str, content: impl Into<Vec<u8>>) -> Self { |
| 1078 | self.blobs.insert( |
| 1079 | Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)), |
| 1080 | content.into(), |
| 1081 | ); |
| 1082 | self |
| 1083 | } |
| 1084 | |
| 1085 | |
| 1086 | pub fn with_last_commits( |
| 1087 | mut self, |
| 1088 | rev: &str, |
| 1089 | path: &str, |
| 1090 | commits: Vec<(&str, EntryCommit)>, |
| 1091 | ) -> Self { |
| 1092 | self.last_commits.insert( |
| 1093 | Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)), |
| 1094 | commits |
| 1095 | .into_iter() |
| 1096 | .map(|(name, commit)| (name.to_owned(), commit)) |
| 1097 | .collect(), |
| 1098 | ); |
| 1099 | self |
| 1100 | } |
| 1101 | |
| 1102 | pub fn with_log(mut self, commits: Vec<CommitSummary>) -> Self { |
| 1103 | self.commits = commits; |
| 1104 | self |
| 1105 | } |
| 1106 | |
| 1107 | |
| 1108 | pub fn with_path_log(mut self, rev: &str, path: &str, commits: Vec<CommitSummary>) -> Self { |
| 1109 | self.path_logs.insert( |
| 1110 | Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)), |
| 1111 | commits, |
| 1112 | ); |
| 1113 | self |
| 1114 | } |
| 1115 | |
| 1116 | |
| 1117 | pub fn with_symlink_target(mut self, id: &ObjectId, target: &str) -> Self { |
| 1118 | self.symlink_targets.insert(id.clone(), target.to_owned()); |
| 1119 | self |
| 1120 | } |
| 1121 | |
| 1122 | pub fn with_branch(self, name: &str) -> Self { |
| 1123 | self.with_ref(name, RefKind::Branch) |
| 1124 | } |
| 1125 | |
| 1126 | pub fn with_tag(self, name: &str) -> Self { |
| 1127 | self.with_ref(name, RefKind::Tag) |
| 1128 | } |
| 1129 | |
| 1130 | |
| 1131 | pub fn with_resolved(mut self, rev: &str, id: &str) -> Self { |
| 1132 | self.resolved |
| 1133 | .insert(rev.to_owned(), ObjectId::from_trusted(format!("{id:0>40}"))); |
| 1134 | self |
| 1135 | } |
| 1136 | |
| 1137 | pub fn with_commit_count(mut self, count: u64) -> Self { |
| 1138 | self.commit_count = Some(count); |
| 1139 | self |
| 1140 | } |
| 1141 | |
| 1142 | pub fn with_latest_tag(mut self, name: &str, created_at: SystemTime) -> Self { |
| 1143 | self.latest_tag = Some(TagSummary { |
| 1144 | name: RefName::from_trusted(name), |
| 1145 | created_at, |
| 1146 | }); |
| 1147 | self |
| 1148 | } |
| 1149 | |
| 1150 | |
| 1151 | pub fn with_branch_row( |
| 1152 | mut self, |
| 1153 | name: &str, |
| 1154 | is_default: bool, |
| 1155 | committed_at: SystemTime, |
| 1156 | ) -> Self { |
| 1157 | self.branch_rows.push(BranchRow { |
| 1158 | name: RefName::from_trusted(name), |
| 1159 | is_default, |
| 1160 | commit: ObjectId::from_trusted("2".repeat(40)), |
| 1161 | summary: format!("work on {name}"), |
| 1162 | committed_at, |
| 1163 | }); |
| 1164 | self |
| 1165 | } |
| 1166 | |
| 1167 | |
| 1168 | |
| 1169 | pub fn with_tag_row(mut self, name: &str, annotated: bool, created_at: SystemTime) -> Self { |
| 1170 | self.tag_rows.push(TagRow { |
| 1171 | name: RefName::from_trusted(name), |
| 1172 | commit: ObjectId::from_trusted("3".repeat(40)), |
| 1173 | message: annotated.then(|| format!("release {name}")), |
| 1174 | annotated, |
| 1175 | created_at, |
| 1176 | }); |
| 1177 | self |
| 1178 | } |
| 1179 | |
| 1180 | |
| 1181 | |
| 1182 | pub fn with_grep_hits(mut self, hits: Vec<GrepHit>) -> Self { |
| 1183 | self.grep_hits = hits; |
| 1184 | self |
| 1185 | } |
| 1186 | |
| 1187 | |
| 1188 | pub fn with_slow_grep(mut self) -> Self { |
| 1189 | self.slow_grep = true; |
| 1190 | self |
| 1191 | } |
| 1192 | |
| 1193 | |
| 1194 | pub fn with_commit_body(mut self, id: &str, body: &str) -> Self { |
| 1195 | self.bodies.insert(id.to_owned(), body.to_owned()); |
| 1196 | self |
| 1197 | } |
| 1198 | |
| 1199 | pub fn with_commit(mut self, detail: CommitDetail) -> Self { |
| 1200 | self.detail = Some(detail); |
| 1201 | self |
| 1202 | } |
| 1203 | |
| 1204 | pub fn with_diff(mut self, patch: impl Into<Vec<u8>>, numstat: impl Into<Vec<u8>>) -> Self { |
| 1205 | self.diff = Some(RawDiff { |
| 1206 | numstat: numstat.into(), |
| 1207 | patch: patch.into(), |
| 1208 | truncated: false, |
| 1209 | }); |
| 1210 | self |
| 1211 | } |
| 1212 | |
| 1213 | pub fn with_merge_base(mut self, id: &str) -> Self { |
| 1214 | self.merge_base = Some(ObjectId::from_trusted(id)); |
| 1215 | self |
| 1216 | } |
| 1217 | |
| 1218 | |
| 1219 | pub fn with_conflicts(mut self, paths: &[&str]) -> Self { |
| 1220 | self.merge_preview = Some(MergePreview::Conflicted { |
| 1221 | paths: paths.iter().map(|path| (*path).to_owned()).collect(), |
| 1222 | }); |
| 1223 | self |
| 1224 | } |
| 1225 | |
| 1226 | pub fn with_blame(mut self, rev: &str, path: &str, blame: Blame) -> Self { |
| 1227 | self.blames.insert( |
| 1228 | Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)), |
| 1229 | blame, |
| 1230 | ); |
| 1231 | self |
| 1232 | } |
| 1233 | |
| 1234 | |
| 1235 | pub fn with_ref_snapshot(self, refs: &[(&str, &str)]) -> Self { |
| 1236 | self.set_ref_snapshot(refs); |
| 1237 | self |
| 1238 | } |
| 1239 | |
| 1240 | |
| 1241 | |
| 1242 | |
| 1243 | |
| 1244 | pub fn set_ref_snapshot(&self, refs: &[(&str, &str)]) { |
| 1245 | *self.snapshot.lock().expect("lock poisoned") = refs |
| 1246 | .iter() |
| 1247 | .map(|(name, id)| { |
| 1248 | ( |
| 1249 | RefName::from_trusted(*name), |
| 1250 | ObjectId::from_trusted(format!("{id:0>40}")), |
| 1251 | ) |
| 1252 | }) |
| 1253 | .collect(); |
| 1254 | } |
| 1255 | |
| 1256 | fn with_ref(mut self, name: &str, kind: RefKind) -> Self { |
| 1257 | self.refs.push(GitRef { |
| 1258 | name: RefName::from_trusted(name), |
| 1259 | kind, |
| 1260 | }); |
| 1261 | self |
| 1262 | } |
| 1263 | } |
| 1264 | |
| 1265 | impl GitQuery for InMemoryGitQuery { |
| 1266 | async fn default_branch( |
| 1267 | &self, |
| 1268 | _handle: &OrgName, |
| 1269 | _name: &RepoName, |
| 1270 | ) -> Result<Option<RefName>, GitQueryError> { |
| 1271 | Ok(self.default_branch.clone()) |
| 1272 | } |
| 1273 | |
| 1274 | async fn resolve( |
| 1275 | &self, |
| 1276 | _handle: &OrgName, |
| 1277 | _name: &RepoName, |
| 1278 | rev: &RefName, |
| 1279 | ) -> Result<Option<ObjectId>, GitQueryError> { |
| 1280 | if let Some(id) = self.resolved.get(rev.as_str()) { |
| 1281 | return Ok(Some(id.clone())); |
| 1282 | } |
| 1283 | |
| 1284 | Ok(self |
| 1285 | .default_branch |
| 1286 | .as_ref() |
| 1287 | .map(|_| ObjectId::from_trusted("0".repeat(40)))) |
| 1288 | } |
| 1289 | |
| 1290 | async fn list_tree( |
| 1291 | &self, |
| 1292 | _handle: &OrgName, |
| 1293 | _name: &RepoName, |
| 1294 | rev: &RefName, |
| 1295 | path: &RepoPath, |
| 1296 | ) -> Result<Option<Vec<TreeEntry>>, GitQueryError> { |
| 1297 | Ok(self.trees.get(&Self::key(rev, path)).cloned()) |
| 1298 | } |
| 1299 | |
| 1300 | async fn last_commits( |
| 1301 | &self, |
| 1302 | _handle: &OrgName, |
| 1303 | _name: &RepoName, |
| 1304 | rev: &RefName, |
| 1305 | path: &RepoPath, |
| 1306 | entries: &[String], |
| 1307 | ) -> Result<HashMap<String, EntryCommit>, GitQueryError> { |
| 1308 | let Some(seeded) = self.last_commits.get(&Self::key(rev, path)) else { |
| 1309 | return Ok(HashMap::new()); |
| 1310 | }; |
| 1311 | |
| 1312 | |
| 1313 | |
| 1314 | Ok(seeded |
| 1315 | .iter() |
| 1316 | .filter(|(name, _)| entries.iter().any(|entry| entry == *name)) |
| 1317 | .map(|(name, commit)| (name.clone(), commit.clone())) |
| 1318 | .collect()) |
| 1319 | } |
| 1320 | |
| 1321 | async fn read_blob( |
| 1322 | &self, |
| 1323 | _handle: &OrgName, |
| 1324 | _name: &RepoName, |
| 1325 | rev: &RefName, |
| 1326 | path: &RepoPath, |
| 1327 | max_bytes: u64, |
| 1328 | ) -> Result<Option<Blob>, GitQueryError> { |
| 1329 | Ok(self.blobs.get(&Self::key(rev, path)).map(|content| { |
| 1330 | let size = content.len() as u64; |
| 1331 | |
| 1332 | Blob { |
| 1333 | id: ObjectId::from_trusted("1".repeat(40)), |
| 1334 | size, |
| 1335 | |
| 1336 | |
| 1337 | content: (size <= max_bytes).then(|| content.clone()), |
| 1338 | } |
| 1339 | })) |
| 1340 | } |
| 1341 | |
| 1342 | async fn log( |
| 1343 | &self, |
| 1344 | _handle: &OrgName, |
| 1345 | _name: &RepoName, |
| 1346 | _rev: &RefName, |
| 1347 | offset: usize, |
| 1348 | limit: usize, |
| 1349 | ) -> Result<Vec<CommitSummary>, GitQueryError> { |
| 1350 | Ok(self |
| 1351 | .commits |
| 1352 | .iter() |
| 1353 | .skip(offset) |
| 1354 | .take(limit) |
| 1355 | .cloned() |
| 1356 | .collect()) |
| 1357 | } |
| 1358 | |
| 1359 | async fn log_entries( |
| 1360 | &self, |
| 1361 | _handle: &OrgName, |
| 1362 | _name: &RepoName, |
| 1363 | _rev: &RefName, |
| 1364 | limit: usize, |
| 1365 | ) -> Result<Vec<CommitEntry>, GitQueryError> { |
| 1366 | Ok(self |
| 1367 | .commits |
| 1368 | .iter() |
| 1369 | .take(limit) |
| 1370 | .map(|commit| CommitEntry { |
| 1371 | body: self |
| 1372 | .bodies |
| 1373 | .get(commit.id.as_str()) |
| 1374 | .cloned() |
| 1375 | .unwrap_or_default(), |
| 1376 | commit: commit.clone(), |
| 1377 | }) |
| 1378 | .collect()) |
| 1379 | } |
| 1380 | |
| 1381 | async fn list_refs( |
| 1382 | &self, |
| 1383 | _handle: &OrgName, |
| 1384 | _name: &RepoName, |
| 1385 | ) -> Result<Vec<GitRef>, GitQueryError> { |
| 1386 | Ok(self.refs.clone()) |
| 1387 | } |
| 1388 | |
| 1389 | async fn count_commits( |
| 1390 | &self, |
| 1391 | _handle: &OrgName, |
| 1392 | _name: &RepoName, |
| 1393 | _rev: &RefName, |
| 1394 | ) -> Result<u64, GitQueryError> { |
| 1395 | Ok(self.commit_count.unwrap_or(self.commits.len() as u64)) |
| 1396 | } |
| 1397 | |
| 1398 | async fn latest_tag( |
| 1399 | &self, |
| 1400 | _handle: &OrgName, |
| 1401 | _name: &RepoName, |
| 1402 | ) -> Result<Option<TagSummary>, GitQueryError> { |
| 1403 | Ok(self.latest_tag.clone()) |
| 1404 | } |
| 1405 | |
| 1406 | async fn branches( |
| 1407 | &self, |
| 1408 | _handle: &OrgName, |
| 1409 | _name: &RepoName, |
| 1410 | ) -> Result<Vec<BranchRow>, GitQueryError> { |
| 1411 | Ok(self.branch_rows.clone()) |
| 1412 | } |
| 1413 | |
| 1414 | async fn tags( |
| 1415 | &self, |
| 1416 | _handle: &OrgName, |
| 1417 | _name: &RepoName, |
| 1418 | ) -> Result<Vec<TagRow>, GitQueryError> { |
| 1419 | Ok(self.tag_rows.clone()) |
| 1420 | } |
| 1421 | |
| 1422 | async fn grep( |
| 1423 | &self, |
| 1424 | _handle: &OrgName, |
| 1425 | _name: &RepoName, |
| 1426 | _commit: &ObjectId, |
| 1427 | _query: &str, |
| 1428 | limit: usize, |
| 1429 | ) -> Result<Vec<GrepHit>, GitQueryError> { |
| 1430 | if self.slow_grep { |
| 1431 | return Err(GitQueryError::timed_out(std::time::Duration::from_secs(20))); |
| 1432 | } |
| 1433 | |
| 1434 | Ok(self.grep_hits.iter().take(limit).cloned().collect()) |
| 1435 | } |
| 1436 | |
| 1437 | async fn commit( |
| 1438 | &self, |
| 1439 | _handle: &OrgName, |
| 1440 | _name: &RepoName, |
| 1441 | _rev: &RefName, |
| 1442 | ) -> Result<Option<CommitDetail>, GitQueryError> { |
| 1443 | Ok(self.detail.clone()) |
| 1444 | } |
| 1445 | |
| 1446 | async fn diff( |
| 1447 | &self, |
| 1448 | _handle: &OrgName, |
| 1449 | _name: &RepoName, |
| 1450 | _base: Option<&ObjectId>, |
| 1451 | _head: &ObjectId, |
| 1452 | _max_bytes: u64, |
| 1453 | ) -> Result<RawDiff, GitQueryError> { |
| 1454 | Ok(self.diff.clone().unwrap_or_default()) |
| 1455 | } |
| 1456 | |
| 1457 | async fn merge_base( |
| 1458 | &self, |
| 1459 | _handle: &OrgName, |
| 1460 | _name: &RepoName, |
| 1461 | _base: &ObjectId, |
| 1462 | _head: &ObjectId, |
| 1463 | ) -> Result<Option<ObjectId>, GitQueryError> { |
| 1464 | Ok(self.merge_base.clone()) |
| 1465 | } |
| 1466 | |
| 1467 | async fn log_between( |
| 1468 | &self, |
| 1469 | _handle: &OrgName, |
| 1470 | _name: &RepoName, |
| 1471 | _base: Option<&ObjectId>, |
| 1472 | _head: &ObjectId, |
| 1473 | offset: usize, |
| 1474 | limit: usize, |
| 1475 | ) -> Result<Vec<CommitSummary>, GitQueryError> { |
| 1476 | Ok(self |
| 1477 | .commits |
| 1478 | .iter() |
| 1479 | .skip(offset) |
| 1480 | .take(limit) |
| 1481 | .cloned() |
| 1482 | .collect()) |
| 1483 | } |
| 1484 | |
| 1485 | async fn count_between( |
| 1486 | &self, |
| 1487 | _handle: &OrgName, |
| 1488 | _name: &RepoName, |
| 1489 | _base: Option<&ObjectId>, |
| 1490 | _head: &ObjectId, |
| 1491 | ) -> Result<usize, GitQueryError> { |
| 1492 | Ok(self.commits.len()) |
| 1493 | } |
| 1494 | |
| 1495 | async fn blame( |
| 1496 | &self, |
| 1497 | _handle: &OrgName, |
| 1498 | _name: &RepoName, |
| 1499 | rev: &RefName, |
| 1500 | path: &RepoPath, |
| 1501 | ) -> Result<Option<Blame>, GitQueryError> { |
| 1502 | Ok(self.blames.get(&Self::key(rev, path)).cloned()) |
| 1503 | } |
| 1504 | |
| 1505 | async fn ref_snapshot( |
| 1506 | &self, |
| 1507 | _handle: &OrgName, |
| 1508 | _name: &RepoName, |
| 1509 | ) -> Result<Vec<(RefName, ObjectId)>, GitQueryError> { |
| 1510 | Ok(self.snapshot.lock().expect("lock poisoned").clone()) |
| 1511 | } |
| 1512 | |
| 1513 | async fn log_at_path( |
| 1514 | &self, |
| 1515 | _handle: &OrgName, |
| 1516 | _name: &RepoName, |
| 1517 | rev: &RefName, |
| 1518 | path: &RepoPath, |
| 1519 | _follow: bool, |
| 1520 | offset: usize, |
| 1521 | limit: usize, |
| 1522 | ) -> Result<Vec<CommitSummary>, GitQueryError> { |
| 1523 | let Some(commits) = self.path_logs.get(&Self::key(rev, path)) else { |
| 1524 | return Ok(Vec::new()); |
| 1525 | }; |
| 1526 | |
| 1527 | Ok(commits.iter().skip(offset).take(limit).cloned().collect()) |
| 1528 | } |
| 1529 | |
| 1530 | async fn count_commits_at_path( |
| 1531 | &self, |
| 1532 | _handle: &OrgName, |
| 1533 | _name: &RepoName, |
| 1534 | rev: &RefName, |
| 1535 | path: &RepoPath, |
| 1536 | follow: bool, |
| 1537 | ) -> Result<CommitCount, GitQueryError> { |
| 1538 | let counted = self |
| 1539 | .path_logs |
| 1540 | .get(&Self::key(rev, path)) |
| 1541 | .map(Vec::len) |
| 1542 | .unwrap_or(0); |
| 1543 | |
| 1544 | |
| 1545 | |
| 1546 | |
| 1547 | Ok(match follow { |
| 1548 | true => CommitCount { |
| 1549 | total: counted.min(FOLLOWED_LOG_SCAN) as u64, |
| 1550 | capped: counted > FOLLOWED_LOG_SCAN, |
| 1551 | }, |
| 1552 | false => CommitCount { |
| 1553 | total: counted as u64, |
| 1554 | capped: false, |
| 1555 | }, |
| 1556 | }) |
| 1557 | } |
| 1558 | |
| 1559 | async fn symlink_targets( |
| 1560 | &self, |
| 1561 | _handle: &OrgName, |
| 1562 | _name: &RepoName, |
| 1563 | ids: &[ObjectId], |
| 1564 | ) -> Result<HashMap<ObjectId, String>, GitQueryError> { |
| 1565 | Ok(ids |
| 1566 | .iter() |
| 1567 | .filter_map(|id| Some((id.clone(), self.symlink_targets.get(id)?.clone()))) |
| 1568 | .collect()) |
| 1569 | } |
| 1570 | |
| 1571 | async fn merge_preview( |
| 1572 | &self, |
| 1573 | _handle: &OrgName, |
| 1574 | _name: &RepoName, |
| 1575 | _target: &ObjectId, |
| 1576 | _source: &ObjectId, |
| 1577 | ) -> Result<MergePreview, GitQueryError> { |
| 1578 | |
| 1579 | |
| 1580 | Ok(self |
| 1581 | .merge_preview |
| 1582 | .clone() |
| 1583 | .unwrap_or_else(|| MergePreview::Clean { |
| 1584 | tree: ObjectId::from_trusted("7".repeat(40)), |
| 1585 | })) |
| 1586 | } |
| 1587 | } |
| 1588 | |
| 1589 | |
| 1590 | |
| 1591 | |
| 1592 | |
| 1593 | |
| 1594 | |
| 1595 | |
| 1596 | |
| 1597 | |
| 1598 | const IMPORT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600); |
| 1599 | |
| 1600 | |
| 1601 | |
| 1602 | const HTTPS_PORT: u16 = 443; |
| 1603 | |
| 1604 | |
| 1605 | |
| 1606 | |
| 1607 | |
| 1608 | |
| 1609 | |
| 1610 | |
| 1611 | #[derive(Debug, Clone)] |
| 1612 | pub struct DiskGitImport { |
| 1613 | data_dir: PathBuf, |
| 1614 | } |
| 1615 | |
| 1616 | impl DiskGitImport { |
| 1617 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 1618 | Self { |
| 1619 | data_dir: data_dir.into(), |
| 1620 | } |
| 1621 | } |
| 1622 | |
| 1623 | |
| 1624 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 1625 | self.data_dir |
| 1626 | .join(handle.as_str()) |
| 1627 | .join(format!("{name}.git")) |
| 1628 | } |
| 1629 | } |
| 1630 | |
| 1631 | impl GitImport for DiskGitImport { |
| 1632 | async fn mirror( |
| 1633 | &self, |
| 1634 | handle: &OrgName, |
| 1635 | name: &RepoName, |
| 1636 | source: &ImportSource, |
| 1637 | ) -> Result<(), GitImportError> { |
| 1638 | resolve_public_host(source.host()).await?; |
| 1639 | |
| 1640 | let path = self.repo_path(handle, name); |
| 1641 | |
| 1642 | |
| 1643 | |
| 1644 | |
| 1645 | if path.exists() { |
| 1646 | return Err(GitImportError::new( |
| 1647 | "something is already on disk at this repository's path", |
| 1648 | )); |
| 1649 | } |
| 1650 | |
| 1651 | |
| 1652 | |
| 1653 | |
| 1654 | |
| 1655 | run_import( |
| 1656 | [ |
| 1657 | OsStr::new("clone"), |
| 1658 | OsStr::new("--mirror"), |
| 1659 | OsStr::new("--quiet"), |
| 1660 | |
| 1661 | |
| 1662 | |
| 1663 | |
| 1664 | OsStr::new("--"), |
| 1665 | OsStr::new(source.as_str()), |
| 1666 | path.as_os_str(), |
| 1667 | ], |
| 1668 | None, |
| 1669 | ) |
| 1670 | .await?; |
| 1671 | |
| 1672 | finish_mirror(&path).await |
| 1673 | } |
| 1674 | } |
| 1675 | |
| 1676 | |
| 1677 | |
| 1678 | |
| 1679 | |
| 1680 | |
| 1681 | async fn finish_mirror(path: &std::path::Path) -> Result<(), GitImportError> { |
| 1682 | |
| 1683 | |
| 1684 | |
| 1685 | |
| 1686 | run_import( |
| 1687 | [ |
| 1688 | OsStr::new("remote"), |
| 1689 | OsStr::new("remove"), |
| 1690 | OsStr::new("origin"), |
| 1691 | ], |
| 1692 | Some(path), |
| 1693 | ) |
| 1694 | .await?; |
| 1695 | |
| 1696 | |
| 1697 | |
| 1698 | |
| 1699 | |
| 1700 | |
| 1701 | run_import( |
| 1702 | [ |
| 1703 | OsStr::new("config"), |
| 1704 | OsStr::new("core.logAllRefUpdates"), |
| 1705 | OsStr::new("true"), |
| 1706 | ], |
| 1707 | Some(path), |
| 1708 | ) |
| 1709 | .await?; |
| 1710 | |
| 1711 | |
| 1712 | |
| 1713 | |
| 1714 | |
| 1715 | promote_remote_refs(path).await |
| 1716 | } |
| 1717 | |
| 1718 | |
| 1719 | |
| 1720 | |
| 1721 | |
| 1722 | |
| 1723 | |
| 1724 | |
| 1725 | |
| 1726 | |
| 1727 | async fn promote_remote_refs(path: &std::path::Path) -> Result<(), GitImportError> { |
| 1728 | let listed = run_import( |
| 1729 | [ |
| 1730 | OsStr::new("for-each-ref"), |
| 1731 | OsStr::new("--format=%(objectname) %(refname)"), |
| 1732 | OsStr::new("refs/remotes/"), |
| 1733 | ], |
| 1734 | Some(path), |
| 1735 | ) |
| 1736 | .await?; |
| 1737 | |
| 1738 | let listed = String::from_utf8_lossy(&listed.stdout); |
| 1739 | |
| 1740 | for line in listed.lines() { |
| 1741 | let Some((id, reference)) = line.trim().split_once(' ') else { |
| 1742 | continue; |
| 1743 | }; |
| 1744 | |
| 1745 | |
| 1746 | |
| 1747 | |
| 1748 | if let Some(branch) = reference |
| 1749 | .strip_prefix("refs/remotes/origin/") |
| 1750 | .filter(|branch| *branch != "HEAD") |
| 1751 | { |
| 1752 | run_import( |
| 1753 | [ |
| 1754 | OsStr::new("update-ref"), |
| 1755 | OsStr::new(&format!("refs/heads/{branch}")), |
| 1756 | OsStr::new(id), |
| 1757 | ], |
| 1758 | Some(path), |
| 1759 | ) |
| 1760 | .await?; |
| 1761 | } |
| 1762 | |
| 1763 | run_import( |
| 1764 | [ |
| 1765 | OsStr::new("update-ref"), |
| 1766 | OsStr::new("-d"), |
| 1767 | OsStr::new(reference), |
| 1768 | ], |
| 1769 | Some(path), |
| 1770 | ) |
| 1771 | .await?; |
| 1772 | } |
| 1773 | |
| 1774 | Ok(()) |
| 1775 | } |
| 1776 | |
| 1777 | |
| 1778 | |
| 1779 | |
| 1780 | |
| 1781 | |
| 1782 | |
| 1783 | |
| 1784 | |
| 1785 | |
| 1786 | |
| 1787 | |
| 1788 | |
| 1789 | async fn resolve_public_host(host: &str) -> Result<(), GitImportError> { |
| 1790 | let refused = || { |
| 1791 | GitImportError::new(format!( |
| 1792 | "{host} resolves to an address that is not on the public internet" |
| 1793 | )) |
| 1794 | }; |
| 1795 | |
| 1796 | let addresses = tokio::net::lookup_host((host, HTTPS_PORT)) |
| 1797 | .await |
| 1798 | .map_err(|error| GitImportError::new(format!("could not resolve {host}: {error}")))?; |
| 1799 | |
| 1800 | let mut any = false; |
| 1801 | |
| 1802 | for address in addresses { |
| 1803 | any = true; |
| 1804 | |
| 1805 | if !is_public(address.ip()) { |
| 1806 | return Err(refused()); |
| 1807 | } |
| 1808 | } |
| 1809 | |
| 1810 | if !any { |
| 1811 | return Err(GitImportError::new(format!("{host} resolves to nothing"))); |
| 1812 | } |
| 1813 | |
| 1814 | Ok(()) |
| 1815 | } |
| 1816 | |
| 1817 | |
| 1818 | |
| 1819 | |
| 1820 | |
| 1821 | |
| 1822 | |
| 1823 | async fn run_import<I, S>(args: I, repo: Option<&std::path::Path>) -> Result<Output, GitImportError> |
| 1824 | where |
| 1825 | I: IntoIterator<Item = S>, |
| 1826 | S: AsRef<OsStr>, |
| 1827 | { |
| 1828 | let mut command = git_command(); |
| 1829 | |
| 1830 | if let Some(repo) = repo { |
| 1831 | command.arg("-C").arg(repo); |
| 1832 | } |
| 1833 | |
| 1834 | command |
| 1835 | .args(args) |
| 1836 | .stdin(Stdio::null()) |
| 1837 | |
| 1838 | |
| 1839 | |
| 1840 | .env("GIT_TERMINAL_PROMPT", "0") |
| 1841 | |
| 1842 | |
| 1843 | .kill_on_drop(true); |
| 1844 | |
| 1845 | let output = match tokio::time::timeout(IMPORT_TIMEOUT, command.output()).await { |
| 1846 | Ok(result) => { |
| 1847 | result.map_err(|error| GitImportError::new(format!("could not run git: {error}")))? |
| 1848 | } |
| 1849 | Err(_elapsed) => { |
| 1850 | return Err(GitImportError::new(format!( |
| 1851 | "the import did not finish within {IMPORT_TIMEOUT:?}" |
| 1852 | ))); |
| 1853 | } |
| 1854 | }; |
| 1855 | |
| 1856 | if !output.status.success() { |
| 1857 | |
| 1858 | |
| 1859 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 1860 | let reason = stderr.lines().rev().find(|line| !line.trim().is_empty()); |
| 1861 | |
| 1862 | return Err(GitImportError::new(match reason { |
| 1863 | Some(reason) => reason.trim().to_owned(), |
| 1864 | None => format!("git exited with {}", output.status), |
| 1865 | })); |
| 1866 | } |
| 1867 | |
| 1868 | Ok(output) |
| 1869 | } |
| 1870 | |
| 1871 | |
| 1872 | |
| 1873 | |
| 1874 | |
| 1875 | |
| 1876 | #[derive(Debug, Default, Clone)] |
| 1877 | pub struct InMemoryGitImport { |
| 1878 | requests: Arc<Mutex<Vec<(String, String, String)>>>, |
| 1879 | failure: Option<String>, |
| 1880 | } |
| 1881 | |
| 1882 | impl InMemoryGitImport { |
| 1883 | pub fn new() -> Self { |
| 1884 | Self::default() |
| 1885 | } |
| 1886 | |
| 1887 | |
| 1888 | pub fn failing(reason: impl Into<String>) -> Self { |
| 1889 | Self { |
| 1890 | requests: Arc::default(), |
| 1891 | failure: Some(reason.into()), |
| 1892 | } |
| 1893 | } |
| 1894 | |
| 1895 | |
| 1896 | pub fn requests(&self) -> Vec<(String, String, String)> { |
| 1897 | self.requests.lock().expect("lock poisoned").clone() |
| 1898 | } |
| 1899 | } |
| 1900 | |
| 1901 | impl GitImport for InMemoryGitImport { |
| 1902 | async fn mirror( |
| 1903 | &self, |
| 1904 | handle: &OrgName, |
| 1905 | name: &RepoName, |
| 1906 | source: &ImportSource, |
| 1907 | ) -> Result<(), GitImportError> { |
| 1908 | self.requests.lock().expect("lock poisoned").push(( |
| 1909 | handle.to_string(), |
| 1910 | name.to_string(), |
| 1911 | source.as_str().to_owned(), |
| 1912 | )); |
| 1913 | |
| 1914 | match &self.failure { |
| 1915 | Some(reason) => Err(GitImportError::new(reason.clone())), |
| 1916 | None => Ok(()), |
| 1917 | } |
| 1918 | } |
| 1919 | } |
| 1920 | |
| 1921 | |
| 1922 | |
| 1923 | |
| 1924 | |
| 1925 | |
| 1926 | |
| 1927 | |
| 1928 | |
| 1929 | |
| 1930 | |
| 1931 | const MERGE_TREE_SINCE: (u32, u32) = (2, 38); |
| 1932 | |
| 1933 | |
| 1934 | |
| 1935 | |
| 1936 | |
| 1937 | |
| 1938 | |
| 1939 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 1940 | pub struct GitFeatures { |
| 1941 | |
| 1942 | |
| 1943 | pub merge_tree: bool, |
| 1944 | } |
| 1945 | |
| 1946 | impl GitFeatures { |
| 1947 | |
| 1948 | |
| 1949 | |
| 1950 | |
| 1951 | |
| 1952 | |
| 1953 | pub async fn detect() -> Self { |
| 1954 | let Ok(output) = git_command() |
| 1955 | .arg("--version") |
| 1956 | .stdin(Stdio::null()) |
| 1957 | .output() |
| 1958 | .await |
| 1959 | else { |
| 1960 | return Self::default(); |
| 1961 | }; |
| 1962 | |
| 1963 | let version = parse_git_version(&String::from_utf8_lossy(&output.stdout)); |
| 1964 | |
| 1965 | Self { |
| 1966 | merge_tree: version.is_some_and(|version| version >= MERGE_TREE_SINCE), |
| 1967 | } |
| 1968 | } |
| 1969 | } |
| 1970 | |
| 1971 | |
| 1972 | |
| 1973 | |
| 1974 | |
| 1975 | fn parse_git_version(output: &str) -> Option<(u32, u32)> { |
| 1976 | let version = output.split_whitespace().nth(2)?; |
| 1977 | let mut parts = version.split('.'); |
| 1978 | |
| 1979 | Some((parts.next()?.parse().ok()?, parts.next()?.parse().ok()?)) |
| 1980 | } |
| 1981 | |
| 1982 | |
| 1983 | |
| 1984 | |
| 1985 | |
| 1986 | |
| 1987 | |
| 1988 | #[derive(Debug, Clone)] |
| 1989 | pub struct DiskGitMerge { |
| 1990 | data_dir: PathBuf, |
| 1991 | } |
| 1992 | |
| 1993 | impl DiskGitMerge { |
| 1994 | pub fn new(data_dir: impl Into<PathBuf>) -> Self { |
| 1995 | Self { |
| 1996 | data_dir: data_dir.into(), |
| 1997 | } |
| 1998 | } |
| 1999 | |
| 2000 | |
| 2001 | fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 2002 | self.data_dir |
| 2003 | .join(handle.as_str()) |
| 2004 | .join(format!("{name}.git")) |
| 2005 | } |
| 2006 | |
| 2007 | |
| 2008 | |
| 2009 | |
| 2010 | |
| 2011 | |
| 2012 | async fn guarded_update( |
| 2013 | &self, |
| 2014 | handle: &OrgName, |
| 2015 | name: &RepoName, |
| 2016 | branch: &RefName, |
| 2017 | new: Option<&ObjectId>, |
| 2018 | old: &ObjectId, |
| 2019 | ) -> Result<(), GitMergeError> { |
| 2020 | let path = self.repo_path(handle, name); |
| 2021 | let full = format!("refs/heads/{branch}"); |
| 2022 | |
| 2023 | let mut command = git_command(); |
| 2024 | command |
| 2025 | .arg("--git-dir") |
| 2026 | .arg(&path) |
| 2027 | .arg("update-ref") |
| 2028 | .stdin(Stdio::null()); |
| 2029 | |
| 2030 | match new { |
| 2031 | Some(new) => { |
| 2032 | command.arg(&full).arg(new.as_str()).arg(old.as_str()); |
| 2033 | } |
| 2034 | None => { |
| 2035 | command.arg("-d").arg(&full).arg(old.as_str()); |
| 2036 | } |
| 2037 | } |
| 2038 | |
| 2039 | let output = command |
| 2040 | .output() |
| 2041 | .await |
| 2042 | .map_err(|error| GitMergeError::backend(format!("could not run git: {error}")))?; |
| 2043 | |
| 2044 | if output.status.success() { |
| 2045 | return Ok(()); |
| 2046 | } |
| 2047 | |
| 2048 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 2049 | |
| 2050 | |
| 2051 | |
| 2052 | |
| 2053 | |
| 2054 | |
| 2055 | if stderr.contains("but expected") { |
| 2056 | return Err(GitMergeError::Stale); |
| 2057 | } |
| 2058 | |
| 2059 | Err(GitMergeError::backend(format!( |
| 2060 | "git update-ref exited with {}: {}", |
| 2061 | output.status, |
| 2062 | stderr.trim() |
| 2063 | ))) |
| 2064 | } |
| 2065 | } |
| 2066 | |
| 2067 | impl GitMerge for DiskGitMerge { |
| 2068 | async fn commit_tree( |
| 2069 | &self, |
| 2070 | handle: &OrgName, |
| 2071 | name: &RepoName, |
| 2072 | request: &CommitTreeRequest, |
| 2073 | ) -> Result<ObjectId, GitMergeError> { |
| 2074 | let path = self.repo_path(handle, name); |
| 2075 | |
| 2076 | let mut command = git_command(); |
| 2077 | command |
| 2078 | .arg("--git-dir") |
| 2079 | .arg(&path) |
| 2080 | .arg("commit-tree") |
| 2081 | .arg(request.tree.as_str()); |
| 2082 | |
| 2083 | for parent in &request.parents { |
| 2084 | command.arg("-p").arg(parent.as_str()); |
| 2085 | } |
| 2086 | |
| 2087 | |
| 2088 | |
| 2089 | |
| 2090 | command.arg("-m").arg(&request.message); |
| 2091 | |
| 2092 | let stamp = git_timestamp(request.now); |
| 2093 | |
| 2094 | |
| 2095 | |
| 2096 | |
| 2097 | |
| 2098 | |
| 2099 | |
| 2100 | |
| 2101 | |
| 2102 | command |
| 2103 | .env("GIT_AUTHOR_NAME", &request.author_name) |
| 2104 | .env("GIT_AUTHOR_EMAIL", &request.author_email) |
| 2105 | .env("GIT_AUTHOR_DATE", &stamp) |
| 2106 | .env("GIT_COMMITTER_NAME", &request.author_name) |
| 2107 | .env("GIT_COMMITTER_EMAIL", &request.author_email) |
| 2108 | .env("GIT_COMMITTER_DATE", &stamp) |
| 2109 | .stdin(Stdio::null()); |
| 2110 | |
| 2111 | let output = command |
| 2112 | .output() |
| 2113 | .await |
| 2114 | .map_err(|error| GitMergeError::backend(format!("could not run git: {error}")))?; |
| 2115 | |
| 2116 | if !output.status.success() { |
| 2117 | return Err(GitMergeError::backend(format!( |
| 2118 | "git commit-tree exited with {}: {}", |
| 2119 | output.status, |
| 2120 | String::from_utf8_lossy(&output.stderr).trim() |
| 2121 | ))); |
| 2122 | } |
| 2123 | |
| 2124 | let id = String::from_utf8_lossy(&output.stdout); |
| 2125 | |
| 2126 | ObjectId::new(id.trim()) |
| 2127 | .map_err(|error| GitMergeError::backend(format!("git named a bad commit: {error}"))) |
| 2128 | } |
| 2129 | |
| 2130 | async fn update_ref( |
| 2131 | &self, |
| 2132 | handle: &OrgName, |
| 2133 | name: &RepoName, |
| 2134 | branch: &RefName, |
| 2135 | new: &ObjectId, |
| 2136 | old: &ObjectId, |
| 2137 | ) -> Result<(), GitMergeError> { |
| 2138 | self.guarded_update(handle, name, branch, Some(new), old) |
| 2139 | .await |
| 2140 | } |
| 2141 | |
| 2142 | async fn delete_ref( |
| 2143 | &self, |
| 2144 | handle: &OrgName, |
| 2145 | name: &RepoName, |
| 2146 | branch: &RefName, |
| 2147 | old: &ObjectId, |
| 2148 | ) -> Result<(), GitMergeError> { |
| 2149 | self.guarded_update(handle, name, branch, None, old).await |
| 2150 | } |
| 2151 | } |
| 2152 | |
| 2153 | |
| 2154 | |
| 2155 | |
| 2156 | |
| 2157 | |
| 2158 | |
| 2159 | |
| 2160 | |
| 2161 | |
| 2162 | fn git_timestamp(now: SystemTime) -> String { |
| 2163 | let seconds = now |
| 2164 | .duration_since(SystemTime::UNIX_EPOCH) |
| 2165 | .map(|elapsed| elapsed.as_secs()) |
| 2166 | .unwrap_or(0); |
| 2167 | |
| 2168 | format!("@{seconds} +0000") |
| 2169 | } |
| 2170 | |
| 2171 | |
| 2172 | |
| 2173 | |
| 2174 | |
| 2175 | |
| 2176 | |
| 2177 | #[derive(Debug, Default, Clone)] |
| 2178 | pub struct InMemoryGitMerge { |
| 2179 | commits: Arc<Mutex<Vec<CommitTreeRequest>>>, |
| 2180 | updates: Arc<Mutex<Vec<RecordedRefUpdate>>>, |
| 2181 | |
| 2182 | written: Option<ObjectId>, |
| 2183 | |
| 2184 | stale: bool, |
| 2185 | } |
| 2186 | |
| 2187 | |
| 2188 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 2189 | pub struct RecordedRefUpdate { |
| 2190 | pub branch: RefName, |
| 2191 | pub new: Option<ObjectId>, |
| 2192 | pub old: ObjectId, |
| 2193 | } |
| 2194 | |
| 2195 | impl InMemoryGitMerge { |
| 2196 | pub fn new() -> Self { |
| 2197 | Self::default() |
| 2198 | } |
| 2199 | |
| 2200 | |
| 2201 | pub fn writing(id: &str) -> Self { |
| 2202 | Self { |
| 2203 | written: Some(ObjectId::from_trusted(format!("{id:0>40}"))), |
| 2204 | ..Self::default() |
| 2205 | } |
| 2206 | } |
| 2207 | |
| 2208 | |
| 2209 | pub fn stale() -> Self { |
| 2210 | Self { |
| 2211 | stale: true, |
| 2212 | ..Self::default() |
| 2213 | } |
| 2214 | } |
| 2215 | |
| 2216 | |
| 2217 | pub fn commits(&self) -> Vec<CommitTreeRequest> { |
| 2218 | self.commits.lock().expect("lock poisoned").clone() |
| 2219 | } |
| 2220 | |
| 2221 | |
| 2222 | pub fn updates(&self) -> Vec<RecordedRefUpdate> { |
| 2223 | self.updates.lock().expect("lock poisoned").clone() |
| 2224 | } |
| 2225 | } |
| 2226 | |
| 2227 | impl GitMerge for InMemoryGitMerge { |
| 2228 | async fn commit_tree( |
| 2229 | &self, |
| 2230 | _handle: &OrgName, |
| 2231 | _name: &RepoName, |
| 2232 | request: &CommitTreeRequest, |
| 2233 | ) -> Result<ObjectId, GitMergeError> { |
| 2234 | self.commits |
| 2235 | .lock() |
| 2236 | .expect("lock poisoned") |
| 2237 | .push(request.clone()); |
| 2238 | |
| 2239 | Ok(self |
| 2240 | .written |
| 2241 | .clone() |
| 2242 | .unwrap_or_else(|| ObjectId::from_trusted("c".repeat(40)))) |
| 2243 | } |
| 2244 | |
| 2245 | async fn update_ref( |
| 2246 | &self, |
| 2247 | _handle: &OrgName, |
| 2248 | _name: &RepoName, |
| 2249 | branch: &RefName, |
| 2250 | new: &ObjectId, |
| 2251 | old: &ObjectId, |
| 2252 | ) -> Result<(), GitMergeError> { |
| 2253 | if self.stale { |
| 2254 | return Err(GitMergeError::Stale); |
| 2255 | } |
| 2256 | |
| 2257 | self.updates |
| 2258 | .lock() |
| 2259 | .expect("lock poisoned") |
| 2260 | .push(RecordedRefUpdate { |
| 2261 | branch: branch.clone(), |
| 2262 | new: Some(new.clone()), |
| 2263 | old: old.clone(), |
| 2264 | }); |
| 2265 | |
| 2266 | Ok(()) |
| 2267 | } |
| 2268 | |
| 2269 | async fn delete_ref( |
| 2270 | &self, |
| 2271 | _handle: &OrgName, |
| 2272 | _name: &RepoName, |
| 2273 | branch: &RefName, |
| 2274 | old: &ObjectId, |
| 2275 | ) -> Result<(), GitMergeError> { |
| 2276 | if self.stale { |
| 2277 | return Err(GitMergeError::Stale); |
| 2278 | } |
| 2279 | |
| 2280 | self.updates |
| 2281 | .lock() |
| 2282 | .expect("lock poisoned") |
| 2283 | .push(RecordedRefUpdate { |
| 2284 | branch: branch.clone(), |
| 2285 | new: None, |
| 2286 | old: old.clone(), |
| 2287 | }); |
| 2288 | |
| 2289 | Ok(()) |
| 2290 | } |
| 2291 | } |
| 2292 | |
| 2293 | #[cfg(test)] |
| 2294 | mod tests { |
| 2295 | use std::path::Path; |
| 2296 | |
| 2297 | use tempfile::TempDir; |
| 2298 | |
| 2299 | use tokio::io::AsyncReadExt; |
| 2300 | |
| 2301 | use super::*; |
| 2302 | use crate::application::port::ArchiveFormat; |
| 2303 | |
| 2304 | |
| 2305 | |
| 2306 | fn storage() -> (TempDir, DiskGitStorage) { |
| 2307 | let dir = TempDir::new().expect("temp dir"); |
| 2308 | let storage = DiskGitStorage::new(dir.path()); |
| 2309 | (dir, storage) |
| 2310 | } |
| 2311 | |
| 2312 | fn handle() -> OrgName { |
| 2313 | OrgName::new("jamesgill").expect("valid handle") |
| 2314 | } |
| 2315 | |
| 2316 | fn repo_name(value: &str) -> RepoName { |
| 2317 | RepoName::new(value).expect("valid repository name") |
| 2318 | } |
| 2319 | |
| 2320 | |
| 2321 | |
| 2322 | fn git_says(path: &Path, args: &[&str]) -> String { |
| 2323 | let output = std::process::Command::new("git") |
| 2324 | .arg("-C") |
| 2325 | .arg(path) |
| 2326 | .args(args) |
| 2327 | .output() |
| 2328 | .expect("git should be on PATH"); |
| 2329 | |
| 2330 | assert!( |
| 2331 | output.status.success(), |
| 2332 | "git {args:?} failed: {}", |
| 2333 | String::from_utf8_lossy(&output.stderr) |
| 2334 | ); |
| 2335 | |
| 2336 | String::from_utf8_lossy(&output.stdout).trim().to_owned() |
| 2337 | } |
| 2338 | |
| 2339 | |
| 2340 | |
| 2341 | #[tokio::test] |
| 2342 | async fn every_repository_directory_is_listed_and_the_quarantine_is_not() { |
| 2343 | let (dir, storage) = storage(); |
| 2344 | let handle = handle(); |
| 2345 | |
| 2346 | for name in ["steid", "notes"] { |
| 2347 | storage |
| 2348 | .init_bare(&handle, &repo_name(name)) |
| 2349 | .await |
| 2350 | .expect("init bare"); |
| 2351 | } |
| 2352 | |
| 2353 | |
| 2354 | fs::create_dir_all(dir.path().join(handle.as_str()).join("scratch")) |
| 2355 | .await |
| 2356 | .expect("make a stray directory"); |
| 2357 | |
| 2358 | let mut listed = storage.list_repo_dirs().await.expect("should list"); |
| 2359 | listed.sort_by(|a, b| a.name.cmp(&b.name)); |
| 2360 | |
| 2361 | assert_eq!( |
| 2362 | listed |
| 2363 | .iter() |
| 2364 | .map(|found| (found.handle.as_str(), found.name.as_str())) |
| 2365 | .collect::<Vec<_>>(), |
| 2366 | vec![("jamesgill", "notes"), ("jamesgill", "steid")], |
| 2367 | "only `.git` directories, and the extension is stripped" |
| 2368 | ); |
| 2369 | assert!(listed[0].path.is_dir()); |
| 2370 | } |
| 2371 | |
| 2372 | #[tokio::test] |
| 2373 | async fn an_orphan_is_moved_aside_rather_than_deleted_and_frees_its_name() { |
| 2374 | let (dir, storage) = storage(); |
| 2375 | let handle = handle(); |
| 2376 | let name = repo_name("half-made"); |
| 2377 | |
| 2378 | storage.init_bare(&handle, &name).await.expect("init bare"); |
| 2379 | |
| 2380 | |
| 2381 | |
| 2382 | let marker = storage.repo_path(&handle, &name).join("HEAD"); |
| 2383 | assert!(marker.exists()); |
| 2384 | |
| 2385 | let found = storage.list_repo_dirs().await.expect("should list"); |
| 2386 | let moved = storage |
| 2387 | .quarantine(&found[0], "1757000000-half-made") |
| 2388 | .await |
| 2389 | .expect("should move it aside"); |
| 2390 | |
| 2391 | assert_eq!( |
| 2392 | moved, |
| 2393 | dir.path().join("orphaned").join("1757000000-half-made") |
| 2394 | ); |
| 2395 | assert!(moved.join("HEAD").exists(), "the objects came with it"); |
| 2396 | assert!(!storage.repo_path(&handle, &name).exists()); |
| 2397 | |
| 2398 | |
| 2399 | storage |
| 2400 | .init_bare(&handle, &name) |
| 2401 | .await |
| 2402 | .expect("the name is free"); |
| 2403 | |
| 2404 | |
| 2405 | assert_eq!( |
| 2406 | storage |
| 2407 | .list_repo_dirs() |
| 2408 | .await |
| 2409 | .expect("should list") |
| 2410 | .iter() |
| 2411 | .map(|found| found.name.clone()) |
| 2412 | .collect::<Vec<_>>(), |
| 2413 | vec!["half-made".to_owned()] |
| 2414 | ); |
| 2415 | } |
| 2416 | |
| 2417 | #[test] |
| 2418 | fn the_quarantine_directory_can_never_be_a_real_handle() { |
| 2419 | |
| 2420 | |
| 2421 | |
| 2422 | assert!( |
| 2423 | OrgName::new(QUARANTINE).is_err(), |
| 2424 | "{QUARANTINE} must stay a reserved handle" |
| 2425 | ); |
| 2426 | } |
| 2427 | |
| 2428 | #[tokio::test] |
| 2429 | async fn a_quarantine_never_overwrites_what_is_already_there() { |
| 2430 | let (dir, storage) = storage(); |
| 2431 | let handle = handle(); |
| 2432 | |
| 2433 | storage |
| 2434 | .init_bare(&handle, &repo_name("thing")) |
| 2435 | .await |
| 2436 | .expect("init bare"); |
| 2437 | |
| 2438 | fs::create_dir_all(dir.path().join("orphaned").join("1757000000-thing")) |
| 2439 | .await |
| 2440 | .expect("stage a collision"); |
| 2441 | |
| 2442 | let found = storage.list_repo_dirs().await.expect("should list"); |
| 2443 | |
| 2444 | assert!(matches!( |
| 2445 | storage.quarantine(&found[0], "1757000000-thing").await, |
| 2446 | Err(GitStorageError::AlreadyExists) |
| 2447 | )); |
| 2448 | assert!( |
| 2449 | storage.repo_path(&handle, &repo_name("thing")).exists(), |
| 2450 | "nothing was moved, so nothing was lost" |
| 2451 | ); |
| 2452 | } |
| 2453 | |
| 2454 | |
| 2455 | |
| 2456 | |
| 2457 | |
| 2458 | fn source_repo() -> (TempDir, PathBuf) { |
| 2459 | let dir = TempDir::new().expect("temp dir"); |
| 2460 | let path = dir.path().join("source"); |
| 2461 | |
| 2462 | std::fs::create_dir(&path).expect("create"); |
| 2463 | |
| 2464 | let run = |args: &[&str]| { |
| 2465 | let output = std::process::Command::new("git") |
| 2466 | .arg("-C") |
| 2467 | .arg(&path) |
| 2468 | .args(args) |
| 2469 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 2470 | .env("GIT_CONFIG_SYSTEM", "/dev/null") |
| 2471 | .env("GIT_AUTHOR_NAME", "Ada") |
| 2472 | .env("GIT_AUTHOR_EMAIL", "ada@example.com") |
| 2473 | .env("GIT_COMMITTER_NAME", "Ada") |
| 2474 | .env("GIT_COMMITTER_EMAIL", "ada@example.com") |
| 2475 | .output() |
| 2476 | .expect("git should be on PATH"); |
| 2477 | assert!( |
| 2478 | output.status.success(), |
| 2479 | "git {args:?} failed: {}", |
| 2480 | String::from_utf8_lossy(&output.stderr) |
| 2481 | ); |
| 2482 | }; |
| 2483 | |
| 2484 | run(&["init", "--quiet", "--initial-branch=main"]); |
| 2485 | std::fs::write(path.join("README.md"), "# source\n").expect("write"); |
| 2486 | run(&["add", "README.md"]); |
| 2487 | run(&["commit", "--quiet", "-m", "first"]); |
| 2488 | run(&["tag", "-a", "v0.1.0", "-m", "first"]); |
| 2489 | run(&["checkout", "--quiet", "-b", "side"]); |
| 2490 | std::fs::write(path.join("more.md"), "more\n").expect("write"); |
| 2491 | run(&["add", "more.md"]); |
| 2492 | run(&["commit", "--quiet", "-m", "second"]); |
| 2493 | run(&["checkout", "--quiet", "main"]); |
| 2494 | |
| 2495 | (dir, path) |
| 2496 | } |
| 2497 | |
| 2498 | |
| 2499 | |
| 2500 | |
| 2501 | |
| 2502 | |
| 2503 | |
| 2504 | #[tokio::test] |
| 2505 | async fn a_mirror_lands_as_an_ordinary_bare_repository() { |
| 2506 | let (_source_dir, source) = source_repo(); |
| 2507 | let (dest_dir, _storage) = storage(); |
| 2508 | let destination = dest_dir.path().join("mirrored.git"); |
| 2509 | |
| 2510 | run_import( |
| 2511 | [ |
| 2512 | OsStr::new("clone"), |
| 2513 | OsStr::new("--mirror"), |
| 2514 | OsStr::new("--quiet"), |
| 2515 | OsStr::new("--"), |
| 2516 | source.as_os_str(), |
| 2517 | destination.as_os_str(), |
| 2518 | ], |
| 2519 | None, |
| 2520 | ) |
| 2521 | .await |
| 2522 | .expect("the clone should succeed"); |
| 2523 | |
| 2524 | finish_mirror(&destination) |
| 2525 | .await |
| 2526 | .expect("the mirror should finish"); |
| 2527 | |
| 2528 | |
| 2529 | let branches = git_says( |
| 2530 | &destination, |
| 2531 | &["for-each-ref", "--format=%(refname)", "refs/heads/"], |
| 2532 | ); |
| 2533 | assert_eq!(branches, "refs/heads/main\nrefs/heads/side"); |
| 2534 | |
| 2535 | |
| 2536 | assert_eq!( |
| 2537 | git_says( |
| 2538 | &destination, |
| 2539 | &["for-each-ref", "--format=%(refname)", "refs/tags/"] |
| 2540 | ), |
| 2541 | "refs/tags/v0.1.0" |
| 2542 | ); |
| 2543 | |
| 2544 | |
| 2545 | assert_eq!( |
| 2546 | git_says( |
| 2547 | &destination, |
| 2548 | &["for-each-ref", "--format=%(refname)", "refs/remotes/"] |
| 2549 | ), |
| 2550 | "" |
| 2551 | ); |
| 2552 | assert_eq!(git_says(&destination, &["remote"]), ""); |
| 2553 | |
| 2554 | |
| 2555 | assert_eq!( |
| 2556 | git_says(&destination, &["symbolic-ref", "HEAD"]), |
| 2557 | "refs/heads/main" |
| 2558 | ); |
| 2559 | assert_eq!( |
| 2560 | git_says(&destination, &["rev-parse", "--is-bare-repository"]), |
| 2561 | "true" |
| 2562 | ); |
| 2563 | |
| 2564 | |
| 2565 | |
| 2566 | |
| 2567 | assert_eq!( |
| 2568 | git_says(&destination, &["config", "--get", "core.logAllRefUpdates"]), |
| 2569 | "true" |
| 2570 | ); |
| 2571 | } |
| 2572 | |
| 2573 | |
| 2574 | |
| 2575 | #[tokio::test] |
| 2576 | async fn branches_left_under_refs_remotes_are_moved_to_refs_heads() { |
| 2577 | let (_source_dir, source) = source_repo(); |
| 2578 | let (dest_dir, _storage) = storage(); |
| 2579 | let destination = dest_dir.path().join("remotes.git"); |
| 2580 | |
| 2581 | |
| 2582 | |
| 2583 | run_import( |
| 2584 | [ |
| 2585 | OsStr::new("clone"), |
| 2586 | OsStr::new("--bare"), |
| 2587 | OsStr::new("--quiet"), |
| 2588 | OsStr::new("--"), |
| 2589 | source.as_os_str(), |
| 2590 | destination.as_os_str(), |
| 2591 | ], |
| 2592 | None, |
| 2593 | ) |
| 2594 | .await |
| 2595 | .expect("clone"); |
| 2596 | |
| 2597 | |
| 2598 | run_import( |
| 2599 | [ |
| 2600 | OsStr::new("update-ref"), |
| 2601 | OsStr::new("refs/remotes/origin/side"), |
| 2602 | OsStr::new("refs/heads/main"), |
| 2603 | ], |
| 2604 | Some(&destination), |
| 2605 | ) |
| 2606 | .await |
| 2607 | .expect("stage a remote-tracking ref"); |
| 2608 | run_import( |
| 2609 | [ |
| 2610 | OsStr::new("symbolic-ref"), |
| 2611 | OsStr::new("refs/remotes/origin/HEAD"), |
| 2612 | OsStr::new("refs/remotes/origin/side"), |
| 2613 | ], |
| 2614 | Some(&destination), |
| 2615 | ) |
| 2616 | .await |
| 2617 | .expect("stage origin/HEAD"); |
| 2618 | |
| 2619 | finish_mirror(&destination).await.expect("finish"); |
| 2620 | |
| 2621 | let branches = git_says( |
| 2622 | &destination, |
| 2623 | &["for-each-ref", "--format=%(refname)", "refs/heads/"], |
| 2624 | ); |
| 2625 | assert!( |
| 2626 | branches.contains("refs/heads/side"), |
| 2627 | "expected the remote-tracking branch to become a branch, got {branches:?}" |
| 2628 | ); |
| 2629 | assert_eq!( |
| 2630 | git_says( |
| 2631 | &destination, |
| 2632 | &["for-each-ref", "--format=%(refname)", "refs/remotes/"] |
| 2633 | ), |
| 2634 | "", |
| 2635 | "origin/HEAD is a pointer, not a branch, and must not survive either" |
| 2636 | ); |
| 2637 | } |
| 2638 | |
| 2639 | |
| 2640 | |
| 2641 | #[tokio::test] |
| 2642 | async fn a_host_that_resolves_to_loopback_is_refused() { |
| 2643 | let error = resolve_public_host("localhost") |
| 2644 | .await |
| 2645 | .expect_err("localhost must never be dialled"); |
| 2646 | |
| 2647 | assert!( |
| 2648 | error.message().contains("not on the public internet"), |
| 2649 | "{error}" |
| 2650 | ); |
| 2651 | } |
| 2652 | |
| 2653 | #[tokio::test] |
| 2654 | async fn a_host_that_does_not_resolve_is_a_failed_import_not_a_panic() { |
| 2655 | let error = resolve_public_host("no-such-host.invalid") |
| 2656 | .await |
| 2657 | .expect_err("`.invalid` never resolves"); |
| 2658 | |
| 2659 | assert!(error.message().contains("no-such-host.invalid"), "{error}"); |
| 2660 | } |
| 2661 | |
| 2662 | |
| 2663 | #[tokio::test] |
| 2664 | async fn a_failed_git_command_carries_gits_own_last_word() { |
| 2665 | let (dir, _storage) = storage(); |
| 2666 | |
| 2667 | let error = run_import( |
| 2668 | [OsStr::new("rev-parse"), OsStr::new("HEAD")], |
| 2669 | Some(dir.path()), |
| 2670 | ) |
| 2671 | .await |
| 2672 | .expect_err("an empty directory is not a repository"); |
| 2673 | |
| 2674 | assert!( |
| 2675 | error.message().contains("not a git repository"), |
| 2676 | "expected git's own words, got {error}" |
| 2677 | ); |
| 2678 | } |
| 2679 | |
| 2680 | #[tokio::test] |
| 2681 | async fn an_import_refuses_a_path_that_is_already_occupied() { |
| 2682 | let (dir, storage) = storage(); |
| 2683 | let importer = DiskGitImport::new(dir.path()); |
| 2684 | |
| 2685 | storage |
| 2686 | .init_bare(&handle(), &repo_name("taken")) |
| 2687 | .await |
| 2688 | .expect("seed"); |
| 2689 | |
| 2690 | let error = importer |
| 2691 | .mirror( |
| 2692 | &handle(), |
| 2693 | &repo_name("taken"), |
| 2694 | &ImportSource::new("https://example.com/taken.git").expect("valid"), |
| 2695 | ) |
| 2696 | .await |
| 2697 | .expect_err("must not adopt what is already there"); |
| 2698 | |
| 2699 | assert!(error.message().contains("already on disk"), "{error}"); |
| 2700 | } |
| 2701 | |
| 2702 | #[tokio::test] |
| 2703 | async fn the_in_memory_importer_records_what_it_was_asked_for() { |
| 2704 | let importer = InMemoryGitImport::new(); |
| 2705 | let source = ImportSource::new("https://example.com/thing.git").expect("valid"); |
| 2706 | |
| 2707 | importer |
| 2708 | .mirror(&handle(), &repo_name("thing"), &source) |
| 2709 | .await |
| 2710 | .expect("succeeds"); |
| 2711 | |
| 2712 | assert_eq!( |
| 2713 | importer.requests(), |
| 2714 | vec![( |
| 2715 | "jamesgill".to_owned(), |
| 2716 | "thing".to_owned(), |
| 2717 | "https://example.com/thing.git".to_owned() |
| 2718 | )] |
| 2719 | ); |
| 2720 | } |
| 2721 | |
| 2722 | #[tokio::test] |
| 2723 | async fn a_created_repository_keeps_a_reflog() { |
| 2724 | |
| 2725 | |
| 2726 | let dir = TempDir::new().expect("temp dir"); |
| 2727 | let storage = DiskGitStorage::new(dir.path()); |
| 2728 | |
| 2729 | storage |
| 2730 | .init_bare(&handle(), &repo_name("steid")) |
| 2731 | .await |
| 2732 | .expect("should create"); |
| 2733 | |
| 2734 | let config = std::fs::read_to_string( |
| 2735 | storage |
| 2736 | .repo_path(&handle(), &repo_name("steid")) |
| 2737 | .join("config"), |
| 2738 | ) |
| 2739 | .expect("read config"); |
| 2740 | |
| 2741 | assert!( |
| 2742 | config.to_lowercase().contains("logallrefupdates = true"), |
| 2743 | "a bare repository needs reflogs turned on: {config}" |
| 2744 | ); |
| 2745 | } |
| 2746 | |
| 2747 | #[tokio::test] |
| 2748 | async fn the_boot_sweep_gives_an_older_repository_a_reflog() { |
| 2749 | |
| 2750 | |
| 2751 | |
| 2752 | let (_dir, storage) = storage(); |
| 2753 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 2754 | |
| 2755 | storage |
| 2756 | .init_bare(&handle(), &repo_name("steid")) |
| 2757 | .await |
| 2758 | .expect("should create"); |
| 2759 | |
| 2760 | git_command() |
| 2761 | .args([ |
| 2762 | OsStr::new("--git-dir"), |
| 2763 | path.as_os_str(), |
| 2764 | OsStr::new("config"), |
| 2765 | OsStr::new("--unset"), |
| 2766 | OsStr::new("core.logAllRefUpdates"), |
| 2767 | ]) |
| 2768 | .output() |
| 2769 | .await |
| 2770 | .expect("unset"); |
| 2771 | |
| 2772 | assert_eq!(storage.enable_reflogs().await.expect("should sweep"), 1); |
| 2773 | |
| 2774 | let config = std::fs::read_to_string(path.join("config")).expect("read config"); |
| 2775 | assert!( |
| 2776 | config.to_lowercase().contains("logallrefupdates = true"), |
| 2777 | "the sweep should have turned reflogs on: {config}" |
| 2778 | ); |
| 2779 | |
| 2780 | |
| 2781 | |
| 2782 | assert_eq!(storage.enable_reflogs().await.expect("should sweep"), 0); |
| 2783 | } |
| 2784 | |
| 2785 | #[tokio::test] |
| 2786 | async fn the_boot_sweep_leaves_a_deliberate_false_alone() { |
| 2787 | |
| 2788 | |
| 2789 | let (_dir, storage) = storage(); |
| 2790 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 2791 | |
| 2792 | storage |
| 2793 | .init_bare(&handle(), &repo_name("steid")) |
| 2794 | .await |
| 2795 | .expect("should create"); |
| 2796 | |
| 2797 | run_git([ |
| 2798 | OsStr::new("--git-dir"), |
| 2799 | path.as_os_str(), |
| 2800 | OsStr::new("config"), |
| 2801 | OsStr::new("core.logAllRefUpdates"), |
| 2802 | OsStr::new("false"), |
| 2803 | ]) |
| 2804 | .await |
| 2805 | .expect("set false"); |
| 2806 | |
| 2807 | assert_eq!(storage.enable_reflogs().await.expect("should sweep"), 0); |
| 2808 | |
| 2809 | let config = std::fs::read_to_string(path.join("config")).expect("read config"); |
| 2810 | assert!(config.to_lowercase().contains("logallrefupdates = false")); |
| 2811 | } |
| 2812 | |
| 2813 | #[tokio::test] |
| 2814 | async fn the_boot_sweep_ignores_what_is_not_a_repository() { |
| 2815 | |
| 2816 | |
| 2817 | let dir = TempDir::new().expect("temp dir"); |
| 2818 | let missing = DiskGitStorage::new(dir.path().join("not-created-yet")); |
| 2819 | |
| 2820 | assert_eq!(missing.enable_reflogs().await.expect("should sweep"), 0); |
| 2821 | |
| 2822 | let (_dir, storage) = storage(); |
| 2823 | std::fs::create_dir_all(dir.path().join("jamesgill")).expect("mkdir"); |
| 2824 | std::fs::write(dir.path().join("jamesgill").join("notes.txt"), b"hello").expect("write"); |
| 2825 | |
| 2826 | assert_eq!(storage.enable_reflogs().await.expect("should sweep"), 0); |
| 2827 | } |
| 2828 | |
| 2829 | #[tokio::test] |
| 2830 | async fn init_bare_creates_a_bare_repository() { |
| 2831 | let (_dir, storage) = storage(); |
| 2832 | |
| 2833 | storage |
| 2834 | .init_bare(&handle(), &repo_name("steid")) |
| 2835 | .await |
| 2836 | .expect("should create"); |
| 2837 | |
| 2838 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 2839 | assert!(path.is_dir(), "expected a repository at {path:?}"); |
| 2840 | assert_eq!( |
| 2841 | git_says(&path, &["rev-parse", "--is-bare-repository"]), |
| 2842 | "true" |
| 2843 | ); |
| 2844 | } |
| 2845 | |
| 2846 | #[tokio::test] |
| 2847 | async fn a_new_repository_is_empty() { |
| 2848 | |
| 2849 | let (_dir, storage) = storage(); |
| 2850 | storage |
| 2851 | .init_bare(&handle(), &repo_name("steid")) |
| 2852 | .await |
| 2853 | .expect("should create"); |
| 2854 | |
| 2855 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 2856 | |
| 2857 | assert_eq!(git_says(&path, &["for-each-ref"]), ""); |
| 2858 | } |
| 2859 | |
| 2860 | #[tokio::test] |
| 2861 | async fn a_new_repository_defaults_to_main() { |
| 2862 | |
| 2863 | |
| 2864 | let (_dir, storage) = storage(); |
| 2865 | storage |
| 2866 | .init_bare(&handle(), &repo_name("steid")) |
| 2867 | .await |
| 2868 | .expect("should create"); |
| 2869 | |
| 2870 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 2871 | |
| 2872 | assert_eq!( |
| 2873 | git_says(&path, &["symbolic-ref", "HEAD"]), |
| 2874 | "refs/heads/main" |
| 2875 | ); |
| 2876 | } |
| 2877 | |
| 2878 | #[tokio::test] |
| 2879 | async fn no_sample_hooks_are_installed() { |
| 2880 | |
| 2881 | let (_dir, storage) = storage(); |
| 2882 | storage |
| 2883 | .init_bare(&handle(), &repo_name("steid")) |
| 2884 | .await |
| 2885 | .expect("should create"); |
| 2886 | |
| 2887 | let hooks = storage |
| 2888 | .repo_path(&handle(), &repo_name("steid")) |
| 2889 | .join("hooks"); |
| 2890 | |
| 2891 | let samples = std::fs::read_dir(&hooks) |
| 2892 | .map(|entries| entries.count()) |
| 2893 | .unwrap_or(0); |
| 2894 | assert_eq!(samples, 0, "expected no templated hooks in {hooks:?}"); |
| 2895 | } |
| 2896 | |
| 2897 | #[tokio::test] |
| 2898 | async fn init_bare_creates_the_handle_directory() { |
| 2899 | let (dir, storage) = storage(); |
| 2900 | assert!(!dir.path().join("jamesgill").exists()); |
| 2901 | |
| 2902 | storage |
| 2903 | .init_bare(&handle(), &repo_name("steid")) |
| 2904 | .await |
| 2905 | .expect("should create"); |
| 2906 | |
| 2907 | assert!(dir.path().join("jamesgill").is_dir()); |
| 2908 | } |
| 2909 | |
| 2910 | #[tokio::test] |
| 2911 | async fn one_handle_can_own_several_repositories() { |
| 2912 | let (_dir, storage) = storage(); |
| 2913 | |
| 2914 | for name in ["steid", "foo.js", ".github"] { |
| 2915 | storage |
| 2916 | .init_bare(&handle(), &repo_name(name)) |
| 2917 | .await |
| 2918 | .unwrap_or_else(|error| panic!("{name} should create: {error}")); |
| 2919 | } |
| 2920 | |
| 2921 | for name in ["steid", "foo.js", ".github"] { |
| 2922 | assert!(storage.repo_path(&handle(), &repo_name(name)).is_dir()); |
| 2923 | } |
| 2924 | } |
| 2925 | |
| 2926 | #[tokio::test] |
| 2927 | async fn init_bare_refuses_a_repository_that_already_exists() { |
| 2928 | let (_dir, storage) = storage(); |
| 2929 | storage |
| 2930 | .init_bare(&handle(), &repo_name("steid")) |
| 2931 | .await |
| 2932 | .expect("should create"); |
| 2933 | |
| 2934 | let error = storage |
| 2935 | .init_bare(&handle(), &repo_name("steid")) |
| 2936 | .await |
| 2937 | .expect_err("should refuse"); |
| 2938 | |
| 2939 | assert!(matches!(error, GitStorageError::AlreadyExists)); |
| 2940 | } |
| 2941 | |
| 2942 | #[tokio::test] |
| 2943 | async fn a_refused_init_leaves_the_existing_repository_alone() { |
| 2944 | |
| 2945 | |
| 2946 | let (_dir, storage) = storage(); |
| 2947 | storage |
| 2948 | .init_bare(&handle(), &repo_name("steid")) |
| 2949 | .await |
| 2950 | .expect("should create"); |
| 2951 | |
| 2952 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 2953 | let marker = path.join("objects").join("marker"); |
| 2954 | std::fs::write(&marker, b"existing data").expect("write marker"); |
| 2955 | |
| 2956 | let _ = storage.init_bare(&handle(), &repo_name("steid")).await; |
| 2957 | |
| 2958 | assert_eq!( |
| 2959 | std::fs::read(&marker).expect("marker should survive"), |
| 2960 | b"existing data" |
| 2961 | ); |
| 2962 | } |
| 2963 | |
| 2964 | #[tokio::test] |
| 2965 | async fn repo_path_creates_nothing() { |
| 2966 | let (dir, storage) = storage(); |
| 2967 | |
| 2968 | let path = storage.repo_path(&handle(), &repo_name("never-created")); |
| 2969 | |
| 2970 | assert!(!path.exists()); |
| 2971 | assert_eq!( |
| 2972 | std::fs::read_dir(dir.path()) |
| 2973 | .expect("data dir should exist") |
| 2974 | .count(), |
| 2975 | 0, |
| 2976 | "repo_path must be pure" |
| 2977 | ); |
| 2978 | } |
| 2979 | |
| 2980 | #[tokio::test] |
| 2981 | async fn repo_path_lands_under_the_data_directory() { |
| 2982 | let (dir, storage) = storage(); |
| 2983 | |
| 2984 | let path = storage.repo_path(&handle(), &repo_name("steid")); |
| 2985 | |
| 2986 | assert_eq!(path, dir.path().join("jamesgill").join("steid.git")); |
| 2987 | } |
| 2988 | |
| 2989 | #[tokio::test] |
| 2990 | async fn remove_deletes_the_repository() { |
| 2991 | let (_dir, storage) = storage(); |
| 2992 | storage |
| 2993 | .init_bare(&handle(), &repo_name("steid")) |
| 2994 | .await |
| 2995 | .expect("should create"); |
| 2996 | |
| 2997 | storage |
| 2998 | .remove(&handle(), &repo_name("steid")) |
| 2999 | .await |
| 3000 | .expect("should remove"); |
| 3001 | |
| 3002 | assert!(!storage.repo_path(&handle(), &repo_name("steid")).exists()); |
| 3003 | } |
| 3004 | |
| 3005 | #[tokio::test] |
| 3006 | async fn removing_what_is_not_there_succeeds() { |
| 3007 | |
| 3008 | let (_dir, storage) = storage(); |
| 3009 | |
| 3010 | storage |
| 3011 | .remove(&handle(), &repo_name("never-created")) |
| 3012 | .await |
| 3013 | .expect("should succeed with nothing to do"); |
| 3014 | } |
| 3015 | |
| 3016 | #[tokio::test] |
| 3017 | async fn a_compensated_create_can_be_retried() { |
| 3018 | |
| 3019 | let (_dir, storage) = storage(); |
| 3020 | |
| 3021 | storage |
| 3022 | .init_bare(&handle(), &repo_name("steid")) |
| 3023 | .await |
| 3024 | .expect("should create"); |
| 3025 | storage |
| 3026 | .remove(&handle(), &repo_name("steid")) |
| 3027 | .await |
| 3028 | .expect("should remove"); |
| 3029 | storage |
| 3030 | .init_bare(&handle(), &repo_name("steid")) |
| 3031 | .await |
| 3032 | .expect("should create again"); |
| 3033 | } |
| 3034 | |
| 3035 | #[tokio::test] |
| 3036 | async fn removing_one_repository_leaves_its_neighbours() { |
| 3037 | let (_dir, storage) = storage(); |
| 3038 | storage |
| 3039 | .init_bare(&handle(), &repo_name("steid")) |
| 3040 | .await |
| 3041 | .expect("should create"); |
| 3042 | storage |
| 3043 | .init_bare(&handle(), &repo_name("keeper")) |
| 3044 | .await |
| 3045 | .expect("should create"); |
| 3046 | |
| 3047 | storage |
| 3048 | .remove(&handle(), &repo_name("steid")) |
| 3049 | .await |
| 3050 | .expect("should remove"); |
| 3051 | |
| 3052 | assert!(storage.repo_path(&handle(), &repo_name("keeper")).is_dir()); |
| 3053 | } |
| 3054 | |
| 3055 | #[tokio::test] |
| 3056 | async fn a_failing_git_invocation_carries_gits_own_message() { |
| 3057 | let error = run_git(["not-a-real-subcommand"]) |
| 3058 | .await |
| 3059 | .expect_err("should fail"); |
| 3060 | |
| 3061 | let message = error.to_string(); |
| 3062 | assert!( |
| 3063 | message.contains("not-a-real-subcommand"), |
| 3064 | "expected git's own words, got: {message}" |
| 3065 | ); |
| 3066 | } |
| 3067 | |
| 3068 | |
| 3069 | |
| 3070 | |
| 3071 | async fn backend() -> (TempDir, GitHttpBackend) { |
| 3072 | let dir = TempDir::new().expect("temp dir"); |
| 3073 | let storage = DiskGitStorage::new(dir.path()); |
| 3074 | |
| 3075 | let acme = OrgName::new("acme").expect("valid handle"); |
| 3076 | storage |
| 3077 | .init_bare(&acme, &repo_name("steid")) |
| 3078 | .await |
| 3079 | .expect("init bare"); |
| 3080 | |
| 3081 | let backend = GitHttpBackend::new(dir.path()); |
| 3082 | (dir, backend) |
| 3083 | } |
| 3084 | |
| 3085 | fn advertisement(path_info: &str) -> GitRequest { |
| 3086 | GitRequest { |
| 3087 | method: GitMethod::Get, |
| 3088 | path_info: path_info.to_owned(), |
| 3089 | query: "service=git-upload-pack".to_owned(), |
| 3090 | content_type: None, |
| 3091 | content_encoding: None, |
| 3092 | content_length: None, |
| 3093 | git_protocol: None, |
| 3094 | allow_receive_pack: false, |
| 3095 | remote_user: None, |
| 3096 | body: Box::pin(tokio::io::empty()), |
| 3097 | } |
| 3098 | } |
| 3099 | |
| 3100 | async fn drain(response: GitResponse) -> Vec<u8> { |
| 3101 | let mut body = response.body; |
| 3102 | let mut bytes = Vec::new(); |
| 3103 | body.read_to_end(&mut bytes).await.expect("read body"); |
| 3104 | bytes |
| 3105 | } |
| 3106 | |
| 3107 | #[tokio::test] |
| 3108 | async fn the_backend_advertises_refs() { |
| 3109 | let (_dir, backend) = backend().await; |
| 3110 | |
| 3111 | let response = backend |
| 3112 | .serve(advertisement("/acme/steid.git/info/refs")) |
| 3113 | .await |
| 3114 | .expect("should serve"); |
| 3115 | |
| 3116 | assert_eq!(response.status, 200); |
| 3117 | assert!( |
| 3118 | response |
| 3119 | .headers |
| 3120 | .iter() |
| 3121 | .any(|(name, value)| name == "Content-Type" |
| 3122 | && value == "application/x-git-upload-pack-advertisement"), |
| 3123 | "git sets its own content type and we forward it: {:?}", |
| 3124 | response.headers |
| 3125 | ); |
| 3126 | |
| 3127 | |
| 3128 | |
| 3129 | let body = drain(response).await; |
| 3130 | assert!( |
| 3131 | body.starts_with(b"001e# service=git-upload-pack\n"), |
| 3132 | "unexpected advertisement: {:?}", |
| 3133 | String::from_utf8_lossy(&body[..body.len().min(40)]) |
| 3134 | ); |
| 3135 | } |
| 3136 | |
| 3137 | #[tokio::test] |
| 3138 | async fn a_missing_repository_is_reported_as_404_not_as_a_failure() { |
| 3139 | |
| 3140 | |
| 3141 | let (_dir, backend) = backend().await; |
| 3142 | |
| 3143 | let response = backend |
| 3144 | .serve(advertisement("/acme/nothing-here.git/info/refs")) |
| 3145 | .await |
| 3146 | .expect("serving should not itself fail"); |
| 3147 | |
| 3148 | assert_eq!(response.status, 404); |
| 3149 | } |
| 3150 | |
| 3151 | #[tokio::test] |
| 3152 | async fn the_status_header_is_translated_rather_than_forwarded() { |
| 3153 | let (_dir, backend) = backend().await; |
| 3154 | |
| 3155 | let response = backend |
| 3156 | .serve(advertisement("/acme/nothing-here.git/info/refs")) |
| 3157 | .await |
| 3158 | .expect("should serve"); |
| 3159 | |
| 3160 | assert!( |
| 3161 | !response |
| 3162 | .headers |
| 3163 | .iter() |
| 3164 | .any(|(name, _)| name.eq_ignore_ascii_case("status")), |
| 3165 | "Status: is CGI's, and means nothing to an HTTP client: {:?}", |
| 3166 | response.headers |
| 3167 | ); |
| 3168 | } |
| 3169 | |
| 3170 | #[tokio::test] |
| 3171 | async fn the_protocol_version_reaches_upload_pack() { |
| 3172 | |
| 3173 | |
| 3174 | |
| 3175 | let (_dir, backend) = backend().await; |
| 3176 | |
| 3177 | let mut request = advertisement("/acme/steid.git/info/refs"); |
| 3178 | request.git_protocol = Some("version=2".to_owned()); |
| 3179 | |
| 3180 | let body = drain(backend.serve(request).await.expect("should serve")).await; |
| 3181 | |
| 3182 | assert!( |
| 3183 | String::from_utf8_lossy(&body).contains("version 2"), |
| 3184 | "expected a v2 capability advertisement: {:?}", |
| 3185 | String::from_utf8_lossy(&body[..body.len().min(80)]) |
| 3186 | ); |
| 3187 | } |
| 3188 | |
| 3189 | #[tokio::test] |
| 3190 | async fn the_in_memory_protocol_records_what_it_was_asked() { |
| 3191 | let protocol = InMemoryGitProtocol::new(); |
| 3192 | |
| 3193 | protocol |
| 3194 | .serve(advertisement("/acme/steid.git/info/refs")) |
| 3195 | .await |
| 3196 | .expect("should serve"); |
| 3197 | |
| 3198 | assert_eq!( |
| 3199 | protocol.requests(), |
| 3200 | vec![RecordedGitRequest { |
| 3201 | method: GitMethod::Get, |
| 3202 | path_info: "/acme/steid.git/info/refs".to_owned(), |
| 3203 | query: "service=git-upload-pack".to_owned(), |
| 3204 | git_protocol: None, |
| 3205 | content_encoding: None, |
| 3206 | allow_receive_pack: false, |
| 3207 | remote_user: None, |
| 3208 | }] |
| 3209 | ); |
| 3210 | assert!(protocol.was_called()); |
| 3211 | } |
| 3212 | |
| 3213 | |
| 3214 | |
| 3215 | |
| 3216 | |
| 3217 | |
| 3218 | |
| 3219 | fn archivable() -> (TempDir, DiskGitArchive, ObjectId) { |
| 3220 | let dir = TempDir::new().expect("temp dir"); |
| 3221 | let storage = DiskGitStorage::new(dir.path()); |
| 3222 | let repo = storage.repo_path(&handle(), &repo_name("steid")); |
| 3223 | let work = dir.path().join("work"); |
| 3224 | |
| 3225 | let git = |at: &Path, args: &[&str]| { |
| 3226 | let output = std::process::Command::new("git") |
| 3227 | .arg("-C") |
| 3228 | .arg(at) |
| 3229 | .args(args) |
| 3230 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 3231 | .env("GIT_CONFIG_SYSTEM", "/dev/null") |
| 3232 | .env("GIT_AUTHOR_NAME", "Ada Lovelace") |
| 3233 | .env("GIT_AUTHOR_EMAIL", "ada@example.com") |
| 3234 | .env("GIT_COMMITTER_NAME", "Ada Lovelace") |
| 3235 | .env("GIT_COMMITTER_EMAIL", "ada@example.com") |
| 3236 | .output() |
| 3237 | .expect("git should be on PATH"); |
| 3238 | |
| 3239 | assert!( |
| 3240 | output.status.success(), |
| 3241 | "git {args:?} failed: {}", |
| 3242 | String::from_utf8_lossy(&output.stderr) |
| 3243 | ); |
| 3244 | |
| 3245 | String::from_utf8_lossy(&output.stdout).trim().to_owned() |
| 3246 | }; |
| 3247 | |
| 3248 | std::fs::create_dir_all(&work).expect("create work tree"); |
| 3249 | git( |
| 3250 | dir.path(), |
| 3251 | &[ |
| 3252 | "init", |
| 3253 | "--bare", |
| 3254 | "--quiet", |
| 3255 | "--template=", |
| 3256 | "--initial-branch=main", |
| 3257 | "--", |
| 3258 | repo.to_str().expect("utf-8 fixture path"), |
| 3259 | ], |
| 3260 | ); |
| 3261 | git(&work, &["init", "--quiet", "-b", "main"]); |
| 3262 | std::fs::write(work.join("README.md"), b"hello\n").expect("write"); |
| 3263 | git(&work, &["add", "-A"]); |
| 3264 | git(&work, &["commit", "--quiet", "-m", "first"]); |
| 3265 | git( |
| 3266 | &work, |
| 3267 | &["push", "--quiet", repo.to_str().expect("utf-8"), "main"], |
| 3268 | ); |
| 3269 | |
| 3270 | let head = git(&repo, &["rev-parse", "main"]); |
| 3271 | let archives = DiskGitArchive::new(dir.path()); |
| 3272 | |
| 3273 | ( |
| 3274 | dir, |
| 3275 | archives, |
| 3276 | ObjectId::new(head).expect("a real object id"), |
| 3277 | ) |
| 3278 | } |
| 3279 | |
| 3280 | async fn packed(format: ArchiveFormat) -> Vec<u8> { |
| 3281 | let (dir, archives, commit) = archivable(); |
| 3282 | |
| 3283 | let mut stream = archives |
| 3284 | .archive(ArchiveRequest { |
| 3285 | handle: handle(), |
| 3286 | name: repo_name("steid"), |
| 3287 | format, |
| 3288 | commit, |
| 3289 | prefix: "steid-main/".to_owned(), |
| 3290 | }) |
| 3291 | .await |
| 3292 | .expect("should pack"); |
| 3293 | |
| 3294 | let mut bytes = Vec::new(); |
| 3295 | stream.read_to_end(&mut bytes).await.expect("should stream"); |
| 3296 | |
| 3297 | |
| 3298 | |
| 3299 | drop(dir); |
| 3300 | |
| 3301 | bytes |
| 3302 | } |
| 3303 | |
| 3304 | #[tokio::test] |
| 3305 | async fn a_tarball_carries_the_prefix_directory() { |
| 3306 | let bytes = packed(ArchiveFormat::TarGz).await; |
| 3307 | |
| 3308 | |
| 3309 | |
| 3310 | assert_eq!(&bytes[..2], &[0x1f, 0x8b], "expected gzip"); |
| 3311 | assert!(bytes.len() > 100, "expected a real archive"); |
| 3312 | } |
| 3313 | |
| 3314 | #[tokio::test] |
| 3315 | async fn a_zip_is_a_zip() { |
| 3316 | let bytes = packed(ArchiveFormat::Zip).await; |
| 3317 | |
| 3318 | assert_eq!(&bytes[..2], b"PK", "expected a zip"); |
| 3319 | |
| 3320 | |
| 3321 | assert!( |
| 3322 | bytes.windows(11).any(|window| window == b"steid-main/"), |
| 3323 | "expected the prefix directory in the archive" |
| 3324 | ); |
| 3325 | } |
| 3326 | |
| 3327 | |
| 3328 | |
| 3329 | |
| 3330 | |
| 3331 | |
| 3332 | |
| 3333 | |
| 3334 | fn mergeable() -> (TempDir, DiskGitMerge, PathBuf) { |
| 3335 | let dir = TempDir::new().expect("temp dir"); |
| 3336 | let repo = dir.path().join("jamesgill").join("steid.git"); |
| 3337 | let work = dir.path().join("work"); |
| 3338 | |
| 3339 | let git = |path: &Path, args: &[&str]| -> String { |
| 3340 | let output = std::process::Command::new("git") |
| 3341 | .arg("-C") |
| 3342 | .arg(path) |
| 3343 | .args(args) |
| 3344 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 3345 | .env("GIT_CONFIG_SYSTEM", "/dev/null") |
| 3346 | .env("GIT_AUTHOR_NAME", "Ada Lovelace") |
| 3347 | .env("GIT_AUTHOR_EMAIL", "ada@example.com") |
| 3348 | .env("GIT_COMMITTER_NAME", "Ada Lovelace") |
| 3349 | .env("GIT_COMMITTER_EMAIL", "ada@example.com") |
| 3350 | .output() |
| 3351 | .expect("git should be on PATH"); |
| 3352 | |
| 3353 | assert!( |
| 3354 | output.status.success(), |
| 3355 | "git {args:?} failed: {}", |
| 3356 | String::from_utf8_lossy(&output.stderr) |
| 3357 | ); |
| 3358 | |
| 3359 | String::from_utf8_lossy(&output.stdout).trim().to_owned() |
| 3360 | }; |
| 3361 | |
| 3362 | std::fs::create_dir_all(&work).expect("create work tree"); |
| 3363 | git( |
| 3364 | dir.path(), |
| 3365 | &[ |
| 3366 | "init", |
| 3367 | "--bare", |
| 3368 | "--quiet", |
| 3369 | "--template=", |
| 3370 | "--initial-branch=main", |
| 3371 | "--", |
| 3372 | repo.to_str().expect("utf-8 fixture path"), |
| 3373 | ], |
| 3374 | ); |
| 3375 | |
| 3376 | git(&work, &["init", "--quiet", "-b", "main"]); |
| 3377 | std::fs::write(work.join("README.md"), b"hello\n").expect("write"); |
| 3378 | git(&work, &["add", "-A"]); |
| 3379 | git(&work, &["commit", "--quiet", "-m", "first"]); |
| 3380 | |
| 3381 | git(&work, &["checkout", "--quiet", "-b", "tidy"]); |
| 3382 | std::fs::write(work.join("other.txt"), b"tidy\n").expect("write"); |
| 3383 | git(&work, &["add", "-A"]); |
| 3384 | git(&work, &["commit", "--quiet", "-m", "tidy"]); |
| 3385 | |
| 3386 | git( |
| 3387 | &work, |
| 3388 | &[ |
| 3389 | "push", |
| 3390 | "--quiet", |
| 3391 | repo.to_str().expect("utf-8"), |
| 3392 | "main", |
| 3393 | "tidy", |
| 3394 | ], |
| 3395 | ); |
| 3396 | |
| 3397 | let merges = DiskGitMerge::new(dir.path()); |
| 3398 | |
| 3399 | (dir, merges, repo) |
| 3400 | } |
| 3401 | |
| 3402 | |
| 3403 | fn head(repo: &Path, revision: &str) -> ObjectId { |
| 3404 | ObjectId::new(git_says(repo, &["rev-parse", revision])).expect("a real object id") |
| 3405 | } |
| 3406 | |
| 3407 | #[tokio::test] |
| 3408 | async fn a_merge_commit_carries_both_parents_and_the_person_who_pressed_merge() { |
| 3409 | let (_dir, merges, repo) = mergeable(); |
| 3410 | let main = head(&repo, "main"); |
| 3411 | let tidy = head(&repo, "tidy"); |
| 3412 | let tree = ObjectId::new(git_says(&repo, &["rev-parse", "tidy^{tree}"])).expect("a tree"); |
| 3413 | |
| 3414 | let commit = merges |
| 3415 | .commit_tree( |
| 3416 | &handle(), |
| 3417 | &repo_name("steid"), |
| 3418 | &CommitTreeRequest { |
| 3419 | tree, |
| 3420 | parents: vec![main.clone(), tidy.clone()], |
| 3421 | message: "Merge pull request #7 from tidy\n\nTidy things up.".to_owned(), |
| 3422 | author_name: "Ada Lovelace".to_owned(), |
| 3423 | author_email: "ada@example.com".to_owned(), |
| 3424 | now: SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000), |
| 3425 | }, |
| 3426 | ) |
| 3427 | .await |
| 3428 | .expect("should write a commit"); |
| 3429 | |
| 3430 | |
| 3431 | assert_eq!( |
| 3432 | git_says( |
| 3433 | &repo, |
| 3434 | &["rev-list", "--parents", "-n", "1", commit.as_str()] |
| 3435 | ), |
| 3436 | format!("{commit} {main} {tidy}") |
| 3437 | ); |
| 3438 | assert_eq!( |
| 3439 | git_says( |
| 3440 | &repo, |
| 3441 | &["log", "-1", "--format=%an <%ae> %at", commit.as_str()] |
| 3442 | ), |
| 3443 | "Ada Lovelace <ada@example.com> 1700000000", |
| 3444 | "the caller's `now` decides the commit's date, not git's clock" |
| 3445 | ); |
| 3446 | |
| 3447 | assert_eq!(git_says(&repo, &["rev-parse", "main"]), main.as_str()); |
| 3448 | } |
| 3449 | |
| 3450 | #[tokio::test] |
| 3451 | async fn a_squash_commit_has_one_parent() { |
| 3452 | let (_dir, merges, repo) = mergeable(); |
| 3453 | let main = head(&repo, "main"); |
| 3454 | let tree = ObjectId::new(git_says(&repo, &["rev-parse", "tidy^{tree}"])).expect("a tree"); |
| 3455 | |
| 3456 | let commit = merges |
| 3457 | .commit_tree( |
| 3458 | &handle(), |
| 3459 | &repo_name("steid"), |
| 3460 | &CommitTreeRequest { |
| 3461 | tree, |
| 3462 | parents: vec![main.clone()], |
| 3463 | message: "Tidy things up (#7)".to_owned(), |
| 3464 | author_name: "Ada Lovelace".to_owned(), |
| 3465 | author_email: "ada@example.com".to_owned(), |
| 3466 | now: SystemTime::UNIX_EPOCH, |
| 3467 | }, |
| 3468 | ) |
| 3469 | .await |
| 3470 | .expect("should write a commit"); |
| 3471 | |
| 3472 | assert_eq!( |
| 3473 | git_says( |
| 3474 | &repo, |
| 3475 | &["rev-list", "--parents", "-n", "1", commit.as_str()] |
| 3476 | ), |
| 3477 | format!("{commit} {main}") |
| 3478 | ); |
| 3479 | } |
| 3480 | |
| 3481 | #[tokio::test] |
| 3482 | async fn moving_a_branch_from_where_it_is_moves_it() { |
| 3483 | let (_dir, merges, repo) = mergeable(); |
| 3484 | let main = head(&repo, "main"); |
| 3485 | let tidy = head(&repo, "tidy"); |
| 3486 | |
| 3487 | merges |
| 3488 | .update_ref( |
| 3489 | &handle(), |
| 3490 | &repo_name("steid"), |
| 3491 | &RefName::from_trusted("main"), |
| 3492 | &tidy, |
| 3493 | &main, |
| 3494 | ) |
| 3495 | .await |
| 3496 | .expect("should move the branch"); |
| 3497 | |
| 3498 | assert_eq!(git_says(&repo, &["rev-parse", "main"]), tidy.as_str()); |
| 3499 | } |
| 3500 | |
| 3501 | #[tokio::test] |
| 3502 | async fn moving_a_branch_from_where_it_is_not_changes_nothing() { |
| 3503 | |
| 3504 | |
| 3505 | let (_dir, merges, repo) = mergeable(); |
| 3506 | let main = head(&repo, "main"); |
| 3507 | let tidy = head(&repo, "tidy"); |
| 3508 | |
| 3509 | let error = merges |
| 3510 | .update_ref( |
| 3511 | &handle(), |
| 3512 | &repo_name("steid"), |
| 3513 | &RefName::from_trusted("main"), |
| 3514 | &main, |
| 3515 | &tidy, |
| 3516 | ) |
| 3517 | .await |
| 3518 | .expect_err("expected the guard to refuse"); |
| 3519 | |
| 3520 | assert!(error.is_stale(), "expected staleness, got {error:?}"); |
| 3521 | assert_eq!(git_says(&repo, &["rev-parse", "main"]), main.as_str()); |
| 3522 | } |
| 3523 | |
| 3524 | #[tokio::test] |
| 3525 | async fn deleting_a_branch_is_guarded_the_same_way() { |
| 3526 | let (_dir, merges, repo) = mergeable(); |
| 3527 | let main = head(&repo, "main"); |
| 3528 | let tidy = head(&repo, "tidy"); |
| 3529 | |
| 3530 | let refused = merges |
| 3531 | .delete_ref( |
| 3532 | &handle(), |
| 3533 | &repo_name("steid"), |
| 3534 | &RefName::from_trusted("tidy"), |
| 3535 | &main, |
| 3536 | ) |
| 3537 | .await |
| 3538 | .expect_err("expected the guard to refuse"); |
| 3539 | assert!(refused.is_stale(), "expected staleness, got {refused:?}"); |
| 3540 | |
| 3541 | merges |
| 3542 | .delete_ref( |
| 3543 | &handle(), |
| 3544 | &repo_name("steid"), |
| 3545 | &RefName::from_trusted("tidy"), |
| 3546 | &tidy, |
| 3547 | ) |
| 3548 | .await |
| 3549 | .expect("should delete the branch"); |
| 3550 | |
| 3551 | assert_eq!( |
| 3552 | git_says( |
| 3553 | &repo, |
| 3554 | &["for-each-ref", "--format=%(refname)", "refs/heads/"] |
| 3555 | ), |
| 3556 | "refs/heads/main" |
| 3557 | ); |
| 3558 | } |
| 3559 | |
| 3560 | |
| 3561 | |
| 3562 | #[test] |
| 3563 | fn a_version_reads_as_major_and_minor() { |
| 3564 | assert_eq!(parse_git_version("git version 2.47.1\n"), Some((2, 47))); |
| 3565 | |
| 3566 | assert_eq!( |
| 3567 | parse_git_version("git version 2.39.5 (Apple Git-154)\n"), |
| 3568 | Some((2, 39)) |
| 3569 | ); |
| 3570 | assert_eq!(parse_git_version(""), None); |
| 3571 | assert_eq!(parse_git_version("git version banana"), None); |
| 3572 | } |
| 3573 | |
| 3574 | #[tokio::test] |
| 3575 | async fn this_machine_reports_what_its_git_can_do() { |
| 3576 | |
| 3577 | |
| 3578 | let features = GitFeatures::detect().await; |
| 3579 | |
| 3580 | assert_eq!( |
| 3581 | features.merge_tree, |
| 3582 | parse_git_version(&git_says(Path::new("."), &["--version"])) |
| 3583 | .is_some_and(|version| version >= MERGE_TREE_SINCE) |
| 3584 | ); |
| 3585 | } |
| 3586 | } |