| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Import: git history into braid objects. |
| 5 | //! |
| 6 | //! [`import`] does everything on the calling thread. [`import_parallel`] |
| 7 | //! makes exactly the same objects, the same map and the same report, gives |
| 8 | //! the store the same hints and makes the same checks, with the reading, |
| 9 | //! storing and checking spread over threads: see its documentation for how. |
| 10 | |
| 11 | use std::collections::{HashMap, HashSet}; |
| 12 | use std::ops::Deref; |
| 13 | use std::path::Path; |
| 14 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 15 | use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; |
| 16 | |
| 17 | use braid_format::name::forbidden_as_symlink; |
| 18 | use braid_format::{ |
| 19 | ChangesetParts, Directory, Entry, EntryKind, GitId, Kind, ObjectId, Objects, Signature, |
| 20 | build_directory, validate_name, |
| 21 | }; |
| 22 | use rayon::prelude::*; |
| 23 | |
| 24 | use crate::diff; |
| 25 | use crate::error::Error; |
| 26 | use crate::export::Exporter; |
| 27 | use crate::fetch::{self, TreeCache}; |
| 28 | use crate::map::{Added, GitMap, TagEntry}; |
| 29 | use crate::oid::{GitKind, GitOid}; |
| 30 | use crate::raw::{self, EntryType}; |
| 31 | use crate::repo::GitRepo; |
| 32 | |
| 33 | /// Commits per batch of a parallel import. |
| 34 | const BATCH_COMMITS: usize = 64; |
| 35 | |
| 36 | /// Threads of a parallel import that leaves the choice to it: one per core, |
| 37 | /// up to this many. Past that, the one thread that converts commits in order |
| 38 | /// sets the pace, and more threads only contend for the store and spin while |
| 39 | /// they wait. |
| 40 | const DEFAULT_THREADS: usize = 8; |
| 41 | |
| 42 | /// How many bytes of blob content the reading ahead of one batch keeps until |
| 43 | /// the blobs are stored. Past that, a blob read ahead keeps only its id and |
| 44 | /// size, and is read again when it is stored. |
| 45 | const KEPT_BYTES: usize = 128 << 20; |
| 46 | |
| 47 | /// Blobs of this size or larger are never kept between reading and storing: |
| 48 | /// they are read again when they are stored. |
| 49 | const LARGE_BLOB: usize = 4 << 20; |
| 50 | |
| 51 | /// What to import. |
| 52 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 53 | pub struct ImportOptions { |
| 54 | /// The refs to import, by full name such as `refs/heads/main` (a short |
| 55 | /// name is looked up the way git does). Empty means every branch and |
| 56 | /// every tag. |
| 57 | pub refs: Vec<Vec<u8>>, |
| 58 | } |
| 59 | |
| 60 | /// A ref that was imported. |
| 61 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 62 | pub struct ImportedRef { |
| 63 | /// Its full name. |
| 64 | pub name: Vec<u8>, |
| 65 | /// The git object it points to. |
| 66 | pub oid: GitOid, |
| 67 | /// The kind of that object. |
| 68 | pub kind: GitKind, |
| 69 | /// The braid object for it: the changeset of a commit, the blob with the |
| 70 | /// raw bytes of an annotated tag, the braid tree of a tree, the braid blob |
| 71 | /// of a blob. |
| 72 | pub braid: ObjectId, |
| 73 | } |
| 74 | |
| 75 | /// What an import did. Counts are of objects new to the map. |
| 76 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 77 | pub struct ImportReport { |
| 78 | /// Commits imported. |
| 79 | pub commits: usize, |
| 80 | /// Git trees converted. |
| 81 | pub trees: usize, |
| 82 | /// Of those trees, the ones kept as raw bytes because they are not |
| 83 | /// canonical. |
| 84 | pub raw_trees: usize, |
| 85 | /// Blobs imported. |
| 86 | pub blobs: usize, |
| 87 | /// Annotated tags imported. |
| 88 | pub tags: usize, |
| 89 | /// Every ref that was asked for, sorted by name, new or not. |
| 90 | pub refs: Vec<ImportedRef>, |
| 91 | } |
| 92 | |
| 93 | /// Imports the history of the git repository at `git_repo` into `objects`, |
| 94 | /// recording every mapping in `map`. |
| 95 | /// |
| 96 | /// Every commit reachable from the refs is imported, parents before |
| 97 | /// children; commits already in `map` are skipped together with their |
| 98 | /// history, so an import can be repeated to bring in new commits, or resumed |
| 99 | /// after a failure. For each commit: |
| 100 | /// |
| 101 | /// - its tree is converted, each git tree once: blobs keep their exact bytes, |
| 102 | /// modes become file, executable, symlink, directory or submodule entries, |
| 103 | /// and a git tree that the export cannot regenerate exactly keeps its raw |
| 104 | /// bytes. Braid trees never hold an empty subdirectory, so empty |
| 105 | /// directories, and directories holding only empty ones, are left out; a |
| 106 | /// git tree that loses entries this way keeps its raw bytes too; |
| 107 | /// - its raw bytes are stored and become the changeset's git origin, with the |
| 108 | /// change list against its first parent, the parents, and the author, |
| 109 | /// committer and message read from it; |
| 110 | /// - it is exported again from what was stored, and the import stops with an |
| 111 | /// error naming the commit unless the id is the same. |
| 112 | /// |
| 113 | /// Annotated tags keep their raw bytes too, and are checked the same way. |
| 114 | /// |
| 115 | /// Shallow clones and SHA-256 repositories are refused. Replacement objects |
| 116 | /// and grafts are ignored, and objects are read raw: no filters, no |
| 117 | /// line-ending conversion, no LFS. A tree holding a name that braid refuses, |
| 118 | /// such as an alias of `.git`, stops the import with an error naming the |
| 119 | /// commit and the path. |
| 120 | /// |
| 121 | /// Everything happens on the calling thread; [`import_parallel`] does the |
| 122 | /// same work on several. |
| 123 | pub fn import<O: Objects>( |
| 124 | git_repo: &Path, |
| 125 | objects: &O, |
| 126 | map: &mut GitMap, |
| 127 | options: &ImportOptions, |
| 128 | ) -> Result<ImportReport, Error> { |
| 129 | let (mut importer, refs, plan) = Importer::start(git_repo, objects, map, options)?; |
| 130 | for commit in importer.commit_order(&plan.tips)? { |
| 131 | importer.import_commit(commit)?; |
| 132 | } |
| 133 | importer.import_loose(&plan)?; |
| 134 | importer.import_tags(&plan)?; |
| 135 | importer.finish(refs) |
| 136 | } |
| 137 | |
| 138 | /// [`import`], on `threads` threads; 0 means one per core, up to eight. |
| 139 | /// |
| 140 | /// The result is the same as [`import`]'s: the same objects, the same map, |
| 141 | /// the same report, and the same hints to the store, each given while the |
| 142 | /// object it names is stored, or not, as it was then. Commits are still |
| 143 | /// converted and mapped one at a time, parents before children, and every |
| 144 | /// check [`import`] makes by reading back what it stored is made too; what |
| 145 | /// changes is who does the work, and when: |
| 146 | /// |
| 147 | /// - Commits go in batches. Before a batch is converted, its commits, the |
| 148 | /// git trees it will convert and the blobs it will import are read from |
| 149 | /// git on every thread, and each blob's braid id is computed there. |
| 150 | /// - Converting a batch makes every object and maps it, but stores nothing: |
| 151 | /// each object to store and each check to make is queued, in the order |
| 152 | /// [`import`] would have stored and checked them. Whether a git tree is |
| 153 | /// canonical is decided from the directory as converted, which is what |
| 154 | /// reading it back gives. |
| 155 | /// - A batch's objects are stored on every thread while the next batch is |
| 156 | /// read and converted. An object whose hint names another object of its |
| 157 | /// batch is stored after it, and an object queued twice is stored once. |
| 158 | /// Then the batch's checks run on every thread, each reading back from |
| 159 | /// the store what it checks: every git tree converted, from its braid |
| 160 | /// tree or its raw bytes, and every commit, exported again. |
| 161 | /// - The first failure, in that order, is the error, as with [`import`]; |
| 162 | /// what the import added to the map after it is taken back, so that the |
| 163 | /// map is the one [`import`] would have left, and never names an object |
| 164 | /// that was not stored. |
| 165 | /// |
| 166 | /// When the threads cannot be started, this is [`import`]. |
| 167 | pub fn import_parallel<O: Objects + Sync>( |
| 168 | git_repo: &Path, |
| 169 | objects: &O, |
| 170 | map: &mut GitMap, |
| 171 | options: &ImportOptions, |
| 172 | threads: usize, |
| 173 | ) -> Result<ImportReport, Error> { |
| 174 | let threads = match threads { |
| 175 | 0 => std::thread::available_parallelism() |
| 176 | .map_or(1, usize::from) |
| 177 | .min(DEFAULT_THREADS), |
| 178 | threads => threads, |
| 179 | }; |
| 180 | let Ok(pool) = rayon::ThreadPoolBuilder::new().num_threads(threads).build() else { |
| 181 | return import(git_repo, objects, map, options); |
| 182 | }; |
| 183 | pool.install(|| { |
| 184 | let (mut importer, refs, plan) = Importer::start(git_repo, objects, map, options)?; |
| 185 | let order = importer.commit_order(&plan.tips)?; |
| 186 | let handles = Handles::new(&importer.repo); |
| 187 | importer.import_in_batches(&order, &plan, &handles)?; |
| 188 | importer.import_tags(&plan)?; |
| 189 | importer.finish(refs) |
| 190 | }) |
| 191 | } |
| 192 | |
| 193 | /// The refs to import, each with the object it points to. |
| 194 | type Refs = Vec<(Vec<u8>, GitOid)>; |
| 195 | |
| 196 | #[derive(Default)] |
| 197 | struct Plan { |
| 198 | /// Commits to walk from. |
| 199 | tips: Vec<GitOid>, |
| 200 | /// Trees and blobs that refs or tags point to. |
| 201 | loose: Vec<(GitOid, GitKind)>, |
| 202 | /// Annotated tags to import, each after the tags it points to. |
| 203 | tags: Vec<GitOid>, |
| 204 | planned_tags: HashSet<GitOid>, |
| 205 | } |
| 206 | |
| 207 | struct Importer<'o, 'm, O: Objects> { |
| 208 | repo: GitRepo, |
| 209 | objects: &'o O, |
| 210 | map: &'m mut GitMap, |
| 211 | report: ImportReport, |
| 212 | /// Root trees and git origins of the changesets seen in this import. |
| 213 | roots: HashMap<ObjectId, (ObjectId, Option<ObjectId>)>, |
| 214 | /// The braid id of the empty directory. |
| 215 | empty_tree: ObjectId, |
| 216 | /// Directories read back from `objects`, and in a parallel import those |
| 217 | /// converted and not stored yet. |
| 218 | trees: TreeCache, |
| 219 | /// In a parallel import, what was read ahead for the batch being |
| 220 | /// converted, and what converting it queued to store and check. |
| 221 | deferred: Option<Deferred>, |
| 222 | } |
| 223 | |
| 224 | /// The state of a parallel import between its batches. |
| 225 | #[derive(Default)] |
| 226 | struct Deferred { |
| 227 | /// What was read ahead for the batch being converted. |
| 228 | ahead: ReadAhead, |
| 229 | /// What converting the batch did that is not finished yet. |
| 230 | batch: Batch, |
| 231 | /// The place of the last put, check or addition queued, in the order a |
| 232 | /// one-thread import would have made them. |
| 233 | last: u64, |
| 234 | } |
| 235 | |
| 236 | impl Deferred { |
| 237 | fn next(&mut self) -> u64 { |
| 238 | self.last += 1; |
| 239 | self.last |
| 240 | } |
| 241 | |
| 242 | /// Queues an object to store, unless the batch stores it already: storing |
| 243 | /// an object that is there does nothing. |
| 244 | fn put(&mut self, kind: Kind, id: ObjectId, data: Data, similar: Option<ObjectId>) { |
| 245 | if self.batch.queued.insert(id) { |
| 246 | let seq = self.next(); |
| 247 | self.batch.puts.push(Put { |
| 248 | seq, |
| 249 | kind, |
| 250 | id, |
| 251 | data, |
| 252 | similar, |
| 253 | }); |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | fn check(&mut self, check: Check) { |
| 258 | let seq = self.next(); |
| 259 | self.batch.checks.push((seq, check)); |
| 260 | } |
| 261 | |
| 262 | fn added(&mut self, added: Added) { |
| 263 | let seq = self.next(); |
| 264 | self.batch.added.push((seq, added)); |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | /// Objects read from git ahead of converting a batch, by id. Each was read |
| 269 | /// with [`GitRepo::read_kind`] for the kind it is listed under, so taking it |
| 270 | /// from here is the same as reading it then. |
| 271 | #[derive(Default)] |
| 272 | struct ReadAhead { |
| 273 | commits: HashMap<GitOid, Vec<u8>>, |
| 274 | trees: HashMap<GitOid, Vec<u8>>, |
| 275 | blobs: HashMap<GitOid, ReadBlob>, |
| 276 | } |
| 277 | |
| 278 | /// A blob read from git: its braid id and size, and its content unless it was |
| 279 | /// let go to save memory. |
| 280 | struct ReadBlob { |
| 281 | id: ObjectId, |
| 282 | size: u64, |
| 283 | content: Option<Vec<u8>>, |
| 284 | } |
| 285 | |
| 286 | impl ReadBlob { |
| 287 | fn new(content: Vec<u8>, keep: bool) -> Self { |
| 288 | Self { |
| 289 | id: ObjectId::hash(Kind::Blob, &content), |
| 290 | size: content.len() as u64, |
| 291 | content: keep.then_some(content), |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | /// What converting a batch did that is not finished: the objects to store, |
| 297 | /// the checks to make, and what it added to the map, each with its place in |
| 298 | /// the order a one-thread import would have made them. |
| 299 | #[derive(Default)] |
| 300 | struct Batch { |
| 301 | puts: Vec<Put>, |
| 302 | /// The ids of `puts`. |
| 303 | queued: HashSet<ObjectId>, |
| 304 | checks: Vec<(u64, Check)>, |
| 305 | added: Vec<(u64, Added)>, |
| 306 | /// The directories it converted, held by the tree cache until stored. |
| 307 | held: Vec<ObjectId>, |
| 308 | } |
| 309 | |
| 310 | /// An object to store, with the hint [`import`] would have given the store. |
| 311 | struct Put { |
| 312 | seq: u64, |
| 313 | kind: Kind, |
| 314 | id: ObjectId, |
| 315 | data: Data, |
| 316 | similar: Option<ObjectId>, |
| 317 | } |
| 318 | |
| 319 | /// What an object to store holds. |
| 320 | enum Data { |
| 321 | /// Its payload. |
| 322 | Bytes(Vec<u8>), |
| 323 | /// A blob let go to save memory, to read from git again. |
| 324 | Blob(GitOid), |
| 325 | } |
| 326 | |
| 327 | /// A check that reads back what was stored, as [`import`] does right after |
| 328 | /// storing it. |
| 329 | enum Check { |
| 330 | /// The git tree with bytes `raw` is canonical: the braid tree `braid`, |
| 331 | /// read back, must export as exactly these bytes. |
| 332 | Canonical { braid: ObjectId, raw: Vec<u8> }, |
| 333 | /// The git tree `oid` keeps its raw bytes in `blob`: they must read back. |
| 334 | Raw { oid: GitOid, blob: ObjectId }, |
| 335 | /// The commit `oid`: its changeset, exported again, must give it back, |
| 336 | /// and its tree must export. |
| 337 | Commit { |
| 338 | oid: GitOid, |
| 339 | changeset: ObjectId, |
| 340 | tree: GitOid, |
| 341 | }, |
| 342 | } |
| 343 | |
| 344 | /// A failure of a parallel import, with its place in the order of a |
| 345 | /// one-thread import. |
| 346 | type Failure = (u64, Error); |
| 347 | |
| 348 | /// A git tree being converted, waiting for its subtrees. |
| 349 | struct Frame { |
| 350 | oid: GitOid, |
| 351 | raw: Vec<u8>, |
| 352 | /// Path from the root of the commit's tree; empty for the root. |
| 353 | path: Vec<u8>, |
| 354 | /// The entries as written, with their types. |
| 355 | entries: Vec<(EntryType, Vec<u8>, GitOid)>, |
| 356 | next: usize, |
| 357 | /// Braid entries for the entries converted so far, in the same order. |
| 358 | done: Vec<Entry>, |
| 359 | /// Whether every subtree so far is canonical. |
| 360 | canonical_subtrees: bool, |
| 361 | /// Whether an empty directory was left out. |
| 362 | dropped_empty: bool, |
| 363 | /// The same path in the first parent, as hints for the store. |
| 364 | similar: Similar, |
| 365 | } |
| 366 | |
| 367 | /// The braid tree at a path in the first parent of the commit being |
| 368 | /// imported: what its new trees and blobs are probably close to. |
| 369 | struct Similar { |
| 370 | tree: Option<ObjectId>, |
| 371 | /// Its entries, read on first use. |
| 372 | entries: Option<Arc<[Entry]>>, |
| 373 | } |
| 374 | |
| 375 | impl Similar { |
| 376 | fn new(tree: Option<ObjectId>) -> Self { |
| 377 | Self { |
| 378 | tree, |
| 379 | entries: None, |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | /// The entry named `name`, reading the directory the first time. |
| 384 | fn entry<O: Objects>( |
| 385 | &mut self, |
| 386 | objects: &O, |
| 387 | trees: &TreeCache, |
| 388 | name: &[u8], |
| 389 | ) -> Result<Option<EntryKind>, Error> { |
| 390 | let entries = self.entries(objects, trees)?; |
| 391 | Ok(entries |
| 392 | .binary_search_by(|entry| entry.name.as_slice().cmp(name)) |
| 393 | .ok() |
| 394 | .map(|at| entries[at].kind.clone())) |
| 395 | } |
| 396 | |
| 397 | fn entries<O: Objects>(&mut self, objects: &O, trees: &TreeCache) -> Result<&[Entry], Error> { |
| 398 | if self.entries.is_none() { |
| 399 | self.entries = Some(match self.tree { |
| 400 | Some(tree) => trees.entries(objects, tree)?, |
| 401 | None => Vec::new().into(), |
| 402 | }); |
| 403 | } |
| 404 | Ok(self.entries.as_deref().unwrap_or_default()) |
| 405 | } |
| 406 | |
| 407 | /// The tree at `name` below this one. |
| 408 | fn subtree<O: Objects>( |
| 409 | &mut self, |
| 410 | objects: &O, |
| 411 | trees: &TreeCache, |
| 412 | name: &[u8], |
| 413 | ) -> Result<Similar, Error> { |
| 414 | Ok(Similar::new(match self.entry(objects, trees, name)? { |
| 415 | Some(EntryKind::Tree { tree }) => Some(tree), |
| 416 | _ => None, |
| 417 | })) |
| 418 | } |
| 419 | |
| 420 | /// The blob of the file, executable or symlink at `name`. |
| 421 | fn blob<O: Objects>( |
| 422 | &mut self, |
| 423 | objects: &O, |
| 424 | trees: &TreeCache, |
| 425 | name: &[u8], |
| 426 | ) -> Result<Option<ObjectId>, Error> { |
| 427 | Ok(match self.entry(objects, trees, name)? { |
| 428 | Some( |
| 429 | EntryKind::File { blob, .. } |
| 430 | | EntryKind::Executable { blob, .. } |
| 431 | | EntryKind::Symlink { blob, .. }, |
| 432 | ) => Some(blob), |
| 433 | _ => None, |
| 434 | }) |
| 435 | } |
| 436 | |
| 437 | /// For each node of the new directory `directory`, the node of this one |
| 438 | /// it most likely replaces. A split directory with as many nodes as |
| 439 | /// before pairs them in order, since boundaries depend only on names; |
| 440 | /// otherwise only the root is paired, with the old root. |
| 441 | fn nodes<O: Objects>( |
| 442 | &mut self, |
| 443 | objects: &O, |
| 444 | trees: &TreeCache, |
| 445 | directory: &Directory, |
| 446 | ) -> Result<Vec<Option<ObjectId>>, Error> { |
| 447 | let count = directory.nodes.len(); |
| 448 | let mut similar = vec![None; count]; |
| 449 | let Some(tree) = self.tree else { |
| 450 | return Ok(similar); |
| 451 | }; |
| 452 | if count > 1 |
| 453 | && let Ok(old) = build_directory(self.entries(objects, trees)?.to_vec()) |
| 454 | && old.nodes.len() == count |
| 455 | { |
| 456 | return Ok(old.nodes.iter().map(|(id, _)| Some(*id)).collect()); |
| 457 | } |
| 458 | if let Some(root) = similar.last_mut() { |
| 459 | *root = Some(tree); |
| 460 | } |
| 461 | Ok(similar) |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | impl<'o, 'm, O: Objects> Importer<'o, 'm, O> { |
| 466 | /// Opens the repository, reads the refs, and plans what they point to: |
| 467 | /// commits to walk from, trees and blobs that tags point to directly, |
| 468 | /// and annotated tags, each after its target. |
| 469 | fn start( |
| 470 | git_repo: &Path, |
| 471 | objects: &'o O, |
| 472 | map: &'m mut GitMap, |
| 473 | options: &ImportOptions, |
| 474 | ) -> Result<(Self, Refs, Plan), Error> { |
| 475 | let repo = GitRepo::open(git_repo)?; |
| 476 | if repo.is_shallow()? { |
| 477 | return Err(Error::Shallow); |
| 478 | } |
| 479 | let refs = repo.refs(&options.refs)?; |
| 480 | let mut importer = Importer { |
| 481 | repo, |
| 482 | objects, |
| 483 | map, |
| 484 | report: ImportReport::default(), |
| 485 | roots: HashMap::new(), |
| 486 | empty_tree: build_directory(Vec::new()) |
| 487 | .expect("the empty directory is valid") |
| 488 | .root(), |
| 489 | trees: TreeCache::default(), |
| 490 | deferred: None, |
| 491 | }; |
| 492 | let mut plan = Plan::default(); |
| 493 | for (_, oid) in &refs { |
| 494 | importer.plan_ref(*oid, &mut plan)?; |
| 495 | } |
| 496 | Ok((importer, refs, plan)) |
| 497 | } |
| 498 | |
| 499 | /// Imports the trees and blobs that refs or tags point to directly. |
| 500 | fn import_loose(&mut self, plan: &Plan) -> Result<(), Error> { |
| 501 | for (oid, kind) in &plan.loose { |
| 502 | match kind { |
| 503 | GitKind::Tree => { |
| 504 | self.convert_tree(*oid, *oid, None)?; |
| 505 | } |
| 506 | _ => { |
| 507 | self.import_blob(*oid, None)?; |
| 508 | } |
| 509 | } |
| 510 | } |
| 511 | Ok(()) |
| 512 | } |
| 513 | |
| 514 | fn import_tags(&mut self, plan: &Plan) -> Result<(), Error> { |
| 515 | for tag in &plan.tags { |
| 516 | self.import_tag(*tag)?; |
| 517 | } |
| 518 | Ok(()) |
| 519 | } |
| 520 | |
| 521 | /// The report, with every ref that was asked for, after recording the |
| 522 | /// names of annotated tags. |
| 523 | fn finish(mut self, refs: Refs) -> Result<ImportReport, Error> { |
| 524 | for (name, oid) in refs { |
| 525 | let kind = self.repo.kind(&oid)?; |
| 526 | let map = &mut *self.map; |
| 527 | let braid = match kind { |
| 528 | GitKind::Commit => map.changeset(&oid), |
| 529 | GitKind::Tag => map.tag(&oid).map(|entry| entry.raw), |
| 530 | GitKind::Tree => map.tree(&oid), |
| 531 | GitKind::Blob => map.blob(&oid).map(|(id, _)| id), |
| 532 | } |
| 533 | .ok_or_else(|| Error::NotMapped { |
| 534 | what: kind.name(), |
| 535 | id: oid.to_hex(), |
| 536 | })?; |
| 537 | if name.starts_with(b"refs/tags/") { |
| 538 | match kind { |
| 539 | GitKind::Tag => map.set_tag_name(name.clone(), oid), |
| 540 | // The name may have pointed to an annotated tag before. |
| 541 | _ => map.remove_tag_name(&name), |
| 542 | } |
| 543 | } |
| 544 | self.report.refs.push(ImportedRef { |
| 545 | name, |
| 546 | oid, |
| 547 | kind, |
| 548 | braid, |
| 549 | }); |
| 550 | } |
| 551 | Ok(self.report) |
| 552 | } |
| 553 | |
| 554 | /// Follows a ref through annotated tags to a commit, a tree or a blob. |
| 555 | fn plan_ref(&mut self, oid: GitOid, plan: &mut Plan) -> Result<(), Error> { |
| 556 | let mut chain = Vec::new(); |
| 557 | let mut current = oid; |
| 558 | loop { |
| 559 | match self.repo.kind(¤t)? { |
| 560 | GitKind::Commit => { |
| 561 | plan.tips.push(current); |
| 562 | break; |
| 563 | } |
| 564 | kind @ (GitKind::Tree | GitKind::Blob) => { |
| 565 | plan.loose.push((current, kind)); |
| 566 | break; |
| 567 | } |
| 568 | GitKind::Tag => { |
| 569 | // A tag already imported or planned has its target taken |
| 570 | // care of. |
| 571 | if self.map.tag(¤t).is_some() |
| 572 | || plan.planned_tags.contains(¤t) |
| 573 | || chain.contains(¤t) |
| 574 | { |
| 575 | break; |
| 576 | } |
| 577 | chain.push(current); |
| 578 | let bytes = self.repo.read_kind(¤t, GitKind::Tag)?; |
| 579 | current = raw::parse_tag(&bytes).map_err(|reason| Error::Malformed { |
| 580 | oid: current, |
| 581 | kind: GitKind::Tag, |
| 582 | reason, |
| 583 | })?; |
| 584 | } |
| 585 | } |
| 586 | } |
| 587 | for tag in chain.into_iter().rev() { |
| 588 | plan.planned_tags.insert(tag); |
| 589 | plan.tags.push(tag); |
| 590 | } |
| 591 | Ok(()) |
| 592 | } |
| 593 | |
| 594 | /// Every commit reachable from `tips` and not yet in the map, parents |
| 595 | /// before children. The walk is depth first along first parents, without |
| 596 | /// recursion. |
| 597 | fn commit_order(&self, tips: &[GitOid]) -> Result<Vec<GitOid>, Error> { |
| 598 | let mut order = Vec::new(); |
| 599 | let mut seen = HashSet::new(); |
| 600 | for tip in tips { |
| 601 | if self.map.changeset(tip).is_some() || !seen.insert(*tip) { |
| 602 | continue; |
| 603 | } |
| 604 | let mut stack = vec![(*tip, self.parents(tip)?, 0usize)]; |
| 605 | while let Some((oid, parents, next)) = stack.last_mut() { |
| 606 | if let Some(parent) = parents.get(*next).copied() { |
| 607 | *next += 1; |
| 608 | if self.map.changeset(&parent).is_none() && seen.insert(parent) { |
| 609 | let grandparents = self.parents(&parent)?; |
| 610 | stack.push((parent, grandparents, 0)); |
| 611 | } |
| 612 | continue; |
| 613 | } |
| 614 | order.push(*oid); |
| 615 | stack.pop(); |
| 616 | } |
| 617 | } |
| 618 | Ok(order) |
| 619 | } |
| 620 | |
| 621 | fn parents(&self, commit: &GitOid) -> Result<Vec<GitOid>, Error> { |
| 622 | let bytes = self.repo.read_kind(commit, GitKind::Commit)?; |
| 623 | let fields = raw::parse_commit(&bytes).map_err(|reason| Error::Malformed { |
| 624 | oid: *commit, |
| 625 | kind: GitKind::Commit, |
| 626 | reason, |
| 627 | })?; |
| 628 | Ok(fields.parents) |
| 629 | } |
| 630 | |
| 631 | /// Reads a git object of `kind`, taking it from what was read ahead if it |
| 632 | /// is there. |
| 633 | fn read(&mut self, oid: &GitOid, kind: GitKind) -> Result<Vec<u8>, Error> { |
| 634 | if let Some(deferred) = &mut self.deferred { |
| 635 | let ahead = match kind { |
| 636 | GitKind::Commit => deferred.ahead.commits.remove(oid), |
| 637 | GitKind::Tree => deferred.ahead.trees.remove(oid), |
| 638 | GitKind::Blob | GitKind::Tag => None, |
| 639 | }; |
| 640 | if let Some(bytes) = ahead { |
| 641 | return Ok(bytes); |
| 642 | } |
| 643 | } |
| 644 | self.repo.read_kind(oid, kind) |
| 645 | } |
| 646 | |
| 647 | /// Keeps track, in a parallel import, of what an insert added to the |
| 648 | /// map. |
| 649 | fn added(&mut self, added: Added) { |
| 650 | if let Some(deferred) = &mut self.deferred { |
| 651 | deferred.added(added); |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | /// Stores an object, or in a parallel import queues it with its batch. |
| 656 | /// `id` is `ObjectId::hash(kind, payload)`. |
| 657 | fn put( |
| 658 | &mut self, |
| 659 | kind: Kind, |
| 660 | payload: &[u8], |
| 661 | similar: Option<ObjectId>, |
| 662 | id: ObjectId, |
| 663 | ) -> Result<(), Error> { |
| 664 | match &mut self.deferred { |
| 665 | None => { |
| 666 | fetch::put_known(self.objects, kind, payload, similar.as_ref(), id)?; |
| 667 | } |
| 668 | Some(deferred) => deferred.put(kind, id, Data::Bytes(payload.to_vec()), similar), |
| 669 | } |
| 670 | Ok(()) |
| 671 | } |
| 672 | |
| 673 | fn import_commit(&mut self, oid: GitOid) -> Result<(), Error> { |
| 674 | let bytes = self.read(&oid, GitKind::Commit)?; |
| 675 | let fields = raw::parse_commit(&bytes).map_err(|reason| Error::Malformed { |
| 676 | oid, |
| 677 | kind: GitKind::Commit, |
| 678 | reason, |
| 679 | })?; |
| 680 | let mut parents = Vec::with_capacity(fields.parents.len()); |
| 681 | for parent in &fields.parents { |
| 682 | parents.push(self.map.changeset(parent).ok_or_else(|| Error::NotMapped { |
| 683 | what: "commit", |
| 684 | id: parent.to_hex(), |
| 685 | })?); |
| 686 | } |
| 687 | let (base, base_origin) = match parents.first() { |
| 688 | Some(parent) => { |
| 689 | let (root, origin) = self.root_of(parent)?; |
| 690 | (Some(root), origin) |
| 691 | } |
| 692 | None => (None, None), |
| 693 | }; |
| 694 | // What the first parent has at each path, and its own raw bytes, are |
| 695 | // what the store may keep new trees, blobs and bytes as deltas |
| 696 | // against. |
| 697 | let root = self.convert_tree(fields.tree, oid, base)?; |
| 698 | let changes = diff::changes(self.objects, &self.trees, base, root)?; |
| 699 | let origin = ObjectId::hash(Kind::Blob, &bytes); |
| 700 | self.put(Kind::Blob, &bytes, base_origin, origin)?; |
| 701 | let unknown = || Signature { |
| 702 | name: Vec::new(), |
| 703 | email: Vec::new(), |
| 704 | seconds: 0, |
| 705 | offset_minutes: 0, |
| 706 | }; |
| 707 | let assembled = ChangesetParts { |
| 708 | parents, |
| 709 | root, |
| 710 | changes, |
| 711 | author: fields.author.map_or_else(unknown, raw::parse_signature), |
| 712 | committer: fields.committer.map_or_else(unknown, raw::parse_signature), |
| 713 | message: fields.message.to_vec(), |
| 714 | extras: Vec::new(), |
| 715 | git_origin: Some(origin), |
| 716 | } |
| 717 | .assemble() |
| 718 | .map_err(|err| Error::Verification { |
| 719 | oid, |
| 720 | kind: GitKind::Commit, |
| 721 | detail: format!("its changeset cannot be assembled: {err}"), |
| 722 | })?; |
| 723 | if let Some((_, list)) = &assembled.external_list { |
| 724 | self.put(Kind::Blob, list, None, ObjectId::hash(Kind::Blob, list))?; |
| 725 | } |
| 726 | let changeset = ObjectId::hash(Kind::Changeset, &assembled.encoded); |
| 727 | self.put(Kind::Changeset, &assembled.encoded, None, changeset)?; |
| 728 | |
| 729 | // Export what was stored and compare. The commit enters the map only |
| 730 | // once it has passed, so a resumed import checks it again; a |
| 731 | // parallel import maps it now, and takes it back if it fails. |
| 732 | match &mut self.deferred { |
| 733 | None => { |
| 734 | let mut exporter = Exporter::with_cache(self.objects, &*self.map, &self.trees); |
| 735 | check_commit(&mut exporter, oid, &changeset, &fields.tree)?; |
| 736 | } |
| 737 | Some(deferred) => deferred.check(Check::Commit { |
| 738 | oid, |
| 739 | changeset, |
| 740 | tree: fields.tree, |
| 741 | }), |
| 742 | } |
| 743 | |
| 744 | let added = self.map.insert_commit(oid, changeset); |
| 745 | self.added(added); |
| 746 | self.roots.insert(changeset, (root, Some(origin))); |
| 747 | self.report.commits += 1; |
| 748 | Ok(()) |
| 749 | } |
| 750 | |
| 751 | /// The root tree and the git origin of a changeset. |
| 752 | fn root_of(&mut self, changeset: &ObjectId) -> Result<(ObjectId, Option<ObjectId>), Error> { |
| 753 | if let Some(found) = self.roots.get(changeset) { |
| 754 | return Ok(*found); |
| 755 | } |
| 756 | let read = fetch::changeset(self.objects, changeset)?; |
| 757 | let found = (read.root, read.git_origin); |
| 758 | self.roots.insert(*changeset, found); |
| 759 | Ok(found) |
| 760 | } |
| 761 | |
| 762 | /// Converts a git tree and everything below it, and returns its braid |
| 763 | /// tree. `commit` names the commit (or the object a ref points to) in |
| 764 | /// errors, and `similar` is the braid tree of its first parent, if it |
| 765 | /// has one. Subtrees are converted before their parents, without |
| 766 | /// recursion. |
| 767 | fn convert_tree( |
| 768 | &mut self, |
| 769 | root: GitOid, |
| 770 | commit: GitOid, |
| 771 | similar: Option<ObjectId>, |
| 772 | ) -> Result<ObjectId, Error> { |
| 773 | if let Some(tree) = self.map.tree(&root) { |
| 774 | return Ok(tree); |
| 775 | } |
| 776 | let mut stack = vec![self.open_tree(root, Vec::new(), commit, Similar::new(similar))?]; |
| 777 | loop { |
| 778 | let top = stack |
| 779 | .last_mut() |
| 780 | .expect("the stack holds the root until it returns"); |
| 781 | if let Some((kind, name, oid)) = top.entries.get(top.next).cloned() { |
| 782 | let kind = match kind { |
| 783 | EntryType::Tree => match self.map.tree(&oid) { |
| 784 | Some(tree) => { |
| 785 | top.canonical_subtrees &= self.map.raw_tree(&oid).is_none(); |
| 786 | if tree == self.empty_tree { |
| 787 | top.dropped_empty = true; |
| 788 | top.next += 1; |
| 789 | continue; |
| 790 | } |
| 791 | EntryKind::Tree { tree } |
| 792 | } |
| 793 | None => { |
| 794 | let path = join(&top.path, &name); |
| 795 | let similar = top.similar.subtree(self.objects, &self.trees, &name)?; |
| 796 | let child = self.open_tree(oid, path, commit, similar)?; |
| 797 | stack.push(child); |
| 798 | continue; |
| 799 | } |
| 800 | }, |
| 801 | EntryType::Gitlink => EntryKind::Gitlink { |
| 802 | commit: GitId::from(oid), |
| 803 | }, |
| 804 | EntryType::File | EntryType::Executable | EntryType::Symlink => { |
| 805 | let (blob, size) = match self.map.blob(&oid) { |
| 806 | Some(found) => found, |
| 807 | None => { |
| 808 | let similar = top.similar.blob(self.objects, &self.trees, &name)?; |
| 809 | self.import_blob(oid, similar)? |
| 810 | } |
| 811 | }; |
| 812 | match kind { |
| 813 | EntryType::File => EntryKind::File { blob, size }, |
| 814 | EntryType::Executable => EntryKind::Executable { blob, size }, |
| 815 | _ => EntryKind::Symlink { blob, size }, |
| 816 | } |
| 817 | } |
| 818 | }; |
| 819 | top.done.push(Entry { name, kind }); |
| 820 | top.next += 1; |
| 821 | continue; |
| 822 | } |
| 823 | let finished = stack |
| 824 | .pop() |
| 825 | .expect("the stack holds the root until it returns"); |
| 826 | let tree = self.finish_tree(finished, commit)?; |
| 827 | match stack.last_mut() { |
| 828 | Some(parent) => { |
| 829 | let (_, name, oid) = parent.entries[parent.next].clone(); |
| 830 | parent.canonical_subtrees &= self.map.raw_tree(&oid).is_none(); |
| 831 | if tree == self.empty_tree { |
| 832 | // An empty directory, or one holding only empty |
| 833 | // ones: braid trees leave it out. |
| 834 | parent.dropped_empty = true; |
| 835 | } else { |
| 836 | parent.done.push(Entry { |
| 837 | name, |
| 838 | kind: EntryKind::Tree { tree }, |
| 839 | }); |
| 840 | } |
| 841 | parent.next += 1; |
| 842 | } |
| 843 | // A root may be empty. |
| 844 | None => return Ok(tree), |
| 845 | } |
| 846 | } |
| 847 | } |
| 848 | |
| 849 | /// Reads a git tree and checks every entry's mode and name before any of |
| 850 | /// its content is read. |
| 851 | fn open_tree( |
| 852 | &mut self, |
| 853 | oid: GitOid, |
| 854 | path: Vec<u8>, |
| 855 | commit: GitOid, |
| 856 | similar: Similar, |
| 857 | ) -> Result<Frame, Error> { |
| 858 | let raw = self.read(&oid, GitKind::Tree)?; |
| 859 | let parsed = raw::parse_tree(&raw).map_err(|reason| Error::Malformed { |
| 860 | oid, |
| 861 | kind: GitKind::Tree, |
| 862 | reason, |
| 863 | })?; |
| 864 | let mut entries = Vec::with_capacity(parsed.len()); |
| 865 | for entry in &parsed { |
| 866 | let kind = EntryType::from_mode(entry.mode).ok_or_else(|| Error::UnsupportedMode { |
| 867 | commit, |
| 868 | path: join(&path, entry.name), |
| 869 | mode: entry.mode.to_vec(), |
| 870 | })?; |
| 871 | let refused = |reason: String| Error::RefusedPath { |
| 872 | commit, |
| 873 | path: join(&path, entry.name), |
| 874 | reason, |
| 875 | }; |
| 876 | validate_name(entry.name).map_err(|err| refused(err.to_string()))?; |
| 877 | if kind == EntryType::Symlink && forbidden_as_symlink(entry.name) { |
| 878 | return Err(refused("this name must not be a symlink".into())); |
| 879 | } |
| 880 | entries.push((kind, entry.name.to_vec(), entry.oid)); |
| 881 | } |
| 882 | let count = entries.len(); |
| 883 | Ok(Frame { |
| 884 | oid, |
| 885 | raw, |
| 886 | path, |
| 887 | entries, |
| 888 | next: 0, |
| 889 | done: Vec::with_capacity(count), |
| 890 | canonical_subtrees: true, |
| 891 | dropped_empty: false, |
| 892 | similar, |
| 893 | }) |
| 894 | } |
| 895 | |
| 896 | /// Stores the braid tree of a converted git tree, decides whether the git |
| 897 | /// tree is canonical, and records it. |
| 898 | fn finish_tree(&mut self, frame: Frame, commit: GitOid) -> Result<ObjectId, Error> { |
| 899 | let Frame { |
| 900 | oid, |
| 901 | raw, |
| 902 | path, |
| 903 | done, |
| 904 | canonical_subtrees, |
| 905 | dropped_empty, |
| 906 | mut similar, |
| 907 | .. |
| 908 | } = frame; |
| 909 | // Braid names are unique: of duplicate entries, the last one written |
| 910 | // stays, which is the one git puts in the index and checks out. The |
| 911 | // raw bytes keep the others. |
| 912 | // |
| 913 | // Every entry passed `validate_entry`'s checks already: `open_tree` |
| 914 | // checked each name, and each name of kind symlink, of the git tree |
| 915 | // these entries come from, and kinds carry over (only a git symlink |
| 916 | // becomes a braid symlink). |
| 917 | let written = done.len(); |
| 918 | let mut names = HashSet::with_capacity(written); |
| 919 | let mut entries: Vec<Entry> = done |
| 920 | .into_iter() |
| 921 | .rev() |
| 922 | .filter(|entry| names.insert(entry.name.clone())) |
| 923 | .collect(); |
| 924 | let unique = entries.len() == written; |
| 925 | // A parallel import keeps the entries, sorted as they are read back, |
| 926 | // for what it converts before the tree is stored. |
| 927 | let kept: Option<Arc<[Entry]>> = self.deferred.is_some().then(|| { |
| 928 | entries.sort_by(|a, b| a.name.cmp(&b.name)); |
| 929 | entries.as_slice().into() |
| 930 | }); |
| 931 | let directory = build_directory(entries).map_err(|err| Error::RefusedPath { |
| 932 | commit, |
| 933 | path: path.clone(), |
| 934 | reason: err.to_string(), |
| 935 | })?; |
| 936 | let hints = similar.nodes(self.objects, &self.trees, &directory)?; |
| 937 | for ((id, bytes), hint) in directory.nodes.iter().zip(hints) { |
| 938 | // A node that did not change is its own old version: no hint. |
| 939 | let hint = hint.filter(|hint| hint != id); |
| 940 | self.put(Kind::Tree, bytes, hint, *id)?; |
| 941 | } |
| 942 | let tree = directory.root(); |
| 943 | |
| 944 | // Canonical means the export, reading back what was just stored, |
| 945 | // gives exactly these bytes. A tree naming a subtree that is not |
| 946 | // canonical cannot be: the subtree's canonical id differs. Neither can |
| 947 | // one that lost duplicates or empty directories. |
| 948 | let raw_blob = match kept { |
| 949 | // A parallel import decides from the directory as converted, |
| 950 | // which is what reading it back gives, and reads it back later. |
| 951 | Some(kept) => { |
| 952 | let canonical = canonical_subtrees |
| 953 | && unique |
| 954 | && !dropped_empty |
| 955 | && Exporter::new(self.objects, &*self.map) |
| 956 | .tree_of(&tree, &kept)? |
| 957 | .1 |
| 958 | == raw; |
| 959 | self.trees.hold(tree, kept); |
| 960 | self.defer_tree_checks(tree, oid, raw, canonical) |
| 961 | } |
| 962 | None => { |
| 963 | let canonical = canonical_subtrees |
| 964 | && unique |
| 965 | && !dropped_empty |
| 966 | && Exporter::with_cache(self.objects, &*self.map, &self.trees) |
| 967 | .tree(&tree)? |
| 968 | .1 |
| 969 | == raw; |
| 970 | if canonical { |
| 971 | None |
| 972 | } else { |
| 973 | let blob = fetch::put(self.objects, Kind::Blob, &raw)?; |
| 974 | check_raw(self.objects, oid, &blob)?; |
| 975 | Some(blob) |
| 976 | } |
| 977 | } |
| 978 | }; |
| 979 | let added = self.map.insert_tree(oid, tree, raw_blob); |
| 980 | self.added(added); |
| 981 | self.report.trees += 1; |
| 982 | if raw_blob.is_some() { |
| 983 | self.report.raw_trees += 1; |
| 984 | } |
| 985 | Ok(tree) |
| 986 | } |
| 987 | |
| 988 | /// In a parallel import, queues what [`finish_tree`](Self::finish_tree) |
| 989 | /// checks of a tree right after storing it, and the tree's raw bytes when |
| 990 | /// it is not canonical, whose blob it returns then. |
| 991 | fn defer_tree_checks( |
| 992 | &mut self, |
| 993 | tree: ObjectId, |
| 994 | oid: GitOid, |
| 995 | raw: Vec<u8>, |
| 996 | canonical: bool, |
| 997 | ) -> Option<ObjectId> { |
| 998 | let deferred = self |
| 999 | .deferred |
| 1000 | .as_mut() |
| 1001 | .expect("only a parallel import defers its checks"); |
| 1002 | deferred.batch.held.push(tree); |
| 1003 | if canonical { |
| 1004 | deferred.check(Check::Canonical { braid: tree, raw }); |
| 1005 | return None; |
| 1006 | } |
| 1007 | let blob = ObjectId::hash(Kind::Blob, &raw); |
| 1008 | deferred.put(Kind::Blob, blob, Data::Bytes(raw), None); |
| 1009 | deferred.check(Check::Raw { oid, blob }); |
| 1010 | Some(blob) |
| 1011 | } |
| 1012 | |
| 1013 | /// Imports a blob, with the first parent's blob at the same path, if |
| 1014 | /// any, as a hint for the store. In a parallel import, the blob is |
| 1015 | /// mapped now and stored with its batch. |
| 1016 | fn import_blob( |
| 1017 | &mut self, |
| 1018 | oid: GitOid, |
| 1019 | similar: Option<ObjectId>, |
| 1020 | ) -> Result<(ObjectId, u64), Error> { |
| 1021 | if let Some(found) = self.map.blob(&oid) { |
| 1022 | return Ok(found); |
| 1023 | } |
| 1024 | let Some(deferred) = &mut self.deferred else { |
| 1025 | let bytes = self.repo.read_kind(&oid, GitKind::Blob)?; |
| 1026 | let blob = fetch::put_hinted(self.objects, Kind::Blob, &bytes, similar.as_ref())?; |
| 1027 | let size = bytes.len() as u64; |
| 1028 | self.map.insert_blob(oid, blob, size); |
| 1029 | self.report.blobs += 1; |
| 1030 | return Ok((blob, size)); |
| 1031 | }; |
| 1032 | let read = match deferred.ahead.blobs.remove(&oid) { |
| 1033 | Some(read) => read, |
| 1034 | None => { |
| 1035 | let content = self.repo.read_kind(&oid, GitKind::Blob)?; |
| 1036 | let keep = content.len() < LARGE_BLOB; |
| 1037 | ReadBlob::new(content, keep) |
| 1038 | } |
| 1039 | }; |
| 1040 | let (id, size) = (read.id, read.size); |
| 1041 | let data = match read.content { |
| 1042 | Some(content) => Data::Bytes(content), |
| 1043 | None => Data::Blob(oid), |
| 1044 | }; |
| 1045 | deferred.put(Kind::Blob, id, data, similar); |
| 1046 | let added = self.map.insert_blob(oid, id, size); |
| 1047 | deferred.added(added); |
| 1048 | self.report.blobs += 1; |
| 1049 | Ok((id, size)) |
| 1050 | } |
| 1051 | |
| 1052 | fn import_tag(&mut self, oid: GitOid) -> Result<(), Error> { |
| 1053 | if self.map.tag(&oid).is_some() { |
| 1054 | return Ok(()); |
| 1055 | } |
| 1056 | let bytes = self.repo.read_kind(&oid, GitKind::Tag)?; |
| 1057 | let target = raw::parse_tag(&bytes).map_err(|reason| Error::Malformed { |
| 1058 | oid, |
| 1059 | kind: GitKind::Tag, |
| 1060 | reason, |
| 1061 | })?; |
| 1062 | let target_kind = self.repo.kind(&target)?; |
| 1063 | let imported = match target_kind { |
| 1064 | GitKind::Commit => self.map.changeset(&target).is_some(), |
| 1065 | GitKind::Tree => self.map.tree(&target).is_some(), |
| 1066 | GitKind::Blob => self.map.blob(&target).is_some(), |
| 1067 | GitKind::Tag => self.map.tag(&target).is_some(), |
| 1068 | }; |
| 1069 | if !imported { |
| 1070 | return Err(Error::NotMapped { |
| 1071 | what: target_kind.name(), |
| 1072 | id: target.to_hex(), |
| 1073 | }); |
| 1074 | } |
| 1075 | let raw = fetch::put(self.objects, Kind::Blob, &bytes)?; |
| 1076 | let stored = fetch::get(self.objects, &raw, Kind::Blob)?; |
| 1077 | if GitOid::for_object(GitKind::Tag, &stored)? != oid { |
| 1078 | return Err(Error::Verification { |
| 1079 | oid, |
| 1080 | kind: GitKind::Tag, |
| 1081 | detail: "its raw bytes do not read back".into(), |
| 1082 | }); |
| 1083 | } |
| 1084 | self.map.insert_tag( |
| 1085 | oid, |
| 1086 | TagEntry { |
| 1087 | raw, |
| 1088 | target, |
| 1089 | target_kind, |
| 1090 | }, |
| 1091 | ); |
| 1092 | self.report.tags += 1; |
| 1093 | Ok(()) |
| 1094 | } |
| 1095 | |
| 1096 | /// Takes back, the last first, what a batch added to the map after the |
| 1097 | /// place `after`, or all of it. |
| 1098 | fn take_back(&mut self, added: &[(u64, Added)], after: Option<u64>) { |
| 1099 | for (seq, added) in added.iter().rev() { |
| 1100 | if after.is_none_or(|after| *seq > after) { |
| 1101 | self.map.take_back(added); |
| 1102 | } |
| 1103 | } |
| 1104 | } |
| 1105 | } |
| 1106 | |
| 1107 | impl<O: Objects + Sync> Importer<'_, '_, O> { |
| 1108 | /// Imports the commits of `order`, then the trees and blobs that refs or |
| 1109 | /// tags point to, in batches: see [`import_parallel`]. Returns once every |
| 1110 | /// object is stored and checked. |
| 1111 | fn import_in_batches( |
| 1112 | &mut self, |
| 1113 | order: &[GitOid], |
| 1114 | plan: &Plan, |
| 1115 | handles: &Handles, |
| 1116 | ) -> Result<(), Error> { |
| 1117 | self.deferred = Some(Deferred::default()); |
| 1118 | let mut storing = Batch::default(); |
| 1119 | for commits in order.chunks(BATCH_COMMITS) { |
| 1120 | storing = self.step(storing, handles, |importer| { |
| 1121 | importer.read_ahead(commits, handles); |
| 1122 | for commit in commits { |
| 1123 | importer.import_commit(*commit)?; |
| 1124 | } |
| 1125 | Ok(()) |
| 1126 | })?; |
| 1127 | } |
| 1128 | storing = self.step(storing, handles, |importer| importer.import_loose(plan))?; |
| 1129 | self.step(storing, handles, |_| Ok(()))?; |
| 1130 | self.deferred = None; |
| 1131 | Ok(()) |
| 1132 | } |
| 1133 | |
| 1134 | /// Converts one batch with `convert` on this thread while the objects of |
| 1135 | /// the previous one, `storing`, are stored on the others; then checks |
| 1136 | /// them. Returns what the new batch left to store and check. |
| 1137 | fn step( |
| 1138 | &mut self, |
| 1139 | storing: Batch, |
| 1140 | handles: &Handles, |
| 1141 | convert: impl FnOnce(&mut Self) -> Result<(), Error> + Send, |
| 1142 | ) -> Result<Batch, Error> { |
| 1143 | let objects = self.objects; |
| 1144 | let (converted, stored) = rayon::join( |
| 1145 | || convert(&mut *self), |
| 1146 | || store_puts(objects, handles, &storing.puts), |
| 1147 | ); |
| 1148 | let batch = match &mut self.deferred { |
| 1149 | Some(deferred) => { |
| 1150 | deferred.ahead = ReadAhead::default(); |
| 1151 | std::mem::take(&mut deferred.batch) |
| 1152 | } |
| 1153 | None => Batch::default(), |
| 1154 | }; |
| 1155 | if let Some((seq, err)) = self.finish_batch(&storing, stored) { |
| 1156 | // Nothing of the new batch counts: a one-thread import would have |
| 1157 | // stopped before it. |
| 1158 | self.take_back(&batch.added, None); |
| 1159 | self.take_back(&storing.added, Some(seq)); |
| 1160 | return Err(err); |
| 1161 | } |
| 1162 | self.trees.let_go(&storing.held); |
| 1163 | if let Err(err) = converted { |
| 1164 | // Converting stopped: what it did so far is stored and checked |
| 1165 | // first, as a one-thread import would have done before stopping. |
| 1166 | let stored = store_puts(objects, handles, &batch.puts); |
| 1167 | if let Some((seq, failed)) = self.finish_batch(&batch, stored) { |
| 1168 | self.take_back(&batch.added, Some(seq)); |
| 1169 | return Err(failed); |
| 1170 | } |
| 1171 | return Err(err); |
| 1172 | } |
| 1173 | Ok(batch) |
| 1174 | } |
| 1175 | |
| 1176 | /// Checks a batch whose objects were stored, or stored up to a failure, |
| 1177 | /// and returns the first failure, if any: of storing, or of a check made |
| 1178 | /// before it. |
| 1179 | fn finish_batch(&self, batch: &Batch, stored: Result<(), Failure>) -> Option<Failure> { |
| 1180 | let stored = stored.err(); |
| 1181 | let before = stored.as_ref().map(|(seq, _)| *seq); |
| 1182 | let checked = run_checks(self.objects, self.map, &batch.checks, before).err(); |
| 1183 | match (stored, checked) { |
| 1184 | (Some(stored), Some(checked)) => Some(if checked.0 < stored.0 { |
| 1185 | checked |
| 1186 | } else { |
| 1187 | stored |
| 1188 | }), |
| 1189 | (stored, checked) => stored.or(checked), |
| 1190 | } |
| 1191 | } |
| 1192 | |
| 1193 | /// Reads from git, on every thread, what converting `commits` will read: |
| 1194 | /// the commits, the git trees not converted yet below them, and the blobs |
| 1195 | /// not imported yet in those trees, with their braid ids. What fails to |
| 1196 | /// read is left out; converting reads it again and fails there, as it |
| 1197 | /// would have. |
| 1198 | fn read_ahead(&mut self, commits: &[GitOid], handles: &Handles) { |
| 1199 | let map: &GitMap = self.map; |
| 1200 | let read_commits: Vec<(GitOid, Vec<u8>, GitOid)> = commits |
| 1201 | .par_iter() |
| 1202 | .map_init( |
| 1203 | || handles.get(), |
| 1204 | |git, oid| { |
| 1205 | let bytes = git.read_kind(oid, GitKind::Commit).ok()?; |
| 1206 | let tree = raw::parse_commit(&bytes).ok()?.tree; |
| 1207 | Some((*oid, bytes, tree)) |
| 1208 | }, |
| 1209 | ) |
| 1210 | .flatten() |
| 1211 | .collect(); |
| 1212 | |
| 1213 | // Each tree is read once, by whichever thread meets it first. |
| 1214 | let seen = Mutex::new(HashSet::new()); |
| 1215 | let found: Vec<NewTrees> = read_commits |
| 1216 | .par_iter() |
| 1217 | .map_init( |
| 1218 | || handles.get(), |
| 1219 | |git, (_, _, tree)| new_trees(git, map, &seen, *tree), |
| 1220 | ) |
| 1221 | .collect(); |
| 1222 | |
| 1223 | let mut ahead = ReadAhead::default(); |
| 1224 | let mut blobs = Vec::new(); |
| 1225 | let mut seen_blobs = HashSet::new(); |
| 1226 | for (trees, found_blobs) in found { |
| 1227 | ahead.trees.extend(trees); |
| 1228 | blobs.extend( |
| 1229 | found_blobs |
| 1230 | .into_iter() |
| 1231 | .filter(|oid| seen_blobs.insert(*oid)), |
| 1232 | ); |
| 1233 | } |
| 1234 | let kept = AtomicUsize::new(0); |
| 1235 | ahead.blobs = blobs |
| 1236 | .par_iter() |
| 1237 | .map_init( |
| 1238 | || handles.get(), |
| 1239 | |git, oid| { |
| 1240 | let content = git.read_kind(oid, GitKind::Blob).ok()?; |
| 1241 | let len = content.len(); |
| 1242 | let keep = len < LARGE_BLOB |
| 1243 | && kept.fetch_add(len, Ordering::Relaxed) + len <= KEPT_BYTES; |
| 1244 | Some((*oid, ReadBlob::new(content, keep))) |
| 1245 | }, |
| 1246 | ) |
| 1247 | .flatten() |
| 1248 | .collect(); |
| 1249 | ahead.commits = read_commits |
| 1250 | .into_iter() |
| 1251 | .map(|(oid, bytes, _)| (oid, bytes)) |
| 1252 | .collect(); |
| 1253 | if let Some(deferred) = &mut self.deferred { |
| 1254 | deferred.ahead = ahead; |
| 1255 | } |
| 1256 | } |
| 1257 | } |
| 1258 | |
| 1259 | /// Git trees with their bytes, and the blobs they name. |
| 1260 | type NewTrees = (Vec<(GitOid, Vec<u8>)>, Vec<GitOid>); |
| 1261 | |
| 1262 | /// The git trees below `root` that the map does not hold and no other thread |
| 1263 | /// claimed in `seen`, with their bytes, and the blobs they name that the map |
| 1264 | /// does not hold. |
| 1265 | fn new_trees(git: &GitRepo, map: &GitMap, seen: &Mutex<HashSet<GitOid>>, root: GitOid) -> NewTrees { |
| 1266 | let mut trees = Vec::new(); |
| 1267 | let mut blobs = Vec::new(); |
| 1268 | let mut pending = vec![root]; |
| 1269 | while let Some(oid) = pending.pop() { |
| 1270 | if map.tree(&oid).is_some() || !lock(seen).insert(oid) { |
| 1271 | continue; |
| 1272 | } |
| 1273 | let Ok(bytes) = git.read_kind(&oid, GitKind::Tree) else { |
| 1274 | continue; |
| 1275 | }; |
| 1276 | if let Ok(entries) = raw::parse_tree(&bytes) { |
| 1277 | for entry in entries { |
| 1278 | match EntryType::from_mode(entry.mode) { |
| 1279 | Some(EntryType::Tree) => pending.push(entry.oid), |
| 1280 | Some(EntryType::File | EntryType::Executable | EntryType::Symlink) |
| 1281 | if map.blob(&entry.oid).is_none() => |
| 1282 | { |
| 1283 | blobs.push(entry.oid); |
| 1284 | } |
| 1285 | _ => {} |
| 1286 | } |
| 1287 | } |
| 1288 | } |
| 1289 | trees.push((oid, bytes)); |
| 1290 | } |
| 1291 | (trees, blobs) |
| 1292 | } |
| 1293 | |
| 1294 | /// Stores the objects a batch queued, on every thread. An object whose hint |
| 1295 | /// names another object of the batch is stored after it, and the rest in |
| 1296 | /// any order, so that the store sees each hint stored, or not, as it would |
| 1297 | /// have one object at a time. The failure is the first in the order of |
| 1298 | /// `puts`; what depends on an object that failed is not stored. |
| 1299 | fn store_puts<O: Objects + Sync>( |
| 1300 | objects: &O, |
| 1301 | handles: &Handles, |
| 1302 | puts: &[Put], |
| 1303 | ) -> Result<(), Failure> { |
| 1304 | if puts.is_empty() { |
| 1305 | return Ok(()); |
| 1306 | } |
| 1307 | let position: HashMap<ObjectId, usize> = puts |
| 1308 | .iter() |
| 1309 | .enumerate() |
| 1310 | .map(|(at, put)| (put.id, at)) |
| 1311 | .collect(); |
| 1312 | // The objects to store after each one, and the ones to start from, |
| 1313 | // longest chains first. |
| 1314 | let mut after: Vec<Vec<usize>> = vec![Vec::new(); puts.len()]; |
| 1315 | let mut starts = Vec::new(); |
| 1316 | for (at, put) in puts.iter().enumerate() { |
| 1317 | match put.similar.and_then(|similar| position.get(&similar)) { |
| 1318 | Some(&hint) if hint < at => after[hint].push(at), |
| 1319 | _ => starts.push(at), |
| 1320 | } |
| 1321 | } |
| 1322 | let mut below = vec![1usize; puts.len()]; |
| 1323 | for at in (0..puts.len()).rev() { |
| 1324 | below[at] += after[at].iter().map(|next| below[*next]).sum::<usize>(); |
| 1325 | } |
| 1326 | starts.sort_by_key(|start| std::cmp::Reverse(below[*start])); |
| 1327 | let failed = starts |
| 1328 | .par_iter() |
| 1329 | .with_max_len(1) |
| 1330 | .map_init( |
| 1331 | || handles.get(), |
| 1332 | |git, start| { |
| 1333 | let mut pending = vec![*start]; |
| 1334 | while let Some(at) = pending.pop() { |
| 1335 | let put = &puts[at]; |
| 1336 | if let Err(err) = store_put(objects, git, put) { |
| 1337 | return Some((put.seq, err)); |
| 1338 | } |
| 1339 | pending.extend(after[at].iter().rev()); |
| 1340 | } |
| 1341 | None |
| 1342 | }, |
| 1343 | ) |
| 1344 | .flatten() |
| 1345 | .min_by_key(|(seq, _)| *seq); |
| 1346 | match failed { |
| 1347 | Some(failure) => Err(failure), |
| 1348 | None => Ok(()), |
| 1349 | } |
| 1350 | } |
| 1351 | |
| 1352 | fn store_put<O: Objects>(objects: &O, git: &GitRepo, put: &Put) -> Result<(), Error> { |
| 1353 | let read; |
| 1354 | let payload = match &put.data { |
| 1355 | Data::Bytes(bytes) => bytes, |
| 1356 | Data::Blob(oid) => { |
| 1357 | read = git.read_kind(oid, GitKind::Blob)?; |
| 1358 | &read |
| 1359 | } |
| 1360 | }; |
| 1361 | fetch::put_known(objects, put.kind, payload, put.similar.as_ref(), put.id)?; |
| 1362 | Ok(()) |
| 1363 | } |
| 1364 | |
| 1365 | /// Makes a batch's checks, on every thread, reading back from the store; with |
| 1366 | /// `before`, only the checks before that place. The failure is the first in |
| 1367 | /// the order of `checks`. |
| 1368 | fn run_checks<O: Objects + Sync>( |
| 1369 | objects: &O, |
| 1370 | map: &GitMap, |
| 1371 | checks: &[(u64, Check)], |
| 1372 | before: Option<u64>, |
| 1373 | ) -> Result<(), Failure> { |
| 1374 | let failed = checks |
| 1375 | .par_iter() |
| 1376 | .filter(|(seq, _)| before.is_none_or(|before| *seq < before)) |
| 1377 | .filter_map(|(seq, check)| { |
| 1378 | let mut exporter = Exporter::new(objects, map); |
| 1379 | let checked = match check { |
| 1380 | Check::Canonical { braid, raw } => match exporter.tree(braid) { |
| 1381 | Ok((_, bytes)) if bytes == *raw => Ok(()), |
| 1382 | Ok((oid, _)) => Err(Error::Verification { |
| 1383 | oid, |
| 1384 | kind: GitKind::Tree, |
| 1385 | detail: "it does not read back as it was converted".into(), |
| 1386 | }), |
| 1387 | Err(err) => Err(err), |
| 1388 | }, |
| 1389 | Check::Raw { oid, blob } => check_raw(objects, *oid, blob), |
| 1390 | Check::Commit { |
| 1391 | oid, |
| 1392 | changeset, |
| 1393 | tree, |
| 1394 | } => check_commit(&mut exporter, *oid, changeset, tree), |
| 1395 | }; |
| 1396 | checked.err().map(|err| (*seq, err)) |
| 1397 | }) |
| 1398 | .min_by_key(|(seq, _)| *seq); |
| 1399 | match failed { |
| 1400 | Some(failure) => Err(failure), |
| 1401 | None => Ok(()), |
| 1402 | } |
| 1403 | } |
| 1404 | |
| 1405 | /// Exports a changeset again from what was stored, and checks that it is the |
| 1406 | /// commit `oid` it was imported from, and that the commit's tree exports. |
| 1407 | fn check_commit<O: Objects>( |
| 1408 | exporter: &mut Exporter<'_, O>, |
| 1409 | oid: GitOid, |
| 1410 | changeset: &ObjectId, |
| 1411 | tree: &GitOid, |
| 1412 | ) -> Result<(), Error> { |
| 1413 | let verification = |detail: String| Error::Verification { |
| 1414 | oid, |
| 1415 | kind: GitKind::Commit, |
| 1416 | detail, |
| 1417 | }; |
| 1418 | let (exported, _) = exporter |
| 1419 | .commit(changeset) |
| 1420 | .map_err(|err| verification(err.to_string()))?; |
| 1421 | if exported != oid { |
| 1422 | return Err(verification(format!("exported again as {exported}"))); |
| 1423 | } |
| 1424 | exporter |
| 1425 | .object(tree) |
| 1426 | .map_err(|err| verification(format!("its tree: {err}")))?; |
| 1427 | Ok(()) |
| 1428 | } |
| 1429 | |
| 1430 | /// Checks that the raw bytes of the git tree `oid`, stored as `blob`, read |
| 1431 | /// back as that tree. |
| 1432 | fn check_raw<O: Objects>(objects: &O, oid: GitOid, blob: &ObjectId) -> Result<(), Error> { |
| 1433 | let stored = fetch::get(objects, blob, Kind::Blob)?; |
| 1434 | if GitOid::for_object(GitKind::Tree, &stored)? != oid { |
| 1435 | return Err(Error::Verification { |
| 1436 | oid, |
| 1437 | kind: GitKind::Tree, |
| 1438 | detail: "its raw bytes do not read back".into(), |
| 1439 | }); |
| 1440 | } |
| 1441 | Ok(()) |
| 1442 | } |
| 1443 | |
| 1444 | /// Handles on the git repository for the threads of a parallel import, which |
| 1445 | /// cannot share one. |
| 1446 | struct Handles { |
| 1447 | /// What new handles are made from. |
| 1448 | template: Mutex<GitRepo>, |
| 1449 | /// Handles not in use. |
| 1450 | free: Mutex<Vec<GitRepo>>, |
| 1451 | } |
| 1452 | |
| 1453 | impl Handles { |
| 1454 | fn new(repo: &GitRepo) -> Self { |
| 1455 | Self { |
| 1456 | template: Mutex::new(repo.worker_handle()), |
| 1457 | free: Mutex::new(Vec::new()), |
| 1458 | } |
| 1459 | } |
| 1460 | |
| 1461 | /// A handle for this thread, until the guard is dropped. |
| 1462 | fn get(&self) -> Handle<'_> { |
| 1463 | let free = lock(&self.free).pop(); |
| 1464 | let repo = free.unwrap_or_else(|| lock(&self.template).worker_handle()); |
| 1465 | Handle { |
| 1466 | handles: self, |
| 1467 | repo: Some(repo), |
| 1468 | } |
| 1469 | } |
| 1470 | } |
| 1471 | |
| 1472 | /// A handle in use; it goes back to its [`Handles`] when dropped. |
| 1473 | struct Handle<'h> { |
| 1474 | handles: &'h Handles, |
| 1475 | repo: Option<GitRepo>, |
| 1476 | } |
| 1477 | |
| 1478 | impl Deref for Handle<'_> { |
| 1479 | type Target = GitRepo; |
| 1480 | |
| 1481 | fn deref(&self) -> &GitRepo { |
| 1482 | self.repo |
| 1483 | .as_ref() |
| 1484 | .expect("a handle holds its repository until dropped") |
| 1485 | } |
| 1486 | } |
| 1487 | |
| 1488 | impl Drop for Handle<'_> { |
| 1489 | fn drop(&mut self) { |
| 1490 | if let Some(repo) = self.repo.take() { |
| 1491 | lock(&self.handles.free).push(repo); |
| 1492 | } |
| 1493 | } |
| 1494 | } |
| 1495 | |
| 1496 | /// Locks a mutex that only guards plain inserts and removals: a panic while |
| 1497 | /// it was held cannot have left it half-written. |
| 1498 | fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> { |
| 1499 | mutex.lock().unwrap_or_else(PoisonError::into_inner) |
| 1500 | } |
| 1501 | |
| 1502 | fn join(prefix: &[u8], name: &[u8]) -> Vec<u8> { |
| 1503 | if prefix.is_empty() { |
| 1504 | return name.to_vec(); |
| 1505 | } |
| 1506 | let mut path = Vec::with_capacity(prefix.len() + 1 + name.len()); |
| 1507 | path.extend_from_slice(prefix); |
| 1508 | path.push(b'/'); |
| 1509 | path.extend_from_slice(name); |
| 1510 | path |
| 1511 | } |