|
| 1 | +use git2::{DiffFormat, DiffOptions, Repository}; |
1 | 2 | use ignore::{ |
2 | 3 | Walk, |
3 | 4 | overrides::{Override, OverrideBuilder}, |
4 | 5 | }; |
| 6 | +use sha2::{Digest, Sha256}; |
5 | 7 | use std::path::{Path, PathBuf}; |
6 | 8 | use utils::error::{Error, Result}; |
7 | 9 |
|
@@ -357,6 +359,52 @@ pub fn collect_tags(entries: &[CodeownersEntry]) -> Vec<Tag> { |
357 | 359 | tags.into_iter().collect() |
358 | 360 | } |
359 | 361 |
|
| 362 | +pub fn get_repo_hash(repo_path: &Path) -> Result<[u8; 32]> { |
| 363 | + let repo = Repository::open(repo_path) |
| 364 | + .map_err(|e| Error::with_source("Failed to open repo", Box::new(e)))?; |
| 365 | + |
| 366 | + // 1. Get HEAD commit hash (or zeros if unborn) |
| 367 | + let head_oid = repo |
| 368 | + .head() |
| 369 | + .and_then(|r| r.resolve()) |
| 370 | + .and_then(|r| Ok(r.target())) |
| 371 | + .unwrap_or(None); |
| 372 | + |
| 373 | + // 2. Get index/staging area tree hash |
| 374 | + let mut index = repo |
| 375 | + .index() |
| 376 | + .map_err(|e| Error::with_source("Failed to get index", Box::new(e)))?; |
| 377 | + |
| 378 | + let index_tree = index |
| 379 | + .write_tree() |
| 380 | + .map_err(|e| Error::with_source("Failed to write index tree", Box::new(e)))?; |
| 381 | + |
| 382 | + // 3. Calculate hash of unstaged changes |
| 383 | + // TODO: this doesn't work and also we need to exclude .codeowners.cache file |
| 384 | + // otherwise the hash will change every time we parse the repo |
| 385 | + let unstaged_hash = { |
| 386 | + let diff = repo |
| 387 | + .diff_index_to_workdir(None, Some(DiffOptions::new().include_untracked(true))) |
| 388 | + .map_err(|e| Error::with_source("Failed to get diff", Box::new(e)))?; |
| 389 | + |
| 390 | + let mut hasher = Sha256::new(); |
| 391 | + diff.print(DiffFormat::Patch, |_, _, line| { |
| 392 | + hasher.update(line.content()); |
| 393 | + true |
| 394 | + }) |
| 395 | + .map_err(|e| Error::with_source("Failed to print diff", Box::new(e)))?; |
| 396 | + hasher.finalize() |
| 397 | + }; |
| 398 | + |
| 399 | + // 4. Combine all components into final hash |
| 400 | + let mut hasher = Sha256::new(); |
| 401 | + hasher.update(head_oid.unwrap_or(git2::Oid::zero()).as_bytes()); |
| 402 | + hasher.update(index_tree.as_bytes()); |
| 403 | + hasher.update(&unstaged_hash); |
| 404 | + |
| 405 | + Ok(hasher.finalize().into()) |
| 406 | +} |
| 407 | + |
360 | 408 | #[cfg(test)] |
361 | 409 | mod tests { |
362 | 410 | use super::*; |
|
0 commit comments