| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use std::path::Path; |
| 6 | use std::process::{Output, Stdio}; |
| 7 | |
| 8 | use tokio::io::AsyncWriteExt; |
| 9 | |
| 10 | use crate::browse::{CommitInfo, validate_repo_path}; |
| 11 | use crate::command::{GitCommand, GitEnv, ObjectSource}; |
| 12 | use crate::error::{Error, Result}; |
| 13 | use crate::history::{ |
| 14 | CommitDiff, DiffLimits, diff_between, empty_tree_for, git, new_commits_with, validate_oid, |
| 15 | }; |
| 16 | |
| 17 | |
| 18 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 19 | pub enum MergeCheck { |
| 20 | |
| 21 | Clean { tree: String }, |
| 22 | |
| 23 | Conflict { files: Vec<String> }, |
| 24 | |
| 25 | UpToDate, |
| 26 | } |
| 27 | |
| 28 | |
| 29 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 30 | pub struct Signature { |
| 31 | pub name: String, |
| 32 | pub email: String, |
| 33 | pub time_unix: i64, |
| 34 | } |
| 35 | |
| 36 | |
| 37 | async fn run_raw(cmd: GitCommand, stdin: Option<&[u8]>) -> Result<Output> { |
| 38 | let mut command = cmd.into_tokio(); |
| 39 | command.stdout(Stdio::piped()).stderr(Stdio::piped()); |
| 40 | if stdin.is_some() { |
| 41 | command.stdin(Stdio::piped()); |
| 42 | } |
| 43 | let mut child = command.spawn()?; |
| 44 | if let (Some(data), Some(mut pipe)) = (stdin, child.stdin.take()) { |
| 45 | pipe.write_all(data).await?; |
| 46 | |
| 47 | } |
| 48 | Ok(child.wait_with_output().await?) |
| 49 | } |
| 50 | |
| 51 | fn failed(subcommand: &str, out: &Output) -> Error { |
| 52 | Error::Failed(format!( |
| 53 | "git {subcommand} exited with {}: {}", |
| 54 | out.status, |
| 55 | String::from_utf8_lossy(&out.stderr).trim() |
| 56 | )) |
| 57 | } |
| 58 | |
| 59 | fn stdout_trimmed(out: &Output) -> String { |
| 60 | String::from_utf8_lossy(&out.stdout).trim().to_owned() |
| 61 | } |
| 62 | |
| 63 | |
| 64 | fn validate_ref(refname: &str) -> Result<()> { |
| 65 | let heads_ok = refname |
| 66 | .strip_prefix("refs/heads/") |
| 67 | .is_some_and(valid_branch_rest); |
| 68 | let pull_ok = refname |
| 69 | .strip_prefix("refs/pull/") |
| 70 | .and_then(|r| r.strip_suffix("/head")) |
| 71 | .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())); |
| 72 | if heads_ok || pull_ok { |
| 73 | Ok(()) |
| 74 | } else { |
| 75 | Err(Error::InvalidInput(format!( |
| 76 | "invalid ref name: {refname:?}" |
| 77 | ))) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | fn valid_branch_rest(rest: &str) -> bool { |
| 82 | !rest.is_empty() |
| 83 | && !rest.contains("..") |
| 84 | && !rest.contains("@{") |
| 85 | && !rest.contains("//") |
| 86 | && !rest.ends_with(['/', '.']) |
| 87 | && !rest.ends_with(".lock") |
| 88 | && rest |
| 89 | .split('/') |
| 90 | .all(|c| !c.is_empty() && !c.starts_with(['.', '-'])) |
| 91 | && rest |
| 92 | .bytes() |
| 93 | .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'.' | b'_' | b'-' | b'+')) |
| 94 | } |
| 95 | |
| 96 | |
| 97 | fn validate_signature(sig: &Signature) -> Result<()> { |
| 98 | let bad = |s: &str| s.is_empty() || s.contains(['<', '>', '\n', '\0']); |
| 99 | if bad(&sig.name) || bad(&sig.email) { |
| 100 | return Err(Error::InvalidInput("invalid identity name or email".into())); |
| 101 | } |
| 102 | Ok(()) |
| 103 | } |
| 104 | |
| 105 | |
| 106 | fn same_repo(a: &Path, b: &Path) -> bool { |
| 107 | if a == b { |
| 108 | return true; |
| 109 | } |
| 110 | match (std::fs::canonicalize(a), std::fs::canonicalize(b)) { |
| 111 | (Ok(x), Ok(y)) => x == y, |
| 112 | _ => false, |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | async fn fetch_object(env: &GitEnv, base_repo: &Path, head_repo: &Path, oid: &str) -> Result<()> { |
| 120 | let head_path = head_repo |
| 121 | .to_str() |
| 122 | .ok_or_else(|| Error::InvalidInput("repo path is not valid UTF-8".into()))?; |
| 123 | let build = |allow_any: bool| -> Result<GitCommand> { |
| 124 | |
| 125 | let cmd = git(env, "fetch") |
| 126 | .allow_local_transport() |
| 127 | .git_dir(base_repo) |
| 128 | .arg("--no-tags") |
| 129 | .arg("--no-write-fetch-head"); |
| 130 | let cmd = if allow_any { |
| 131 | cmd.env("GIT_CONFIG_COUNT", "2") |
| 132 | .env("GIT_CONFIG_KEY_1", "uploadpack.allowAnySHA1InWant") |
| 133 | .env("GIT_CONFIG_VALUE_1", "true") |
| 134 | } else { |
| 135 | cmd |
| 136 | }; |
| 137 | cmd.user_revs(&[head_path, oid]) |
| 138 | }; |
| 139 | match build(false)?.status().await { |
| 140 | Ok(()) => Ok(()), |
| 141 | Err(Error::Failed(_)) => build(true)?.status().await, |
| 142 | Err(e) => Err(e), |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | |
| 147 | |
| 148 | pub async fn fetch_into_pull_ref( |
| 149 | env: &GitEnv, |
| 150 | base_repo: &Path, |
| 151 | head_repo: &Path, |
| 152 | head_oid: &str, |
| 153 | number: i64, |
| 154 | ) -> Result<()> { |
| 155 | validate_oid(head_oid)?; |
| 156 | if number < 1 { |
| 157 | return Err(Error::InvalidInput(format!( |
| 158 | "invalid pull number: {number}" |
| 159 | ))); |
| 160 | } |
| 161 | let refname = format!("refs/pull/{number}/head"); |
| 162 | validate_ref(&refname)?; |
| 163 | if !same_repo(base_repo, head_repo) { |
| 164 | fetch_object(env, base_repo, head_repo, head_oid).await?; |
| 165 | } |
| 166 | git(env, "update-ref") |
| 167 | .git_dir(base_repo) |
| 168 | .user_arg(&refname)? |
| 169 | .user_arg(head_oid)? |
| 170 | .status() |
| 171 | .await |
| 172 | } |
| 173 | |
| 174 | |
| 175 | pub async fn merge_base(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<Option<String>> { |
| 176 | merge_base_with(env, repo, ObjectSource::default(), a, b).await |
| 177 | } |
| 178 | |
| 179 | |
| 180 | |
| 181 | pub async fn merge_base_with( |
| 182 | env: &GitEnv, |
| 183 | repo: &Path, |
| 184 | src: ObjectSource<'_>, |
| 185 | a: &str, |
| 186 | b: &str, |
| 187 | ) -> Result<Option<String>> { |
| 188 | validate_oid(a)?; |
| 189 | validate_oid(b)?; |
| 190 | let cmd = git(env, "merge-base") |
| 191 | .git_dir(repo) |
| 192 | .objects(src)? |
| 193 | .user_revs(&[a, b])?; |
| 194 | let out = run_raw(cmd, None).await?; |
| 195 | match out.status.code() { |
| 196 | Some(0) => { |
| 197 | let oid = stdout_trimmed(&out); |
| 198 | validate_oid(&oid)?; |
| 199 | Ok(Some(oid)) |
| 200 | } |
| 201 | Some(1) => Ok(None), |
| 202 | _ => Err(failed("merge-base", &out)), |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | |
| 207 | |
| 208 | pub async fn blob_at( |
| 209 | env: &GitEnv, |
| 210 | repo: &Path, |
| 211 | commit: &str, |
| 212 | path: &str, |
| 213 | ) -> Result<Option<String>> { |
| 214 | blob_at_with(env, repo, ObjectSource::default(), commit, path).await |
| 215 | } |
| 216 | |
| 217 | |
| 218 | |
| 219 | pub async fn blob_at_with( |
| 220 | env: &GitEnv, |
| 221 | repo: &Path, |
| 222 | src: ObjectSource<'_>, |
| 223 | commit: &str, |
| 224 | path: &str, |
| 225 | ) -> Result<Option<String>> { |
| 226 | validate_oid(commit)?; |
| 227 | validate_blob_path(path)?; |
| 228 | |
| 229 | |
| 230 | |
| 231 | let spec = format!(":(literal){path}"); |
| 232 | let out = git(env, "ls-tree") |
| 233 | .git_dir(repo) |
| 234 | .objects(src)? |
| 235 | .arg("-z") |
| 236 | .arg("--full-tree") |
| 237 | .user_arg(commit)? |
| 238 | .paths(&[spec.as_str()]) |
| 239 | .output() |
| 240 | .await?; |
| 241 | |
| 242 | let entry = out.split(|&b| b == 0).find_map(|rec| { |
| 243 | let text = std::str::from_utf8(rec).ok()?; |
| 244 | let (meta, name) = text.split_once('\t')?; |
| 245 | if name != path { |
| 246 | return None; |
| 247 | } |
| 248 | let mut fields = meta.split(' '); |
| 249 | let _mode = fields.next()?; |
| 250 | let kind = fields.next()?; |
| 251 | let oid = fields.next()?; |
| 252 | Some((kind.to_owned(), oid.to_owned())) |
| 253 | }); |
| 254 | match entry { |
| 255 | Some((kind, oid)) if kind == "blob" => { |
| 256 | validate_oid(&oid)?; |
| 257 | Ok(Some(oid)) |
| 258 | } |
| 259 | _ => Ok(None), |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | |
| 264 | |
| 265 | fn validate_blob_path(path: &str) -> Result<()> { |
| 266 | if path.is_empty() { |
| 267 | return Err(Error::InvalidInput("empty path".into())); |
| 268 | } |
| 269 | if path.starts_with('/') { |
| 270 | return Err(Error::InvalidInput(format!("absolute path: {path:?}"))); |
| 271 | } |
| 272 | if path.contains('\n') { |
| 273 | return Err(Error::InvalidInput("path contains newline".into())); |
| 274 | } |
| 275 | validate_repo_path(path) |
| 276 | } |
| 277 | |
| 278 | |
| 279 | pub async fn is_ancestor(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<bool> { |
| 280 | validate_oid(a)?; |
| 281 | validate_oid(b)?; |
| 282 | let cmd = git(env, "merge-base") |
| 283 | .git_dir(repo) |
| 284 | .arg("--is-ancestor") |
| 285 | .user_revs(&[a, b])?; |
| 286 | let out = run_raw(cmd, None).await?; |
| 287 | match out.status.code() { |
| 288 | Some(0) => Ok(true), |
| 289 | Some(1) => Ok(false), |
| 290 | _ => Err(failed("merge-base --is-ancestor", &out)), |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | |
| 295 | pub async fn check_merge( |
| 296 | env: &GitEnv, |
| 297 | repo: &Path, |
| 298 | base_oid: &str, |
| 299 | head_oid: &str, |
| 300 | ) -> Result<MergeCheck> { |
| 301 | validate_oid(base_oid)?; |
| 302 | validate_oid(head_oid)?; |
| 303 | if is_ancestor(env, repo, head_oid, base_oid).await? { |
| 304 | return Ok(MergeCheck::UpToDate); |
| 305 | } |
| 306 | let cmd = git(env, "merge-tree") |
| 307 | .git_dir(repo) |
| 308 | .arg("--write-tree") |
| 309 | .arg("--name-only") |
| 310 | .arg("--no-messages") |
| 311 | .user_revs(&[base_oid, head_oid])?; |
| 312 | let out = run_raw(cmd, None).await?; |
| 313 | let text = String::from_utf8_lossy(&out.stdout).into_owned(); |
| 314 | match out.status.code() { |
| 315 | Some(0) => { |
| 316 | let tree = text.lines().next().unwrap_or_default().trim().to_owned(); |
| 317 | validate_oid(&tree)?; |
| 318 | Ok(MergeCheck::Clean { tree }) |
| 319 | } |
| 320 | Some(1) => { |
| 321 | let mut lines = text.lines(); |
| 322 | let tree = lines.next().unwrap_or_default().trim().to_owned(); |
| 323 | validate_oid(&tree)?; |
| 324 | let mut files: Vec<String> = Vec::new(); |
| 325 | for line in lines.map(str::trim).filter(|l| !l.is_empty()) { |
| 326 | if !files.iter().any(|f| f == line) { |
| 327 | files.push(line.to_owned()); |
| 328 | } |
| 329 | } |
| 330 | Ok(MergeCheck::Conflict { files }) |
| 331 | } |
| 332 | _ => Err(failed("merge-tree", &out)), |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | |
| 337 | |
| 338 | pub async fn commit_tree( |
| 339 | env: &GitEnv, |
| 340 | repo: &Path, |
| 341 | tree: &str, |
| 342 | parents: &[&str], |
| 343 | message: &str, |
| 344 | author: &Signature, |
| 345 | committer: &Signature, |
| 346 | ) -> Result<String> { |
| 347 | validate_oid(tree)?; |
| 348 | for p in parents { |
| 349 | validate_oid(p)?; |
| 350 | } |
| 351 | validate_signature(author)?; |
| 352 | validate_signature(committer)?; |
| 353 | if message.contains('\0') { |
| 354 | return Err(Error::InvalidInput("commit message contains NUL".into())); |
| 355 | } |
| 356 | let mut cmd = git(env, "commit-tree").git_dir(repo); |
| 357 | for p in parents { |
| 358 | cmd = cmd.arg("-p").user_arg(p)?; |
| 359 | } |
| 360 | let cmd = cmd |
| 361 | .user_revs(&[tree])? |
| 362 | .env("GIT_AUTHOR_NAME", author.name.as_str()) |
| 363 | .env("GIT_AUTHOR_EMAIL", author.email.as_str()) |
| 364 | .env("GIT_AUTHOR_DATE", format!("{} +0000", author.time_unix)) |
| 365 | .env("GIT_COMMITTER_NAME", committer.name.as_str()) |
| 366 | .env("GIT_COMMITTER_EMAIL", committer.email.as_str()) |
| 367 | .env( |
| 368 | "GIT_COMMITTER_DATE", |
| 369 | format!("{} +0000", committer.time_unix), |
| 370 | ); |
| 371 | let out = run_raw(cmd, Some(message.as_bytes())).await?; |
| 372 | if !out.status.success() { |
| 373 | return Err(failed("commit-tree", &out)); |
| 374 | } |
| 375 | let oid = stdout_trimmed(&out); |
| 376 | validate_oid(&oid)?; |
| 377 | Ok(oid) |
| 378 | } |
| 379 | |
| 380 | |
| 381 | |
| 382 | pub async fn update_ref_cas( |
| 383 | env: &GitEnv, |
| 384 | repo: &Path, |
| 385 | refname: &str, |
| 386 | new: &str, |
| 387 | old: &str, |
| 388 | ) -> Result<()> { |
| 389 | validate_ref(refname)?; |
| 390 | validate_oid(new)?; |
| 391 | validate_oid(old)?; |
| 392 | let cmd = git(env, "update-ref") |
| 393 | .git_dir(repo) |
| 394 | .user_arg(refname)? |
| 395 | .user_arg(new)? |
| 396 | .user_arg(old)?; |
| 397 | let out = run_raw(cmd, None).await?; |
| 398 | if out.status.success() { |
| 399 | crate::maintenance::mark_prune_due(repo); |
| 400 | return Ok(()); |
| 401 | } |
| 402 | let stderr = String::from_utf8_lossy(&out.stderr); |
| 403 | if stderr.contains("but expected") || stderr.contains("unable to resolve reference") { |
| 404 | return Err(Error::RefMoved(refname.to_owned())); |
| 405 | } |
| 406 | Err(failed("update-ref", &out)) |
| 407 | } |
| 408 | |
| 409 | |
| 410 | |
| 411 | pub async fn set_ref(env: &GitEnv, repo: &Path, refname: &str, new: &str) -> Result<()> { |
| 412 | |
| 413 | let queue_ok = refname |
| 414 | .strip_prefix("refs/forge/merge-queue/") |
| 415 | .is_some_and(valid_branch_rest); |
| 416 | if !queue_ok { |
| 417 | return Err(Error::InvalidInput(format!( |
| 418 | "invalid ref name: {refname:?}" |
| 419 | ))); |
| 420 | } |
| 421 | validate_oid(new)?; |
| 422 | let cmd = git(env, "update-ref") |
| 423 | .git_dir(repo) |
| 424 | .user_arg(refname)? |
| 425 | .user_arg(new)?; |
| 426 | let out = run_raw(cmd, None).await?; |
| 427 | if out.status.success() { |
| 428 | return Ok(()); |
| 429 | } |
| 430 | Err(failed("update-ref", &out)) |
| 431 | } |
| 432 | |
| 433 | |
| 434 | |
| 435 | |
| 436 | |
| 437 | pub async fn delete_ref_cas(env: &GitEnv, repo: &Path, refname: &str, old: &str) -> Result<()> { |
| 438 | validate_ref(refname)?; |
| 439 | validate_oid(old)?; |
| 440 | let cmd = git(env, "update-ref") |
| 441 | .git_dir(repo) |
| 442 | .arg("-d") |
| 443 | .user_arg(refname)? |
| 444 | .user_arg(old)?; |
| 445 | let out = run_raw(cmd, None).await?; |
| 446 | if out.status.success() { |
| 447 | return Ok(()); |
| 448 | } |
| 449 | let stderr = String::from_utf8_lossy(&out.stderr); |
| 450 | if stderr.contains("but expected") || stderr.contains("unable to resolve reference") { |
| 451 | return Err(Error::RefMoved(refname.to_owned())); |
| 452 | } |
| 453 | Err(failed("update-ref", &out)) |
| 454 | } |
| 455 | |
| 456 | |
| 457 | |
| 458 | pub async fn range_diff_files( |
| 459 | env: &GitEnv, |
| 460 | repo: &Path, |
| 461 | base_oid: &str, |
| 462 | head_oid: &str, |
| 463 | limits: DiffLimits, |
| 464 | ) -> Result<CommitDiff> { |
| 465 | range_diff_files_with( |
| 466 | env, |
| 467 | repo, |
| 468 | ObjectSource::default(), |
| 469 | base_oid, |
| 470 | head_oid, |
| 471 | limits, |
| 472 | ) |
| 473 | .await |
| 474 | } |
| 475 | |
| 476 | |
| 477 | pub async fn range_diff_files_with( |
| 478 | env: &GitEnv, |
| 479 | repo: &Path, |
| 480 | src: ObjectSource<'_>, |
| 481 | base_oid: &str, |
| 482 | head_oid: &str, |
| 483 | limits: DiffLimits, |
| 484 | ) -> Result<CommitDiff> { |
| 485 | range_diff_files_ws(env, repo, src, base_oid, head_oid, limits, false).await |
| 486 | } |
| 487 | |
| 488 | |
| 489 | pub async fn range_diff_files_ws( |
| 490 | env: &GitEnv, |
| 491 | repo: &Path, |
| 492 | src: ObjectSource<'_>, |
| 493 | base_oid: &str, |
| 494 | head_oid: &str, |
| 495 | limits: DiffLimits, |
| 496 | ignore_ws: bool, |
| 497 | ) -> Result<CommitDiff> { |
| 498 | validate_oid(base_oid)?; |
| 499 | validate_oid(head_oid)?; |
| 500 | let from = match merge_base_with(env, repo, src, base_oid, head_oid).await? { |
| 501 | Some(b) => b, |
| 502 | None => empty_tree_for(head_oid).to_owned(), |
| 503 | }; |
| 504 | diff_between(env, repo, src, &from, head_oid, limits, ignore_ws).await |
| 505 | } |
| 506 | |
| 507 | |
| 508 | |
| 509 | pub async fn range_log( |
| 510 | env: &GitEnv, |
| 511 | repo: &Path, |
| 512 | base_oid: &str, |
| 513 | head_oid: &str, |
| 514 | max: usize, |
| 515 | ) -> Result<Vec<CommitInfo>> { |
| 516 | range_log_with(env, repo, ObjectSource::default(), base_oid, head_oid, max).await |
| 517 | } |
| 518 | |
| 519 | |
| 520 | pub async fn range_log_with( |
| 521 | env: &GitEnv, |
| 522 | repo: &Path, |
| 523 | src: ObjectSource<'_>, |
| 524 | base_oid: &str, |
| 525 | head_oid: &str, |
| 526 | max: usize, |
| 527 | ) -> Result<Vec<CommitInfo>> { |
| 528 | validate_oid(base_oid)?; |
| 529 | validate_oid(head_oid)?; |
| 530 | new_commits_with(env, repo, src, Some(base_oid), head_oid, max).await |
| 531 | } |
| 532 | |
| 533 | |
| 534 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 535 | pub enum RebaseResult { |
| 536 | |
| 537 | |
| 538 | Clean { tip: String, count: usize }, |
| 539 | |
| 540 | Conflict { commit: String, files: Vec<String> }, |
| 541 | } |
| 542 | |
| 543 | |
| 544 | |
| 545 | |
| 546 | |
| 547 | pub async fn rebase_commits( |
| 548 | env: &GitEnv, |
| 549 | repo: &Path, |
| 550 | base_oid: &str, |
| 551 | head_oid: &str, |
| 552 | committer: &Signature, |
| 553 | ) -> Result<RebaseResult> { |
| 554 | validate_oid(base_oid)?; |
| 555 | validate_oid(head_oid)?; |
| 556 | let negated = format!("^{base_oid}"); |
| 557 | let cmd = git(env, "rev-list") |
| 558 | .git_dir(repo) |
| 559 | .arg("--reverse") |
| 560 | .arg("--topo-order") |
| 561 | .arg("--no-merges") |
| 562 | .user_revs(&[head_oid, negated.as_str()])?; |
| 563 | let out = run_raw(cmd, None).await?; |
| 564 | if !out.status.success() { |
| 565 | return Err(failed("rev-list", &out)); |
| 566 | } |
| 567 | let commits: Vec<String> = String::from_utf8_lossy(&out.stdout) |
| 568 | .lines() |
| 569 | .map(str::to_owned) |
| 570 | .collect(); |
| 571 | let mut tip = base_oid.to_owned(); |
| 572 | let mut count = 0usize; |
| 573 | for commit in commits { |
| 574 | validate_oid(&commit)?; |
| 575 | let cmd = git(env, "log") |
| 576 | .git_dir(repo) |
| 577 | .arg("-1") |
| 578 | .arg("--format=%P%x00%an%x00%ae%x00%at%x00%B") |
| 579 | .user_revs(&[commit.as_str()])?; |
| 580 | let out = run_raw(cmd, None).await?; |
| 581 | if !out.status.success() { |
| 582 | return Err(failed("log", &out)); |
| 583 | } |
| 584 | let text = String::from_utf8_lossy(&out.stdout).into_owned(); |
| 585 | let mut parts = text.splitn(5, '\0'); |
| 586 | let parents = parts.next().unwrap_or_default(); |
| 587 | let name = parts.next().unwrap_or_default().to_owned(); |
| 588 | let email = parts.next().unwrap_or_default().to_owned(); |
| 589 | let time_unix = parts |
| 590 | .next() |
| 591 | .and_then(|t| t.trim().parse::<i64>().ok()) |
| 592 | .unwrap_or(committer.time_unix); |
| 593 | let message = parts.next().unwrap_or_default().to_owned(); |
| 594 | let Some(parent) = parents.split_whitespace().next() else { |
| 595 | return Err(Error::InvalidInput( |
| 596 | "cannot rebase a root commit onto the base".into(), |
| 597 | )); |
| 598 | }; |
| 599 | validate_oid(parent)?; |
| 600 | let cmd = git(env, "merge-tree") |
| 601 | .git_dir(repo) |
| 602 | .arg("--write-tree") |
| 603 | .arg("--name-only") |
| 604 | .arg("--no-messages") |
| 605 | .user_opt("--merge-base", parent)? |
| 606 | .user_revs(&[tip.as_str(), commit.as_str()])?; |
| 607 | let out = run_raw(cmd, None).await?; |
| 608 | let text = String::from_utf8_lossy(&out.stdout).into_owned(); |
| 609 | let tree = match out.status.code() { |
| 610 | Some(0) => text.lines().next().unwrap_or_default().trim().to_owned(), |
| 611 | Some(1) => { |
| 612 | let mut files: Vec<String> = Vec::new(); |
| 613 | for line in text |
| 614 | .lines() |
| 615 | .skip(1) |
| 616 | .map(str::trim) |
| 617 | .filter(|l| !l.is_empty()) |
| 618 | { |
| 619 | if !files.iter().any(|f| f == line) { |
| 620 | files.push(line.to_owned()); |
| 621 | } |
| 622 | } |
| 623 | return Ok(RebaseResult::Conflict { commit, files }); |
| 624 | } |
| 625 | _ => return Err(failed("merge-tree", &out)), |
| 626 | }; |
| 627 | validate_oid(&tree)?; |
| 628 | let tip_tree = format!("{tip}^{{tree}}"); |
| 629 | let cmd = git(env, "rev-parse") |
| 630 | .git_dir(repo) |
| 631 | .arg("--verify") |
| 632 | .user_revs(&[tip_tree.as_str()])?; |
| 633 | let out = run_raw(cmd, None).await?; |
| 634 | if !out.status.success() { |
| 635 | return Err(failed("rev-parse", &out)); |
| 636 | } |
| 637 | if stdout_trimmed(&out) == tree { |
| 638 | continue; |
| 639 | } |
| 640 | let author = Signature { |
| 641 | name, |
| 642 | email, |
| 643 | time_unix, |
| 644 | }; |
| 645 | tip = commit_tree( |
| 646 | env, |
| 647 | repo, |
| 648 | &tree, |
| 649 | &[tip.as_str()], |
| 650 | message.trim_end_matches('\n'), |
| 651 | &author, |
| 652 | committer, |
| 653 | ) |
| 654 | .await?; |
| 655 | count += 1; |
| 656 | } |
| 657 | Ok(RebaseResult::Clean { tip, count }) |
| 658 | } |
| 659 | |
| 660 | |
| 661 | #[derive(Debug, Clone, Copy)] |
| 662 | pub struct FileEdit<'a> { |
| 663 | |
| 664 | pub path: &'a str, |
| 665 | |
| 666 | pub content: &'a [u8], |
| 667 | } |
| 668 | |
| 669 | static EDIT_INDEX_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 670 | |
| 671 | |
| 672 | |
| 673 | |
| 674 | |
| 675 | #[allow(clippy::too_many_arguments)] |
| 676 | pub async fn commit_file_edit( |
| 677 | env: &GitEnv, |
| 678 | repo: &Path, |
| 679 | refname: &str, |
| 680 | base: &str, |
| 681 | edit: &FileEdit<'_>, |
| 682 | message: &str, |
| 683 | author: &Signature, |
| 684 | committer: &Signature, |
| 685 | ) -> Result<String> { |
| 686 | validate_ref(refname)?; |
| 687 | validate_oid(base)?; |
| 688 | validate_blob_path(edit.path)?; |
| 689 | let seq = EDIT_INDEX_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 690 | let index = repo.join(format!("forge-edit-index-{}-{seq}", std::process::id())); |
| 691 | let result = edit_and_commit( |
| 692 | env, repo, &index, refname, base, edit, message, author, committer, |
| 693 | ) |
| 694 | .await; |
| 695 | |
| 696 | let _ = tokio::fs::remove_file(&index).await; |
| 697 | result |
| 698 | } |
| 699 | |
| 700 | #[allow(clippy::too_many_arguments)] |
| 701 | async fn edit_and_commit( |
| 702 | env: &GitEnv, |
| 703 | repo: &Path, |
| 704 | index: &Path, |
| 705 | refname: &str, |
| 706 | base: &str, |
| 707 | edit: &FileEdit<'_>, |
| 708 | message: &str, |
| 709 | author: &Signature, |
| 710 | committer: &Signature, |
| 711 | ) -> Result<String> { |
| 712 | let blob = GitCommand::new(env, "hash-object") |
| 713 | .git_dir(repo) |
| 714 | .arg("-w") |
| 715 | .arg("--stdin") |
| 716 | .output_stdin(edit.content) |
| 717 | .await?; |
| 718 | let blob = String::from_utf8_lossy(&blob).trim().to_owned(); |
| 719 | validate_oid(&blob)?; |
| 720 | |
| 721 | GitCommand::new(env, "read-tree") |
| 722 | .git_dir(repo) |
| 723 | .env("GIT_INDEX_FILE", index) |
| 724 | .user_arg(base)? |
| 725 | .status() |
| 726 | .await?; |
| 727 | |
| 728 | |
| 729 | |
| 730 | let listing = GitCommand::new(env, "ls-files") |
| 731 | .git_dir(repo) |
| 732 | .env("GIT_INDEX_FILE", index) |
| 733 | .arg("-s") |
| 734 | .arg("-z") |
| 735 | .arg("--") |
| 736 | .user_arg(edit.path)? |
| 737 | .output() |
| 738 | .await?; |
| 739 | let entry = |
| 740 | String::from_utf8_lossy(listing.split(|b| *b == 0).next().unwrap_or_default()).into_owned(); |
| 741 | let mode = match entry.split_once('\t') { |
| 742 | Some((meta, path)) if path == edit.path => meta.split_whitespace().next().unwrap_or(""), |
| 743 | _ => "", |
| 744 | }; |
| 745 | if mode != "100644" && mode != "100755" { |
| 746 | return Err(Error::InvalidInput(format!( |
| 747 | "{} is not a regular file at this commit", |
| 748 | edit.path |
| 749 | ))); |
| 750 | } |
| 751 | let mode = mode.to_owned(); |
| 752 | |
| 753 | GitCommand::new(env, "update-index") |
| 754 | .git_dir(repo) |
| 755 | .env("GIT_INDEX_FILE", index) |
| 756 | .arg("--add") |
| 757 | .arg("--cacheinfo") |
| 758 | .user_arg(&mode)? |
| 759 | .user_arg(&blob)? |
| 760 | .user_arg(edit.path)? |
| 761 | .status() |
| 762 | .await?; |
| 763 | |
| 764 | let tree = GitCommand::new(env, "write-tree") |
| 765 | .git_dir(repo) |
| 766 | .env("GIT_INDEX_FILE", index) |
| 767 | .output() |
| 768 | .await?; |
| 769 | let tree = String::from_utf8_lossy(&tree).trim().to_owned(); |
| 770 | |
| 771 | let commit = commit_tree(env, repo, &tree, &[base], message, author, committer).await?; |
| 772 | update_ref_cas(env, repo, refname, &commit, base).await?; |
| 773 | Ok(commit) |
| 774 | } |
| 775 | |
| 776 | #[cfg(test)] |
| 777 | mod tests { |
| 778 | use super::*; |
| 779 | use crate::history::DiffStatus; |
| 780 | use std::path::PathBuf; |
| 781 | use std::process::Command; |
| 782 | |
| 783 | const LIMITS: DiffLimits = DiffLimits { |
| 784 | max_files: 100, |
| 785 | max_lines_per_file: 1000, |
| 786 | max_total_lines: 10_000, |
| 787 | }; |
| 788 | |
| 789 | |
| 790 | fn git_in(dir: &Path, home: &Path, args: &[&str]) -> String { |
| 791 | let out = Command::new("/usr/bin/git") |
| 792 | .arg("-C") |
| 793 | .arg(dir) |
| 794 | .args(["-c", "commit.gpgsign=false"]) |
| 795 | .args(args) |
| 796 | .env_clear() |
| 797 | .env("PATH", "/usr/bin:/bin") |
| 798 | .env("HOME", home) |
| 799 | .env("GIT_CONFIG_NOSYSTEM", "1") |
| 800 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 801 | .env("GIT_AUTHOR_NAME", "Tester") |
| 802 | .env("GIT_AUTHOR_EMAIL", "tester@example.com") |
| 803 | .env("GIT_COMMITTER_NAME", "Tester") |
| 804 | .env("GIT_COMMITTER_EMAIL", "tester@example.com") |
| 805 | .output() |
| 806 | .expect("git runs"); |
| 807 | assert!( |
| 808 | out.status.success(), |
| 809 | "git {args:?} failed: {}", |
| 810 | String::from_utf8_lossy(&out.stderr) |
| 811 | ); |
| 812 | String::from_utf8_lossy(&out.stdout).trim().to_owned() |
| 813 | } |
| 814 | |
| 815 | struct Sandbox { |
| 816 | _dir: tempfile::TempDir, |
| 817 | home: PathBuf, |
| 818 | } |
| 819 | |
| 820 | impl Sandbox { |
| 821 | |
| 822 | |
| 823 | fn new() -> Self { |
| 824 | let dir = tempfile::tempdir().expect("tempdir"); |
| 825 | let home = dir.path().join("home"); |
| 826 | std::fs::create_dir(&home).expect("home dir"); |
| 827 | crate::setup::write_managed_gitconfig(&home).expect("managed gitconfig"); |
| 828 | Self { _dir: dir, home } |
| 829 | } |
| 830 | |
| 831 | fn env(&self) -> GitEnv { |
| 832 | GitEnv { |
| 833 | git_bin: PathBuf::from("/usr/bin/git"), |
| 834 | data_dir: self.home.clone(), |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | |
| 839 | fn repo(&self, name: &str) -> Work { |
| 840 | let work = self._dir.path().join(name); |
| 841 | std::fs::create_dir(&work).expect("work dir"); |
| 842 | git_in(&work, &self.home, &["init", "-q", "-b", "main"]); |
| 843 | Work { |
| 844 | work, |
| 845 | home: self.home.clone(), |
| 846 | } |
| 847 | } |
| 848 | } |
| 849 | |
| 850 | struct Work { |
| 851 | work: PathBuf, |
| 852 | home: PathBuf, |
| 853 | } |
| 854 | |
| 855 | impl Work { |
| 856 | fn git_dir(&self) -> PathBuf { |
| 857 | self.work.join(".git") |
| 858 | } |
| 859 | |
| 860 | fn git(&self, args: &[&str]) -> String { |
| 861 | git_in(&self.work, &self.home, args) |
| 862 | } |
| 863 | |
| 864 | fn write(&self, name: &str, content: &str) { |
| 865 | std::fs::write(self.work.join(name), content).expect("write file"); |
| 866 | } |
| 867 | |
| 868 | |
| 869 | fn commit(&self, msg: &str) -> String { |
| 870 | self.git(&["add", "-A"]); |
| 871 | self.git(&["commit", "-q", "--allow-empty", "-m", msg]); |
| 872 | self.git(&["rev-parse", "HEAD"]) |
| 873 | } |
| 874 | } |
| 875 | |
| 876 | #[tokio::test] |
| 877 | async fn clean_merge_builds_merge_commit_with_author() { |
| 878 | let sb = Sandbox::new(); |
| 879 | let env = sb.env(); |
| 880 | let w = sb.repo("repo"); |
| 881 | w.write("a.txt", "1\n"); |
| 882 | let c0 = w.commit("c0"); |
| 883 | w.git(&["switch", "-q", "-c", "feature"]); |
| 884 | w.write("b.txt", "feature\n"); |
| 885 | let head = w.commit("feature work"); |
| 886 | w.git(&["switch", "-q", "main"]); |
| 887 | w.write("c.txt", "main\n"); |
| 888 | let base = w.commit("main work"); |
| 889 | let gd = w.git_dir(); |
| 890 | |
| 891 | assert_eq!( |
| 892 | merge_base(&env, &gd, &base, &head) |
| 893 | .await |
| 894 | .expect("merge-base"), |
| 895 | Some(c0) |
| 896 | ); |
| 897 | let tree = match check_merge(&env, &gd, &base, &head).await.expect("check") { |
| 898 | MergeCheck::Clean { tree } => tree, |
| 899 | other => panic!("expected clean merge, got {other:?}"), |
| 900 | }; |
| 901 | assert_eq!(tree.len(), 40); |
| 902 | |
| 903 | let author = Signature { |
| 904 | name: "Tahinli Author".into(), |
| 905 | email: "tahinli@example.com".into(), |
| 906 | time_unix: 1_700_000_000, |
| 907 | }; |
| 908 | let committer = Signature { |
| 909 | name: "Carol Committer".into(), |
| 910 | email: "carol@example.com".into(), |
| 911 | time_unix: 1_700_000_100, |
| 912 | }; |
| 913 | let merge = commit_tree( |
| 914 | &env, |
| 915 | &gd, |
| 916 | &tree, |
| 917 | &[base.as_str(), head.as_str()], |
| 918 | "Merge pull request #1 from owner/feature\n\nFeature", |
| 919 | &author, |
| 920 | &committer, |
| 921 | ) |
| 922 | .await |
| 923 | .expect("commit-tree"); |
| 924 | |
| 925 | assert_eq!( |
| 926 | w.git(&["rev-list", "--parents", "-n1", merge.as_str()]), |
| 927 | format!("{merge} {base} {head}") |
| 928 | ); |
| 929 | assert_eq!( |
| 930 | w.git(&[ |
| 931 | "log", |
| 932 | "-1", |
| 933 | "--format=%T|%an|%ae|%at|%cn|%ce|%ct|%s", |
| 934 | merge.as_str() |
| 935 | ]), |
| 936 | format!( |
| 937 | "{tree}|Tahinli Author|tahinli@example.com|1700000000|Carol Committer|carol@example.com|1700000100|Merge pull request #1 from owner/feature" |
| 938 | ) |
| 939 | ); |
| 940 | assert!( |
| 941 | is_ancestor(&env, &gd, &head, &merge) |
| 942 | .await |
| 943 | .expect("ancestor") |
| 944 | ); |
| 945 | } |
| 946 | |
| 947 | #[tokio::test] |
| 948 | async fn conflicting_merge_lists_the_file() { |
| 949 | let sb = Sandbox::new(); |
| 950 | let env = sb.env(); |
| 951 | let w = sb.repo("repo"); |
| 952 | w.write("f.txt", "base\n"); |
| 953 | w.commit("c0"); |
| 954 | w.git(&["switch", "-q", "-c", "feature"]); |
| 955 | w.write("f.txt", "head\n"); |
| 956 | let head = w.commit("feature edits f"); |
| 957 | w.git(&["switch", "-q", "main"]); |
| 958 | w.write("f.txt", "other\n"); |
| 959 | let base = w.commit("main edits f"); |
| 960 | |
| 961 | let check = check_merge(&env, &w.git_dir(), &base, &head) |
| 962 | .await |
| 963 | .expect("check"); |
| 964 | assert_eq!( |
| 965 | check, |
| 966 | MergeCheck::Conflict { |
| 967 | files: vec!["f.txt".to_owned()] |
| 968 | } |
| 969 | ); |
| 970 | } |
| 971 | |
| 972 | #[tokio::test] |
| 973 | async fn head_contained_in_base_is_up_to_date() { |
| 974 | let sb = Sandbox::new(); |
| 975 | let env = sb.env(); |
| 976 | let w = sb.repo("repo"); |
| 977 | w.write("a.txt", "1\n"); |
| 978 | let c0 = w.commit("c0"); |
| 979 | w.write("a.txt", "2\n"); |
| 980 | let c1 = w.commit("c1"); |
| 981 | let gd = w.git_dir(); |
| 982 | |
| 983 | assert_eq!( |
| 984 | check_merge(&env, &gd, &c1, &c0).await.expect("check"), |
| 985 | MergeCheck::UpToDate |
| 986 | ); |
| 987 | assert!(is_ancestor(&env, &gd, &c0, &c1).await.expect("ancestor")); |
| 988 | assert!(!is_ancestor(&env, &gd, &c1, &c0).await.expect("ancestor")); |
| 989 | } |
| 990 | |
| 991 | #[tokio::test] |
| 992 | async fn update_ref_cas_succeeds_then_refuses_stale_old() { |
| 993 | let sb = Sandbox::new(); |
| 994 | let env = sb.env(); |
| 995 | let w = sb.repo("repo"); |
| 996 | w.write("a.txt", "1\n"); |
| 997 | let c0 = w.commit("c0"); |
| 998 | w.write("a.txt", "2\n"); |
| 999 | let c1 = w.commit("c1"); |
| 1000 | w.write("a.txt", "3\n"); |
| 1001 | let c2 = w.commit("c2"); |
| 1002 | let gd = w.git_dir(); |
| 1003 | |
| 1004 | |
| 1005 | let stale = update_ref_cas(&env, &gd, "refs/heads/main", &c1, &c0).await; |
| 1006 | assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}"); |
| 1007 | assert_eq!(w.git(&["rev-parse", "main"]), c2); |
| 1008 | |
| 1009 | update_ref_cas(&env, &gd, "refs/heads/main", &c1, &c2) |
| 1010 | .await |
| 1011 | .expect("cas with current old"); |
| 1012 | assert_eq!(w.git(&["rev-parse", "main"]), c1); |
| 1013 | } |
| 1014 | |
| 1015 | #[tokio::test] |
| 1016 | async fn delete_ref_cas_deletes_only_at_expected_value() { |
| 1017 | let sb = Sandbox::new(); |
| 1018 | let env = sb.env(); |
| 1019 | let w = sb.repo("repo"); |
| 1020 | w.write("a.txt", "1\n"); |
| 1021 | let c0 = w.commit("c0"); |
| 1022 | w.git(&["branch", "topic"]); |
| 1023 | w.write("a.txt", "2\n"); |
| 1024 | let c1 = w.commit("c1"); |
| 1025 | let gd = w.git_dir(); |
| 1026 | |
| 1027 | |
| 1028 | let stale = delete_ref_cas(&env, &gd, "refs/heads/topic", &c1).await; |
| 1029 | assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}"); |
| 1030 | assert_eq!(w.git(&["rev-parse", "topic"]), c0); |
| 1031 | |
| 1032 | delete_ref_cas(&env, &gd, "refs/heads/topic", &c0) |
| 1033 | .await |
| 1034 | .expect("delete at current value"); |
| 1035 | let gone = w.git(&["for-each-ref", "refs/heads/topic"]); |
| 1036 | assert!(gone.is_empty(), "{gone:?}"); |
| 1037 | |
| 1038 | |
| 1039 | let missing = delete_ref_cas(&env, &gd, "refs/heads/topic", &c0).await; |
| 1040 | assert!(matches!(missing, Err(Error::RefMoved(_))), "{missing:?}"); |
| 1041 | } |
| 1042 | |
| 1043 | #[tokio::test] |
| 1044 | async fn range_log_returns_head_side_commits_oldest_first() { |
| 1045 | let sb = Sandbox::new(); |
| 1046 | let env = sb.env(); |
| 1047 | let w = sb.repo("repo"); |
| 1048 | w.write("a.txt", "1\n"); |
| 1049 | w.commit("c0"); |
| 1050 | w.git(&["switch", "-q", "-c", "feature"]); |
| 1051 | w.write("f1.txt", "1\n"); |
| 1052 | w.commit("f1"); |
| 1053 | w.write("f2.txt", "1\n"); |
| 1054 | let head = w.commit("f2"); |
| 1055 | w.git(&["switch", "-q", "main"]); |
| 1056 | w.write("m.txt", "1\n"); |
| 1057 | let base = w.commit("m1"); |
| 1058 | |
| 1059 | let log = range_log(&env, &w.git_dir(), &base, &head, 100) |
| 1060 | .await |
| 1061 | .expect("range log"); |
| 1062 | let summaries: Vec<&str> = log.iter().map(|c| c.summary.as_str()).collect(); |
| 1063 | assert_eq!(summaries, vec!["f1", "f2"]); |
| 1064 | } |
| 1065 | |
| 1066 | #[tokio::test] |
| 1067 | async fn range_diff_shows_only_head_side_after_base_moved() { |
| 1068 | let sb = Sandbox::new(); |
| 1069 | let env = sb.env(); |
| 1070 | let w = sb.repo("repo"); |
| 1071 | w.write("a.txt", "1\n"); |
| 1072 | w.commit("c0"); |
| 1073 | w.git(&["switch", "-q", "-c", "feature"]); |
| 1074 | w.write("feat.txt", "feature\n"); |
| 1075 | let head = w.commit("feature"); |
| 1076 | w.git(&["switch", "-q", "main"]); |
| 1077 | w.write("base.txt", "base\n"); |
| 1078 | let base = w.commit("base moves"); |
| 1079 | |
| 1080 | let diff = range_diff_files(&env, &w.git_dir(), &base, &head, LIMITS) |
| 1081 | .await |
| 1082 | .expect("range diff"); |
| 1083 | let paths: Vec<String> = diff |
| 1084 | .files |
| 1085 | .iter() |
| 1086 | .map(|f| f.new_path.clone().unwrap_or_default()) |
| 1087 | .collect(); |
| 1088 | assert_eq!(paths, vec!["feat.txt".to_owned()]); |
| 1089 | assert_eq!(diff.files[0].status, DiffStatus::Added); |
| 1090 | } |
| 1091 | |
| 1092 | |
| 1093 | fn has_object(git_dir: &Path, oid: &str) -> bool { |
| 1094 | Command::new("/usr/bin/git") |
| 1095 | .arg("--git-dir") |
| 1096 | .arg(git_dir) |
| 1097 | .args(["cat-file", "-e", oid]) |
| 1098 | .env_clear() |
| 1099 | .env("PATH", "/usr/bin:/bin") |
| 1100 | .env("GIT_CONFIG_NOSYSTEM", "1") |
| 1101 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 1102 | .status() |
| 1103 | .expect("git runs") |
| 1104 | .success() |
| 1105 | } |
| 1106 | |
| 1107 | #[tokio::test] |
| 1108 | async fn alternate_objects_read_fork_commit_without_copying_it() { |
| 1109 | let sb = Sandbox::new(); |
| 1110 | let env = sb.env(); |
| 1111 | let base = sb.repo("base"); |
| 1112 | base.write("a.txt", "1\n"); |
| 1113 | let base_tip = base.commit("base"); |
| 1114 | |
| 1115 | let fork_dir = sb._dir.path().join("fork"); |
| 1116 | git_in( |
| 1117 | sb._dir.path(), |
| 1118 | &sb.home, |
| 1119 | &["clone", "-q", base.work.to_str().expect("utf8"), "fork"], |
| 1120 | ); |
| 1121 | let fork = Work { |
| 1122 | work: fork_dir, |
| 1123 | home: sb.home.clone(), |
| 1124 | }; |
| 1125 | fork.write("b.txt", "fork\n"); |
| 1126 | let fork_head = fork.commit("fork work"); |
| 1127 | let base_git = base.git_dir(); |
| 1128 | let fork_objects = fork.git_dir().join("objects"); |
| 1129 | assert!(!has_object(&base_git, &fork_head)); |
| 1130 | |
| 1131 | |
| 1132 | assert!( |
| 1133 | range_log(&env, &base_git, &base_tip, &fork_head, 10) |
| 1134 | .await |
| 1135 | .is_err() |
| 1136 | ); |
| 1137 | |
| 1138 | let src = ObjectSource { |
| 1139 | extra: Some(fork_objects.as_path()), |
| 1140 | }; |
| 1141 | let log = range_log_with(&env, &base_git, src, &base_tip, &fork_head, 10) |
| 1142 | .await |
| 1143 | .expect("range log through alternate"); |
| 1144 | let summaries: Vec<&str> = log.iter().map(|c| c.summary.as_str()).collect(); |
| 1145 | assert_eq!(summaries, vec!["fork work"]); |
| 1146 | |
| 1147 | let merge = merge_base_with(&env, &base_git, src, &base_tip, &fork_head) |
| 1148 | .await |
| 1149 | .expect("merge base through alternate"); |
| 1150 | assert_eq!(merge.as_deref(), Some(base_tip.as_str())); |
| 1151 | |
| 1152 | let diff = range_diff_files_with(&env, &base_git, src, &base_tip, &fork_head, LIMITS) |
| 1153 | .await |
| 1154 | .expect("range diff through alternate"); |
| 1155 | let paths: Vec<String> = diff |
| 1156 | .files |
| 1157 | .iter() |
| 1158 | .map(|f| f.new_path.clone().unwrap_or_default()) |
| 1159 | .collect(); |
| 1160 | assert_eq!(paths, vec!["b.txt".to_owned()]); |
| 1161 | |
| 1162 | |
| 1163 | assert!(!has_object(&base_git, &fork_head)); |
| 1164 | } |
| 1165 | |
| 1166 | #[tokio::test] |
| 1167 | async fn fetch_into_pull_ref_from_fork_and_same_repo() { |
| 1168 | let sb = Sandbox::new(); |
| 1169 | let env = sb.env(); |
| 1170 | let base = sb.repo("base"); |
| 1171 | base.write("a.txt", "1\n"); |
| 1172 | let base_tip = base.commit("base"); |
| 1173 | let fork = sb.repo("fork"); |
| 1174 | fork.write("x.txt", "fork\n"); |
| 1175 | let fork_tip = fork.commit("fork work"); |
| 1176 | |
| 1177 | fetch_into_pull_ref(&env, &base.git_dir(), &fork.git_dir(), &fork_tip, 1) |
| 1178 | .await |
| 1179 | .expect("fork fetch"); |
| 1180 | assert_eq!(base.git(&["rev-parse", "refs/pull/1/head"]), fork_tip); |
| 1181 | |
| 1182 | fetch_into_pull_ref(&env, &base.git_dir(), &base.git_dir(), &base_tip, 2) |
| 1183 | .await |
| 1184 | .expect("same-repo update"); |
| 1185 | assert_eq!(base.git(&["rev-parse", "refs/pull/2/head"]), base_tip); |
| 1186 | } |
| 1187 | |
| 1188 | #[tokio::test] |
| 1189 | async fn fetch_into_pull_ref_handles_unadvertised_fork_commit() { |
| 1190 | let sb = Sandbox::new(); |
| 1191 | let env = sb.env(); |
| 1192 | let base = sb.repo("base"); |
| 1193 | base.write("a.txt", "1\n"); |
| 1194 | base.commit("base"); |
| 1195 | let fork = sb.repo("fork"); |
| 1196 | fork.write("x.txt", "fork\n"); |
| 1197 | fork.commit("main work"); |
| 1198 | fork.git(&["switch", "-q", "-c", "topic"]); |
| 1199 | fork.write("y.txt", "topic\n"); |
| 1200 | let topic_tip = fork.commit("topic work"); |
| 1201 | fork.git(&["switch", "-q", "main"]); |
| 1202 | fork.git(&["branch", "-q", "-D", "topic"]); |
| 1203 | |
| 1204 | fetch_into_pull_ref(&env, &base.git_dir(), &fork.git_dir(), &topic_tip, 3) |
| 1205 | .await |
| 1206 | .expect("unadvertised fetch"); |
| 1207 | assert_eq!(base.git(&["rev-parse", "refs/pull/3/head"]), topic_tip); |
| 1208 | } |
| 1209 | |
| 1210 | #[tokio::test] |
| 1211 | async fn blob_at_returns_blob_ids_for_files_only() { |
| 1212 | let sb = Sandbox::new(); |
| 1213 | let env = sb.env(); |
| 1214 | let w = sb.repo("repo"); |
| 1215 | let gd = w.git_dir(); |
| 1216 | w.write("a.txt", "1\n"); |
| 1217 | std::fs::create_dir(w.work.join("dir")).expect("dir"); |
| 1218 | w.write("dir/x.txt", "x\n"); |
| 1219 | let c0 = w.commit("c0"); |
| 1220 | let a0 = w.git(&["hash-object", "a.txt"]); |
| 1221 | |
| 1222 | assert_eq!( |
| 1223 | blob_at(&env, &gd, &c0, "a.txt").await.expect("ok"), |
| 1224 | Some(a0.clone()) |
| 1225 | ); |
| 1226 | assert_eq!( |
| 1227 | blob_at(&env, &gd, &c0, "dir/x.txt").await.expect("ok"), |
| 1228 | Some(w.git(&["hash-object", "dir/x.txt"])) |
| 1229 | ); |
| 1230 | assert_eq!( |
| 1231 | blob_at(&env, &gd, &c0, "missing.txt").await.expect("ok"), |
| 1232 | None |
| 1233 | ); |
| 1234 | assert_eq!(blob_at(&env, &gd, &c0, "dir").await.expect("ok"), None); |
| 1235 | |
| 1236 | w.write("a.txt", "2\n"); |
| 1237 | let c1 = w.commit("c1"); |
| 1238 | let a1 = blob_at(&env, &gd, &c1, "a.txt").await.expect("ok"); |
| 1239 | assert_eq!(a1, Some(w.git(&["hash-object", "a.txt"]))); |
| 1240 | assert_ne!(a1, Some(a0)); |
| 1241 | |
| 1242 | let old_spec = format!("{c0}:a.txt"); |
| 1243 | assert_eq!( |
| 1244 | blob_at(&env, &gd, &c0, "a.txt").await.expect("ok"), |
| 1245 | Some(w.git(&["rev-parse", old_spec.as_str()])) |
| 1246 | ); |
| 1247 | } |
| 1248 | |
| 1249 | #[tokio::test] |
| 1250 | async fn blob_at_handles_literal_special_and_unicode_names() { |
| 1251 | let sb = Sandbox::new(); |
| 1252 | let env = sb.env(); |
| 1253 | let w = sb.repo("repo"); |
| 1254 | let gd = w.git_dir(); |
| 1255 | std::fs::create_dir(w.work.join("dir with space")).expect("dir"); |
| 1256 | w.write("dir with space/füß ü.txt", "u\n"); |
| 1257 | w.write("star*", "s\n"); |
| 1258 | w.write(":colon", "c\n"); |
| 1259 | w.write("other", "o\n"); |
| 1260 | let c0 = w.commit("c0"); |
| 1261 | |
| 1262 | assert_eq!( |
| 1263 | blob_at(&env, &gd, &c0, "dir with space/füß ü.txt") |
| 1264 | .await |
| 1265 | .expect("ok"), |
| 1266 | Some(w.git(&["hash-object", "dir with space/füß ü.txt"])) |
| 1267 | ); |
| 1268 | assert_eq!( |
| 1269 | blob_at(&env, &gd, &c0, "star*").await.expect("ok"), |
| 1270 | Some(w.git(&["hash-object", "star*"])) |
| 1271 | ); |
| 1272 | assert_eq!( |
| 1273 | blob_at(&env, &gd, &c0, ":colon").await.expect("ok"), |
| 1274 | Some(w.git(&["hash-object", ":colon"])) |
| 1275 | ); |
| 1276 | |
| 1277 | assert_eq!(blob_at(&env, &gd, &c0, "st*").await.expect("ok"), None); |
| 1278 | assert_eq!(blob_at(&env, &gd, &c0, "*").await.expect("ok"), None); |
| 1279 | } |
| 1280 | |
| 1281 | #[tokio::test] |
| 1282 | async fn invalid_inputs_are_rejected_before_git() { |
| 1283 | let sb = Sandbox::new(); |
| 1284 | let env = sb.env(); |
| 1285 | let w = sb.repo("repo"); |
| 1286 | w.write("a.txt", "1\n"); |
| 1287 | let c0 = w.commit("c0"); |
| 1288 | let gd = w.git_dir(); |
| 1289 | let short = "a".repeat(39); |
| 1290 | |
| 1291 | for bad in [ |
| 1292 | "", "../x", "a/../x", "/a", "a//b", "a/", "./a", "a/./b", "a\nb", "a\0b", |
| 1293 | ] { |
| 1294 | let r = blob_at(&env, &gd, &c0, bad).await; |
| 1295 | assert!(matches!(r, Err(Error::InvalidInput(_))), "{bad:?}: {r:?}"); |
| 1296 | } |
| 1297 | let r = blob_at(&env, &gd, "not-hex", "a.txt").await; |
| 1298 | assert!(matches!(r, Err(Error::InvalidInput(_))), "{r:?}"); |
| 1299 | |
| 1300 | let bad_oid = |r: Result<()>| assert!(matches!(r, Err(Error::InvalidInput(_))), "{r:?}"); |
| 1301 | bad_oid(check_merge(&env, &gd, "not-hex", &c0).await.map(|_| ())); |
| 1302 | bad_oid(merge_base(&env, &gd, &short, &c0).await.map(|_| ())); |
| 1303 | bad_oid( |
| 1304 | commit_tree( |
| 1305 | &env, |
| 1306 | &gd, |
| 1307 | "--output=/tmp/x", |
| 1308 | &[], |
| 1309 | "m", |
| 1310 | &Signature { |
| 1311 | name: "a".into(), |
| 1312 | email: "a@example.com".into(), |
| 1313 | time_unix: 0, |
| 1314 | }, |
| 1315 | &Signature { |
| 1316 | name: "a".into(), |
| 1317 | email: "a@example.com".into(), |
| 1318 | time_unix: 0, |
| 1319 | }, |
| 1320 | ) |
| 1321 | .await |
| 1322 | .map(|_| ()), |
| 1323 | ); |
| 1324 | bad_oid(update_ref_cas(&env, &gd, "refs/heads/main", "HEAD", &c0).await); |
| 1325 | bad_oid(update_ref_cas(&env, &gd, "refs/heads/../x", &c0, &c0).await); |
| 1326 | bad_oid(update_ref_cas(&env, &gd, "refs/heads/-x", &c0, &c0).await); |
| 1327 | bad_oid(fetch_into_pull_ref(&env, &gd, &gd, "--upload-pack=x", 1).await); |
| 1328 | bad_oid(fetch_into_pull_ref(&env, &gd, &gd, &c0, 0).await); |
| 1329 | bad_oid(range_log(&env, &gd, "main", &c0, 10).await.map(|_| ())); |
| 1330 | bad_oid( |
| 1331 | range_diff_files(&env, &gd, &c0, &short, LIMITS) |
| 1332 | .await |
| 1333 | .map(|_| ()), |
| 1334 | ); |
| 1335 | let bad_name = Signature { |
| 1336 | name: "Eve <eve@example.com>".into(), |
| 1337 | email: "eve@example.com".into(), |
| 1338 | time_unix: 0, |
| 1339 | }; |
| 1340 | bad_oid( |
| 1341 | commit_tree(&env, &gd, &c0, &[], "m", &bad_name, &bad_name) |
| 1342 | .await |
| 1343 | .map(|_| ()), |
| 1344 | ); |
| 1345 | } |
| 1346 | |
| 1347 | #[tokio::test] |
| 1348 | async fn rebase_replays_commits_keeping_authors() { |
| 1349 | let sb = Sandbox::new(); |
| 1350 | let env = sb.env(); |
| 1351 | let w = sb.repo("repo"); |
| 1352 | w.write("a.txt", "1\n"); |
| 1353 | w.commit("c0"); |
| 1354 | w.git(&["switch", "-q", "-c", "feature"]); |
| 1355 | w.write("b.txt", "one\n"); |
| 1356 | w.commit("first"); |
| 1357 | w.write("b.txt", "two\n"); |
| 1358 | let head = w.commit("second"); |
| 1359 | w.git(&["switch", "-q", "main"]); |
| 1360 | w.write("c.txt", "main\n"); |
| 1361 | let base = w.commit("main work"); |
| 1362 | let gd = w.git_dir(); |
| 1363 | let committer = Signature { |
| 1364 | name: "tahinli".into(), |
| 1365 | email: "tahinli@example.com".into(), |
| 1366 | time_unix: 1_700_000_000, |
| 1367 | }; |
| 1368 | let (tip, count) = match rebase_commits(&env, &gd, &base, &head, &committer) |
| 1369 | .await |
| 1370 | .expect("rebase") |
| 1371 | { |
| 1372 | RebaseResult::Clean { tip, count } => (tip, count), |
| 1373 | other => panic!("expected clean, got {other:?}"), |
| 1374 | }; |
| 1375 | assert_eq!(count, 2); |
| 1376 | assert_eq!(w.git(&["rev-parse", &format!("{tip}~2")]), base); |
| 1377 | assert_eq!( |
| 1378 | w.git(&["log", "-1", "--format=%an|%cn|%s", &tip]), |
| 1379 | "Tester|tahinli|second" |
| 1380 | ); |
| 1381 | assert_eq!(w.git(&["show", &format!("{tip}:b.txt")]), "two"); |
| 1382 | assert_eq!(w.git(&["show", &format!("{tip}:c.txt")]), "main"); |
| 1383 | } |
| 1384 | |
| 1385 | #[tokio::test] |
| 1386 | async fn rebase_reports_conflicts() { |
| 1387 | let sb = Sandbox::new(); |
| 1388 | let env = sb.env(); |
| 1389 | let w = sb.repo("repo"); |
| 1390 | w.write("a.txt", "1\n"); |
| 1391 | w.commit("c0"); |
| 1392 | w.git(&["switch", "-q", "-c", "feature"]); |
| 1393 | w.write("a.txt", "feature\n"); |
| 1394 | let head = w.commit("feature edit"); |
| 1395 | w.git(&["switch", "-q", "main"]); |
| 1396 | w.write("a.txt", "main\n"); |
| 1397 | let base = w.commit("main edit"); |
| 1398 | let committer = Signature { |
| 1399 | name: "tahinli".into(), |
| 1400 | email: "tahinli@example.com".into(), |
| 1401 | time_unix: 1_700_000_000, |
| 1402 | }; |
| 1403 | match rebase_commits(&env, &w.git_dir(), &base, &head, &committer) |
| 1404 | .await |
| 1405 | .expect("rebase") |
| 1406 | { |
| 1407 | RebaseResult::Conflict { commit, files } => { |
| 1408 | assert_eq!(commit, head); |
| 1409 | assert_eq!(files, vec!["a.txt".to_owned()]); |
| 1410 | } |
| 1411 | other => panic!("expected conflict, got {other:?}"), |
| 1412 | } |
| 1413 | } |
| 1414 | } |