| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
use super::*; |
| 11 |
use std::process::{Command, Stdio}; |
| 12 |
use std::sync::Arc; |
| 13 |
|
| 14 |
#[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 15 |
pub struct GitImportReport { |
| 16 |
pub commits: usize, |
| 17 |
pub merges: usize, |
| 18 |
|
| 19 |
pub submodules: usize, |
| 20 |
pub heads: usize, |
| 21 |
} |
| 22 |
|
| 23 |
|
| 24 |
struct CatFile { |
| 25 |
child: std::process::Child, |
| 26 |
stdin: std::process::ChildStdin, |
| 27 |
stdout: std::io::BufReader<std::process::ChildStdout>, |
| 28 |
} |
| 29 |
|
| 30 |
impl CatFile { |
| 31 |
fn start(git_dir: &Path) -> Result<CatFile> { |
| 32 |
let mut child = Command::new("git") |
| 33 |
.arg("-C") |
| 34 |
.arg(git_dir) |
| 35 |
.args(["cat-file", "--batch"]) |
| 36 |
.stdin(Stdio::piped()) |
| 37 |
.stdout(Stdio::piped()) |
| 38 |
.stderr(Stdio::null()) |
| 39 |
.spawn() |
| 40 |
.map_err(|e| RepoError::Msg(format!("running git cat-file: {e}")))?; |
| 41 |
let stdin = child.stdin.take().unwrap(); |
| 42 |
let stdout = std::io::BufReader::new(child.stdout.take().unwrap()); |
| 43 |
Ok(CatFile { |
| 44 |
child, |
| 45 |
stdin, |
| 46 |
stdout, |
| 47 |
}) |
| 48 |
} |
| 49 |
|
| 50 |
fn read(&mut self, sha: &str) -> Result<Vec<u8>> { |
| 51 |
use std::io::{BufRead, Read}; |
| 52 |
writeln!(self.stdin, "{sha}")?; |
| 53 |
self.stdin.flush()?; |
| 54 |
let mut header = String::new(); |
| 55 |
self.stdout.read_line(&mut header)?; |
| 56 |
let parts: Vec<&str> = header.trim_end().split(' ').collect(); |
| 57 |
if parts.len() != 3 { |
| 58 |
return fail(format!("git cat-file: object {sha} not found")); |
| 59 |
} |
| 60 |
let size: usize = parts[2] |
| 61 |
.parse() |
| 62 |
.map_err(|_| RepoError::Msg("git cat-file: bad size".into()))?; |
| 63 |
let mut body = vec![0u8; size]; |
| 64 |
self.stdout.read_exact(&mut body)?; |
| 65 |
let mut nl = [0u8; 1]; |
| 66 |
self.stdout.read_exact(&mut nl)?; |
| 67 |
Ok(body) |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
impl Drop for CatFile { |
| 72 |
fn drop(&mut self) { |
| 73 |
let _ = self.child.kill(); |
| 74 |
let _ = self.child.wait(); |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
type TreeDiff = Vec<(String, Option<(String, String)>)>; |
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
struct DiffTree { |
| 87 |
child: std::process::Child, |
| 88 |
stdout: std::io::BufReader<std::process::ChildStdout>, |
| 89 |
feeder: Option<std::thread::JoinHandle<()>>, |
| 90 |
|
| 91 |
next: Option<String>, |
| 92 |
} |
| 93 |
|
| 94 |
impl DiffTree { |
| 95 |
fn start(git_dir: &Path, pairs: Vec<(String, String)>) -> Result<DiffTree> { |
| 96 |
let mut child = Command::new("git") |
| 97 |
.arg("-C") |
| 98 |
.arg(git_dir) |
| 99 |
.args([ |
| 100 |
"diff-tree", |
| 101 |
"--stdin", |
| 102 |
"--always", |
| 103 |
"-r", |
| 104 |
"-z", |
| 105 |
"--no-renames", |
| 106 |
]) |
| 107 |
.stdin(Stdio::piped()) |
| 108 |
.stdout(Stdio::piped()) |
| 109 |
.stderr(Stdio::null()) |
| 110 |
.spawn() |
| 111 |
.map_err(|e| RepoError::Msg(format!("running git diff-tree: {e}")))?; |
| 112 |
let mut stdin = child.stdin.take().unwrap(); |
| 113 |
let stdout = std::io::BufReader::new(child.stdout.take().unwrap()); |
| 114 |
|
| 115 |
let feeder = std::thread::spawn(move || { |
| 116 |
let mut w = std::io::BufWriter::new(&mut stdin); |
| 117 |
for (c, p) in pairs { |
| 118 |
if writeln!(w, "{c} {p}").is_err() { |
| 119 |
return; |
| 120 |
} |
| 121 |
} |
| 122 |
let _ = w.flush(); |
| 123 |
}); |
| 124 |
Ok(DiffTree { |
| 125 |
child, |
| 126 |
stdout, |
| 127 |
feeder: Some(feeder), |
| 128 |
next: None, |
| 129 |
}) |
| 130 |
} |
| 131 |
|
| 132 |
fn field(&mut self) -> Result<Option<String>> { |
| 133 |
use std::io::BufRead; |
| 134 |
let mut buf = Vec::new(); |
| 135 |
if self.stdout.read_until(0, &mut buf)? == 0 { |
| 136 |
return Ok(None); |
| 137 |
} |
| 138 |
if buf.last() == Some(&0) { |
| 139 |
buf.pop(); |
| 140 |
} |
| 141 |
Ok(Some(String::from_utf8_lossy(&buf).into_owned())) |
| 142 |
} |
| 143 |
|
| 144 |
|
| 145 |
fn diff(&mut self, sha: &str) -> Result<TreeDiff> { |
| 146 |
let header = match self.next.take() { |
| 147 |
Some(h) => Some(h), |
| 148 |
None => self.field()?, |
| 149 |
}; |
| 150 |
if header.as_deref() != Some(sha) { |
| 151 |
return fail(format!("git diff-tree: expected {sha}, got {header:?}")); |
| 152 |
} |
| 153 |
let mut out = Vec::new(); |
| 154 |
while let Some(f) = self.field()? { |
| 155 |
let Some(meta) = f.strip_prefix(':') else { |
| 156 |
self.next = Some(f); |
| 157 |
break; |
| 158 |
}; |
| 159 |
let Some(path) = self.field()? else { |
| 160 |
return fail("git diff-tree: record without a path"); |
| 161 |
}; |
| 162 |
|
| 163 |
let m: Vec<&str> = meta.split(' ').collect(); |
| 164 |
if m.len() != 5 { |
| 165 |
return fail(format!("git diff-tree: bad record {f:?}")); |
| 166 |
} |
| 167 |
let entry = if m[4].starts_with('D') { |
| 168 |
None |
| 169 |
} else { |
| 170 |
Some((m[1].to_string(), m[3].to_string())) |
| 171 |
}; |
| 172 |
out.push((path, entry)); |
| 173 |
} |
| 174 |
Ok(out) |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
impl Drop for DiffTree { |
| 179 |
fn drop(&mut self) { |
| 180 |
let _ = self.child.kill(); |
| 181 |
let _ = self.child.wait(); |
| 182 |
if let Some(f) = self.feeder.take() { |
| 183 |
let _ = f.join(); |
| 184 |
} |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
|
| 189 |
struct GitCommit { |
| 190 |
sha: String, |
| 191 |
parents: Vec<String>, |
| 192 |
author_secs: u64, |
| 193 |
author: String, |
| 194 |
message: String, |
| 195 |
} |
| 196 |
|
| 197 |
fn list_commits(git_dir: &Path, branch: &str) -> Result<Vec<GitCommit>> { |
| 198 |
let out = Command::new("git") |
| 199 |
.arg("-C") |
| 200 |
.arg(git_dir) |
| 201 |
.args([ |
| 202 |
"log", |
| 203 |
"--reverse", |
| 204 |
"--topo-order", |
| 205 |
"--format=%H%x00%P%x00%at%x00%an <%ae>%x00%B%x1e", |
| 206 |
branch, |
| 207 |
]) |
| 208 |
.output() |
| 209 |
.map_err(|e| RepoError::Msg(format!("running git log: {e}")))?; |
| 210 |
if !out.status.success() { |
| 211 |
return fail(format!( |
| 212 |
"git log {branch} failed: {}", |
| 213 |
String::from_utf8_lossy(&out.stderr).trim() |
| 214 |
)); |
| 215 |
} |
| 216 |
let text = String::from_utf8_lossy(&out.stdout); |
| 217 |
let mut commits = Vec::new(); |
| 218 |
for record in text.split('\x1e') { |
| 219 |
let record = record.trim_start_matches('\n'); |
| 220 |
if record.trim().is_empty() { |
| 221 |
continue; |
| 222 |
} |
| 223 |
let f: Vec<&str> = record.splitn(5, '\0').collect(); |
| 224 |
if f.len() != 5 { |
| 225 |
return fail("unexpected git log record"); |
| 226 |
} |
| 227 |
commits.push(GitCommit { |
| 228 |
sha: f[0].to_string(), |
| 229 |
parents: f[1].split_whitespace().map(str::to_string).collect(), |
| 230 |
author_secs: f[2].parse().unwrap_or(0), |
| 231 |
author: f[3].to_string(), |
| 232 |
message: f[4].trim_end().to_string(), |
| 233 |
}); |
| 234 |
} |
| 235 |
Ok(commits) |
| 236 |
} |
| 237 |
|
| 238 |
|
| 239 |
fn list_tree(git_dir: &Path, sha: &str) -> Result<BTreeMap<String, (String, String)>> { |
| 240 |
let text = git(git_dir, &["ls-tree", "-r", "-z", sha])?; |
| 241 |
let mut out = BTreeMap::new(); |
| 242 |
for entry in text.split('\0') { |
| 243 |
if entry.is_empty() { |
| 244 |
continue; |
| 245 |
} |
| 246 |
let Some((meta, path)) = entry.split_once('\t') else { |
| 247 |
continue; |
| 248 |
}; |
| 249 |
let m: Vec<&str> = meta.split(' ').collect(); |
| 250 |
if m.len() == 3 { |
| 251 |
out.insert(path.to_string(), (m[0].to_string(), m[2].to_string())); |
| 252 |
} |
| 253 |
} |
| 254 |
Ok(out) |
| 255 |
} |
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
fn change_id_for(sha: &str, message: &str) -> ChangeId { |
| 260 |
for line in message.lines().rev() { |
| 261 |
if let Some(v) = line.strip_prefix("Change-Id:") { |
| 262 |
if let Some(id) = ChangeId::from_hex(v.trim()) { |
| 263 |
return id; |
| 264 |
} |
| 265 |
} |
| 266 |
} |
| 267 |
let h = blake3::hash(sha.as_bytes()); |
| 268 |
ChangeId(h.as_bytes()[..16].try_into().unwrap()) |
| 269 |
} |
| 270 |
|
| 271 |
|
| 272 |
struct GitKnown { |
| 273 |
|
| 274 |
imported: HashMap<String, ChangeHash>, |
| 275 |
|
| 276 |
exported: HashMap<String, ObjectRef>, |
| 277 |
} |
| 278 |
|
| 279 |
#[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 280 |
pub struct GitExportReport { |
| 281 |
pub exported: usize, |
| 282 |
pub skipped: usize, |
| 283 |
|
| 284 |
pub skipped_subrepos: usize, |
| 285 |
pub branch: String, |
| 286 |
pub heads: usize, |
| 287 |
} |
| 288 |
|
| 289 |
|
| 290 |
const MERGE_SHED_COMMITS: usize = 100; |
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
const KEPT_ATOMS: usize = 1_500_000; |
| 295 |
|
| 296 |
const KEPT_GRAPHS: usize = 2000; |
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
const CHECKPOINT_COMMITS: usize = 2000; |
| 301 |
|
| 302 |
fn git(dir: &Path, args: &[&str]) -> Result<String> { |
| 303 |
let out = Command::new("git") |
| 304 |
.arg("-C") |
| 305 |
.arg(dir) |
| 306 |
.args(args) |
| 307 |
.output() |
| 308 |
.map_err(|e| RepoError::Msg(format!("running git: {e}")))?; |
| 309 |
if !out.status.success() { |
| 310 |
return fail(format!( |
| 311 |
"git {} failed: {}", |
| 312 |
args.join(" "), |
| 313 |
String::from_utf8_lossy(&out.stderr).trim() |
| 314 |
)); |
| 315 |
} |
| 316 |
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) |
| 317 |
} |
| 318 |
|
| 319 |
impl Repo { |
| 320 |
fn git_marks_dir(&self, git_dir: &Path) -> Result<PathBuf> { |
| 321 |
let canonical = git_dir |
| 322 |
.canonicalize() |
| 323 |
.unwrap_or_else(|_| git_dir.to_path_buf()); |
| 324 |
let key = hash_object(ObjectType::Chunk, canonical.to_string_lossy().as_bytes()).short(16); |
| 325 |
let dir = self.oxy.join("git").join(key); |
| 326 |
fs::create_dir_all(&dir)?; |
| 327 |
Ok(dir) |
| 328 |
} |
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
fn read_git_states(path: &Path) -> Result<BTreeMap<ObjectRef, String>> { |
| 333 |
let mut out = BTreeMap::new(); |
| 334 |
if let Ok(text) = fs::read_to_string(path) { |
| 335 |
for line in text.lines() { |
| 336 |
if let Some((h, sha)) = line.split_once(' ') { |
| 337 |
if let Some(h) = ObjectRef::from_hex(h) { |
| 338 |
out.insert(h, sha.trim().to_string()); |
| 339 |
} |
| 340 |
} |
| 341 |
} |
| 342 |
} |
| 343 |
Ok(out) |
| 344 |
} |
| 345 |
|
| 346 |
fn record_git_state(&self, git_dir: &Path, state: &ObjectRef, sha: &str) -> Result<()> { |
| 347 |
let path = self.git_marks_dir(git_dir)?.join("git-states"); |
| 348 |
let mut states = Self::read_git_states(&path)?; |
| 349 |
states.insert(*state, sha.to_string()); |
| 350 |
let text: String = states |
| 351 |
.iter() |
| 352 |
.map(|(h, s)| format!("{} {s}\n", h.to_hex())) |
| 353 |
.collect(); |
| 354 |
write_atomic(&path, text.as_bytes()) |
| 355 |
} |
| 356 |
|
| 357 |
|
| 358 |
fn git_mirror(&self, url: &str) -> Result<PathBuf> { |
| 359 |
let key = hash_object(ObjectType::Chunk, url.as_bytes()).short(16); |
| 360 |
let dir = self.oxy.join("git").join(key).join("mirror.git"); |
| 361 |
if !dir.join("HEAD").exists() { |
| 362 |
fs::create_dir_all(&dir)?; |
| 363 |
git(&dir, &["init", "--bare", "-q"])?; |
| 364 |
} |
| 365 |
Ok(dir) |
| 366 |
} |
| 367 |
|
| 368 |
|
| 369 |
pub(crate) fn imported_commits(&self) -> Result<HashMap<String, ChangeHash>> { |
| 370 |
let mut map = HashMap::new(); |
| 371 |
for e in self.log()? { |
| 372 |
if e.is_working_copy { |
| 373 |
continue; |
| 374 |
} |
| 375 |
if let Some(sha) = e |
| 376 |
.change |
| 377 |
.message |
| 378 |
.lines() |
| 379 |
.rev() |
| 380 |
.find_map(|l| l.strip_prefix("Git-Commit: ")) |
| 381 |
{ |
| 382 |
map.insert(sha.trim().to_string(), e.hash); |
| 383 |
} |
| 384 |
} |
| 385 |
Ok(map) |
| 386 |
} |
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
fn git_mirror_fetch(&self, mirror: &Path, url: &str, branch: &str) -> Result<()> { |
| 391 |
let spec = format!("+refs/heads/{branch}:refs/heads/{branch}"); |
| 392 |
match git(mirror, &["fetch", "-q", url, &spec]) { |
| 393 |
Ok(_) => Ok(()), |
| 394 |
Err(e) => { |
| 395 |
let ls = git(mirror, &["ls-remote", "--heads", url, branch]).unwrap_or_default(); |
| 396 |
if ls.trim().is_empty() { |
| 397 |
Ok(()) |
| 398 |
} else { |
| 399 |
Err(e) |
| 400 |
} |
| 401 |
} |
| 402 |
} |
| 403 |
} |
| 404 |
|
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
pub fn git_fetch(&self, url: &str, branch: &str) -> Result<GitImportReport> { |
| 410 |
|
| 411 |
let local = Path::new(url) |
| 412 |
.canonicalize() |
| 413 |
.ok() |
| 414 |
.filter(|_| !url.contains("://")); |
| 415 |
let absolute = local.as_ref().map(|p| p.to_string_lossy().into_owned()); |
| 416 |
let url = absolute.as_deref().unwrap_or(url); |
| 417 |
let mirror = self.git_mirror(url)?; |
| 418 |
self.git_mirror_fetch(&mirror, url, branch)?; |
| 419 |
if git( |
| 420 |
&mirror, |
| 421 |
&[ |
| 422 |
"rev-parse", |
| 423 |
"--verify", |
| 424 |
"-q", |
| 425 |
&format!("refs/heads/{branch}"), |
| 426 |
], |
| 427 |
) |
| 428 |
.is_err() |
| 429 |
{ |
| 430 |
return fail(format!("{url} has no branch {branch:?}")); |
| 431 |
} |
| 432 |
self.import_git_commits( |
| 433 |
&mirror, |
| 434 |
branch, |
| 435 |
&format!("oxy git fetch {url} {branch}"), |
| 436 |
&mut |_| {}, |
| 437 |
) |
| 438 |
} |
| 439 |
|
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
pub fn git_push(&self, url: &str, branch: &str) -> Result<GitExportReport> { |
| 444 |
let mirror = self.git_mirror(url)?; |
| 445 |
self.git_mirror_fetch(&mirror, url, branch)?; |
| 446 |
if let Ok(tip) = git( |
| 447 |
&mirror, |
| 448 |
&[ |
| 449 |
"rev-parse", |
| 450 |
"--verify", |
| 451 |
"-q", |
| 452 |
&format!("refs/heads/{branch}"), |
| 453 |
], |
| 454 |
) { |
| 455 |
let known = self.git_known(&mirror)?; |
| 456 |
if !known.imported.contains_key(&tip) && !known.exported.contains_key(&tip) { |
| 457 |
return fail(format!( |
| 458 |
"{url} {branch} has commits not yet fetched; run `oxy git fetch {url}` first" |
| 459 |
)); |
| 460 |
} |
| 461 |
} |
| 462 |
let report = self.git_export_as(&mirror, branch)?; |
| 463 |
let spec = format!("refs/heads/{branch}:refs/heads/{branch}"); |
| 464 |
git(&mirror, &["push", "-q", url, &spec])?; |
| 465 |
Ok(report) |
| 466 |
} |
| 467 |
|
| 468 |
fn read_oxy_marks(path: &Path) -> Result<BTreeMap<ObjectRef, u64>> { |
| 469 |
let mut out = BTreeMap::new(); |
| 470 |
if let Ok(text) = fs::read_to_string(path) { |
| 471 |
for line in text.lines() { |
| 472 |
if let Some((h, m)) = line.split_once(' ') { |
| 473 |
if let (Some(h), Ok(m)) = (ObjectRef::from_hex(h), m.parse()) { |
| 474 |
out.insert(h, m); |
| 475 |
} |
| 476 |
} |
| 477 |
} |
| 478 |
} |
| 479 |
Ok(out) |
| 480 |
} |
| 481 |
|
| 482 |
|
| 483 |
|
| 484 |
|
| 485 |
|
| 486 |
pub fn git_export(&self, git_dir: &Path) -> Result<GitExportReport> { |
| 487 |
let bookmark = self.config.bookmark.clone(); |
| 488 |
self.git_export_as(git_dir, &bookmark) |
| 489 |
} |
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
pub fn git_export_as(&self, git_dir: &Path, branch: &str) -> Result<GitExportReport> { |
| 495 |
if !git_dir.join("HEAD").exists() && !git_dir.join(".git").exists() { |
| 496 |
fs::create_dir_all(git_dir)?; |
| 497 |
git(git_dir, &["init", "--bare", "-q"])?; |
| 498 |
} |
| 499 |
let marks_dir = self.git_marks_dir(git_dir)?; |
| 500 |
let git_marks = marks_dir.join("git-marks"); |
| 501 |
let oxy_marks_path = marks_dir.join("oxy-marks"); |
| 502 |
let mut marks = Self::read_oxy_marks(&oxy_marks_path)?; |
| 503 |
let git_states = Self::read_git_states(&marks_dir.join("git-states"))?; |
| 504 |
let mut next_mark = marks.values().copied().max().unwrap_or(0) + 1; |
| 505 |
|
| 506 |
let bookmark = self.config.bookmark.clone(); |
| 507 |
let mut stream: Vec<u8> = Vec::new(); |
| 508 |
let mut report = GitExportReport { |
| 509 |
branch: branch.to_string(), |
| 510 |
heads: self.bookmark_heads()?.len(), |
| 511 |
..Default::default() |
| 512 |
}; |
| 513 |
|
| 514 |
|
| 515 |
let mut ops = self.op_log()?; |
| 516 |
ops.reverse(); |
| 517 |
let mut prev: Option<(ObjectRef, Vec<ChangeHash>)> = None; |
| 518 |
|
| 519 |
let mut last_parent: Option<String> = None; |
| 520 |
for (_, op) in &ops { |
| 521 |
let Some(state_ref) = op.view.bookmarks.get(&bookmark).copied() else { |
| 522 |
continue; |
| 523 |
}; |
| 524 |
if prev.as_ref().is_some_and(|(p, _)| *p == state_ref) { |
| 525 |
continue; |
| 526 |
} |
| 527 |
let Ok(state) = self.store.get_state(&state_ref) else { |
| 528 |
continue; |
| 529 |
}; |
| 530 |
if state.heads.is_empty() { |
| 531 |
prev = Some((state_ref, vec![])); |
| 532 |
continue; |
| 533 |
} |
| 534 |
if let Some(sha) = git_states.get(&state_ref) { |
| 535 |
report.skipped += 1; |
| 536 |
last_parent = Some(sha.clone()); |
| 537 |
prev = Some((state_ref, state.heads.clone())); |
| 538 |
continue; |
| 539 |
} |
| 540 |
if let Some(m) = marks.get(&state_ref) { |
| 541 |
report.skipped += 1; |
| 542 |
last_parent = Some(format!(":{m}")); |
| 543 |
prev = Some((state_ref, state.heads.clone())); |
| 544 |
continue; |
| 545 |
} |
| 546 |
let prev_heads = prev.as_ref().map(|(_, h)| h.clone()).unwrap_or_default(); |
| 547 |
let added = self |
| 548 |
.negotiate(&prev_heads, &state.heads) |
| 549 |
.unwrap_or_default(); |
| 550 |
let loaded = self.load_state(&state.heads)?; |
| 551 |
let snapshot = loaded.materialize(); |
| 552 |
let (author, secs, mut message) = match added.as_slice() { |
| 553 |
[h] => { |
| 554 |
let c = self.store.get_change(h)?; |
| 555 |
let mut m = c.message.clone(); |
| 556 |
if !m.ends_with('\n') { |
| 557 |
m.push('\n'); |
| 558 |
} |
| 559 |
m.push_str(&format!( |
| 560 |
"\nChange-Id: {}\nOxy-Hash: {}\n", |
| 561 |
c.change_id.to_hex(), |
| 562 |
h.to_hex() |
| 563 |
)); |
| 564 |
(self.git_author(&c), c.hlc.wall_ms / 1000, m) |
| 565 |
} |
| 566 |
[] => ( |
| 567 |
"oxy <oxy@localhost>".to_string(), |
| 568 |
op.hlc.wall_ms / 1000, |
| 569 |
format!("oxy: {}\n\n", op.command), |
| 570 |
), |
| 571 |
many => { |
| 572 |
let mut m = format!("oxy: {} ({} changes)\n\n", op.command, many.len()); |
| 573 |
for h in many { |
| 574 |
let c = self.store.get_change(h)?; |
| 575 |
m.push_str(&format!( |
| 576 |
"- {} {}\n", |
| 577 |
c.change_id.short(8), |
| 578 |
c.message.lines().next().unwrap_or("") |
| 579 |
)); |
| 580 |
} |
| 581 |
m.push_str(&format!( |
| 582 |
"\nOxy-Changes: {}\n", |
| 583 |
many.iter() |
| 584 |
.map(|h| h.to_hex()) |
| 585 |
.collect::<Vec<_>>() |
| 586 |
.join(" ") |
| 587 |
)); |
| 588 |
("oxy <oxy@localhost>".to_string(), op.hlc.wall_ms / 1000, m) |
| 589 |
} |
| 590 |
}; |
| 591 |
message.push_str(&format!("Oxy-State: {}\n", state_ref.to_hex())); |
| 592 |
if snapshot.is_conflicted() { |
| 593 |
message.push_str("Oxy-Conflicted: true\n"); |
| 594 |
} |
| 595 |
let mark = next_mark; |
| 596 |
next_mark += 1; |
| 597 |
let parents: Vec<String> = last_parent.clone().into_iter().collect(); |
| 598 |
self.write_commit( |
| 599 |
&mut stream, |
| 600 |
"refs/oxy/export", |
| 601 |
mark, |
| 602 |
&author, |
| 603 |
secs, |
| 604 |
&message, |
| 605 |
&parents, |
| 606 |
&snapshot, |
| 607 |
)?; |
| 608 |
marks.insert(state_ref, mark); |
| 609 |
last_parent = Some(format!(":{mark}")); |
| 610 |
prev = Some((state_ref, state.heads.clone())); |
| 611 |
report.exported += 1; |
| 612 |
} |
| 613 |
if let Some(p) = &last_parent { |
| 614 |
stream.extend_from_slice(format!("reset refs/heads/{branch}\nfrom {p}\n\n").as_bytes()); |
| 615 |
} |
| 616 |
|
| 617 |
|
| 618 |
for t in self.tags()? { |
| 619 |
let target = match (git_states.get(&t.state), marks.get(&t.state)) { |
| 620 |
(Some(sha), _) => sha.clone(), |
| 621 |
(None, Some(m)) => format!(":{m}"), |
| 622 |
(None, None) => { |
| 623 |
let loaded = self.load_state(&t.heads)?; |
| 624 |
let snapshot = loaded.materialize(); |
| 625 |
let mark = next_mark; |
| 626 |
next_mark += 1; |
| 627 |
let message = format!( |
| 628 |
"oxy: tag {}\n\n{}Oxy-State: {}\n", |
| 629 |
t.name, |
| 630 |
if t.message.is_empty() { |
| 631 |
String::new() |
| 632 |
} else { |
| 633 |
format!("{}\n\n", t.message) |
| 634 |
}, |
| 635 |
t.state.to_hex() |
| 636 |
); |
| 637 |
self.write_commit( |
| 638 |
&mut stream, |
| 639 |
"refs/oxy/export", |
| 640 |
mark, |
| 641 |
"oxy <oxy@localhost>", |
| 642 |
Hlc::now().wall_ms / 1000, |
| 643 |
&message, |
| 644 |
&[], |
| 645 |
&snapshot, |
| 646 |
)?; |
| 647 |
marks.insert(t.state, mark); |
| 648 |
report.exported += 1; |
| 649 |
format!(":{mark}") |
| 650 |
} |
| 651 |
}; |
| 652 |
stream.extend_from_slice( |
| 653 |
format!("reset refs/tags/{}\nfrom {target}\n\n", t.name).as_bytes(), |
| 654 |
); |
| 655 |
} |
| 656 |
stream.extend_from_slice(b"done\n"); |
| 657 |
|
| 658 |
let mut cmd = Command::new("git"); |
| 659 |
|
| 660 |
cmd.arg("-C") |
| 661 |
.arg(git_dir) |
| 662 |
.args(["fast-import", "--quiet", "--done", "--force"]) |
| 663 |
.arg(format!("--export-marks={}", git_marks.display())); |
| 664 |
if git_marks.exists() { |
| 665 |
cmd.arg(format!("--import-marks={}", git_marks.display())); |
| 666 |
} |
| 667 |
let mut child = cmd |
| 668 |
.stdin(Stdio::piped()) |
| 669 |
.stdout(Stdio::null()) |
| 670 |
.stderr(Stdio::piped()) |
| 671 |
.spawn() |
| 672 |
.map_err(|e| RepoError::Msg(format!("running git fast-import: {e}")))?; |
| 673 |
child.stdin.take().unwrap().write_all(&stream)?; |
| 674 |
let out = child.wait_with_output()?; |
| 675 |
if !out.status.success() { |
| 676 |
return fail(format!( |
| 677 |
"git fast-import failed: {}", |
| 678 |
String::from_utf8_lossy(&out.stderr).trim() |
| 679 |
)); |
| 680 |
} |
| 681 |
let text: String = marks |
| 682 |
.iter() |
| 683 |
.map(|(h, m)| format!("{} {m}\n", h.to_hex())) |
| 684 |
.collect(); |
| 685 |
write_atomic(&oxy_marks_path, text.as_bytes())?; |
| 686 |
let _ = git(git_dir, &["update-ref", "-d", "refs/oxy/export"]); |
| 687 |
report.skipped_subrepos = self.git_export_skipped.replace(0); |
| 688 |
Ok(report) |
| 689 |
} |
| 690 |
|
| 691 |
|
| 692 |
|
| 693 |
|
| 694 |
|
| 695 |
pub fn import_git(&self, git_dir: &Path, branch: &str) -> Result<GitImportReport> { |
| 696 |
self.import_git_with(git_dir, branch, &mut |_| {}) |
| 697 |
} |
| 698 |
|
| 699 |
|
| 700 |
|
| 701 |
|
| 702 |
pub fn import_git_with( |
| 703 |
&self, |
| 704 |
git_dir: &Path, |
| 705 |
branch: &str, |
| 706 |
progress: crate::store::Progress<'_>, |
| 707 |
) -> Result<GitImportReport> { |
| 708 |
if !self.bookmark_heads()?.is_empty() { |
| 709 |
return fail("git import needs an empty bookmark; import into a fresh repository"); |
| 710 |
} |
| 711 |
self.import_git_commits( |
| 712 |
git_dir, |
| 713 |
branch, |
| 714 |
&format!("oxy git import {} {branch}", git_dir.display()), |
| 715 |
progress, |
| 716 |
) |
| 717 |
} |
| 718 |
|
| 719 |
|
| 720 |
|
| 721 |
fn import_git_commits( |
| 722 |
&self, |
| 723 |
git_dir: &Path, |
| 724 |
branch: &str, |
| 725 |
command: &str, |
| 726 |
progress: crate::store::Progress<'_>, |
| 727 |
) -> Result<GitImportReport> { |
| 728 |
let batch = self.store.begin_batch()?; |
| 729 |
let result = self.import_git_commits_batched(git_dir, branch, command, progress); |
| 730 |
batch.finish()?; |
| 731 |
result |
| 732 |
} |
| 733 |
|
| 734 |
fn import_git_commits_batched( |
| 735 |
&self, |
| 736 |
git_dir: &Path, |
| 737 |
branch: &str, |
| 738 |
command: &str, |
| 739 |
progress: crate::store::Progress<'_>, |
| 740 |
) -> Result<GitImportReport> { |
| 741 |
let commits = list_commits(git_dir, branch)?; |
| 742 |
let mut cat = CatFile::start(git_dir)?; |
| 743 |
let mut report = GitImportReport::default(); |
| 744 |
let mut known = self.git_known(git_dir)?; |
| 745 |
let old_heads = self.bookmark_heads()?; |
| 746 |
|
| 747 |
|
| 748 |
|
| 749 |
let mut heads_now: BTreeSet<ChangeHash> = old_heads.iter().copied().collect(); |
| 750 |
|
| 751 |
|
| 752 |
|
| 753 |
|
| 754 |
|
| 755 |
|
| 756 |
let max_kept: usize = std::env::var("OXY_IMPORT_KEEP") |
| 757 |
.ok() |
| 758 |
.and_then(|v| v.parse().ok()) |
| 759 |
.unwrap_or(8); |
| 760 |
let mut waiting: HashMap<&str, usize> = HashMap::new(); |
| 761 |
for gc in &commits { |
| 762 |
if let Some(p1) = gc.parents.first() { |
| 763 |
*waiting.entry(p1.as_str()).or_default() += 1; |
| 764 |
} |
| 765 |
} |
| 766 |
type Kept = (State, BTreeMap<String, (String, String)>); |
| 767 |
let mut kept: HashMap<String, Kept> = HashMap::new(); |
| 768 |
|
| 769 |
let pairs: Vec<(String, String)> = commits |
| 770 |
.iter() |
| 771 |
.filter(|gc| { |
| 772 |
!known.imported.contains_key(&gc.sha) && !known.exported.contains_key(&gc.sha) |
| 773 |
}) |
| 774 |
.filter_map(|gc| Some((gc.sha.clone(), gc.parents.first()?.clone()))) |
| 775 |
.collect(); |
| 776 |
let mut diffs = DiffTree::start(git_dir, pairs)?; |
| 777 |
let mut rebuilt = 0usize; |
| 778 |
let mut kept_order: std::collections::VecDeque<String> = std::collections::VecDeque::new(); |
| 779 |
let mut last: Option<String> = None; |
| 780 |
let mut blob_cache: HashMap<String, Vec<u8>> = HashMap::new(); |
| 781 |
let mut cache_bytes: usize = 0; |
| 782 |
|
| 783 |
let mut spent = [std::time::Duration::ZERO; 6]; |
| 784 |
let mut clock = std::time::Instant::now(); |
| 785 |
|
| 786 |
|
| 787 |
|
| 788 |
let trace = std::env::var_os("OXY_IMPORT_TRACE").is_some(); |
| 789 |
let rss_mb = || -> u64 { |
| 790 |
std::fs::read_to_string("/proc/self/statm") |
| 791 |
.ok() |
| 792 |
.and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok()) |
| 793 |
.map(|pages| pages * 4096 >> 20) |
| 794 |
.unwrap_or(0) |
| 795 |
}; |
| 796 |
let mut done = 0usize; |
| 797 |
|
| 798 |
|
| 799 |
let kept_atoms: usize = std::env::var("OXY_IMPORT_KEPT_ATOMS") |
| 800 |
.ok() |
| 801 |
.and_then(|v| v.parse().ok()) |
| 802 |
.unwrap_or(KEPT_ATOMS); |
| 803 |
|
| 804 |
let mut shed = 0usize; |
| 805 |
let mut lap = |i: usize, clock: &mut std::time::Instant| { |
| 806 |
let now = std::time::Instant::now(); |
| 807 |
spent[i] += now - *clock; |
| 808 |
*clock = now; |
| 809 |
}; |
| 810 |
|
| 811 |
|
| 812 |
let checkpoint_every: usize = std::env::var("OXY_IMPORT_CHECKPOINT") |
| 813 |
.ok() |
| 814 |
.and_then(|v| v.parse().ok()) |
| 815 |
.filter(|n| *n > 0) |
| 816 |
.unwrap_or(CHECKPOINT_COMMITS); |
| 817 |
|
| 818 |
|
| 819 |
let stop_after: Option<usize> = std::env::var("OXY_IMPORT_STOP_AFTER") |
| 820 |
.ok() |
| 821 |
.and_then(|v| v.parse().ok()); |
| 822 |
let total = commits.len(); |
| 823 |
for (index, gc) in commits.iter().enumerate() { |
| 824 |
if known.imported.contains_key(&gc.sha) || known.exported.contains_key(&gc.sha) { |
| 825 |
continue; |
| 826 |
} |
| 827 |
if stop_after.is_some_and(|n| done >= n) { |
| 828 |
break; |
| 829 |
} |
| 830 |
let commit_started = std::time::Instant::now(); |
| 831 |
if index % 500 == 0 { |
| 832 |
progress(&format!( |
| 833 |
"{index} of {total} commits, {} merges; at {} {}", |
| 834 |
report.merges, |
| 835 |
&gc.sha[..12.min(gc.sha.len())], |
| 836 |
gc.message |
| 837 |
.lines() |
| 838 |
.next() |
| 839 |
.unwrap_or("") |
| 840 |
.chars() |
| 841 |
.take(60) |
| 842 |
.collect::<String>() |
| 843 |
)); |
| 844 |
} |
| 845 |
let mut base_how = "root"; |
| 846 |
|
| 847 |
|
| 848 |
|
| 849 |
let (mut base, prev_tree) = match gc.parents.first() { |
| 850 |
Some(p1) => { |
| 851 |
let left = waiting.get_mut(p1.as_str()).map(|n| { |
| 852 |
*n -= 1; |
| 853 |
*n |
| 854 |
}); |
| 855 |
let found = if left == Some(0) { |
| 856 |
kept_order.retain(|k| k != p1); |
| 857 |
kept.remove(p1.as_str()) |
| 858 |
} else { |
| 859 |
kept.get(p1.as_str()).cloned() |
| 860 |
}; |
| 861 |
let how = match (&found, left) { |
| 862 |
(Some(_), Some(0)) => "kept", |
| 863 |
(Some(_), _) => "cloned", |
| 864 |
(None, _) => "rebuilt", |
| 865 |
}; |
| 866 |
if trace { |
| 867 |
base_how = how; |
| 868 |
} |
| 869 |
match found { |
| 870 |
Some((st, tree)) => (st, Some(tree)), |
| 871 |
None => { |
| 872 |
|
| 873 |
|
| 874 |
|
| 875 |
let mut st = State::new_history_only(); |
| 876 |
self.add_git_ancestors(&mut st, git_dir, &[p1.as_str()], &known)?; |
| 877 |
|
| 878 |
|
| 879 |
rebuilt += 1; |
| 880 |
(st, Some(list_tree(git_dir, p1)?)) |
| 881 |
} |
| 882 |
} |
| 883 |
} |
| 884 |
None => (State::new_history_only(), None), |
| 885 |
}; |
| 886 |
|
| 887 |
|
| 888 |
let mut touched: HashSet<NodeId> = HashSet::new(); |
| 889 |
let mut merged = 0usize; |
| 890 |
if gc.parents.len() > 1 { |
| 891 |
report.merges += 1; |
| 892 |
let mut args: Vec<String> = gc.parents[1..].to_vec(); |
| 893 |
args.push(format!("^{}", gc.parents[0])); |
| 894 |
let refs: Vec<&str> = args.iter().map(String::as_str).collect(); |
| 895 |
|
| 896 |
|
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
if base.built_count() > 0 { |
| 902 |
let mut count_args = vec!["rev-list", "--count"]; |
| 903 |
count_args.extend(refs.iter().copied()); |
| 904 |
let others: usize = git(git_dir, &count_args)?.trim().parse().unwrap_or(0); |
| 905 |
if others > MERGE_SHED_COMMITS { |
| 906 |
shed += base.shed_graphs(|b| self.store_blob(b))?; |
| 907 |
} |
| 908 |
} |
| 909 |
let before = base.len(); |
| 910 |
self.add_git_ancestors_touching(&mut base, git_dir, &refs, &known, &mut touched)?; |
| 911 |
merged = base.len() - before; |
| 912 |
} |
| 913 |
lap(0, &mut clock); |
| 914 |
|
| 915 |
|
| 916 |
let diff = match gc.parents.first() { |
| 917 |
Some(_) => Some(diffs.diff(&gc.sha)?), |
| 918 |
None => None, |
| 919 |
}; |
| 920 |
let (tree, changed) = match (prev_tree, diff) { |
| 921 |
(Some(mut t), Some(diff)) => { |
| 922 |
let mut changed: HashSet<String> = HashSet::new(); |
| 923 |
for (path, entry) in diff { |
| 924 |
match entry { |
| 925 |
Some(v) => { |
| 926 |
t.insert(path.clone(), v); |
| 927 |
} |
| 928 |
None => { |
| 929 |
t.remove(&path); |
| 930 |
} |
| 931 |
} |
| 932 |
changed.insert(path); |
| 933 |
} |
| 934 |
(t, Some(changed)) |
| 935 |
} |
| 936 |
_ => (list_tree(git_dir, &gc.sha)?, None), |
| 937 |
}; |
| 938 |
lap(1, &mut clock); |
| 939 |
|
| 940 |
|
| 941 |
|
| 942 |
|
| 943 |
let mut same: HashMap<&str, NodeId> = HashMap::new(); |
| 944 |
|
| 945 |
|
| 946 |
let mut same_opaque: HashSet<&str> = HashSet::new(); |
| 947 |
|
| 948 |
|
| 949 |
|
| 950 |
|
| 951 |
|
| 952 |
let partial = changed.is_some() |
| 953 |
&& gc.parents.len() == 1 |
| 954 |
&& !tree.values().any(|(mode, _)| mode == "160000"); |
| 955 |
let mut rel: BTreeSet<&str> = BTreeSet::new(); |
| 956 |
let base_snapshot = if let (true, Some(changed)) = (partial, &changed) { |
| 957 |
let view = base.tree().view(); |
| 958 |
rel.extend(changed.iter().map(String::as_str)); |
| 959 |
rel.extend( |
| 960 |
tree.keys() |
| 961 |
.map(String::as_str) |
| 962 |
.filter(|p| *p == ".oxyattributes" || p.ends_with("/.oxyattributes")), |
| 963 |
); |
| 964 |
let mut dirs: BTreeSet<&str> = BTreeSet::new(); |
| 965 |
for p in changed.iter().filter(|p| !tree.contains_key(*p)) { |
| 966 |
let mut end = p.len(); |
| 967 |
while let Some(i) = p[..end].rfind('/') { |
| 968 |
if !dirs.insert(&p[..i]) { |
| 969 |
break; |
| 970 |
} |
| 971 |
end = i; |
| 972 |
} |
| 973 |
} |
| 974 |
let need: Vec<NodeId> = rel |
| 975 |
.iter() |
| 976 |
.filter_map(|p| view.entries.get(*p)) |
| 977 |
.filter(|e| e.kind == NodeKind::File && !e.mode.opaque) |
| 978 |
.map(|e| e.node) |
| 979 |
.collect(); |
| 980 |
crate::timing::add("render: same and need", clock.elapsed()); |
| 981 |
let t = std::time::Instant::now(); |
| 982 |
self.load_graphs_of(&mut base, &need)?; |
| 983 |
crate::timing::add("render: load graphs", t.elapsed()); |
| 984 |
let t = std::time::Instant::now(); |
| 985 |
let snap = base.materialize_paths(view, rel.iter().chain(dirs.iter()).copied()); |
| 986 |
crate::timing::add("render: materialize", t.elapsed()); |
| 987 |
snap |
| 988 |
} else { |
| 989 |
if let Some(changed) = &changed { |
| 990 |
let view = base.tree().view(); |
| 991 |
for path in tree.keys() { |
| 992 |
|
| 993 |
if changed.contains(path) || path == ".gitmodules" || path == ".oxymodules" |
| 994 |
{ |
| 995 |
continue; |
| 996 |
} |
| 997 |
if let Some(e) = view.entries.get(path) { |
| 998 |
if touched.contains(&e.node) { |
| 999 |
continue; |
| 1000 |
} |
| 1001 |
let opaque = e.kind == NodeKind::Symlink |
| 1002 |
|| (e.kind == NodeKind::File && e.mode.opaque); |
| 1003 |
if e.kind == NodeKind::File && !e.mode.opaque { |
| 1004 |
same.insert(path.as_str(), e.node); |
| 1005 |
} else if opaque && base.live_blobs(&e.node).len() == 1 { |
| 1006 |
same_opaque.insert(path.as_str()); |
| 1007 |
} |
| 1008 |
} |
| 1009 |
} |
| 1010 |
} |
| 1011 |
|
| 1012 |
let skip: HashSet<NodeId> = same.values().copied().collect(); |
| 1013 |
let need: Vec<NodeId> = base |
| 1014 |
.tree() |
| 1015 |
.view() |
| 1016 |
.entries |
| 1017 |
.values() |
| 1018 |
.filter(|e| { |
| 1019 |
e.kind == NodeKind::File && !e.mode.opaque && !skip.contains(&e.node) |
| 1020 |
}) |
| 1021 |
.map(|e| e.node) |
| 1022 |
.collect(); |
| 1023 |
crate::timing::add("render: same and need", clock.elapsed()); |
| 1024 |
let t = std::time::Instant::now(); |
| 1025 |
self.load_graphs_of(&mut base, &need)?; |
| 1026 |
crate::timing::add("render: load graphs, whole tree", t.elapsed()); |
| 1027 |
let t = std::time::Instant::now(); |
| 1028 |
let snap = base.materialize_except(&skip); |
| 1029 |
crate::timing::add("render: materialize, whole tree", t.elapsed()); |
| 1030 |
snap |
| 1031 |
}; |
| 1032 |
|
| 1033 |
lap(2, &mut clock); |
| 1034 |
|
| 1035 |
let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new(); |
| 1036 |
let mut gitlinks: Vec<(String, String)> = Vec::new(); |
| 1037 |
let listed: Box<dyn Iterator<Item = (&String, &(String, String))>> = if partial { |
| 1038 |
Box::new(rel.iter().filter_map(|p| tree.get_key_value(*p))) |
| 1039 |
} else { |
| 1040 |
Box::new(tree.iter()) |
| 1041 |
}; |
| 1042 |
for (path, (mode, sha)) in listed { |
| 1043 |
let (path, sha) = (path.clone(), sha.clone()); |
| 1044 |
let (kind, exec) = match mode.as_str() { |
| 1045 |
"100644" | "100664" => (NodeKind::File, false), |
| 1046 |
"100755" => (NodeKind::File, true), |
| 1047 |
"120000" => (NodeKind::Symlink, false), |
| 1048 |
"160000" => { |
| 1049 |
gitlinks.push((path, sha)); |
| 1050 |
continue; |
| 1051 |
} |
| 1052 |
_ => continue, |
| 1053 |
}; |
| 1054 |
if same.contains_key(path.as_str()) || same_opaque.contains(path.as_str()) { |
| 1055 |
let mut e = FsEntry::new(kind, exec, Vec::new()); |
| 1056 |
e.unchanged = true; |
| 1057 |
entries.insert(path, e); |
| 1058 |
continue; |
| 1059 |
} |
| 1060 |
let content = match blob_cache.get(&sha) { |
| 1061 |
Some(c) => c.clone(), |
| 1062 |
None => { |
| 1063 |
let c = cat.read(&sha)?; |
| 1064 |
if cache_bytes + c.len() > 64 * 1024 * 1024 { |
| 1065 |
blob_cache.clear(); |
| 1066 |
cache_bytes = 0; |
| 1067 |
} |
| 1068 |
cache_bytes += c.len(); |
| 1069 |
blob_cache.insert(sha.clone(), c.clone()); |
| 1070 |
c |
| 1071 |
} |
| 1072 |
}; |
| 1073 |
entries.insert(path, FsEntry::new(kind, exec, content)); |
| 1074 |
} |
| 1075 |
|
| 1076 |
|
| 1077 |
|
| 1078 |
if !gitlinks.is_empty() { |
| 1079 |
report.submodules += gitlinks.len(); |
| 1080 |
let gm = entries |
| 1081 |
.get(".gitmodules") |
| 1082 |
.map(|e| { |
| 1083 |
crate::subrepo::Modules::from_gitmodules(&String::from_utf8_lossy( |
| 1084 |
&e.content, |
| 1085 |
)) |
| 1086 |
}) |
| 1087 |
.unwrap_or_default(); |
| 1088 |
let mut modules = entries |
| 1089 |
.get(".oxymodules") |
| 1090 |
.map(|e| crate::subrepo::Modules::parse(&String::from_utf8_lossy(&e.content))) |
| 1091 |
.unwrap_or_default(); |
| 1092 |
for (path, sha) in &gitlinks { |
| 1093 |
let m = gm.entries.get(path); |
| 1094 |
let branch = m |
| 1095 |
.and_then(|m| m.bookmark.clone()) |
| 1096 |
.unwrap_or_else(|| "HEAD".into()); |
| 1097 |
entries.insert( |
| 1098 |
path.clone(), |
| 1099 |
FsEntry::new( |
| 1100 |
NodeKind::Subrepo, |
| 1101 |
false, |
| 1102 |
crate::subrepo::Pin::Git { |
| 1103 |
sha: sha.clone(), |
| 1104 |
branch, |
| 1105 |
} |
| 1106 |
.encode(), |
| 1107 |
), |
| 1108 |
); |
| 1109 |
if let Some(m) = m { |
| 1110 |
modules.entries.insert(path.clone(), m.clone()); |
| 1111 |
} |
| 1112 |
} |
| 1113 |
if !modules.entries.is_empty() { |
| 1114 |
entries.insert( |
| 1115 |
".oxymodules".into(), |
| 1116 |
FsEntry::new(NodeKind::File, false, modules.to_text().into_bytes()), |
| 1117 |
); |
| 1118 |
} |
| 1119 |
} |
| 1120 |
lap(3, &mut clock); |
| 1121 |
|
| 1122 |
|
| 1123 |
let seed = *blake3::hash(format!("oxy git import\0{}", gc.sha).as_bytes()).as_bytes(); |
| 1124 |
let mut built = if partial { |
| 1125 |
|
| 1126 |
let dir_needed = |dir: &str| { |
| 1127 |
let prefix = format!("{dir}/"); |
| 1128 |
tree.range(prefix.clone()..) |
| 1129 |
.next() |
| 1130 |
.is_some_and(|(k, _)| k.starts_with(&prefix)) |
| 1131 |
}; |
| 1132 |
self.build_from_entries_seeded( |
| 1133 |
&base, |
| 1134 |
&base_snapshot, |
| 1135 |
&entries, |
| 1136 |
seed, |
| 1137 |
Some(&dir_needed), |
| 1138 |
)? |
| 1139 |
} else { |
| 1140 |
self.build_from_entries_seeded(&base, &base_snapshot, &entries, seed, None)? |
| 1141 |
}; |
| 1142 |
lap(4, &mut clock); |
| 1143 |
|
| 1144 |
|
| 1145 |
|
| 1146 |
|
| 1147 |
for (path, f) in &base_snapshot.files { |
| 1148 |
let (FileContent::Opaque { blobs }, Some(e)) = (&f.content, entries.get(path)) |
| 1149 |
else { |
| 1150 |
continue; |
| 1151 |
}; |
| 1152 |
if blobs.len() < 2 || f.kind != e.kind { |
| 1153 |
continue; |
| 1154 |
} |
| 1155 |
let chosen = self.store_blob(&e.content)?; |
| 1156 |
for b in blobs { |
| 1157 |
built.edits.push(Edit::Replace { |
| 1158 |
node: f.node, |
| 1159 |
old: Some(*b), |
| 1160 |
new: Some(chosen), |
| 1161 |
}); |
| 1162 |
} |
| 1163 |
built.resolves = true; |
| 1164 |
built |
| 1165 |
.contributors |
| 1166 |
.extend(base.live_replaces(&f.node).into_iter().map(|(c, _)| c)); |
| 1167 |
} |
| 1168 |
|
| 1169 |
|
| 1170 |
drop(base_snapshot); |
| 1171 |
drop(entries); |
| 1172 |
let mut deps: BTreeSet<ChangeHash> = built.contributors.iter().copied().collect(); |
| 1173 |
let mut message = gc.message.clone(); |
| 1174 |
if !message.ends_with('\n') { |
| 1175 |
message.push('\n'); |
| 1176 |
} |
| 1177 |
message.push_str(&format!( |
| 1178 |
"\nGit-Commit: {}\nGit-Author: {}\n", |
| 1179 |
gc.sha, gc.author |
| 1180 |
)); |
| 1181 |
let mut change = Change { |
| 1182 |
version: crate::objects::CHANGE_VERSION, |
| 1183 |
change_id: change_id_for(&gc.sha, &gc.message), |
| 1184 |
deps: vec![], |
| 1185 |
author: ObjectRef::ZERO, |
| 1186 |
hlc: Hlc { |
| 1187 |
wall_ms: gc.author_secs * 1000, |
| 1188 |
logical: 0, |
| 1189 |
}, |
| 1190 |
message, |
| 1191 |
tree_ops: built.tree_ops, |
| 1192 |
edits: built.edits, |
| 1193 |
kind: if built.resolves { |
| 1194 |
ChangeKind::Resolution |
| 1195 |
} else { |
| 1196 |
ChangeKind::Normal |
| 1197 |
}, |
| 1198 |
}; |
| 1199 |
let t = std::time::Instant::now(); |
| 1200 |
deps.extend(referenced_changes(&change, &base)); |
| 1201 |
crate::timing::add("store: referenced", t.elapsed()); |
| 1202 |
change.deps = deps.into_iter().collect(); |
| 1203 |
change.normalize(); |
| 1204 |
let hash = self.store.put_change(&change)?; |
| 1205 |
for d in &change.deps { |
| 1206 |
heads_now.remove(d); |
| 1207 |
} |
| 1208 |
heads_now.insert(hash); |
| 1209 |
|
| 1210 |
|
| 1211 |
let t = std::time::Instant::now(); |
| 1212 |
let (skeleton, texts) = self.store.get_change_lazy(&hash)?; |
| 1213 |
base.add_known_mixed(hash, change, skeleton, texts); |
| 1214 |
crate::timing::add("store: add to state", t.elapsed()); |
| 1215 |
known.imported.insert(gc.sha.clone(), hash); |
| 1216 |
if waiting.get(gc.sha.as_str()).is_some_and(|n| *n > 0) { |
| 1217 |
|
| 1218 |
|
| 1219 |
|
| 1220 |
|
| 1221 |
|
| 1222 |
if base.built_count() > KEPT_GRAPHS || base.built_atoms() > kept_atoms { |
| 1223 |
shed += base.shed_graphs(|b| self.store_blob(b))?; |
| 1224 |
} |
| 1225 |
kept.insert(gc.sha.clone(), (base, tree)); |
| 1226 |
kept_order.push_back(gc.sha.clone()); |
| 1227 |
if kept_order.len() > max_kept { |
| 1228 |
if let Some(old) = kept_order.pop_front() { |
| 1229 |
kept.remove(&old); |
| 1230 |
} |
| 1231 |
} |
| 1232 |
} |
| 1233 |
last = Some(gc.sha.clone()); |
| 1234 |
report.commits += 1; |
| 1235 |
lap(5, &mut clock); |
| 1236 |
done += 1; |
| 1237 |
if done.is_multiple_of(checkpoint_every) { |
| 1238 |
self.checkpoint_import(&heads_now, done)?; |
| 1239 |
} |
| 1240 |
|
| 1241 |
|
| 1242 |
|
| 1243 |
let before_trim = if trace { rss_mb() } else { 0 }; |
| 1244 |
if gc.parents.len() > 1 { |
| 1245 |
crate::alloc_stats::release_freed_memory(); |
| 1246 |
} |
| 1247 |
if trace { |
| 1248 |
let built = kept |
| 1249 |
.get(gc.sha.as_str()) |
| 1250 |
.map(|(st, _)| st.built_count()) |
| 1251 |
.unwrap_or(0); |
| 1252 |
let (edits, most) = kept |
| 1253 |
.get(gc.sha.as_str()) |
| 1254 |
.map(|(st, _)| st.deferred_edit_count()) |
| 1255 |
.unwrap_or((0, 0)); |
| 1256 |
let atoms = kept |
| 1257 |
.get(gc.sha.as_str()) |
| 1258 |
.map(|(st, _)| st.built_atoms()) |
| 1259 |
.unwrap_or(0); |
| 1260 |
eprintln!( |
| 1261 |
"trace {done} {} parents={} base={base_how} merged={merged} built={built} atoms={atoms} kept={} shed={shed} rss_mb={} before_trim_mb={before_trim} deferred_edits={edits} most={most} ms={}", |
| 1262 |
&gc.sha[..12.min(gc.sha.len())], |
| 1263 |
gc.parents.len(), |
| 1264 |
kept.len(), |
| 1265 |
rss_mb(), |
| 1266 |
commit_started.elapsed().as_millis() |
| 1267 |
); |
| 1268 |
} |
| 1269 |
} |
| 1270 |
for (name, d) in [ |
| 1271 |
"git import: bases", |
| 1272 |
"git import: tree", |
| 1273 |
"git import: render base", |
| 1274 |
"git import: read blobs", |
| 1275 |
"git import: build change", |
| 1276 |
"git import: store change", |
| 1277 |
] |
| 1278 |
.iter() |
| 1279 |
.zip(spent) |
| 1280 |
{ |
| 1281 |
crate::timing::record(name, d); |
| 1282 |
} |
| 1283 |
crate::timing::report_totals(); |
| 1284 |
if crate::timing::enabled() { |
| 1285 |
eprintln!( |
| 1286 |
"timing git import: {rebuilt} bases rebuilt from history, {shed} graphs shed" |
| 1287 |
); |
| 1288 |
} |
| 1289 |
|
| 1290 |
|
| 1291 |
report.heads = old_heads.len(); |
| 1292 |
if last.is_none() { |
| 1293 |
return Ok(report); |
| 1294 |
} |
| 1295 |
let heads: Vec<ChangeHash> = heads_now.into_iter().collect(); |
| 1296 |
report.heads = heads.len(); |
| 1297 |
let (op_ref, op) = self.head_op()?; |
| 1298 |
let mut view = op.view.clone(); |
| 1299 |
let old_state_ref = view.bookmarks.get(&self.config.bookmark).copied(); |
| 1300 |
let state_ref = self.store.put_state(&StateObject::new(heads.clone()))?; |
| 1301 |
view.bookmarks |
| 1302 |
.insert(self.config.bookmark.clone(), state_ref); |
| 1303 |
self.record_op(&[op_ref], command, view)?; |
| 1304 |
|
| 1305 |
|
| 1306 |
let old_known = old_heads.is_empty() |
| 1307 |
|| old_state_ref.is_some_and(|s| known.exported.values().any(|e| *e == s)); |
| 1308 |
if let (Some(tip), true) = (commits.last(), old_known) { |
| 1309 |
self.record_git_state(git_dir, &state_ref, &tip.sha)?; |
| 1310 |
} |
| 1311 |
|
| 1312 |
if old_heads.is_empty() { |
| 1313 |
self.checkout(&heads, true, &format!("{command} (checkout)"))?; |
| 1314 |
} else { |
| 1315 |
let snap = self.snapshot(command)?; |
| 1316 |
let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty(); |
| 1317 |
let mut base = snap.base.maximal(&snap.wc.deps); |
| 1318 |
base.sort(); |
| 1319 |
let mut sorted_old = old_heads.clone(); |
| 1320 |
sorted_old.sort(); |
| 1321 |
|
| 1322 |
|
| 1323 |
if clean && (base == sorted_old || base.is_empty()) { |
| 1324 |
self.checkout(&heads, false, &format!("{command} (checkout)"))?; |
| 1325 |
} |
| 1326 |
} |
| 1327 |
Ok(report) |
| 1328 |
} |
| 1329 |
|
| 1330 |
|
| 1331 |
|
| 1332 |
|
| 1333 |
fn add_git_ancestors( |
| 1334 |
&self, |
| 1335 |
st: &mut State, |
| 1336 |
git_dir: &Path, |
| 1337 |
args: &[&str], |
| 1338 |
known: &GitKnown, |
| 1339 |
) -> Result<()> { |
| 1340 |
self.add_git_ancestors_touching(st, git_dir, args, known, &mut HashSet::new()) |
| 1341 |
} |
| 1342 |
|
| 1343 |
|
| 1344 |
|
| 1345 |
fn add_git_ancestors_touching( |
| 1346 |
&self, |
| 1347 |
st: &mut State, |
| 1348 |
git_dir: &Path, |
| 1349 |
args: &[&str], |
| 1350 |
known: &GitKnown, |
| 1351 |
touched: &mut HashSet<NodeId>, |
| 1352 |
) -> Result<()> { |
| 1353 |
let mut full = vec!["rev-list"]; |
| 1354 |
full.extend(args); |
| 1355 |
let out = git(git_dir, &full)?; |
| 1356 |
let mut add = |st: &mut State, h: &ChangeHash| -> Result<()> { |
| 1357 |
if st.contains(h) { |
| 1358 |
return Ok(()); |
| 1359 |
} |
| 1360 |
if !st.is_history_only() { |
| 1361 |
let c = self.store.get_change(h)?; |
| 1362 |
touched.extend(c.edits.iter().map(|e| e.node())); |
| 1363 |
touched.extend(c.tree_ops.iter().map(|o| o.node())); |
| 1364 |
st.add_unchecked(c); |
| 1365 |
return Ok(()); |
| 1366 |
} |
| 1367 |
|
| 1368 |
|
| 1369 |
let (skeleton, texts) = self.store.get_change_lazy(h)?; |
| 1370 |
touched.extend(skeleton.edits.iter().map(|e| e.node())); |
| 1371 |
touched.extend(skeleton.tree_ops.iter().map(|o| o.node())); |
| 1372 |
let built = skeleton |
| 1373 |
.edits |
| 1374 |
.iter() |
| 1375 |
.any(|e| !matches!(e, Edit::Replace { .. }) && st.is_built(&e.node())); |
| 1376 |
if built { |
| 1377 |
let full = self.store.get_change(h)?; |
| 1378 |
st.add_known_mixed(*h, full, skeleton, texts); |
| 1379 |
} else { |
| 1380 |
st.add_known(*h, skeleton, texts); |
| 1381 |
} |
| 1382 |
Ok(()) |
| 1383 |
}; |
| 1384 |
for sha in out.lines() { |
| 1385 |
if let Some(h) = known.imported.get(sha) { |
| 1386 |
add(st, h)?; |
| 1387 |
} else if let Some(state_ref) = known.exported.get(sha) { |
| 1388 |
let heads = self.store.get_state(state_ref)?.heads; |
| 1389 |
for h in self.negotiate(&[], &heads)? { |
| 1390 |
add(st, &h)?; |
| 1391 |
} |
| 1392 |
} |
| 1393 |
} |
| 1394 |
Ok(()) |
| 1395 |
} |
| 1396 |
|
| 1397 |
|
| 1398 |
|
| 1399 |
fn checkpoint_import(&self, heads: &BTreeSet<ChangeHash>, done: usize) -> Result<()> { |
| 1400 |
let heads: Vec<ChangeHash> = heads.iter().copied().collect(); |
| 1401 |
let (op_ref, op) = self.head_op()?; |
| 1402 |
let mut view = op.view.clone(); |
| 1403 |
let state_ref = self.store.put_state(&StateObject::new(heads))?; |
| 1404 |
view.bookmarks |
| 1405 |
.insert(self.config.bookmark.clone(), state_ref); |
| 1406 |
self.record_op( |
| 1407 |
&[op_ref], |
| 1408 |
&format!("oxy git import (checkpoint after {done} commits)"), |
| 1409 |
view, |
| 1410 |
)?; |
| 1411 |
Ok(()) |
| 1412 |
} |
| 1413 |
|
| 1414 |
|
| 1415 |
|
| 1416 |
fn git_known(&self, git_dir: &Path) -> Result<GitKnown> { |
| 1417 |
let imported = self.imported_commits()?; |
| 1418 |
let marks_dir = self.git_marks_dir(git_dir)?; |
| 1419 |
let oxy_marks = Self::read_oxy_marks(&marks_dir.join("oxy-marks"))?; |
| 1420 |
let mut sha_of_mark: HashMap<u64, String> = HashMap::new(); |
| 1421 |
if let Ok(text) = fs::read_to_string(marks_dir.join("git-marks")) { |
| 1422 |
for line in text.lines() { |
| 1423 |
if let Some((m, sha)) = line.split_once(' ') { |
| 1424 |
if let Ok(m) = m.trim_start_matches(':').parse::<u64>() { |
| 1425 |
sha_of_mark.insert(m, sha.trim().to_string()); |
| 1426 |
} |
| 1427 |
} |
| 1428 |
} |
| 1429 |
} |
| 1430 |
let mut exported = HashMap::new(); |
| 1431 |
for (state_ref, m) in oxy_marks { |
| 1432 |
if let Some(sha) = sha_of_mark.get(&m) { |
| 1433 |
exported.insert(sha.clone(), state_ref); |
| 1434 |
} |
| 1435 |
} |
| 1436 |
for (state_ref, sha) in Self::read_git_states(&marks_dir.join("git-states"))? { |
| 1437 |
exported.entry(sha).or_insert(state_ref); |
| 1438 |
} |
| 1439 |
Ok(GitKnown { imported, exported }) |
| 1440 |
} |
| 1441 |
|
| 1442 |
fn git_author(&self, c: &Change) -> String { |
| 1443 |
match self.store.get_identity(&c.author) { |
| 1444 |
Ok(id) if !id.name.is_empty() => format!( |
| 1445 |
"{} <{}>", |
| 1446 |
id.name.replace(['<', '>', '\n'], " "), |
| 1447 |
id.email.replace(['<', '>', '\n', ' '], "") |
| 1448 |
), |
| 1449 |
_ => "oxy <oxy@localhost>".to_string(), |
| 1450 |
} |
| 1451 |
} |
| 1452 |
|
| 1453 |
#[allow(clippy::too_many_arguments)] |
| 1454 |
fn write_commit( |
| 1455 |
&self, |
| 1456 |
out: &mut Vec<u8>, |
| 1457 |
reference: &str, |
| 1458 |
mark: u64, |
| 1459 |
author: &str, |
| 1460 |
secs: u64, |
| 1461 |
message: &str, |
| 1462 |
parents: &[String], |
| 1463 |
snapshot: &Snapshot, |
| 1464 |
) -> Result<()> { |
| 1465 |
out.extend_from_slice(format!("commit {reference}\nmark :{mark}\nauthor {author} {secs} +0000\ncommitter {author} {secs} +0000\ndata {}\n{message}\n", message.len()).as_bytes()); |
| 1466 |
for (i, p) in parents.iter().enumerate() { |
| 1467 |
out.extend_from_slice( |
| 1468 |
format!("{} {p}\n", if i == 0 { "from" } else { "merge" }).as_bytes(), |
| 1469 |
); |
| 1470 |
} |
| 1471 |
out.extend_from_slice(b"deleteall\n"); |
| 1472 |
let has_gitmodules = snapshot.files.contains_key(".gitmodules"); |
| 1473 |
for (path, f) in &snapshot.files { |
| 1474 |
if path == ".oxymodules" { |
| 1475 |
|
| 1476 |
if !has_gitmodules { |
| 1477 |
if let FileContent::Text { bytes, .. } = &f.content { |
| 1478 |
let gm = crate::subrepo::Modules::parse(&String::from_utf8_lossy(bytes)) |
| 1479 |
.to_gitmodules(); |
| 1480 |
if !gm.is_empty() { |
| 1481 |
out.extend_from_slice( |
| 1482 |
format!("M 100644 inline .gitmodules\ndata {}\n", gm.len()) |
| 1483 |
.as_bytes(), |
| 1484 |
); |
| 1485 |
out.extend_from_slice(gm.as_bytes()); |
| 1486 |
out.push(b'\n'); |
| 1487 |
} |
| 1488 |
} |
| 1489 |
} |
| 1490 |
continue; |
| 1491 |
} |
| 1492 |
if f.kind == NodeKind::Subrepo { |
| 1493 |
if let FileContent::Opaque { blobs } = &f.content { |
| 1494 |
if let Some(b) = blobs.first() { |
| 1495 |
match crate::subrepo::Pin::decode(&self.read_blob(b)?)? { |
| 1496 |
crate::subrepo::Pin::Git { sha, .. } => { |
| 1497 |
out.extend_from_slice(format!("M 160000 {sha} {path}\n").as_bytes()) |
| 1498 |
} |
| 1499 |
crate::subrepo::Pin::Oxy { .. } => self |
| 1500 |
.git_export_skipped |
| 1501 |
.set(self.git_export_skipped.get() + 1), |
| 1502 |
} |
| 1503 |
} |
| 1504 |
} |
| 1505 |
continue; |
| 1506 |
} |
| 1507 |
let (mode, bytes): (&str, Vec<u8>) = match (&f.kind, &f.content) { |
| 1508 |
(NodeKind::Dir, _) => continue, |
| 1509 |
(NodeKind::Symlink, FileContent::Opaque { blobs }) => ( |
| 1510 |
"120000", |
| 1511 |
blobs |
| 1512 |
.first() |
| 1513 |
.map(|b| self.read_blob(b)) |
| 1514 |
.transpose()? |
| 1515 |
.unwrap_or_default(), |
| 1516 |
), |
| 1517 |
(_, FileContent::Text { bytes, .. }) => { |
| 1518 |
(if f.mode.exec { "100755" } else { "100644" }, bytes.clone()) |
| 1519 |
} |
| 1520 |
(_, FileContent::Opaque { blobs }) => ( |
| 1521 |
if f.mode.exec { "100755" } else { "100644" }, |
| 1522 |
blobs |
| 1523 |
.first() |
| 1524 |
.map(|b| self.read_blob(b)) |
| 1525 |
.transpose()? |
| 1526 |
.unwrap_or_default(), |
| 1527 |
), |
| 1528 |
(_, FileContent::Dir) => continue, |
| 1529 |
}; |
| 1530 |
out.extend_from_slice( |
| 1531 |
format!("M {mode} inline {path}\ndata {}\n", bytes.len()).as_bytes(), |
| 1532 |
); |
| 1533 |
out.extend_from_slice(&bytes); |
| 1534 |
out.push(b'\n'); |
| 1535 |
} |
| 1536 |
out.push(b'\n'); |
| 1537 |
Ok(()) |
| 1538 |
} |
| 1539 |
} |
| 1540 |
|
| 1541 |
|
| 1542 |
#[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 1543 |
pub struct GitVerifyReport { |
| 1544 |
pub commits: usize, |
| 1545 |
pub files_compared: usize, |
| 1546 |
|
| 1547 |
pub mismatches: Vec<(String, String)>, |
| 1548 |
} |
| 1549 |
|
| 1550 |
impl Repo { |
| 1551 |
|
| 1552 |
|
| 1553 |
|
| 1554 |
|
| 1555 |
|
| 1556 |
pub fn verify_git_import(&self, git_dir: &Path, branch: &str) -> Result<GitVerifyReport> { |
| 1557 |
let commits = list_commits(git_dir, branch)?; |
| 1558 |
let imported = self.imported_commits()?; |
| 1559 |
let mut cat = CatFile::start(git_dir)?; |
| 1560 |
let mut rep = GitVerifyReport::default(); |
| 1561 |
|
| 1562 |
let mut closure: HashMap<String, Arc<BTreeSet<ChangeHash>>> = HashMap::new(); |
| 1563 |
|
| 1564 |
let mut verified_graphs: HashMap<[u8; 32], String> = HashMap::new(); |
| 1565 |
let mut verified_blobs: HashMap<ObjectRef, String> = HashMap::new(); |
| 1566 |
|
| 1567 |
|
| 1568 |
|
| 1569 |
let mut waiting: HashMap<&str, usize> = HashMap::new(); |
| 1570 |
for c in &commits { |
| 1571 |
if let Some(p1) = c.parents.first() { |
| 1572 |
*waiting.entry(p1.as_str()).or_default() += 1; |
| 1573 |
} |
| 1574 |
} |
| 1575 |
let mut kept: HashMap<String, State> = HashMap::new(); |
| 1576 |
let mut kept_order: std::collections::VecDeque<String> = std::collections::VecDeque::new(); |
| 1577 |
for c in &commits { |
| 1578 |
rep.commits += 1; |
| 1579 |
let mut set: BTreeSet<ChangeHash> = BTreeSet::new(); |
| 1580 |
for p in &c.parents { |
| 1581 |
if let Some(ps) = closure.get(p) { |
| 1582 |
set.extend(ps.iter().copied()); |
| 1583 |
} |
| 1584 |
} |
| 1585 |
match imported.get(&c.sha) { |
| 1586 |
Some(h) => { |
| 1587 |
set.insert(*h); |
| 1588 |
} |
| 1589 |
None => { |
| 1590 |
rep.mismatches.push(( |
| 1591 |
c.sha.clone(), |
| 1592 |
"no imported change carries this commit".into(), |
| 1593 |
)); |
| 1594 |
} |
| 1595 |
} |
| 1596 |
let set = Arc::new(set); |
| 1597 |
closure.insert(c.sha.clone(), set.clone()); |
| 1598 |
if rep.mismatches.len() >= 50 { |
| 1599 |
break; |
| 1600 |
} |
| 1601 |
let heads: Vec<ChangeHash> = set.iter().copied().collect(); |
| 1602 |
|
| 1603 |
|
| 1604 |
|
| 1605 |
let from_parent = c.parents.first().and_then(|p1| { |
| 1606 |
let left = waiting.get_mut(p1.as_str()).map(|n| { |
| 1607 |
*n -= 1; |
| 1608 |
*n |
| 1609 |
}); |
| 1610 |
if left == Some(0) { |
| 1611 |
kept_order.retain(|k| k != p1); |
| 1612 |
kept.remove(p1.as_str()) |
| 1613 |
} else { |
| 1614 |
kept.get(p1.as_str()).cloned() |
| 1615 |
} |
| 1616 |
}); |
| 1617 |
let state = match from_parent { |
| 1618 |
Some(mut st) => { |
| 1619 |
|
| 1620 |
|
| 1621 |
|
| 1622 |
for h in set.iter() { |
| 1623 |
if !st.contains(h) { |
| 1624 |
let (change, texts) = self.store.get_change_lazy(h)?; |
| 1625 |
st.add_known(*h, change, texts); |
| 1626 |
} |
| 1627 |
} |
| 1628 |
st |
| 1629 |
} |
| 1630 |
None => self.load_state_history(&heads)?, |
| 1631 |
}; |
| 1632 |
let view = state.tree().view(); |
| 1633 |
let tree = list_tree(git_dir, &c.sha)?; |
| 1634 |
let short = &c.sha[..12.min(c.sha.len())]; |
| 1635 |
let mut differ = |what: String| rep.mismatches.push((c.sha.clone(), what)); |
| 1636 |
let mut conflicted: Vec<String> = |
| 1637 |
view.conflicts.iter().map(|c| format!("{c:?}")).collect(); |
| 1638 |
let mut need: Vec<NodeId> = Vec::new(); |
| 1639 |
for (path, (mode, sha)) in &tree { |
| 1640 |
let Some(e) = view.entries.get(path) else { |
| 1641 |
continue; |
| 1642 |
}; |
| 1643 |
if mode != "160000" |
| 1644 |
&& mode != "120000" |
| 1645 |
&& e.kind == NodeKind::File |
| 1646 |
&& !e.mode.opaque |
| 1647 |
{ |
| 1648 |
let known = state |
| 1649 |
.graph_key(&e.node) |
| 1650 |
.is_some_and(|k| verified_graphs.get(&k) == Some(sha)); |
| 1651 |
if !known { |
| 1652 |
need.push(e.node); |
| 1653 |
} |
| 1654 |
} |
| 1655 |
} |
| 1656 |
|
| 1657 |
let keys: HashMap<NodeId, [u8; 32]> = need |
| 1658 |
.iter() |
| 1659 |
.filter_map(|n| Some((*n, state.graph_key(n)?))) |
| 1660 |
.collect(); |
| 1661 |
let need_set: HashSet<NodeId> = need.iter().copied().collect(); |
| 1662 |
let graphs = self.build_graphs_detached(&state, &need)?; |
| 1663 |
for (path, (mode, sha)) in &tree { |
| 1664 |
let Some(e) = view.entries.get(path) else { |
| 1665 |
differ(format!("{short}: {path} is missing")); |
| 1666 |
continue; |
| 1667 |
}; |
| 1668 |
rep.files_compared += 1; |
| 1669 |
match mode.as_str() { |
| 1670 |
"160000" => { |
| 1671 |
let blobs = state.live_blobs(&e.node); |
| 1672 |
match (e.kind, blobs.as_slice()) { |
| 1673 |
(NodeKind::Subrepo, [b]) => { |
| 1674 |
let pin = crate::subrepo::Pin::decode(&self.read_blob(b)?)?; |
| 1675 |
if !matches!(&pin, crate::subrepo::Pin::Git { sha: s, .. } if s == sha) |
| 1676 |
{ |
| 1677 |
differ(format!("{short}: {path} pins another commit")); |
| 1678 |
} |
| 1679 |
} |
| 1680 |
(kind, _) => differ(format!( |
| 1681 |
"{short}: {path} is not one submodule pin: {kind:?} with {} pins", |
| 1682 |
blobs.len() |
| 1683 |
)), |
| 1684 |
} |
| 1685 |
} |
| 1686 |
"120000" => { |
| 1687 |
let target = cat.read(sha)?; |
| 1688 |
let blobs = state.live_blobs(&e.node); |
| 1689 |
match (e.kind, blobs.as_slice()) { |
| 1690 |
(NodeKind::Symlink, [b]) if self.read_blob(b)? == target => {} |
| 1691 |
_ => differ(format!("{short}: symlink {path} differs")), |
| 1692 |
} |
| 1693 |
} |
| 1694 |
_ => { |
| 1695 |
if e.mode.exec != (mode == "100755") { |
| 1696 |
differ(format!("{short}: {path} executable bit differs")); |
| 1697 |
} |
| 1698 |
if e.kind == NodeKind::File && !e.mode.opaque { |
| 1699 |
if !need_set.contains(&e.node) { |
| 1700 |
|
| 1701 |
continue; |
| 1702 |
} |
| 1703 |
let (have, m) = match graphs.get(&e.node) { |
| 1704 |
Some(g) => state.render_graph(g), |
| 1705 |
None => (Vec::new(), Default::default()), |
| 1706 |
}; |
| 1707 |
if m.is_conflicted() { |
| 1708 |
|
| 1709 |
let mut detail = state.clone(); |
| 1710 |
self.load_graphs_of(&mut detail, &[e.node])?; |
| 1711 |
let who: Vec<String> = detail |
| 1712 |
.conflict_regions(&e.node) |
| 1713 |
.contributors |
| 1714 |
.iter() |
| 1715 |
.filter_map(|h| state.get(h)) |
| 1716 |
.map(|m| { |
| 1717 |
let sha = m |
| 1718 |
.message |
| 1719 |
.lines() |
| 1720 |
.rev() |
| 1721 |
.find_map(|l| l.strip_prefix("Git-Commit: ")) |
| 1722 |
.unwrap_or("?"); |
| 1723 |
format!( |
| 1724 |
"{} {:?}", |
| 1725 |
&sha[..12.min(sha.len())], |
| 1726 |
m.message.lines().next().unwrap_or("") |
| 1727 |
) |
| 1728 |
}) |
| 1729 |
.collect(); |
| 1730 |
conflicted.push(format!("{path} between {}", who.join(" and "))); |
| 1731 |
} |
| 1732 |
let want = cat.read(sha)?; |
| 1733 |
if have != want { |
| 1734 |
differ(format!( |
| 1735 |
"{short}: {path} differs: {}", |
| 1736 |
first_difference(&have, &want) |
| 1737 |
)); |
| 1738 |
} else if !m.is_conflicted() { |
| 1739 |
if let Some(k) = keys.get(&e.node) { |
| 1740 |
verified_graphs.insert(*k, sha.clone()); |
| 1741 |
} |
| 1742 |
} |
| 1743 |
continue; |
| 1744 |
} |
| 1745 |
let blobs = state.live_blobs(&e.node); |
| 1746 |
let [b] = blobs.as_slice() else { |
| 1747 |
differ(format!("{short}: {path} is not one file")); |
| 1748 |
continue; |
| 1749 |
}; |
| 1750 |
if verified_blobs.get(b) == Some(sha) { |
| 1751 |
continue; |
| 1752 |
} |
| 1753 |
if self.read_blob(b)? != cat.read(sha)? { |
| 1754 |
differ(format!("{short}: {path} differs")); |
| 1755 |
} else { |
| 1756 |
verified_blobs.insert(*b, sha.clone()); |
| 1757 |
} |
| 1758 |
} |
| 1759 |
} |
| 1760 |
} |
| 1761 |
if !conflicted.is_empty() { |
| 1762 |
differ(format!( |
| 1763 |
"{short}: the state is conflicted: {}", |
| 1764 |
conflicted.join("; ") |
| 1765 |
)); |
| 1766 |
} |
| 1767 |
|
| 1768 |
|
| 1769 |
let has_submodules = tree.values().any(|(m, _)| m == "160000"); |
| 1770 |
for (path, e) in view.entries.iter() { |
| 1771 |
if e.kind != NodeKind::Dir |
| 1772 |
&& !tree.contains_key(path) |
| 1773 |
&& !(has_submodules && path == ".oxymodules") |
| 1774 |
{ |
| 1775 |
differ(format!("{short}: {path} is extra")); |
| 1776 |
} |
| 1777 |
} |
| 1778 |
if waiting.get(c.sha.as_str()).is_some_and(|n| *n > 0) { |
| 1779 |
kept.insert(c.sha.clone(), state); |
| 1780 |
kept_order.push_back(c.sha.clone()); |
| 1781 |
if kept_order.len() > 8 { |
| 1782 |
if let Some(old) = kept_order.pop_front() { |
| 1783 |
kept.remove(&old); |
| 1784 |
} |
| 1785 |
} |
| 1786 |
} |
| 1787 |
if rep.mismatches.len() >= 50 { |
| 1788 |
break; |
| 1789 |
} |
| 1790 |
} |
| 1791 |
Ok(rep) |
| 1792 |
} |
| 1793 |
} |
| 1794 |
|
| 1795 |
|
| 1796 |
fn first_difference(have: &[u8], want: &[u8]) -> String { |
| 1797 |
let (h, w): (Vec<&[u8]>, Vec<&[u8]>) = ( |
| 1798 |
have.split(|b| *b == b'\n').collect(), |
| 1799 |
want.split(|b| *b == b'\n').collect(), |
| 1800 |
); |
| 1801 |
let i = h |
| 1802 |
.iter() |
| 1803 |
.zip(&w) |
| 1804 |
.position(|(a, b)| a != b) |
| 1805 |
.unwrap_or(h.len().min(w.len())); |
| 1806 |
let show = |l: Option<&&[u8]>| { |
| 1807 |
l.map(|l| String::from_utf8_lossy(&l[..l.len().min(60)]).into_owned()) |
| 1808 |
.unwrap_or_else(|| "(end)".into()) |
| 1809 |
}; |
| 1810 |
format!( |
| 1811 |
"line {}: has {:?}, Git has {:?} ({} lines, Git has {})", |
| 1812 |
i + 1, |
| 1813 |
show(h.get(i)), |
| 1814 |
show(w.get(i)), |
| 1815 |
h.len(), |
| 1816 |
w.len() |
| 1817 |
) |
| 1818 |
} |