Git layer for whitespace diffs, patches, file lists, blame and branch counts
Browse files at this commit620ce2cbd6e1d57e1a1de37ee7660119d2a9820cParent: 4791c8a- feat
- git layer for whitespace diffs, patches, file lists, blame and branch counts
6 changed files +628 -6
- crates/forge-git/src/blame.rs +159 -0
- crates/forge-git/src/branches.rs +54 -0
- crates/forge-git/src/history.rs +157 -5
- crates/forge-git/src/lib.rs +2 -0
- crates/forge-git/src/pulls.rs +14 -1
- crates/forge-git/tests/browse_tools.rs +242 -0
crates/forge-git/src/blame.rsadded+159 -0
| @@ -0,0 +1,159 @@ | |||
| 1 | +//! `blame --porcelain`, parsed into runs of consecutive lines that share a commit. | ||
| 2 | +//! The subprocess pattern is the same as `history`: validated arguments, a byte cap on stdout. | ||
| 3 | + | ||
| 4 | +use std::collections::HashMap; | ||
| 5 | +use std::path::Path; | ||
| 6 | + | ||
| 7 | +use crate::browse::validate_repo_path; | ||
| 8 | +use crate::command::GitEnv; | ||
| 9 | +use crate::error::{Error, Result}; | ||
| 10 | +use crate::history::{git, read_capped, validate_oid}; | ||
| 11 | + | ||
| 12 | +/// What blame knows about one commit. | ||
| 13 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 14 | +pub struct BlameCommit { | ||
| 15 | + pub oid: String, | ||
| 16 | + pub author: String, | ||
| 17 | + pub author_time: i64, | ||
| 18 | + pub summary: String, | ||
| 19 | + /// The parent revision and the file's name there, for "blame prior to this commit". None for | ||
| 20 | + /// a boundary or root commit. | ||
| 21 | + pub previous: Option<(String, String)>, | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +/// A run of consecutive final lines that came from the same commit. | ||
| 25 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 26 | +pub struct BlameGroup { | ||
| 27 | + pub commit: String, | ||
| 28 | + /// First final line number of the run (1-based). | ||
| 29 | + pub start: u32, | ||
| 30 | + pub lines: u32, | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 34 | +pub struct Blame { | ||
| 35 | + pub groups: Vec<BlameGroup>, | ||
| 36 | + pub commits: HashMap<String, BlameCommit>, | ||
| 37 | + /// Total lines blamed. | ||
| 38 | + pub total: u32, | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +fn is_header(line: &str) -> Option<(&str, u32)> { | ||
| 42 | + let mut parts = line.split(' '); | ||
| 43 | + let oid = parts.next()?; | ||
| 44 | + if !(oid.len() == 40 || oid.len() == 64) || !oid.bytes().all(|b| b.is_ascii_hexdigit()) { | ||
| 45 | + return None; | ||
| 46 | + } | ||
| 47 | + let _orig = parts.next()?.parse::<u32>().ok()?; | ||
| 48 | + let fin = parts.next()?.parse::<u32>().ok()?; | ||
| 49 | + Some((oid, fin)) | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/// Parses `--porcelain` output. | ||
| 53 | +pub fn parse_porcelain(text: &str) -> Blame { | ||
| 54 | + let mut commits: HashMap<String, BlameCommit> = HashMap::new(); | ||
| 55 | + let mut groups: Vec<BlameGroup> = Vec::new(); | ||
| 56 | + let mut current: Option<String> = None; | ||
| 57 | + let mut total = 0u32; | ||
| 58 | + for line in text.split('\n') { | ||
| 59 | + if line.starts_with('\t') { | ||
| 60 | + // Content line: the final line number came from the header just before it. | ||
| 61 | + continue; | ||
| 62 | + } | ||
| 63 | + if let Some((oid, fin)) = is_header(line) { | ||
| 64 | + commits | ||
| 65 | + .entry(oid.to_owned()) | ||
| 66 | + .or_insert_with(|| BlameCommit { | ||
| 67 | + oid: oid.to_owned(), | ||
| 68 | + author: String::new(), | ||
| 69 | + author_time: 0, | ||
| 70 | + summary: String::new(), | ||
| 71 | + previous: None, | ||
| 72 | + }); | ||
| 73 | + current = Some(oid.to_owned()); | ||
| 74 | + total = total.max(fin); | ||
| 75 | + match groups.last_mut() { | ||
| 76 | + Some(g) if g.commit == oid && g.start + g.lines == fin => g.lines += 1, | ||
| 77 | + _ => groups.push(BlameGroup { | ||
| 78 | + commit: oid.to_owned(), | ||
| 79 | + start: fin, | ||
| 80 | + lines: 1, | ||
| 81 | + }), | ||
| 82 | + } | ||
| 83 | + continue; | ||
| 84 | + } | ||
| 85 | + let Some(oid) = current.as_ref() else { | ||
| 86 | + continue; | ||
| 87 | + }; | ||
| 88 | + let Some(c) = commits.get_mut(oid) else { | ||
| 89 | + continue; | ||
| 90 | + }; | ||
| 91 | + if let Some(v) = line.strip_prefix("author ") { | ||
| 92 | + c.author = v.to_owned(); | ||
| 93 | + } else if let Some(v) = line.strip_prefix("author-time ") { | ||
| 94 | + c.author_time = v.parse().unwrap_or(0); | ||
| 95 | + } else if let Some(v) = line.strip_prefix("summary ") { | ||
| 96 | + c.summary = v.to_owned(); | ||
| 97 | + } else if let Some(v) = line.strip_prefix("previous ") | ||
| 98 | + && let Some((prev, file)) = v.split_once(' ') | ||
| 99 | + { | ||
| 100 | + c.previous = Some((prev.to_owned(), file.to_owned())); | ||
| 101 | + } | ||
| 102 | + } | ||
| 103 | + Blame { | ||
| 104 | + groups, | ||
| 105 | + commits, | ||
| 106 | + total, | ||
| 107 | + } | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// Blames `path` at `commit` (a full oid). Output beyond the cap is an error, so the caller can | ||
| 111 | +/// show its "too large" message rather than a partial blame. The caller bounds the run time. | ||
| 112 | +pub async fn blame( | ||
| 113 | + env: &GitEnv, | ||
| 114 | + repo: &Path, | ||
| 115 | + commit: &str, | ||
| 116 | + path: &str, | ||
| 117 | + ignore_ws: bool, | ||
| 118 | +) -> Result<Blame> { | ||
| 119 | + validate_oid(commit)?; | ||
| 120 | + validate_repo_path(path)?; | ||
| 121 | + let cmd = git(env, "blame").git_dir(repo).arg("--porcelain"); | ||
| 122 | + let cmd = if ignore_ws { cmd.arg("-w") } else { cmd }; | ||
| 123 | + // `blame` does not understand `--end-of-options`; the oid is validated hex. | ||
| 124 | + let cmd = cmd.user_arg(commit)?.paths(&[path]); | ||
| 125 | + let (buf, complete) = read_capped(cmd).await?; | ||
| 126 | + if !complete { | ||
| 127 | + return Err(Error::Failed("blame output too large".into())); | ||
| 128 | + } | ||
| 129 | + Ok(parse_porcelain(&String::from_utf8_lossy(&buf))) | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +#[cfg(test)] | ||
| 133 | +mod tests { | ||
| 134 | + use super::*; | ||
| 135 | + | ||
| 136 | + #[test] | ||
| 137 | + fn groups_consecutive_lines() { | ||
| 138 | + let a = "a".repeat(40); | ||
| 139 | + let b = "b".repeat(40); | ||
| 140 | + let text = format!( | ||
| 141 | + "{a} 1 1 2\nauthor tahinli\nauthor-time 100\nsummary first\nfilename f\n\tone\n\ | ||
| 142 | + {a} 2 2\n\ttwo\n\ | ||
| 143 | + {b} 1 3 1\nauthor other\nauthor-time 200\nsummary second\nprevious {a} f\nfilename f\n\tthree\n\ | ||
| 144 | + {a} 3 4 1\n\tfour\n" | ||
| 145 | + ); | ||
| 146 | + let blame = parse_porcelain(&text); | ||
| 147 | + assert_eq!(blame.total, 4); | ||
| 148 | + assert_eq!(blame.groups.len(), 3); | ||
| 149 | + assert_eq!((blame.groups[0].start, blame.groups[0].lines), (1, 2)); | ||
| 150 | + assert_eq!(blame.groups[1].commit, b); | ||
| 151 | + assert_eq!(blame.groups[2].commit, a); | ||
| 152 | + assert_eq!(blame.commits[&a].author, "tahinli"); | ||
| 153 | + assert_eq!( | ||
| 154 | + blame.commits[&b].previous, | ||
| 155 | + Some((a.clone(), "f".to_owned())) | ||
| 156 | + ); | ||
| 157 | + assert_eq!(blame.commits[&a].previous, None); | ||
| 158 | + } | ||
| 159 | +} | ||
crates/forge-git/src/branches.rsadded+54 -0
| @@ -0,0 +1,54 @@ | |||
| 1 | +//! Branch operations used by the branches page: ahead/behind counts, creating and deleting. | ||
| 2 | + | ||
| 3 | +use std::path::Path; | ||
| 4 | + | ||
| 5 | +use crate::command::GitEnv; | ||
| 6 | +use crate::error::{Error, Result}; | ||
| 7 | +use crate::history::{git, validate_oid}; | ||
| 8 | +use crate::pulls::{delete_ref_cas, update_ref_cas}; | ||
| 9 | + | ||
| 10 | +/// `(ahead, behind)` of `tip` relative to `base`: commits only in `tip`, and commits only in `base`. | ||
| 11 | +pub async fn ahead_behind(env: &GitEnv, repo: &Path, base: &str, tip: &str) -> Result<(u32, u32)> { | ||
| 12 | + validate_oid(base)?; | ||
| 13 | + validate_oid(tip)?; | ||
| 14 | + let range = format!("{base}...{tip}"); | ||
| 15 | + let out = git(env, "rev-list") | ||
| 16 | + .git_dir(repo) | ||
| 17 | + .arg("--left-right") | ||
| 18 | + .arg("--count") | ||
| 19 | + .user_revs(&[range.as_str()])? | ||
| 20 | + .output() | ||
| 21 | + .await?; | ||
| 22 | + let text = String::from_utf8_lossy(&out); | ||
| 23 | + let mut it = text.split_whitespace(); | ||
| 24 | + let behind = it.next().and_then(|n| n.parse().ok()); | ||
| 25 | + let ahead = it.next().and_then(|n| n.parse().ok()); | ||
| 26 | + match (ahead, behind) { | ||
| 27 | + (Some(a), Some(b)) => Ok((a, b)), | ||
| 28 | + _ => Err(Error::Failed(format!( | ||
| 29 | + "unexpected rev-list output: {text:?}" | ||
| 30 | + ))), | ||
| 31 | + } | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +fn zero_oid(like: &str) -> String { | ||
| 35 | + "0".repeat(like.len()) | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// Creates `refs/heads/<name>` at `oid`. Fails when the branch exists already. | ||
| 39 | +pub async fn create_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> { | ||
| 40 | + validate_oid(oid)?; | ||
| 41 | + update_ref_cas( | ||
| 42 | + env, | ||
| 43 | + repo, | ||
| 44 | + &format!("refs/heads/{name}"), | ||
| 45 | + oid, | ||
| 46 | + &zero_oid(oid), | ||
| 47 | + ) | ||
| 48 | + .await | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// Deletes `refs/heads/<name>` if it still points at `oid`. | ||
| 52 | +pub async fn delete_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> { | ||
| 53 | + delete_ref_cas(env, repo, &format!("refs/heads/{name}"), oid).await | ||
| 54 | +} | ||
crates/forge-git/src/history.rsmodified+157 -5
| @@ -181,7 +181,7 @@ async fn for_each_chunk(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Re | |||
| 181 | } | 181 | } |
| 182 | 182 | ||
| 183 | /// Reads the whole stdout up to [`OUTPUT_CAP`]. The flag is `false` when the cap cut it short. | 183 | /// Reads the whole stdout up to [`OUTPUT_CAP`]. The flag is `false` when the cap cut it short. |
| 184 | -async fn read_capped(cmd: GitCommand) -> Result<(Vec<u8>, bool)> { | 184 | +pub(crate) async fn read_capped(cmd: GitCommand) -> Result<(Vec<u8>, bool)> { |
| 185 | let mut buf = Vec::new(); | 185 | let mut buf = Vec::new(); |
| 186 | let complete = for_each_chunk(cmd, |c| { | 186 | let complete = for_each_chunk(cmd, |c| { |
| 187 | buf.extend_from_slice(c); | 187 | buf.extend_from_slice(c); |
| @@ -329,6 +329,7 @@ fn diff_tree_cmd( | |||
| 329 | base: &str, | 329 | base: &str, |
| 330 | oid: &str, | 330 | oid: &str, |
| 331 | mode: DiffMode, | 331 | mode: DiffMode, |
| 332 | + ignore_ws: bool, | ||
| 332 | ) -> Result<GitCommand> { | 333 | ) -> Result<GitCommand> { |
| 333 | let cmd = git(env, "diff-tree") | 334 | let cmd = git(env, "diff-tree") |
| 334 | .git_dir(repo) | 335 | .git_dir(repo) |
| @@ -338,6 +339,9 @@ fn diff_tree_cmd( | |||
| 338 | .arg("--no-color") | 339 | .arg("--no-color") |
| 339 | .arg("--no-ext-diff") | 340 | .arg("--no-ext-diff") |
| 340 | .arg("--no-textconv"); | 341 | .arg("--no-textconv"); |
| 342 | + // `-w` on both runs drops files whose only changes are whitespace from the names as well as | ||
| 343 | + // the patch, so the two streams still line up by position. | ||
| 344 | + let cmd = if ignore_ws { cmd.arg("-w") } else { cmd }; | ||
| 341 | let cmd = match mode { | 345 | let cmd = match mode { |
| 342 | DiffMode::NameStatus => cmd.arg("-z").arg("--name-status"), | 346 | DiffMode::NameStatus => cmd.arg("-z").arg("--name-status"), |
| 343 | DiffMode::Patch => cmd.arg("-p").arg("--full-index"), | 347 | DiffMode::Patch => cmd.arg("-p").arg("--full-index"), |
| @@ -345,7 +349,7 @@ fn diff_tree_cmd( | |||
| 345 | cmd.objects(src)?.user_revs(&[base, oid]) | 349 | cmd.objects(src)?.user_revs(&[base, oid]) |
| 346 | } | 350 | } |
| 347 | 351 | ||
| 348 | -pub(crate) fn empty_tree_for(oid: &str) -> &'static str { | 352 | +pub fn empty_tree_for(oid: &str) -> &'static str { |
| 349 | if oid.len() == 64 { | 353 | if oid.len() == 64 { |
| 350 | EMPTY_TREE_SHA256 | 354 | EMPTY_TREE_SHA256 |
| 351 | } else { | 355 | } else { |
| @@ -545,13 +549,33 @@ pub async fn commit_diff( | |||
| 545 | repo: &Path, | 549 | repo: &Path, |
| 546 | oid: &str, | 550 | oid: &str, |
| 547 | limits: DiffLimits, | 551 | limits: DiffLimits, |
| 552 | +) -> Result<CommitDiff> { | ||
| 553 | + commit_diff_ws(env, repo, oid, limits, false).await | ||
| 554 | +} | ||
| 555 | + | ||
| 556 | +/// [`commit_diff`], optionally ignoring whitespace changes (`git diff -w`). | ||
| 557 | +pub async fn commit_diff_ws( | ||
| 558 | + env: &GitEnv, | ||
| 559 | + repo: &Path, | ||
| 560 | + oid: &str, | ||
| 561 | + limits: DiffLimits, | ||
| 562 | + ignore_ws: bool, | ||
| 548 | ) -> Result<CommitDiff> { | 563 | ) -> Result<CommitDiff> { |
| 549 | validate_oid(oid)?; | 564 | validate_oid(oid)?; |
| 550 | let base = match first_parent(env, repo, oid).await? { | 565 | let base = match first_parent(env, repo, oid).await? { |
| 551 | Some(p) => p, | 566 | Some(p) => p, |
| 552 | None => empty_tree_for(oid).to_owned(), | 567 | None => empty_tree_for(oid).to_owned(), |
| 553 | }; | 568 | }; |
| 554 | - diff_between(env, repo, ObjectSource::default(), &base, oid, limits).await | 569 | + diff_between( |
| 570 | + env, | ||
| 571 | + repo, | ||
| 572 | + ObjectSource::default(), | ||
| 573 | + &base, | ||
| 574 | + oid, | ||
| 575 | + limits, | ||
| 576 | + ignore_ws, | ||
| 577 | + ) | ||
| 578 | + .await | ||
| 555 | } | 579 | } |
| 556 | 580 | ||
| 557 | /// The diff from `base` (a commit or tree id) to `oid` (a commit id), with the same parsing and | 581 | /// The diff from `base` (a commit or tree id) to `oid` (a commit id), with the same parsing and |
| @@ -563,6 +587,7 @@ pub(crate) async fn diff_between( | |||
| 563 | base: &str, | 587 | base: &str, |
| 564 | oid: &str, | 588 | oid: &str, |
| 565 | limits: DiffLimits, | 589 | limits: DiffLimits, |
| 590 | + ignore_ws: bool, | ||
| 566 | ) -> Result<CommitDiff> { | 591 | ) -> Result<CommitDiff> { |
| 567 | validate_oid(base)?; | 592 | validate_oid(base)?; |
| 568 | validate_oid(oid)?; | 593 | validate_oid(oid)?; |
| @@ -573,6 +598,7 @@ pub(crate) async fn diff_between( | |||
| 573 | base, | 598 | base, |
| 574 | oid, | 599 | oid, |
| 575 | DiffMode::NameStatus, | 600 | DiffMode::NameStatus, |
| 601 | + ignore_ws, | ||
| 576 | )?) | 602 | )?) |
| 577 | .await?; | 603 | .await?; |
| 578 | let mut entries = parse_name_status(&name_buf); | 604 | let mut entries = parse_name_status(&name_buf); |
| @@ -586,8 +612,16 @@ pub(crate) async fn diff_between( | |||
| 586 | truncated_files = true; | 612 | truncated_files = true; |
| 587 | } | 613 | } |
| 588 | 614 | ||
| 589 | - let (patch_buf, patch_complete) = | 615 | + let (patch_buf, patch_complete) = read_capped(diff_tree_cmd( |
| 590 | - read_capped(diff_tree_cmd(env, repo, src, base, oid, DiffMode::Patch)?).await?; | 616 | + env, |
| 617 | + repo, | ||
| 618 | + src, | ||
| 619 | + base, | ||
| 620 | + oid, | ||
| 621 | + DiffMode::Patch, | ||
| 622 | + ignore_ws, | ||
| 623 | + )?) | ||
| 624 | + .await?; | ||
| 591 | let patch = String::from_utf8_lossy(&patch_buf); | 625 | let patch = String::from_utf8_lossy(&patch_buf); |
| 592 | let starts = block_starts(&patch); | 626 | let starts = block_starts(&patch); |
| 593 | // A capped patch may end inside its last section, so that section is dropped. | 627 | // A capped patch may end inside its last section, so that section is dropped. |
| @@ -631,6 +665,124 @@ pub(crate) async fn diff_between( | |||
| 631 | }) | 665 | }) |
| 632 | } | 666 | } |
| 633 | 667 | ||
| 668 | +/// A downloadable patch: the bytes and whether they are complete (not cut at the output cap). | ||
| 669 | +pub struct PatchOut { | ||
| 670 | + pub data: Vec<u8>, | ||
| 671 | + pub complete: bool, | ||
| 672 | +} | ||
| 673 | + | ||
| 674 | +/// Mbox of one commit in `format-patch` style (`/commit/{oid}.patch`). Binary changes are | ||
| 675 | +/// included so the patch applies. | ||
| 676 | +pub async fn commit_patch(env: &GitEnv, repo: &Path, oid: &str) -> Result<PatchOut> { | ||
| 677 | + validate_oid(oid)?; | ||
| 678 | + let cmd = git(env, "format-patch") | ||
| 679 | + .git_dir(repo) | ||
| 680 | + .arg("--stdout") | ||
| 681 | + .arg("--binary") | ||
| 682 | + .arg("--no-signature") | ||
| 683 | + .arg("--no-color") | ||
| 684 | + .arg("--root") | ||
| 685 | + .arg("-1") | ||
| 686 | + .user_revs(&[oid])?; | ||
| 687 | + let (data, complete) = read_capped(cmd).await?; | ||
| 688 | + Ok(PatchOut { data, complete }) | ||
| 689 | +} | ||
| 690 | + | ||
| 691 | +/// Plain unified diff of one commit against its first parent (`/commit/{oid}.diff`). | ||
| 692 | +pub async fn commit_raw_diff(env: &GitEnv, repo: &Path, oid: &str) -> Result<PatchOut> { | ||
| 693 | + validate_oid(oid)?; | ||
| 694 | + let base = match first_parent(env, repo, oid).await? { | ||
| 695 | + Some(p) => p, | ||
| 696 | + None => empty_tree_for(oid).to_owned(), | ||
| 697 | + }; | ||
| 698 | + raw_diff(env, repo, ObjectSource::default(), &base, oid).await | ||
| 699 | +} | ||
| 700 | + | ||
| 701 | +/// Plain unified diff from `base` to `oid`, both full object ids. | ||
| 702 | +pub async fn raw_diff( | ||
| 703 | + env: &GitEnv, | ||
| 704 | + repo: &Path, | ||
| 705 | + src: ObjectSource<'_>, | ||
| 706 | + base: &str, | ||
| 707 | + oid: &str, | ||
| 708 | +) -> Result<PatchOut> { | ||
| 709 | + validate_oid(base)?; | ||
| 710 | + validate_oid(oid)?; | ||
| 711 | + let cmd = git(env, "diff-tree") | ||
| 712 | + .git_dir(repo) | ||
| 713 | + .arg("-r") | ||
| 714 | + .arg("-p") | ||
| 715 | + .arg("-M") | ||
| 716 | + .arg("--binary") | ||
| 717 | + .arg("--no-commit-id") | ||
| 718 | + .arg("--no-color") | ||
| 719 | + .arg("--no-ext-diff") | ||
| 720 | + .arg("--no-textconv") | ||
| 721 | + .objects(src)? | ||
| 722 | + .user_revs(&[base, oid])?; | ||
| 723 | + let (data, complete) = read_capped(cmd).await?; | ||
| 724 | + Ok(PatchOut { data, complete }) | ||
| 725 | +} | ||
| 726 | + | ||
| 727 | +/// Mbox of the commits reachable from `head` but not from `base`, oldest first. | ||
| 728 | +pub async fn range_patch( | ||
| 729 | + env: &GitEnv, | ||
| 730 | + repo: &Path, | ||
| 731 | + src: ObjectSource<'_>, | ||
| 732 | + base: &str, | ||
| 733 | + head: &str, | ||
| 734 | +) -> Result<PatchOut> { | ||
| 735 | + validate_oid(base)?; | ||
| 736 | + validate_oid(head)?; | ||
| 737 | + let exclude = format!("^{base}"); | ||
| 738 | + let cmd = git(env, "format-patch") | ||
| 739 | + .git_dir(repo) | ||
| 740 | + .arg("--stdout") | ||
| 741 | + .arg("--binary") | ||
| 742 | + .arg("--no-signature") | ||
| 743 | + .arg("--no-color") | ||
| 744 | + .objects(src)? | ||
| 745 | + .user_revs(&[head, exclude.as_str()])?; | ||
| 746 | + let (data, complete) = read_capped(cmd).await?; | ||
| 747 | + Ok(PatchOut { data, complete }) | ||
| 748 | +} | ||
| 749 | + | ||
| 750 | +/// Every file path in the tree of `commit`, in tree order, at most `max` of them. The flag is true | ||
| 751 | +/// when the list was cut at `max` or at the output cap. | ||
| 752 | +pub async fn list_files( | ||
| 753 | + env: &GitEnv, | ||
| 754 | + repo: &Path, | ||
| 755 | + commit: &str, | ||
| 756 | + max: usize, | ||
| 757 | +) -> Result<(Vec<String>, bool)> { | ||
| 758 | + validate_oid(commit)?; | ||
| 759 | + let cmd = git(env, "ls-tree") | ||
| 760 | + .git_dir(repo) | ||
| 761 | + .arg("-r") | ||
| 762 | + .arg("-z") | ||
| 763 | + .arg("--name-only") | ||
| 764 | + .arg("--full-tree") | ||
| 765 | + .user_revs(&[commit])?; | ||
| 766 | + let (buf, complete) = read_capped(cmd).await?; | ||
| 767 | + let mut paths: Vec<&[u8]> = buf.split(|&b| b == 0).filter(|p| !p.is_empty()).collect(); | ||
| 768 | + let mut cut = !complete; | ||
| 769 | + if !complete { | ||
| 770 | + // The last record may be partial. | ||
| 771 | + paths.pop(); | ||
| 772 | + } | ||
| 773 | + if paths.len() > max { | ||
| 774 | + paths.truncate(max); | ||
| 775 | + cut = true; | ||
| 776 | + } | ||
| 777 | + Ok(( | ||
| 778 | + paths | ||
| 779 | + .into_iter() | ||
| 780 | + .map(|p| String::from_utf8_lossy(p).into_owned()) | ||
| 781 | + .collect(), | ||
| 782 | + cut, | ||
| 783 | + )) | ||
| 784 | +} | ||
| 785 | + | ||
| 634 | /// The newest commit (walking back from `commit`) that touched each direct child of `dir`, | 786 | /// The newest commit (walking back from `commit`) that touched each direct child of `dir`, |
| 635 | /// keyed by child name. One `git log` walk, limited to `max_walk` commits, and it stops | 787 | /// keyed by child name. One `git log` walk, limited to `max_walk` commits, and it stops |
| 636 | /// early once every name is found. `dir` is `""` for the repo root. | 788 | /// early once every name is found. `dir` is `""` for the repo root. |
crates/forge-git/src/lib.rsmodified+2 -0
| @@ -1,6 +1,8 @@ | |||
| 1 | //! Git plumbing for forge: a safe command builder, repo management and smart-HTTP helpers. | 1 | //! Git plumbing for forge: a safe command builder, repo management and smart-HTTP helpers. |
| 2 | 2 | ||
| 3 | pub mod backup; | 3 | pub mod backup; |
| 4 | +pub mod blame; | ||
| 5 | +pub mod branches; | ||
| 4 | pub mod browse; | 6 | pub mod browse; |
| 5 | pub mod command; | 7 | pub mod command; |
| 6 | pub mod error; | 8 | pub mod error; |
crates/forge-git/src/pulls.rsmodified+14 -1
| @@ -456,6 +456,19 @@ pub async fn range_diff_files_with( | |||
| 456 | base_oid: &str, | 456 | base_oid: &str, |
| 457 | head_oid: &str, | 457 | head_oid: &str, |
| 458 | limits: DiffLimits, | 458 | limits: DiffLimits, |
| 459 | +) -> Result<CommitDiff> { | ||
| 460 | + range_diff_files_ws(env, repo, src, base_oid, head_oid, limits, false).await | ||
| 461 | +} | ||
| 462 | + | ||
| 463 | +/// [`range_diff_files_with`], optionally ignoring whitespace changes. | ||
| 464 | +pub async fn range_diff_files_ws( | ||
| 465 | + env: &GitEnv, | ||
| 466 | + repo: &Path, | ||
| 467 | + src: ObjectSource<'_>, | ||
| 468 | + base_oid: &str, | ||
| 469 | + head_oid: &str, | ||
| 470 | + limits: DiffLimits, | ||
| 471 | + ignore_ws: bool, | ||
| 459 | ) -> Result<CommitDiff> { | 472 | ) -> Result<CommitDiff> { |
| 460 | validate_oid(base_oid)?; | 473 | validate_oid(base_oid)?; |
| 461 | validate_oid(head_oid)?; | 474 | validate_oid(head_oid)?; |
| @@ -463,7 +476,7 @@ pub async fn range_diff_files_with( | |||
| 463 | Some(b) => b, | 476 | Some(b) => b, |
| 464 | None => empty_tree_for(head_oid).to_owned(), | 477 | None => empty_tree_for(head_oid).to_owned(), |
| 465 | }; | 478 | }; |
| 466 | - diff_between(env, repo, src, &from, head_oid, limits).await | 479 | + diff_between(env, repo, src, &from, head_oid, limits, ignore_ws).await |
| 467 | } | 480 | } |
| 468 | 481 | ||
| 469 | /// Commits reachable from `head` but not from `base` (`log <head> ^<base>`), oldest first. | 482 | /// Commits reachable from `head` but not from `base` (`log <head> ^<base>`), oldest first. |
crates/forge-git/tests/browse_tools.rsadded+242 -0
| @@ -0,0 +1,242 @@ | |||
| 1 | +//! Tests for the code-browsing helpers: whitespace-free diffs, patches, the recursive file list, | ||
| 2 | +//! blame and branch operations. | ||
| 3 | + | ||
| 4 | +use std::path::{Path, PathBuf}; | ||
| 5 | +use std::process::Command; | ||
| 6 | + | ||
| 7 | +use forge_git::GitEnv; | ||
| 8 | +use forge_git::blame::blame; | ||
| 9 | +use forge_git::branches::{ahead_behind, create_branch, delete_branch}; | ||
| 10 | +use forge_git::command::ObjectSource; | ||
| 11 | +use forge_git::history::{ | ||
| 12 | + DiffLimits, commit_diff_ws, commit_patch, commit_raw_diff, list_files, range_patch, | ||
| 13 | +}; | ||
| 14 | + | ||
| 15 | +const BIG: DiffLimits = DiffLimits { | ||
| 16 | + max_files: 1000, | ||
| 17 | + max_lines_per_file: 10_000, | ||
| 18 | + max_total_lines: 100_000, | ||
| 19 | +}; | ||
| 20 | + | ||
| 21 | +struct Fixture { | ||
| 22 | + _dir: tempfile::TempDir, | ||
| 23 | + work: PathBuf, | ||
| 24 | + git_dir: PathBuf, | ||
| 25 | + env: GitEnv, | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +fn run(dir: &Path, home: &Path, args: &[&str]) -> String { | ||
| 29 | + let out = Command::new("/usr/bin/git") | ||
| 30 | + .arg("-C") | ||
| 31 | + .arg(dir) | ||
| 32 | + .args([ | ||
| 33 | + "-c", | ||
| 34 | + "user.name=tahinli", | ||
| 35 | + "-c", | ||
| 36 | + "user.email=tahinli@example.com", | ||
| 37 | + "-c", | ||
| 38 | + "commit.gpgsign=false", | ||
| 39 | + ]) | ||
| 40 | + .args(args) | ||
| 41 | + .env_clear() | ||
| 42 | + .env("PATH", "/usr/bin:/bin") | ||
| 43 | + .env("HOME", home) | ||
| 44 | + .env("GIT_CONFIG_NOSYSTEM", "1") | ||
| 45 | + .env("GIT_CONFIG_GLOBAL", "/dev/null") | ||
| 46 | + .output() | ||
| 47 | + .unwrap(); | ||
| 48 | + assert!( | ||
| 49 | + out.status.success(), | ||
| 50 | + "{args:?} failed: {}", | ||
| 51 | + String::from_utf8_lossy(&out.stderr) | ||
| 52 | + ); | ||
| 53 | + String::from_utf8_lossy(&out.stdout).into_owned() | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +fn fixture() -> Fixture { | ||
| 57 | + let dir = tempfile::tempdir().unwrap(); | ||
| 58 | + let work = dir.path().join("work"); | ||
| 59 | + std::fs::create_dir(&work).unwrap(); | ||
| 60 | + run(&work, dir.path(), &["init", "-q", "-b", "main"]); | ||
| 61 | + let env = GitEnv { | ||
| 62 | + git_bin: PathBuf::from("/usr/bin/git"), | ||
| 63 | + data_dir: dir.path().to_path_buf(), | ||
| 64 | + }; | ||
| 65 | + let git_dir = work.join(".git"); | ||
| 66 | + Fixture { | ||
| 67 | + _dir: dir, | ||
| 68 | + work, | ||
| 69 | + git_dir, | ||
| 70 | + env, | ||
| 71 | + } | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +impl Fixture { | ||
| 75 | + fn sh(&self, args: &[&str]) -> String { | ||
| 76 | + run(&self.work, self._dir.path(), args) | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + fn write(&self, name: &str, content: &str) { | ||
| 80 | + let p = self.work.join(name); | ||
| 81 | + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); | ||
| 82 | + std::fs::write(p, content).unwrap(); | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + fn commit(&self, msg: &str) -> String { | ||
| 86 | + self.sh(&["add", "-A"]); | ||
| 87 | + self.sh(&["commit", "-q", "--allow-empty", "-m", msg]); | ||
| 88 | + self.sh(&["rev-parse", "HEAD"]).trim().to_owned() | ||
| 89 | + } | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +#[tokio::test] | ||
| 93 | +async fn ignore_whitespace_drops_whitespace_only_files() { | ||
| 94 | + let f = fixture(); | ||
| 95 | + f.write("x.txt", "a\nb\n"); | ||
| 96 | + f.write("y.txt", "c\n"); | ||
| 97 | + f.commit("one"); | ||
| 98 | + f.write("x.txt", "a \nb\n"); | ||
| 99 | + f.write("y.txt", "c\nd\n"); | ||
| 100 | + let head = f.commit("two"); | ||
| 101 | + | ||
| 102 | + let full = commit_diff_ws(&f.env, &f.git_dir, &head, BIG, false) | ||
| 103 | + .await | ||
| 104 | + .unwrap(); | ||
| 105 | + assert_eq!(full.files.len(), 2); | ||
| 106 | + let ws = commit_diff_ws(&f.env, &f.git_dir, &head, BIG, true) | ||
| 107 | + .await | ||
| 108 | + .unwrap(); | ||
| 109 | + assert_eq!(ws.files.len(), 1); | ||
| 110 | + assert_eq!(ws.files[0].new_path.as_deref(), Some("y.txt")); | ||
| 111 | + assert_eq!(ws.files[0].additions, 1); | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +#[tokio::test] | ||
| 115 | +async fn patch_and_diff_outputs() { | ||
| 116 | + let f = fixture(); | ||
| 117 | + f.write("x.txt", "a\n"); | ||
| 118 | + let root = f.commit("root commit"); | ||
| 119 | + f.write("x.txt", "a\nb\n"); | ||
| 120 | + let head = f.commit("add b"); | ||
| 121 | + | ||
| 122 | + let patch = commit_patch(&f.env, &f.git_dir, &head).await.unwrap(); | ||
| 123 | + assert!(patch.complete); | ||
| 124 | + let text = String::from_utf8(patch.data).unwrap(); | ||
| 125 | + assert!(text.starts_with(&format!("From {head} "))); | ||
| 126 | + assert!(text.contains("Subject: [PATCH] add b")); | ||
| 127 | + assert!(text.contains("+b")); | ||
| 128 | + | ||
| 129 | + let root_patch = commit_patch(&f.env, &f.git_dir, &root).await.unwrap(); | ||
| 130 | + assert!( | ||
| 131 | + String::from_utf8(root_patch.data) | ||
| 132 | + .unwrap() | ||
| 133 | + .contains("+++ b/x.txt") | ||
| 134 | + ); | ||
| 135 | + | ||
| 136 | + let diff = commit_raw_diff(&f.env, &f.git_dir, &head).await.unwrap(); | ||
| 137 | + let diff = String::from_utf8(diff.data).unwrap(); | ||
| 138 | + assert!(diff.starts_with("diff --git a/x.txt b/x.txt")); | ||
| 139 | + | ||
| 140 | + let range = range_patch(&f.env, &f.git_dir, ObjectSource::default(), &root, &head) | ||
| 141 | + .await | ||
| 142 | + .unwrap(); | ||
| 143 | + let range = String::from_utf8(range.data).unwrap(); | ||
| 144 | + assert_eq!(range.matches("\nSubject: ").count(), 1); | ||
| 145 | + assert!(range.contains("add b")); | ||
| 146 | + assert!(!range.contains("root commit")); | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +#[tokio::test] | ||
| 150 | +async fn list_files_is_recursive_and_capped() { | ||
| 151 | + let f = fixture(); | ||
| 152 | + f.write("a.txt", "1"); | ||
| 153 | + f.write("dir/b.txt", "2"); | ||
| 154 | + f.write("dir/sub/c.txt", "3"); | ||
| 155 | + let head = f.commit("files"); | ||
| 156 | + | ||
| 157 | + let (all, cut) = list_files(&f.env, &f.git_dir, &head, 100).await.unwrap(); | ||
| 158 | + assert!(!cut); | ||
| 159 | + assert_eq!(all, ["a.txt", "dir/b.txt", "dir/sub/c.txt"]); | ||
| 160 | + let (two, cut) = list_files(&f.env, &f.git_dir, &head, 2).await.unwrap(); | ||
| 161 | + assert!(cut); | ||
| 162 | + assert_eq!(two.len(), 2); | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +#[tokio::test] | ||
| 166 | +async fn blame_groups_by_commit() { | ||
| 167 | + let f = fixture(); | ||
| 168 | + f.write("f.txt", "one\ntwo\nthree\n"); | ||
| 169 | + let first = f.commit("first"); | ||
| 170 | + f.write("f.txt", "one\nTWO\nthree\nfour\n"); | ||
| 171 | + let second = f.commit("second"); | ||
| 172 | + | ||
| 173 | + let b = blame(&f.env, &f.git_dir, &second, "f.txt", false) | ||
| 174 | + .await | ||
| 175 | + .unwrap(); | ||
| 176 | + assert_eq!(b.total, 4); | ||
| 177 | + let shape: Vec<(&str, u32, u32)> = b | ||
| 178 | + .groups | ||
| 179 | + .iter() | ||
| 180 | + .map(|g| (g.commit.as_str(), g.start, g.lines)) | ||
| 181 | + .collect(); | ||
| 182 | + assert_eq!( | ||
| 183 | + shape, | ||
| 184 | + [ | ||
| 185 | + (first.as_str(), 1, 1), | ||
| 186 | + (second.as_str(), 2, 1), | ||
| 187 | + (first.as_str(), 3, 1), | ||
| 188 | + (second.as_str(), 4, 1), | ||
| 189 | + ] | ||
| 190 | + ); | ||
| 191 | + assert_eq!(b.commits[&second].summary, "second"); | ||
| 192 | + assert_eq!(b.commits[&second].author, "tahinli"); | ||
| 193 | + assert_eq!( | ||
| 194 | + b.commits[&second].previous, | ||
| 195 | + Some((first.clone(), "f.txt".to_owned())) | ||
| 196 | + ); | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +#[tokio::test] | ||
| 200 | +async fn branch_counts_create_and_delete() { | ||
| 201 | + let f = fixture(); | ||
| 202 | + f.write("a.txt", "1"); | ||
| 203 | + let base = f.commit("base"); | ||
| 204 | + f.sh(&["checkout", "-q", "-b", "feature"]); | ||
| 205 | + f.write("b.txt", "2"); | ||
| 206 | + f.commit("feature 1"); | ||
| 207 | + let tip = f.commit("feature 2"); | ||
| 208 | + f.sh(&["checkout", "-q", "main"]); | ||
| 209 | + f.write("c.txt", "3"); | ||
| 210 | + let main_tip = f.commit("main moved"); | ||
| 211 | + | ||
| 212 | + let (ahead, behind) = ahead_behind(&f.env, &f.git_dir, &main_tip, &tip) | ||
| 213 | + .await | ||
| 214 | + .unwrap(); | ||
| 215 | + assert_eq!((ahead, behind), (2, 1)); | ||
| 216 | + | ||
| 217 | + create_branch(&f.env, &f.git_dir, "topic/x", &base) | ||
| 218 | + .await | ||
| 219 | + .unwrap(); | ||
| 220 | + assert_eq!( | ||
| 221 | + f.sh(&["rev-parse", "refs/heads/topic/x"]).trim(), | ||
| 222 | + base.as_str() | ||
| 223 | + ); | ||
| 224 | + assert!( | ||
| 225 | + create_branch(&f.env, &f.git_dir, "topic/x", &base) | ||
| 226 | + .await | ||
| 227 | + .is_err() | ||
| 228 | + ); | ||
| 229 | + assert!( | ||
| 230 | + create_branch(&f.env, &f.git_dir, "bad..name", &base) | ||
| 231 | + .await | ||
| 232 | + .is_err() | ||
| 233 | + ); | ||
| 234 | + delete_branch(&f.env, &f.git_dir, "topic/x", &base) | ||
| 235 | + .await | ||
| 236 | + .unwrap(); | ||
| 237 | + assert!( | ||
| 238 | + delete_branch(&f.env, &f.git_dir, "topic/x", &base) | ||
| 239 | + .await | ||
| 240 | + .is_err() | ||
| 241 | + ); | ||
| 242 | +} | ||