| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | use std::path::Path; |
| 21 | use std::process::Command; |
| 22 | |
| 23 | use crate::GitError; |
| 24 | |
| 25 | |
| 26 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 27 | pub enum MergeStrategy { |
| 28 | |
| 29 | Merge, |
| 30 | |
| 31 | Squash, |
| 32 | |
| 33 | Rebase, |
| 34 | } |
| 35 | |
| 36 | impl MergeStrategy { |
| 37 | |
| 38 | #[must_use] |
| 39 | pub fn as_str(self) -> &'static str { |
| 40 | match self { |
| 41 | Self::Merge => "merge", |
| 42 | Self::Squash => "squash", |
| 43 | Self::Rebase => "rebase", |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | |
| 48 | |
| 49 | #[must_use] |
| 50 | pub fn from_token(token: &str) -> Self { |
| 51 | match token { |
| 52 | "squash" => Self::Squash, |
| 53 | "rebase" => Self::Rebase, |
| 54 | _ => Self::Merge, |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | |
| 60 | |
| 61 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 62 | pub enum Mergeability { |
| 63 | |
| 64 | Clean, |
| 65 | |
| 66 | AlreadyMerged, |
| 67 | |
| 68 | Conflicts, |
| 69 | } |
| 70 | |
| 71 | |
| 72 | #[derive(Debug, Clone)] |
| 73 | pub struct MergeIdentity<'a> { |
| 74 | |
| 75 | pub home: &'a Path, |
| 76 | |
| 77 | pub name: &'a str, |
| 78 | |
| 79 | pub email: &'a str, |
| 80 | } |
| 81 | |
| 82 | |
| 83 | #[derive(Debug, Clone)] |
| 84 | pub struct MergeRequest<'a> { |
| 85 | |
| 86 | pub binary: &'a str, |
| 87 | |
| 88 | pub repo_path: &'a Path, |
| 89 | |
| 90 | |
| 91 | pub workdir: &'a Path, |
| 92 | |
| 93 | pub base_branch: &'a str, |
| 94 | |
| 95 | pub head_ref: &'a str, |
| 96 | |
| 97 | pub strategy: MergeStrategy, |
| 98 | |
| 99 | pub message: &'a str, |
| 100 | |
| 101 | pub identity: MergeIdentity<'a>, |
| 102 | } |
| 103 | |
| 104 | |
| 105 | fn rev_parse(binary: &str, repo_path: &Path, home: &Path, rev: &str) -> Result<String, GitError> { |
| 106 | |
| 107 | let out = base_command(binary, repo_path, home) |
| 108 | .args(["rev-parse", "--verify", "--quiet"]) |
| 109 | .arg(format!("{rev}^{{commit}}")) |
| 110 | .output() |
| 111 | .map_err(|source| GitError::Io { |
| 112 | path: repo_path.to_path_buf(), |
| 113 | source, |
| 114 | })?; |
| 115 | if !out.status.success() { |
| 116 | return Err(GitError::RevNotFound(rev.to_string())); |
| 117 | } |
| 118 | Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) |
| 119 | } |
| 120 | |
| 121 | |
| 122 | fn base_command(binary: &str, repo_path: &Path, home: &Path) -> Command { |
| 123 | let mut cmd = Command::new(binary); |
| 124 | cmd.env("GIT_DIR", repo_path); |
| 125 | cmd.env("GIT_TERMINAL_PROMPT", "0"); |
| 126 | cmd.env("GIT_CONFIG_NOSYSTEM", "1"); |
| 127 | cmd.env("HOME", home); |
| 128 | cmd.env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES"); |
| 129 | cmd.env_remove("GIT_OBJECT_DIRECTORY"); |
| 130 | cmd |
| 131 | } |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | pub fn analyze( |
| 141 | binary: &str, |
| 142 | repo_path: &Path, |
| 143 | home: &Path, |
| 144 | base_ref: &str, |
| 145 | head_ref: &str, |
| 146 | ) -> Result<Mergeability, GitError> { |
| 147 | let base = rev_parse(binary, repo_path, home, base_ref)?; |
| 148 | let head = rev_parse(binary, repo_path, home, head_ref)?; |
| 149 | |
| 150 | |
| 151 | let contained = base_command(binary, repo_path, home) |
| 152 | .args(["merge-base", "--is-ancestor", &head, &base]) |
| 153 | .status() |
| 154 | .map_err(|source| GitError::Io { |
| 155 | path: repo_path.to_path_buf(), |
| 156 | source, |
| 157 | })?; |
| 158 | if contained.success() { |
| 159 | return Ok(Mergeability::AlreadyMerged); |
| 160 | } |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | let out = base_command(binary, repo_path, home) |
| 166 | .args(["merge-tree", "--write-tree", &base, &head]) |
| 167 | .output() |
| 168 | .map_err(|source| GitError::Io { |
| 169 | path: repo_path.to_path_buf(), |
| 170 | source, |
| 171 | })?; |
| 172 | match out.status.code() { |
| 173 | Some(0) => Ok(Mergeability::Clean), |
| 174 | Some(1) => Ok(Mergeability::Conflicts), |
| 175 | _ => Err(GitError::Merge( |
| 176 | String::from_utf8_lossy(&out.stderr).trim().to_string(), |
| 177 | )), |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | pub fn merge(req: &MergeRequest) -> Result<String, GitError> { |
| 193 | let base = rev_parse( |
| 194 | req.binary, |
| 195 | req.repo_path, |
| 196 | req.identity.home, |
| 197 | req.base_branch, |
| 198 | )?; |
| 199 | let head = rev_parse(req.binary, req.repo_path, req.identity.home, req.head_ref)?; |
| 200 | |
| 201 | let new_tip = match req.strategy { |
| 202 | MergeStrategy::Merge => plumbing_commit(req, &base, &[&base, &head])?, |
| 203 | MergeStrategy::Squash => plumbing_commit(req, &base, &[&base])?, |
| 204 | MergeStrategy::Rebase => rebase(req, &base, &head)?, |
| 205 | }; |
| 206 | |
| 207 | |
| 208 | let status = identified(req) |
| 209 | .args([ |
| 210 | "update-ref", |
| 211 | &format!("refs/heads/{}", req.base_branch), |
| 212 | &new_tip, |
| 213 | &base, |
| 214 | ]) |
| 215 | .status() |
| 216 | .map_err(|source| GitError::Io { |
| 217 | path: req.repo_path.to_path_buf(), |
| 218 | source, |
| 219 | })?; |
| 220 | if !status.success() { |
| 221 | return Err(GitError::Merge(format!( |
| 222 | "base branch {} moved during merge", |
| 223 | req.base_branch |
| 224 | ))); |
| 225 | } |
| 226 | Ok(new_tip) |
| 227 | } |
| 228 | |
| 229 | |
| 230 | |
| 231 | fn plumbing_commit(req: &MergeRequest, base: &str, parents: &[&str]) -> Result<String, GitError> { |
| 232 | let head = rev_parse(req.binary, req.repo_path, req.identity.home, req.head_ref)?; |
| 233 | let tree_out = base_command(req.binary, req.repo_path, req.identity.home) |
| 234 | .args(["merge-tree", "--write-tree", base, &head]) |
| 235 | .output() |
| 236 | .map_err(|source| GitError::Io { |
| 237 | path: req.repo_path.to_path_buf(), |
| 238 | source, |
| 239 | })?; |
| 240 | match tree_out.status.code() { |
| 241 | Some(0) => {} |
| 242 | Some(1) => { |
| 243 | |
| 244 | |
| 245 | let out = String::from_utf8_lossy(&tree_out.stdout); |
| 246 | let detail = out.lines().skip(1).collect::<Vec<_>>().join("; "); |
| 247 | return Err(GitError::MergeConflict(detail.trim().to_string())); |
| 248 | } |
| 249 | _ => { |
| 250 | return Err(GitError::Merge( |
| 251 | String::from_utf8_lossy(&tree_out.stderr).trim().to_string(), |
| 252 | )); |
| 253 | } |
| 254 | } |
| 255 | let tree = String::from_utf8_lossy(&tree_out.stdout).trim().to_string(); |
| 256 | |
| 257 | let mut cmd = identified(req); |
| 258 | cmd.args(["commit-tree", &tree]); |
| 259 | for parent in parents { |
| 260 | cmd.args(["-p", parent]); |
| 261 | } |
| 262 | cmd.args(["-m", req.message]); |
| 263 | let out = cmd.output().map_err(|source| GitError::Io { |
| 264 | path: req.repo_path.to_path_buf(), |
| 265 | source, |
| 266 | })?; |
| 267 | if !out.status.success() { |
| 268 | return Err(GitError::Merge( |
| 269 | String::from_utf8_lossy(&out.stderr).trim().to_string(), |
| 270 | )); |
| 271 | } |
| 272 | Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) |
| 273 | } |
| 274 | |
| 275 | |
| 276 | |
| 277 | fn rebase(req: &MergeRequest, base: &str, head: &str) -> Result<String, GitError> { |
| 278 | |
| 279 | |
| 280 | let linear = base_command(req.binary, req.repo_path, req.identity.home) |
| 281 | .args(["merge-base", "--is-ancestor", base, head]) |
| 282 | .status() |
| 283 | .map_err(|source| GitError::Io { |
| 284 | path: req.repo_path.to_path_buf(), |
| 285 | source, |
| 286 | })?; |
| 287 | if linear.success() { |
| 288 | return Ok(head.to_string()); |
| 289 | } |
| 290 | |
| 291 | let result = rebase_in_worktree(req, base, head); |
| 292 | |
| 293 | let _ = std::fs::remove_dir_all(req.workdir); |
| 294 | let _ = base_command(req.binary, req.repo_path, req.identity.home) |
| 295 | .args(["worktree", "prune"]) |
| 296 | .status(); |
| 297 | result |
| 298 | } |
| 299 | |
| 300 | |
| 301 | fn rebase_in_worktree(req: &MergeRequest, base: &str, head: &str) -> Result<String, GitError> { |
| 302 | let add = base_command(req.binary, req.repo_path, req.identity.home) |
| 303 | .args(["worktree", "add", "--detach"]) |
| 304 | .arg(req.workdir) |
| 305 | .arg(head) |
| 306 | .output() |
| 307 | .map_err(|source| GitError::Io { |
| 308 | path: req.workdir.to_path_buf(), |
| 309 | source, |
| 310 | })?; |
| 311 | if !add.status.success() { |
| 312 | return Err(GitError::Merge( |
| 313 | String::from_utf8_lossy(&add.stderr).trim().to_string(), |
| 314 | )); |
| 315 | } |
| 316 | |
| 317 | let mut cmd = identified(req); |
| 318 | cmd.current_dir(req.workdir) |
| 319 | .env_remove("GIT_DIR") |
| 320 | .args(["rebase", base]); |
| 321 | let out = cmd.output().map_err(|source| GitError::Io { |
| 322 | path: req.workdir.to_path_buf(), |
| 323 | source, |
| 324 | })?; |
| 325 | if !out.status.success() { |
| 326 | |
| 327 | let mut detail = String::from_utf8_lossy(&out.stdout).trim().to_string(); |
| 328 | let err = String::from_utf8_lossy(&out.stderr); |
| 329 | if !err.trim().is_empty() { |
| 330 | detail.push_str(err.trim()); |
| 331 | } |
| 332 | |
| 333 | let _ = identified(req) |
| 334 | .current_dir(req.workdir) |
| 335 | .env_remove("GIT_DIR") |
| 336 | .args(["rebase", "--abort"]) |
| 337 | .status(); |
| 338 | return Err(GitError::MergeConflict(detail)); |
| 339 | } |
| 340 | |
| 341 | let tip = identified(req) |
| 342 | .current_dir(req.workdir) |
| 343 | .env_remove("GIT_DIR") |
| 344 | .args(["rev-parse", "HEAD"]) |
| 345 | .output() |
| 346 | .map_err(|source| GitError::Io { |
| 347 | path: req.workdir.to_path_buf(), |
| 348 | source, |
| 349 | })?; |
| 350 | Ok(String::from_utf8_lossy(&tip.stdout).trim().to_string()) |
| 351 | } |
| 352 | |
| 353 | |
| 354 | fn identified(req: &MergeRequest) -> Command { |
| 355 | let mut cmd = base_command(req.binary, req.repo_path, req.identity.home); |
| 356 | cmd.env("GIT_AUTHOR_NAME", req.identity.name); |
| 357 | cmd.env("GIT_AUTHOR_EMAIL", req.identity.email); |
| 358 | cmd.env("GIT_COMMITTER_NAME", req.identity.name); |
| 359 | cmd.env("GIT_COMMITTER_EMAIL", req.identity.email); |
| 360 | cmd |
| 361 | } |
| 362 | |
| 363 | #[cfg(test)] |
| 364 | mod tests { |
| 365 | #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] |
| 366 | |
| 367 | use std::path::{Path, PathBuf}; |
| 368 | |
| 369 | use git2::{Repository, Signature, Time}; |
| 370 | use tempfile::TempDir; |
| 371 | |
| 372 | use super::*; |
| 373 | use crate::{create_bare, repo_path}; |
| 374 | |
| 375 | const ID: &str = "01hzxk9m2n8p7q6r5s4t3v2w1x"; |
| 376 | |
| 377 | |
| 378 | |
| 379 | fn git_present() -> bool { |
| 380 | Command::new("git").arg("--version").output().is_ok() |
| 381 | } |
| 382 | |
| 383 | |
| 384 | |
| 385 | struct Fixture { |
| 386 | _dir: TempDir, |
| 387 | home: TempDir, |
| 388 | path: PathBuf, |
| 389 | } |
| 390 | |
| 391 | fn fixture() -> Fixture { |
| 392 | let dir = tempfile::tempdir().unwrap(); |
| 393 | create_bare(dir.path(), ID, "main", Path::new("/usr/bin/fabrica")).unwrap(); |
| 394 | let path = repo_path(dir.path(), ID).unwrap(); |
| 395 | let raw = Repository::open_bare(&path).unwrap(); |
| 396 | |
| 397 | let base = commit(&raw, "main", &[], &[("README.md", "hello\n")], "init", 1); |
| 398 | commit( |
| 399 | &raw, |
| 400 | "feature", |
| 401 | &[base], |
| 402 | &[("README.md", "hello\n"), ("feature.txt", "new\n")], |
| 403 | "add feature", |
| 404 | 2, |
| 405 | ); |
| 406 | Fixture { |
| 407 | _dir: dir, |
| 408 | home: tempfile::tempdir().unwrap(), |
| 409 | path, |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | fn commit( |
| 414 | raw: &Repository, |
| 415 | branch: &str, |
| 416 | parents: &[git2::Oid], |
| 417 | files: &[(&str, &str)], |
| 418 | message: &str, |
| 419 | t: i64, |
| 420 | ) -> git2::Oid { |
| 421 | let mut root = raw.treebuilder(None).unwrap(); |
| 422 | for (name, content) in files { |
| 423 | let blob = raw.blob(content.as_bytes()).unwrap(); |
| 424 | root.insert(name, blob, 0o100_644).unwrap(); |
| 425 | } |
| 426 | let tree = raw.find_tree(root.write().unwrap()).unwrap(); |
| 427 | let sig = Signature::new("Ada", "ada@example.com", &Time::new(t, 0)).unwrap(); |
| 428 | let parent_commits: Vec<_> = parents |
| 429 | .iter() |
| 430 | .map(|p| raw.find_commit(*p).unwrap()) |
| 431 | .collect(); |
| 432 | let parent_refs: Vec<&git2::Commit> = parent_commits.iter().collect(); |
| 433 | raw.commit( |
| 434 | Some(&format!("refs/heads/{branch}")), |
| 435 | &sig, |
| 436 | &sig, |
| 437 | message, |
| 438 | &tree, |
| 439 | &parent_refs, |
| 440 | ) |
| 441 | .unwrap() |
| 442 | } |
| 443 | |
| 444 | fn request<'a>( |
| 445 | fx: &'a Fixture, |
| 446 | strategy: MergeStrategy, |
| 447 | workdir: &'a Path, |
| 448 | ) -> MergeRequest<'a> { |
| 449 | MergeRequest { |
| 450 | binary: "git", |
| 451 | repo_path: &fx.path, |
| 452 | workdir, |
| 453 | base_branch: "main", |
| 454 | head_ref: "feature", |
| 455 | strategy, |
| 456 | message: "Merge feature", |
| 457 | identity: MergeIdentity { |
| 458 | home: fx.home.path(), |
| 459 | name: "Ada", |
| 460 | email: "ada@example.com", |
| 461 | }, |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | |
| 466 | |
| 467 | fn tip(fx: &Fixture, rev: &str) -> String { |
| 468 | rev_parse("git", &fx.path, fx.home.path(), rev).unwrap() |
| 469 | } |
| 470 | |
| 471 | #[test] |
| 472 | fn merge_and_rebase_diverged_non_conflicting() { |
| 473 | if !git_present() { |
| 474 | return; |
| 475 | } |
| 476 | let fx = fixture(); |
| 477 | let raw = Repository::open_bare(&fx.path).unwrap(); |
| 478 | |
| 479 | |
| 480 | let base = raw |
| 481 | .find_reference("refs/heads/main") |
| 482 | .unwrap() |
| 483 | .target() |
| 484 | .unwrap(); |
| 485 | commit( |
| 486 | &raw, |
| 487 | "main", |
| 488 | &[base], |
| 489 | &[("README.md", "hello\n"), ("main.txt", "m\n")], |
| 490 | "advance main", |
| 491 | 3, |
| 492 | ); |
| 493 | |
| 494 | |
| 495 | assert_eq!( |
| 496 | analyze("git", &fx.path, fx.home.path(), "main", "feature").unwrap(), |
| 497 | Mergeability::Clean, |
| 498 | ); |
| 499 | |
| 500 | for (strategy, dir) in [ |
| 501 | (MergeStrategy::Merge, "wt-div-merge"), |
| 502 | (MergeStrategy::Squash, "wt-div-squash"), |
| 503 | (MergeStrategy::Rebase, "wt-div-rebase"), |
| 504 | ] { |
| 505 | let wt = fx.path.parent().unwrap().join(dir); |
| 506 | let sha = merge(&request(&fx, strategy, &wt)) |
| 507 | .unwrap_or_else(|e| panic!("{strategy:?} failed: {e:?}")); |
| 508 | let raw = Repository::open_bare(&fx.path).unwrap(); |
| 509 | assert!( |
| 510 | raw.find_commit(git2::Oid::from_str(&sha).unwrap()) |
| 511 | .unwrap() |
| 512 | .tree() |
| 513 | .unwrap() |
| 514 | .get_name("feature.txt") |
| 515 | .is_some(), |
| 516 | "{strategy:?}: merged tree keeps feature.txt" |
| 517 | ); |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | #[test] |
| 522 | fn analyze_reports_clean_and_already_merged() { |
| 523 | if !git_present() { |
| 524 | return; |
| 525 | } |
| 526 | let fx = fixture(); |
| 527 | assert_eq!( |
| 528 | analyze("git", &fx.path, fx.home.path(), "main", "feature").unwrap(), |
| 529 | Mergeability::Clean, |
| 530 | ); |
| 531 | |
| 532 | assert_eq!( |
| 533 | analyze("git", &fx.path, fx.home.path(), "feature", "main").unwrap(), |
| 534 | Mergeability::AlreadyMerged, |
| 535 | ); |
| 536 | } |
| 537 | |
| 538 | #[test] |
| 539 | fn merge_commit_has_two_parents_and_the_feature_file() { |
| 540 | if !git_present() { |
| 541 | return; |
| 542 | } |
| 543 | let fx = fixture(); |
| 544 | let base = tip(&fx, "main"); |
| 545 | let head = tip(&fx, "feature"); |
| 546 | let wt = fx.path.parent().unwrap().join("wt-merge"); |
| 547 | let sha = merge(&request(&fx, MergeStrategy::Merge, &wt)).unwrap(); |
| 548 | |
| 549 | assert_eq!(tip(&fx, "main"), sha, "base advanced to the merge commit"); |
| 550 | let raw = Repository::open_bare(&fx.path).unwrap(); |
| 551 | let merge_commit = raw.find_commit(git2::Oid::from_str(&sha).unwrap()).unwrap(); |
| 552 | let parents: Vec<String> = merge_commit.parent_ids().map(|o| o.to_string()).collect(); |
| 553 | assert_eq!(parents, vec![base, head]); |
| 554 | |
| 555 | assert!( |
| 556 | merge_commit |
| 557 | .tree() |
| 558 | .unwrap() |
| 559 | .get_name("feature.txt") |
| 560 | .is_some() |
| 561 | ); |
| 562 | } |
| 563 | |
| 564 | #[test] |
| 565 | fn squash_has_a_single_parent() { |
| 566 | if !git_present() { |
| 567 | return; |
| 568 | } |
| 569 | let fx = fixture(); |
| 570 | let base = tip(&fx, "main"); |
| 571 | let wt = fx.path.parent().unwrap().join("wt-squash"); |
| 572 | let sha = merge(&request(&fx, MergeStrategy::Squash, &wt)).unwrap(); |
| 573 | let raw = Repository::open_bare(&fx.path).unwrap(); |
| 574 | let commit = raw.find_commit(git2::Oid::from_str(&sha).unwrap()).unwrap(); |
| 575 | let parents: Vec<String> = commit.parent_ids().map(|o| o.to_string()).collect(); |
| 576 | assert_eq!(parents, vec![base]); |
| 577 | assert!(commit.tree().unwrap().get_name("feature.txt").is_some()); |
| 578 | } |
| 579 | |
| 580 | #[test] |
| 581 | fn rebase_of_a_linear_branch_fast_forwards() { |
| 582 | if !git_present() { |
| 583 | return; |
| 584 | } |
| 585 | let fx = fixture(); |
| 586 | let head = tip(&fx, "feature"); |
| 587 | let wt = fx.path.parent().unwrap().join("wt-rebase"); |
| 588 | let sha = merge(&request(&fx, MergeStrategy::Rebase, &wt)).unwrap(); |
| 589 | |
| 590 | assert_eq!(sha, head); |
| 591 | assert_eq!(tip(&fx, "main"), head); |
| 592 | } |
| 593 | } |