| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | use std::{ |
| 51 | collections::HashMap, |
| 52 | ffi::OsStr, |
| 53 | path::{Path, PathBuf}, |
| 54 | process::{Output, Stdio}, |
| 55 | sync::Arc, |
| 56 | time::{Duration, SystemTime, UNIX_EPOCH}, |
| 57 | }; |
| 58 | |
| 59 | use tokio::io::AsyncReadExt; |
| 60 | |
| 61 | use crate::{ |
| 62 | application::{ |
| 63 | blame::{Blame, parse_blame}, |
| 64 | port::{Blob, CommitCount, GitQuery, GitQueryError, MergePreview, RawDiff}, |
| 65 | search::parse_grep_output, |
| 66 | }, |
| 67 | domain::{ |
| 68 | BranchRow, CommitDetail, CommitEntry, CommitSummary, EntryCommit, EntryKind, GitRef, |
| 69 | GrepHit, ObjectId, OrgName, RefName, RepoName, RepoPath, TagRow, TagSummary, TreeEntry, |
| 70 | }, |
| 71 | infrastructure::{ |
| 72 | cat_file::{CatFilePool, ObjectInfo, ObjectKind}, |
| 73 | git::{count_spawn, git_command}, |
| 74 | merge_cache::MergeCache, |
| 75 | }, |
| 76 | }; |
| 77 | |
| 78 | mod parse_diff; |
| 79 | mod parse_log; |
| 80 | mod parse_refs; |
| 81 | mod parse_tree; |
| 82 | |
| 83 | use parse_diff::{parse_merge_tree, split_numstat}; |
| 84 | use parse_log::{ENTRY_FORMAT, LOG_FORMAT, parse_commit_object, parse_log, parse_log_entries}; |
| 85 | use parse_refs::{ |
| 86 | BRANCH_FORMAT, REF_FORMAT, SNAPSHOT_FORMAT, TAG_FORMAT, TAG_ROW_FORMAT, parse_branches, |
| 87 | parse_latest_tag, parse_ref_snapshot, parse_refs, parse_tags, |
| 88 | }; |
| 89 | use parse_tree::{LAST_COMMIT_FORMAT, attribute, parse_tree_object, tree_spec}; |
| 90 | |
| 91 | mod in_memory; |
| 92 | |
| 93 | pub use in_memory::InMemoryGitQuery; |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | #[derive(Debug, Clone)] |
| 104 | pub struct DiskGitQuery { |
| 105 | data_dir: PathBuf, |
| 106 | pool: Arc<CatFilePool>, |
| 107 | |
| 108 | |
| 109 | merges: Arc<MergeCache>, |
| 110 | } |
| 111 | |
| 112 | impl DiskGitQuery { |
| 113 | pub fn new( |
| 114 | data_dir: impl Into<PathBuf>, |
| 115 | pool: Arc<CatFilePool>, |
| 116 | merges: Arc<MergeCache>, |
| 117 | ) -> Self { |
| 118 | Self { |
| 119 | data_dir: data_dir.into(), |
| 120 | pool, |
| 121 | merges, |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | async fn commit_info( |
| 135 | &self, |
| 136 | repo: &Path, |
| 137 | rev: &RefName, |
| 138 | ) -> Result<Option<ObjectInfo>, GitQueryError> { |
| 139 | self.pool |
| 140 | .info(repo, &format!("{}^{{commit}}", rev.as_str())) |
| 141 | .await |
| 142 | } |
| 143 | |
| 144 | |
| 145 | pub(crate) fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf { |
| 146 | self.data_dir |
| 147 | .join(handle.as_str()) |
| 148 | .join(format!("{name}.git")) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | impl GitQuery for DiskGitQuery { |
| 153 | async fn default_branch( |
| 154 | &self, |
| 155 | handle: &OrgName, |
| 156 | name: &RepoName, |
| 157 | ) -> Result<Option<RefName>, GitQueryError> { |
| 158 | let repo = self.repo_path(handle, name); |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | let Some(head) = self.pool.info(&repo, "HEAD").await? else { |
| 164 | return Ok(None); |
| 165 | }; |
| 166 | |
| 167 | let branch = run(&repo, [OsStr::new("symbolic-ref"), OsStr::new("HEAD")]).await; |
| 168 | |
| 169 | match branch { |
| 170 | Ok(output) => { |
| 171 | let full = String::from_utf8_lossy(&output.stdout).trim().to_owned(); |
| 172 | |
| 173 | |
| 174 | |
| 175 | let short = full.strip_prefix("refs/heads/").unwrap_or(&full); |
| 176 | |
| 177 | Ok(Some(RefName::from_trusted(short))) |
| 178 | } |
| 179 | |
| 180 | |
| 181 | |
| 182 | |
| 183 | Err(_) => Ok(Some(RefName::from_trusted(head.id.as_str()))), |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | async fn resolve( |
| 188 | &self, |
| 189 | handle: &OrgName, |
| 190 | name: &RepoName, |
| 191 | rev: &RefName, |
| 192 | ) -> Result<Option<ObjectId>, GitQueryError> { |
| 193 | let repo = self.repo_path(handle, name); |
| 194 | |
| 195 | Ok(self.commit_info(&repo, rev).await?.map(|info| info.id)) |
| 196 | } |
| 197 | |
| 198 | async fn list_tree( |
| 199 | &self, |
| 200 | handle: &OrgName, |
| 201 | name: &RepoName, |
| 202 | rev: &RefName, |
| 203 | path: &RepoPath, |
| 204 | ) -> Result<Option<Vec<TreeEntry>>, GitQueryError> { |
| 205 | let repo = self.repo_path(handle, name); |
| 206 | |
| 207 | let Some(info) = self.pool.info(&repo, &tree_spec(rev, path)).await? else { |
| 208 | return Ok(None); |
| 209 | }; |
| 210 | |
| 211 | |
| 212 | |
| 213 | if info.kind != ObjectKind::Tree { |
| 214 | return Ok(None); |
| 215 | } |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | let mut entries = parse_tree_object(&self.pool.contents(&repo, &info).await?)?; |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | let sized: Vec<usize> = entries |
| 227 | .iter() |
| 228 | .enumerate() |
| 229 | .filter(|(_, entry)| matches!(entry.kind, EntryKind::Blob | EntryKind::Symlink)) |
| 230 | .map(|(index, _)| index) |
| 231 | .collect(); |
| 232 | |
| 233 | let specs: Vec<String> = sized |
| 234 | .iter() |
| 235 | .map(|index| entries[*index].id.as_str().to_owned()) |
| 236 | .collect(); |
| 237 | |
| 238 | for (index, size) in sized.iter().zip(self.pool.info_many(&repo, &specs).await?) { |
| 239 | entries[*index].size = size.map(|size| size.size); |
| 240 | } |
| 241 | |
| 242 | Ok(Some(entries)) |
| 243 | } |
| 244 | |
| 245 | async fn last_commits( |
| 246 | &self, |
| 247 | handle: &OrgName, |
| 248 | name: &RepoName, |
| 249 | rev: &RefName, |
| 250 | path: &RepoPath, |
| 251 | entries: &[String], |
| 252 | ) -> Result<HashMap<String, EntryCommit>, GitQueryError> { |
| 253 | let repo = self.repo_path(handle, name); |
| 254 | |
| 255 | if entries.is_empty() { |
| 256 | return Ok(HashMap::new()); |
| 257 | } |
| 258 | |
| 259 | |
| 260 | |
| 261 | let Some(info) = self.commit_info(&repo, rev).await? else { |
| 262 | return Ok(HashMap::new()); |
| 263 | }; |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | let count = format!("--max-count={LAST_COMMIT_SCAN}"); |
| 270 | |
| 271 | let mut args: Vec<&OsStr> = vec![ |
| 272 | OsStr::new("log"), |
| 273 | OsStr::new(LAST_COMMIT_FORMAT), |
| 274 | OsStr::new("--name-only"), |
| 275 | OsStr::new("-z"), |
| 276 | OsStr::new(&count), |
| 277 | OsStr::new(info.id.as_str()), |
| 278 | ]; |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | let prefix = if path.is_root() { |
| 284 | String::new() |
| 285 | } else { |
| 286 | args.push(OsStr::new("--")); |
| 287 | args.push(OsStr::new(path.as_str())); |
| 288 | |
| 289 | format!("{}/", path.as_str()) |
| 290 | }; |
| 291 | |
| 292 | let output = run(&repo, args).await?; |
| 293 | |
| 294 | Ok(attribute(&output.stdout, &prefix, entries)) |
| 295 | } |
| 296 | |
| 297 | async fn read_blob( |
| 298 | &self, |
| 299 | handle: &OrgName, |
| 300 | name: &RepoName, |
| 301 | rev: &RefName, |
| 302 | path: &RepoPath, |
| 303 | max_bytes: u64, |
| 304 | ) -> Result<Option<Blob>, GitQueryError> { |
| 305 | let repo = self.repo_path(handle, name); |
| 306 | |
| 307 | |
| 308 | |
| 309 | if path.is_root() { |
| 310 | return Ok(None); |
| 311 | } |
| 312 | |
| 313 | let Some(info) = self.pool.info(&repo, &tree_spec(rev, path)).await? else { |
| 314 | return Ok(None); |
| 315 | }; |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | if info.kind != ObjectKind::Blob { |
| 321 | return Ok(None); |
| 322 | } |
| 323 | |
| 324 | |
| 325 | |
| 326 | |
| 327 | let content = if info.size > max_bytes { |
| 328 | None |
| 329 | } else { |
| 330 | Some(self.pool.contents(&repo, &info).await?) |
| 331 | }; |
| 332 | |
| 333 | Ok(Some(Blob { |
| 334 | id: info.id, |
| 335 | size: info.size, |
| 336 | content, |
| 337 | })) |
| 338 | } |
| 339 | |
| 340 | async fn log( |
| 341 | &self, |
| 342 | handle: &OrgName, |
| 343 | name: &RepoName, |
| 344 | rev: &RefName, |
| 345 | offset: usize, |
| 346 | limit: usize, |
| 347 | ) -> Result<Vec<CommitSummary>, GitQueryError> { |
| 348 | let repo = self.repo_path(handle, name); |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | let Some(info) = self.commit_info(&repo, rev).await? else { |
| 355 | return Ok(Vec::new()); |
| 356 | }; |
| 357 | |
| 358 | |
| 359 | |
| 360 | |
| 361 | |
| 362 | |
| 363 | if offset == 0 && limit == 1 { |
| 364 | let detail = parse_commit_object(&info.id, &self.pool.contents(&repo, &info).await?)?; |
| 365 | |
| 366 | return Ok(vec![CommitSummary { |
| 367 | id: detail.id, |
| 368 | summary: detail.summary, |
| 369 | author_name: detail.author_name, |
| 370 | committed_at: detail.committed_at, |
| 371 | }]); |
| 372 | } |
| 373 | |
| 374 | let commit = info.id; |
| 375 | |
| 376 | if limit == 0 { |
| 377 | return Ok(Vec::new()); |
| 378 | } |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 384 | |
| 385 | |
| 386 | let count = format!("--max-count={limit}"); |
| 387 | let skip = format!("--skip={offset}"); |
| 388 | |
| 389 | let output = run( |
| 390 | &repo, |
| 391 | [ |
| 392 | OsStr::new("log"), |
| 393 | OsStr::new("-z"), |
| 394 | OsStr::new(&count), |
| 395 | OsStr::new(&skip), |
| 396 | OsStr::new(LOG_FORMAT), |
| 397 | OsStr::new(commit.as_str()), |
| 398 | ], |
| 399 | ) |
| 400 | .await?; |
| 401 | |
| 402 | parse_log(&output.stdout) |
| 403 | } |
| 404 | |
| 405 | async fn log_entries( |
| 406 | &self, |
| 407 | handle: &OrgName, |
| 408 | name: &RepoName, |
| 409 | rev: &RefName, |
| 410 | limit: usize, |
| 411 | ) -> Result<Vec<CommitEntry>, GitQueryError> { |
| 412 | let repo = self.repo_path(handle, name); |
| 413 | |
| 414 | |
| 415 | |
| 416 | let Some(commit) = self.resolve(handle, name, rev).await? else { |
| 417 | return Ok(Vec::new()); |
| 418 | }; |
| 419 | |
| 420 | if limit == 0 { |
| 421 | return Ok(Vec::new()); |
| 422 | } |
| 423 | |
| 424 | let count = format!("--max-count={limit}"); |
| 425 | |
| 426 | let output = run( |
| 427 | &repo, |
| 428 | [ |
| 429 | OsStr::new("log"), |
| 430 | OsStr::new("-z"), |
| 431 | OsStr::new(&count), |
| 432 | OsStr::new(ENTRY_FORMAT), |
| 433 | OsStr::new(commit.as_str()), |
| 434 | ], |
| 435 | ) |
| 436 | .await?; |
| 437 | |
| 438 | parse_log_entries(&output.stdout) |
| 439 | } |
| 440 | |
| 441 | async fn list_refs( |
| 442 | &self, |
| 443 | handle: &OrgName, |
| 444 | name: &RepoName, |
| 445 | ) -> Result<Vec<GitRef>, GitQueryError> { |
| 446 | let repo = self.repo_path(handle, name); |
| 447 | |
| 448 | |
| 449 | |
| 450 | |
| 451 | |
| 452 | |
| 453 | |
| 454 | |
| 455 | |
| 456 | let output = run( |
| 457 | &repo, |
| 458 | [ |
| 459 | OsStr::new("for-each-ref"), |
| 460 | OsStr::new(REF_FORMAT), |
| 461 | OsStr::new("refs/heads/"), |
| 462 | OsStr::new("refs/tags/"), |
| 463 | ], |
| 464 | ) |
| 465 | .await?; |
| 466 | |
| 467 | Ok(parse_refs(&output.stdout)) |
| 468 | } |
| 469 | |
| 470 | async fn count_commits( |
| 471 | &self, |
| 472 | handle: &OrgName, |
| 473 | name: &RepoName, |
| 474 | rev: &RefName, |
| 475 | ) -> Result<u64, GitQueryError> { |
| 476 | let repo = self.repo_path(handle, name); |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 481 | |
| 482 | |
| 483 | |
| 484 | let Some(commit) = self.resolve(handle, name, rev).await? else { |
| 485 | return Ok(0); |
| 486 | }; |
| 487 | |
| 488 | let output = run( |
| 489 | &repo, |
| 490 | [ |
| 491 | OsStr::new("rev-list"), |
| 492 | OsStr::new("--count"), |
| 493 | OsStr::new(commit.as_str()), |
| 494 | ], |
| 495 | ) |
| 496 | .await?; |
| 497 | |
| 498 | let count = String::from_utf8_lossy(&output.stdout); |
| 499 | let count = count.trim(); |
| 500 | |
| 501 | count.parse().map_err(|_| { |
| 502 | GitQueryError::new(format!( |
| 503 | "git counted commits as {count:?}, which is not a number" |
| 504 | )) |
| 505 | }) |
| 506 | } |
| 507 | |
| 508 | async fn latest_tag( |
| 509 | &self, |
| 510 | handle: &OrgName, |
| 511 | name: &RepoName, |
| 512 | ) -> Result<Option<TagSummary>, GitQueryError> { |
| 513 | let repo = self.repo_path(handle, name); |
| 514 | |
| 515 | |
| 516 | |
| 517 | |
| 518 | let output = run( |
| 519 | &repo, |
| 520 | [ |
| 521 | OsStr::new("for-each-ref"), |
| 522 | OsStr::new("--sort=-creatordate"), |
| 523 | OsStr::new("--count=1"), |
| 524 | OsStr::new(TAG_FORMAT), |
| 525 | OsStr::new("refs/tags/"), |
| 526 | ], |
| 527 | ) |
| 528 | .await?; |
| 529 | |
| 530 | Ok(parse_latest_tag(&output.stdout)) |
| 531 | } |
| 532 | |
| 533 | async fn branches( |
| 534 | &self, |
| 535 | handle: &OrgName, |
| 536 | name: &RepoName, |
| 537 | ) -> Result<Vec<BranchRow>, GitQueryError> { |
| 538 | let repo = self.repo_path(handle, name); |
| 539 | |
| 540 | |
| 541 | |
| 542 | |
| 543 | |
| 544 | let output = run( |
| 545 | &repo, |
| 546 | [ |
| 547 | OsStr::new("for-each-ref"), |
| 548 | OsStr::new("--sort=-committerdate"), |
| 549 | OsStr::new(BRANCH_FORMAT), |
| 550 | OsStr::new("refs/heads/"), |
| 551 | ], |
| 552 | ) |
| 553 | .await?; |
| 554 | |
| 555 | parse_branches(&output.stdout) |
| 556 | } |
| 557 | |
| 558 | async fn tags(&self, handle: &OrgName, name: &RepoName) -> Result<Vec<TagRow>, GitQueryError> { |
| 559 | let repo = self.repo_path(handle, name); |
| 560 | |
| 561 | let output = run( |
| 562 | &repo, |
| 563 | [ |
| 564 | OsStr::new("for-each-ref"), |
| 565 | OsStr::new("--sort=-creatordate"), |
| 566 | OsStr::new(TAG_ROW_FORMAT), |
| 567 | OsStr::new("refs/tags/"), |
| 568 | ], |
| 569 | ) |
| 570 | .await?; |
| 571 | |
| 572 | parse_tags(&output.stdout) |
| 573 | } |
| 574 | |
| 575 | async fn grep( |
| 576 | &self, |
| 577 | handle: &OrgName, |
| 578 | name: &RepoName, |
| 579 | commit: &ObjectId, |
| 580 | query: &str, |
| 581 | limit: usize, |
| 582 | ) -> Result<Vec<GrepHit>, GitQueryError> { |
| 583 | let repo = self.repo_path(handle, name); |
| 584 | |
| 585 | |
| 586 | |
| 587 | |
| 588 | |
| 589 | |
| 590 | |
| 591 | |
| 592 | |
| 593 | |
| 594 | |
| 595 | |
| 596 | |
| 597 | |
| 598 | |
| 599 | |
| 600 | |
| 601 | |
| 602 | |
| 603 | |
| 604 | |
| 605 | let (stdout, _truncated) = run_capped_allowing( |
| 606 | &repo, |
| 607 | [ |
| 608 | OsStr::new("grep"), |
| 609 | OsStr::new("-I"), |
| 610 | OsStr::new("-n"), |
| 611 | OsStr::new("-z"), |
| 612 | OsStr::new("-F"), |
| 613 | OsStr::new("--column"), |
| 614 | OsStr::new("--no-color"), |
| 615 | OsStr::new("-e"), |
| 616 | OsStr::new(query), |
| 617 | OsStr::new(commit.as_str()), |
| 618 | OsStr::new("--"), |
| 619 | ], |
| 620 | MAX_GREP_BYTES, |
| 621 | &[NO_MATCHES], |
| 622 | ) |
| 623 | .await?; |
| 624 | |
| 625 | Ok(parse_grep_output(&stdout, commit, limit)) |
| 626 | } |
| 627 | |
| 628 | async fn commit( |
| 629 | &self, |
| 630 | handle: &OrgName, |
| 631 | name: &RepoName, |
| 632 | rev: &RefName, |
| 633 | ) -> Result<Option<CommitDetail>, GitQueryError> { |
| 634 | let repo = self.repo_path(handle, name); |
| 635 | |
| 636 | |
| 637 | |
| 638 | |
| 639 | |
| 640 | |
| 641 | |
| 642 | |
| 643 | |
| 644 | let Some(info) = self.commit_info(&repo, rev).await? else { |
| 645 | return Ok(None); |
| 646 | }; |
| 647 | |
| 648 | parse_commit_object(&info.id, &self.pool.contents(&repo, &info).await?).map(Some) |
| 649 | } |
| 650 | |
| 651 | async fn diff( |
| 652 | &self, |
| 653 | handle: &OrgName, |
| 654 | name: &RepoName, |
| 655 | base: Option<&ObjectId>, |
| 656 | head: &ObjectId, |
| 657 | max_bytes: u64, |
| 658 | ) -> Result<RawDiff, GitQueryError> { |
| 659 | let repo = self.repo_path(handle, name); |
| 660 | |
| 661 | |
| 662 | |
| 663 | |
| 664 | |
| 665 | |
| 666 | |
| 667 | |
| 668 | |
| 669 | |
| 670 | |
| 671 | |
| 672 | |
| 673 | |
| 674 | let mut args: Vec<&OsStr> = vec![ |
| 675 | OsStr::new("diff-tree"), |
| 676 | OsStr::new("--no-commit-id"), |
| 677 | OsStr::new("-p"), |
| 678 | OsStr::new("-M"), |
| 679 | OsStr::new("--numstat"), |
| 680 | OsStr::new("--no-color"), |
| 681 | ]; |
| 682 | |
| 683 | match base { |
| 684 | Some(base) => { |
| 685 | args.push(OsStr::new(base.as_str())); |
| 686 | } |
| 687 | None => args.push(OsStr::new("--root")), |
| 688 | } |
| 689 | |
| 690 | args.push(OsStr::new(head.as_str())); |
| 691 | |
| 692 | let (stdout, truncated) = run_capped(&repo, args, max_bytes).await?; |
| 693 | let (numstat, patch) = split_numstat(&stdout); |
| 694 | |
| 695 | Ok(RawDiff { |
| 696 | numstat: numstat.to_vec(), |
| 697 | patch: patch.to_vec(), |
| 698 | truncated, |
| 699 | }) |
| 700 | } |
| 701 | |
| 702 | async fn merge_base( |
| 703 | &self, |
| 704 | handle: &OrgName, |
| 705 | name: &RepoName, |
| 706 | base: &ObjectId, |
| 707 | head: &ObjectId, |
| 708 | ) -> Result<Option<ObjectId>, GitQueryError> { |
| 709 | let repo = self.repo_path(handle, name); |
| 710 | |
| 711 | |
| 712 | |
| 713 | |
| 714 | |
| 715 | |
| 716 | |
| 717 | |
| 718 | let output = run_allowing( |
| 719 | &repo, |
| 720 | [ |
| 721 | OsStr::new("merge-base"), |
| 722 | OsStr::new(base.as_str()), |
| 723 | OsStr::new(head.as_str()), |
| 724 | ], |
| 725 | &[NO_COMMON_ANCESTOR], |
| 726 | ) |
| 727 | .await?; |
| 728 | |
| 729 | let id = String::from_utf8_lossy(&output.stdout); |
| 730 | let id = id.trim(); |
| 731 | |
| 732 | if id.is_empty() { |
| 733 | return Ok(None); |
| 734 | } |
| 735 | |
| 736 | Ok(Some(ObjectId::new(id).map_err(|error| { |
| 737 | GitQueryError::new(format!("git named a bad merge base: {error}")) |
| 738 | })?)) |
| 739 | } |
| 740 | |
| 741 | async fn log_between( |
| 742 | &self, |
| 743 | handle: &OrgName, |
| 744 | name: &RepoName, |
| 745 | base: Option<&ObjectId>, |
| 746 | head: &ObjectId, |
| 747 | offset: usize, |
| 748 | limit: usize, |
| 749 | ) -> Result<Vec<CommitSummary>, GitQueryError> { |
| 750 | let repo = self.repo_path(handle, name); |
| 751 | |
| 752 | if limit == 0 { |
| 753 | return Ok(Vec::new()); |
| 754 | } |
| 755 | |
| 756 | |
| 757 | |
| 758 | |
| 759 | let range = match base { |
| 760 | Some(base) => format!("{}..{}", base.as_str(), head.as_str()), |
| 761 | None => head.as_str().to_owned(), |
| 762 | }; |
| 763 | let count = format!("--max-count={limit}"); |
| 764 | let skip = format!("--skip={offset}"); |
| 765 | |
| 766 | let output = run( |
| 767 | &repo, |
| 768 | [ |
| 769 | OsStr::new("log"), |
| 770 | OsStr::new("-z"), |
| 771 | OsStr::new(&count), |
| 772 | OsStr::new(&skip), |
| 773 | OsStr::new(LOG_FORMAT), |
| 774 | OsStr::new(&range), |
| 775 | ], |
| 776 | ) |
| 777 | .await?; |
| 778 | |
| 779 | parse_log(&output.stdout) |
| 780 | } |
| 781 | |
| 782 | async fn count_between( |
| 783 | &self, |
| 784 | handle: &OrgName, |
| 785 | name: &RepoName, |
| 786 | base: Option<&ObjectId>, |
| 787 | head: &ObjectId, |
| 788 | ) -> Result<usize, GitQueryError> { |
| 789 | let repo = self.repo_path(handle, name); |
| 790 | |
| 791 | |
| 792 | |
| 793 | let range = match base { |
| 794 | Some(base) => format!("{}..{}", base.as_str(), head.as_str()), |
| 795 | None => head.as_str().to_owned(), |
| 796 | }; |
| 797 | |
| 798 | let output = run( |
| 799 | &repo, |
| 800 | [ |
| 801 | OsStr::new("rev-list"), |
| 802 | OsStr::new("--count"), |
| 803 | OsStr::new(&range), |
| 804 | ], |
| 805 | ) |
| 806 | .await?; |
| 807 | |
| 808 | let count = String::from_utf8_lossy(&output.stdout); |
| 809 | let count = count.trim(); |
| 810 | |
| 811 | count.parse().map_err(|_| { |
| 812 | GitQueryError::new(format!( |
| 813 | "git counted commits as {count:?}, which is not a number" |
| 814 | )) |
| 815 | }) |
| 816 | } |
| 817 | |
| 818 | async fn blame( |
| 819 | &self, |
| 820 | handle: &OrgName, |
| 821 | name: &RepoName, |
| 822 | rev: &RefName, |
| 823 | path: &RepoPath, |
| 824 | ) -> Result<Option<Blame>, GitQueryError> { |
| 825 | let repo = self.repo_path(handle, name); |
| 826 | |
| 827 | |
| 828 | |
| 829 | |
| 830 | |
| 831 | let Some(info) = self.pool.info(&repo, &tree_spec(rev, path)).await? else { |
| 832 | return Ok(None); |
| 833 | }; |
| 834 | |
| 835 | |
| 836 | if info.kind != ObjectKind::Blob { |
| 837 | return Ok(None); |
| 838 | } |
| 839 | |
| 840 | |
| 841 | |
| 842 | |
| 843 | |
| 844 | let output = run( |
| 845 | &repo, |
| 846 | [ |
| 847 | OsStr::new("blame"), |
| 848 | OsStr::new("--porcelain"), |
| 849 | OsStr::new(rev.as_str()), |
| 850 | OsStr::new("--"), |
| 851 | OsStr::new(path.as_str()), |
| 852 | ], |
| 853 | ) |
| 854 | .await?; |
| 855 | |
| 856 | Ok(Some(parse_blame(&output.stdout))) |
| 857 | } |
| 858 | |
| 859 | async fn ref_snapshot( |
| 860 | &self, |
| 861 | handle: &OrgName, |
| 862 | name: &RepoName, |
| 863 | ) -> Result<Vec<(RefName, ObjectId)>, GitQueryError> { |
| 864 | let repo = self.repo_path(handle, name); |
| 865 | |
| 866 | |
| 867 | |
| 868 | |
| 869 | |
| 870 | let output = run( |
| 871 | &repo, |
| 872 | [ |
| 873 | OsStr::new("for-each-ref"), |
| 874 | OsStr::new(SNAPSHOT_FORMAT), |
| 875 | OsStr::new("refs/"), |
| 876 | ], |
| 877 | ) |
| 878 | .await?; |
| 879 | |
| 880 | Ok(parse_ref_snapshot(&output.stdout)) |
| 881 | } |
| 882 | |
| 883 | async fn log_at_path( |
| 884 | &self, |
| 885 | handle: &OrgName, |
| 886 | name: &RepoName, |
| 887 | rev: &RefName, |
| 888 | path: &RepoPath, |
| 889 | follow: bool, |
| 890 | offset: usize, |
| 891 | limit: usize, |
| 892 | ) -> Result<Vec<CommitSummary>, GitQueryError> { |
| 893 | let repo = self.repo_path(handle, name); |
| 894 | |
| 895 | |
| 896 | |
| 897 | let Some(info) = self.commit_info(&repo, rev).await? else { |
| 898 | return Ok(Vec::new()); |
| 899 | }; |
| 900 | |
| 901 | if limit == 0 { |
| 902 | return Ok(Vec::new()); |
| 903 | } |
| 904 | |
| 905 | let count = format!("--max-count={limit}"); |
| 906 | let skip = format!("--skip={offset}"); |
| 907 | let mut args: Vec<&OsStr> = vec![ |
| 908 | OsStr::new("log"), |
| 909 | OsStr::new("-z"), |
| 910 | OsStr::new(&count), |
| 911 | OsStr::new(&skip), |
| 912 | OsStr::new(LOG_FORMAT), |
| 913 | ]; |
| 914 | |
| 915 | |
| 916 | |
| 917 | |
| 918 | if follow { |
| 919 | args.push(OsStr::new("--follow")); |
| 920 | } |
| 921 | |
| 922 | args.push(OsStr::new(info.id.as_str())); |
| 923 | |
| 924 | |
| 925 | |
| 926 | args.push(OsStr::new("--")); |
| 927 | args.push(OsStr::new(path.as_str())); |
| 928 | |
| 929 | let output = run(&repo, args).await?; |
| 930 | |
| 931 | parse_log(&output.stdout) |
| 932 | } |
| 933 | |
| 934 | async fn count_commits_at_path( |
| 935 | &self, |
| 936 | handle: &OrgName, |
| 937 | name: &RepoName, |
| 938 | rev: &RefName, |
| 939 | path: &RepoPath, |
| 940 | follow: bool, |
| 941 | ) -> Result<CommitCount, GitQueryError> { |
| 942 | let repo = self.repo_path(handle, name); |
| 943 | |
| 944 | let Some(info) = self.commit_info(&repo, rev).await? else { |
| 945 | return Ok(CommitCount::default()); |
| 946 | }; |
| 947 | |
| 948 | |
| 949 | |
| 950 | let scan = format!("-n{}", FOLLOWED_LOG_SCAN + 1); |
| 951 | |
| 952 | |
| 953 | |
| 954 | |
| 955 | |
| 956 | let mut args: Vec<&OsStr> = if follow { |
| 957 | vec![ |
| 958 | OsStr::new("log"), |
| 959 | OsStr::new("--follow"), |
| 960 | OsStr::new("--format=%H"), |
| 961 | OsStr::new(&scan), |
| 962 | ] |
| 963 | } else { |
| 964 | vec![OsStr::new("rev-list"), OsStr::new("--count")] |
| 965 | }; |
| 966 | |
| 967 | args.push(OsStr::new(info.id.as_str())); |
| 968 | args.push(OsStr::new("--")); |
| 969 | args.push(OsStr::new(path.as_str())); |
| 970 | |
| 971 | let output = run(&repo, args).await?; |
| 972 | |
| 973 | if follow { |
| 974 | let counted = output.stdout.iter().filter(|byte| **byte == b'\n').count(); |
| 975 | |
| 976 | return Ok(CommitCount { |
| 977 | total: counted.min(FOLLOWED_LOG_SCAN) as u64, |
| 978 | capped: counted > FOLLOWED_LOG_SCAN, |
| 979 | }); |
| 980 | } |
| 981 | |
| 982 | let count = String::from_utf8_lossy(&output.stdout); |
| 983 | let count = count.trim(); |
| 984 | |
| 985 | Ok(CommitCount { |
| 986 | total: count.parse().map_err(|_| { |
| 987 | GitQueryError::new(format!( |
| 988 | "git counted commits as {count:?}, which is not a number" |
| 989 | )) |
| 990 | })?, |
| 991 | capped: false, |
| 992 | }) |
| 993 | } |
| 994 | |
| 995 | async fn symlink_targets( |
| 996 | &self, |
| 997 | handle: &OrgName, |
| 998 | name: &RepoName, |
| 999 | ids: &[ObjectId], |
| 1000 | ) -> Result<HashMap<ObjectId, String>, GitQueryError> { |
| 1001 | let repo = self.repo_path(handle, name); |
| 1002 | let mut targets = HashMap::new(); |
| 1003 | |
| 1004 | if ids.is_empty() { |
| 1005 | return Ok(targets); |
| 1006 | } |
| 1007 | |
| 1008 | |
| 1009 | |
| 1010 | |
| 1011 | let specs: Vec<String> = ids.iter().map(|id| id.as_str().to_owned()).collect(); |
| 1012 | |
| 1013 | for info in self |
| 1014 | .pool |
| 1015 | .info_many(&repo, &specs) |
| 1016 | .await? |
| 1017 | .into_iter() |
| 1018 | .flatten() |
| 1019 | { |
| 1020 | if info.kind != ObjectKind::Blob { |
| 1021 | continue; |
| 1022 | } |
| 1023 | |
| 1024 | let bytes = self.pool.contents(&repo, &info).await?; |
| 1025 | |
| 1026 | |
| 1027 | |
| 1028 | if let Ok(target) = String::from_utf8(bytes) { |
| 1029 | targets.insert(info.id, target); |
| 1030 | } |
| 1031 | } |
| 1032 | |
| 1033 | Ok(targets) |
| 1034 | } |
| 1035 | |
| 1036 | async fn merge_preview( |
| 1037 | &self, |
| 1038 | handle: &OrgName, |
| 1039 | name: &RepoName, |
| 1040 | target: &ObjectId, |
| 1041 | source: &ObjectId, |
| 1042 | ) -> Result<MergePreview, GitQueryError> { |
| 1043 | |
| 1044 | |
| 1045 | |
| 1046 | |
| 1047 | if let Some(cached) = self.merges.get(target, source) { |
| 1048 | return Ok(cached); |
| 1049 | } |
| 1050 | |
| 1051 | let repo = self.repo_path(handle, name); |
| 1052 | |
| 1053 | |
| 1054 | |
| 1055 | |
| 1056 | |
| 1057 | |
| 1058 | |
| 1059 | |
| 1060 | |
| 1061 | let output = run_allowing( |
| 1062 | &repo, |
| 1063 | [ |
| 1064 | OsStr::new("merge-tree"), |
| 1065 | OsStr::new("--write-tree"), |
| 1066 | OsStr::new(target.as_str()), |
| 1067 | OsStr::new(source.as_str()), |
| 1068 | ], |
| 1069 | &[MERGE_CONFLICTED], |
| 1070 | ) |
| 1071 | .await?; |
| 1072 | |
| 1073 | let preview = parse_merge_tree( |
| 1074 | &output.stdout, |
| 1075 | output.status.code() == Some(MERGE_CONFLICTED), |
| 1076 | )?; |
| 1077 | |
| 1078 | self.merges.put(target, source, preview.clone()); |
| 1079 | |
| 1080 | Ok(preview) |
| 1081 | } |
| 1082 | } |
| 1083 | |
| 1084 | |
| 1085 | |
| 1086 | |
| 1087 | |
| 1088 | |
| 1089 | |
| 1090 | |
| 1091 | |
| 1092 | const LAST_COMMIT_SCAN: usize = 500; |
| 1093 | |
| 1094 | |
| 1095 | |
| 1096 | |
| 1097 | |
| 1098 | |
| 1099 | |
| 1100 | |
| 1101 | |
| 1102 | pub(crate) const FOLLOWED_LOG_SCAN: usize = 500; |
| 1103 | |
| 1104 | |
| 1105 | |
| 1106 | |
| 1107 | |
| 1108 | |
| 1109 | fn unix_time(seconds: i64) -> SystemTime { |
| 1110 | match u64::try_from(seconds) { |
| 1111 | Ok(seconds) => UNIX_EPOCH + Duration::from_secs(seconds), |
| 1112 | Err(_) => UNIX_EPOCH - Duration::from_secs(seconds.unsigned_abs()), |
| 1113 | } |
| 1114 | } |
| 1115 | |
| 1116 | |
| 1117 | |
| 1118 | |
| 1119 | |
| 1120 | |
| 1121 | |
| 1122 | |
| 1123 | |
| 1124 | |
| 1125 | |
| 1126 | |
| 1127 | const GIT_TIMEOUT: Duration = Duration::from_secs(20); |
| 1128 | |
| 1129 | |
| 1130 | |
| 1131 | |
| 1132 | |
| 1133 | |
| 1134 | |
| 1135 | |
| 1136 | |
| 1137 | |
| 1138 | |
| 1139 | |
| 1140 | |
| 1141 | |
| 1142 | const MAX_RUN_BYTES: u64 = 32 * 1024 * 1024; |
| 1143 | |
| 1144 | async fn run<I, S>(repo: &Path, args: I) -> Result<Output, GitQueryError> |
| 1145 | where |
| 1146 | I: IntoIterator<Item = S>, |
| 1147 | S: AsRef<OsStr>, |
| 1148 | { |
| 1149 | run_bounded(repo, args, MAX_RUN_BYTES).await |
| 1150 | } |
| 1151 | |
| 1152 | |
| 1153 | |
| 1154 | async fn run_bounded<I, S>(repo: &Path, args: I, max_bytes: u64) -> Result<Output, GitQueryError> |
| 1155 | where |
| 1156 | I: IntoIterator<Item = S>, |
| 1157 | S: AsRef<OsStr>, |
| 1158 | { |
| 1159 | let (stdout, truncated) = run_capped(repo, args, max_bytes).await?; |
| 1160 | |
| 1161 | if truncated { |
| 1162 | return Err(GitQueryError::too_large(max_bytes)); |
| 1163 | } |
| 1164 | |
| 1165 | |
| 1166 | |
| 1167 | |
| 1168 | Ok(Output { |
| 1169 | status: std::process::ExitStatus::default(), |
| 1170 | stdout, |
| 1171 | stderr: Vec::new(), |
| 1172 | }) |
| 1173 | } |
| 1174 | |
| 1175 | |
| 1176 | |
| 1177 | |
| 1178 | |
| 1179 | |
| 1180 | |
| 1181 | const NO_MATCHES: i32 = 1; |
| 1182 | |
| 1183 | |
| 1184 | |
| 1185 | |
| 1186 | |
| 1187 | |
| 1188 | |
| 1189 | |
| 1190 | |
| 1191 | const MAX_GREP_BYTES: u64 = 4 * 1024 * 1024; |
| 1192 | |
| 1193 | |
| 1194 | |
| 1195 | const NO_COMMON_ANCESTOR: i32 = 1; |
| 1196 | |
| 1197 | |
| 1198 | |
| 1199 | const MERGE_CONFLICTED: i32 = 1; |
| 1200 | |
| 1201 | |
| 1202 | |
| 1203 | |
| 1204 | |
| 1205 | |
| 1206 | |
| 1207 | |
| 1208 | |
| 1209 | async fn run_allowing<I, S>(repo: &Path, args: I, allowed: &[i32]) -> Result<Output, GitQueryError> |
| 1210 | where |
| 1211 | I: IntoIterator<Item = S>, |
| 1212 | S: AsRef<OsStr>, |
| 1213 | { |
| 1214 | run_within_allowing(repo, args, GIT_TIMEOUT, allowed).await |
| 1215 | } |
| 1216 | |
| 1217 | |
| 1218 | |
| 1219 | |
| 1220 | |
| 1221 | |
| 1222 | |
| 1223 | #[cfg(test)] |
| 1224 | async fn run_within<I, S>(repo: &Path, args: I, limit: Duration) -> Result<Output, GitQueryError> |
| 1225 | where |
| 1226 | I: IntoIterator<Item = S>, |
| 1227 | S: AsRef<OsStr>, |
| 1228 | { |
| 1229 | run_within_allowing(repo, args, limit, &[]).await |
| 1230 | } |
| 1231 | |
| 1232 | |
| 1233 | async fn run_within_allowing<I, S>( |
| 1234 | repo: &Path, |
| 1235 | args: I, |
| 1236 | limit: Duration, |
| 1237 | allowed: &[i32], |
| 1238 | ) -> Result<Output, GitQueryError> |
| 1239 | where |
| 1240 | I: IntoIterator<Item = S>, |
| 1241 | S: AsRef<OsStr>, |
| 1242 | { |
| 1243 | let mut command = git_command(); |
| 1244 | command |
| 1245 | .arg("-C") |
| 1246 | .arg(repo) |
| 1247 | .args(args) |
| 1248 | .stdin(Stdio::null()) |
| 1249 | |
| 1250 | |
| 1251 | .kill_on_drop(true); |
| 1252 | count_spawn(&command); |
| 1253 | |
| 1254 | let output = match tokio::time::timeout(limit, command.output()).await { |
| 1255 | Ok(result) => { |
| 1256 | result.map_err(|error| GitQueryError::new(format!("could not run git: {error}")))? |
| 1257 | } |
| 1258 | Err(_elapsed) => return Err(GitQueryError::timed_out(limit)), |
| 1259 | }; |
| 1260 | |
| 1261 | let expected = output |
| 1262 | .status |
| 1263 | .code() |
| 1264 | .is_some_and(|code| allowed.contains(&code)); |
| 1265 | |
| 1266 | if !output.status.success() && !expected { |
| 1267 | return Err(GitQueryError::new(format!( |
| 1268 | "git exited with {}: {}", |
| 1269 | output.status, |
| 1270 | String::from_utf8_lossy(&output.stderr).trim() |
| 1271 | ))); |
| 1272 | } |
| 1273 | |
| 1274 | Ok(output) |
| 1275 | } |
| 1276 | |
| 1277 | |
| 1278 | |
| 1279 | |
| 1280 | |
| 1281 | |
| 1282 | |
| 1283 | |
| 1284 | |
| 1285 | |
| 1286 | |
| 1287 | |
| 1288 | async fn run_capped<I, S>( |
| 1289 | repo: &Path, |
| 1290 | args: I, |
| 1291 | max_bytes: u64, |
| 1292 | ) -> Result<(Vec<u8>, bool), GitQueryError> |
| 1293 | where |
| 1294 | I: IntoIterator<Item = S>, |
| 1295 | S: AsRef<OsStr>, |
| 1296 | { |
| 1297 | run_capped_allowing(repo, args, max_bytes, &[]).await |
| 1298 | } |
| 1299 | |
| 1300 | |
| 1301 | |
| 1302 | |
| 1303 | |
| 1304 | |
| 1305 | async fn run_capped_allowing<I, S>( |
| 1306 | repo: &Path, |
| 1307 | args: I, |
| 1308 | max_bytes: u64, |
| 1309 | allowed: &[i32], |
| 1310 | ) -> Result<(Vec<u8>, bool), GitQueryError> |
| 1311 | where |
| 1312 | I: IntoIterator<Item = S>, |
| 1313 | S: AsRef<OsStr>, |
| 1314 | { |
| 1315 | let mut command = git_command(); |
| 1316 | command |
| 1317 | .arg("-C") |
| 1318 | .arg(repo) |
| 1319 | .args(args) |
| 1320 | .stdin(Stdio::null()) |
| 1321 | .stdout(Stdio::piped()) |
| 1322 | .stderr(Stdio::piped()) |
| 1323 | .kill_on_drop(true); |
| 1324 | count_spawn(&command); |
| 1325 | |
| 1326 | let read = async { |
| 1327 | let mut child = command |
| 1328 | .spawn() |
| 1329 | .map_err(|error| GitQueryError::new(format!("could not run git: {error}")))?; |
| 1330 | |
| 1331 | let mut stdout = child.stdout.take().expect("stdout was piped"); |
| 1332 | let mut bytes = Vec::new(); |
| 1333 | |
| 1334 | |
| 1335 | |
| 1336 | let limit = max_bytes.saturating_add(1); |
| 1337 | |
| 1338 | (&mut stdout) |
| 1339 | .take(limit) |
| 1340 | .read_to_end(&mut bytes) |
| 1341 | .await |
| 1342 | .map_err(|error| GitQueryError::new(format!("could not read from git: {error}")))?; |
| 1343 | |
| 1344 | if bytes.len() as u64 > max_bytes { |
| 1345 | bytes.truncate(max_bytes as usize); |
| 1346 | |
| 1347 | |
| 1348 | let _ = child.start_kill(); |
| 1349 | |
| 1350 | return Ok((bytes, true)); |
| 1351 | } |
| 1352 | |
| 1353 | |
| 1354 | |
| 1355 | let output = child |
| 1356 | .wait_with_output() |
| 1357 | .await |
| 1358 | .map_err(|error| GitQueryError::new(format!("could not wait for git: {error}")))?; |
| 1359 | |
| 1360 | let expected = output |
| 1361 | .status |
| 1362 | .code() |
| 1363 | .is_some_and(|code| allowed.contains(&code)); |
| 1364 | |
| 1365 | if !output.status.success() && !expected { |
| 1366 | return Err(GitQueryError::new(format!( |
| 1367 | "git exited with {}: {}", |
| 1368 | output.status, |
| 1369 | String::from_utf8_lossy(&output.stderr).trim() |
| 1370 | ))); |
| 1371 | } |
| 1372 | |
| 1373 | Ok((bytes, false)) |
| 1374 | }; |
| 1375 | |
| 1376 | match tokio::time::timeout(GIT_TIMEOUT, read).await { |
| 1377 | Ok(result) => result, |
| 1378 | Err(_elapsed) => Err(GitQueryError::timed_out(GIT_TIMEOUT)), |
| 1379 | } |
| 1380 | } |
| 1381 | |
| 1382 | #[cfg(test)] |
| 1383 | #[path = "git_query_tests.rs"] |
| 1384 | mod tests; |