| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Export: braid objects back to git objects, and into a git repository. |
| 5 | |
| 6 | use std::collections::{HashMap, HashSet}; |
| 7 | use std::fmt; |
| 8 | use std::path::Path; |
| 9 | use std::sync::Arc; |
| 10 | |
| 11 | use braid_format::{Changeset, Entry, EntryKind, GitId, Kind, ObjectId, Objects}; |
| 12 | |
| 13 | use crate::error::Error; |
| 14 | use crate::fetch::{self, TreeCache}; |
| 15 | use crate::map::{GitMap, Pairings}; |
| 16 | use crate::oid::{GitKind, GitOid}; |
| 17 | use crate::raw::{self, EntryType, TreeItem}; |
| 18 | use crate::repo::GitRepo; |
| 19 | |
| 20 | /// Produces git objects from braid objects. |
| 21 | /// |
| 22 | /// What came from git goes back byte for byte: a changeset with a git origin |
| 23 | /// is exported as its original commit, after checking that the tree and the |
| 24 | /// parents the commit names are the changeset's (see below); a git tree that |
| 25 | /// is not canonical as its raw bytes; a tag as its raw bytes. |
| 26 | /// |
| 27 | /// The tree a commit from git names must be the changeset's root: the one |
| 28 | /// the map links to it, or, when the map does not know that git tree, the |
| 29 | /// canonical tree of the root as computed here. Each parent it names must |
| 30 | /// be the changeset's parent at the same place: as the map links them, or, |
| 31 | /// when the map does not know that commit, the commit computed here for the |
| 32 | /// parent changeset. So history imported from git exports to its original |
| 33 | /// commits through an exporter whose map knows nothing of it, such as a |
| 34 | /// server's, which receives the changesets and their git origins but not the |
| 35 | /// map of the repository that imported them. Any difference is |
| 36 | /// [`Error::OriginMismatch`]. A commit whose tree is not canonical (one that |
| 37 | /// only its raw bytes reproduce, which only the importing repository's map |
| 38 | /// holds) cannot be checked that way, and is an `OriginMismatch` too. |
| 39 | /// |
| 40 | /// Everything else is generated deterministically from braid content alone: |
| 41 | /// a tree with canonical modes and git's entry order, a commit with `tree`, |
| 42 | /// `parent`, `author` and `committer` headers, one header per extra, and the |
| 43 | /// message unchanged. |
| 44 | /// |
| 45 | /// An exporter caches the git ids it computes, so exporting many related |
| 46 | /// objects through one exporter does each piece of work once. Nothing is |
| 47 | /// recursive: deep histories and deep directories are walked with explicit |
| 48 | /// stacks. What it computed that the map does not know yet is available from |
| 49 | /// [`pairings`](Self::pairings), to record in the map. |
| 50 | pub struct Exporter<'a, O: Objects> { |
| 51 | objects: &'a O, |
| 52 | map: &'a GitMap, |
| 53 | /// Canonical git trees computed here, for braid trees the map does not |
| 54 | /// link to one, and back. |
| 55 | trees: HashMap<ObjectId, GitOid>, |
| 56 | tree_sources: HashMap<GitOid, ObjectId>, |
| 57 | /// Git blobs computed here, with their sizes, and back. |
| 58 | blobs: HashMap<ObjectId, (GitOid, u64)>, |
| 59 | blob_sources: HashMap<GitOid, ObjectId>, |
| 60 | /// Commits exported here, and back. |
| 61 | commits: HashMap<ObjectId, GitOid>, |
| 62 | commit_sources: HashMap<GitOid, ObjectId>, |
| 63 | /// Directories read back already, shared with whoever made this |
| 64 | /// exporter, if anyone. |
| 65 | cache: Option<&'a TreeCache>, |
| 66 | } |
| 67 | |
| 68 | impl<O: Objects> fmt::Debug for Exporter<'_, O> { |
| 69 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 70 | f.debug_struct("Exporter") |
| 71 | .field("computed_trees", &self.trees.len()) |
| 72 | .field("computed_blobs", &self.blobs.len()) |
| 73 | .field("computed_commits", &self.commits.len()) |
| 74 | .finish_non_exhaustive() |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | impl<'a, O: Objects> Exporter<'a, O> { |
| 79 | /// An exporter reading braid objects from `objects`, with what `map` |
| 80 | /// knows about imported git objects. |
| 81 | pub fn new(objects: &'a O, map: &'a GitMap) -> Self { |
| 82 | Self { |
| 83 | objects, |
| 84 | map, |
| 85 | trees: HashMap::new(), |
| 86 | tree_sources: HashMap::new(), |
| 87 | blobs: HashMap::new(), |
| 88 | blob_sources: HashMap::new(), |
| 89 | commits: HashMap::new(), |
| 90 | commit_sources: HashMap::new(), |
| 91 | cache: None, |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | /// An exporter that reads directories through `cache`, and keeps what it |
| 96 | /// reads there. |
| 97 | pub(crate) fn with_cache(objects: &'a O, map: &'a GitMap, cache: &'a TreeCache) -> Self { |
| 98 | Self { |
| 99 | cache: Some(cache), |
| 100 | ..Self::new(objects, map) |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | /// Every entry of a braid directory. |
| 105 | fn entries(&self, tree: ObjectId) -> Result<Arc<[Entry]>, Error> { |
| 106 | match self.cache { |
| 107 | Some(cache) => cache.entries(self.objects, tree), |
| 108 | None => Ok(fetch::tree_entries(self.objects, tree)?.into()), |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | /// Every pairing this exporter computed that its map does not hold: the |
| 113 | /// commits of the changesets it exported, and the canonical trees and |
| 114 | /// the blobs it generated. [`GitMap::record`] adds them to a map, so that |
| 115 | /// importing these git objects later gives back the same braid objects. |
| 116 | pub fn pairings(&self) -> Pairings { |
| 117 | let mut commits: Vec<(GitOid, ObjectId)> = self |
| 118 | .commits |
| 119 | .iter() |
| 120 | .filter(|(changeset, _)| self.map.commit(changeset).is_none()) |
| 121 | .map(|(changeset, oid)| (*oid, *changeset)) |
| 122 | .collect(); |
| 123 | let mut trees: Vec<(GitOid, ObjectId)> = self |
| 124 | .trees |
| 125 | .iter() |
| 126 | .filter(|(tree, _)| self.map.git_tree(tree).is_none()) |
| 127 | .map(|(tree, oid)| (*oid, *tree)) |
| 128 | .collect(); |
| 129 | let mut blobs: Vec<(GitOid, ObjectId, u64)> = self |
| 130 | .blobs |
| 131 | .iter() |
| 132 | .filter(|(blob, _)| self.map.git_blob(blob).is_none()) |
| 133 | .map(|(blob, (oid, size))| (*oid, *blob, *size)) |
| 134 | .collect(); |
| 135 | commits.sort_unstable(); |
| 136 | trees.sort_unstable(); |
| 137 | blobs.sort_unstable(); |
| 138 | Pairings { |
| 139 | commits, |
| 140 | trees, |
| 141 | blobs, |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | /// The git commit of a changeset: its id and its bytes. |
| 146 | pub fn commit(&mut self, changeset: &ObjectId) -> Result<(GitOid, Vec<u8>), Error> { |
| 147 | let decoded = fetch::changeset(self.objects, changeset)?; |
| 148 | self.commit_of(changeset, &decoded) |
| 149 | } |
| 150 | |
| 151 | /// The git id of a changeset's commit. Ancestors whose commits are not |
| 152 | /// known yet are exported first, parents before children: a generated |
| 153 | /// commit names its parents' commits, and a commit from git is checked |
| 154 | /// against them. |
| 155 | pub fn commit_id(&mut self, changeset: &ObjectId) -> Result<GitOid, Error> { |
| 156 | if let Some(oid) = self.known_commit(changeset) { |
| 157 | return Ok(oid); |
| 158 | } |
| 159 | let mut stack = vec![(*changeset, fetch::changeset(self.objects, changeset)?)]; |
| 160 | while let Some((id, decoded)) = stack.pop() { |
| 161 | if self.known_commit(&id).is_some() { |
| 162 | continue; |
| 163 | } |
| 164 | let waiting = decoded |
| 165 | .parents |
| 166 | .iter() |
| 167 | .find(|parent| self.known_commit(parent).is_none()) |
| 168 | .copied(); |
| 169 | match waiting { |
| 170 | Some(parent) => { |
| 171 | let parent_changeset = fetch::changeset(self.objects, &parent)?; |
| 172 | stack.push((id, decoded)); |
| 173 | stack.push((parent, parent_changeset)); |
| 174 | } |
| 175 | None => { |
| 176 | self.commit_of(&id, &decoded)?; |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | self.known_commit(changeset) |
| 181 | .ok_or_else(|| Error::NotMapped { |
| 182 | what: "changeset", |
| 183 | id: changeset.to_hex(), |
| 184 | }) |
| 185 | } |
| 186 | |
| 187 | fn known_commit(&self, changeset: &ObjectId) -> Option<GitOid> { |
| 188 | self.map |
| 189 | .commit(changeset) |
| 190 | .or_else(|| self.commits.get(changeset).copied()) |
| 191 | } |
| 192 | |
| 193 | fn commit_of( |
| 194 | &mut self, |
| 195 | id: &ObjectId, |
| 196 | changeset: &Changeset, |
| 197 | ) -> Result<(GitOid, Vec<u8>), Error> { |
| 198 | let (oid, bytes) = match &changeset.git_origin { |
| 199 | Some(origin) => self.origin_commit(id, changeset, origin)?, |
| 200 | None => { |
| 201 | let mut parents = Vec::with_capacity(changeset.parents.len()); |
| 202 | for parent in &changeset.parents { |
| 203 | parents.push(self.commit_id(parent)?); |
| 204 | } |
| 205 | let tree = self.tree_id(&changeset.root)?; |
| 206 | let bytes = raw::encode_commit( |
| 207 | tree, |
| 208 | &parents, |
| 209 | &changeset.author, |
| 210 | &changeset.committer, |
| 211 | &changeset.extras, |
| 212 | &changeset.message, |
| 213 | ) |
| 214 | .map_err(|detail| Error::Unrepresentable { |
| 215 | changeset: *id, |
| 216 | detail, |
| 217 | })?; |
| 218 | (GitOid::for_object(GitKind::Commit, &bytes)?, bytes) |
| 219 | } |
| 220 | }; |
| 221 | self.commits.insert(*id, oid); |
| 222 | self.commit_sources.insert(oid, *id); |
| 223 | Ok((oid, bytes)) |
| 224 | } |
| 225 | |
| 226 | /// The original commit of a changeset imported from git, after checking |
| 227 | /// that what it names agrees with the changeset: with the map where it |
| 228 | /// knows, and with what this exporter computes where it does not. |
| 229 | fn origin_commit( |
| 230 | &mut self, |
| 231 | id: &ObjectId, |
| 232 | changeset: &Changeset, |
| 233 | origin: &ObjectId, |
| 234 | ) -> Result<(GitOid, Vec<u8>), Error> { |
| 235 | let mismatch = |detail: String| Error::OriginMismatch { |
| 236 | changeset: *id, |
| 237 | detail, |
| 238 | }; |
| 239 | let bytes = fetch::get(self.objects, origin, Kind::Blob)?; |
| 240 | let fields = raw::parse_commit(&bytes) |
| 241 | .map_err(|reason| mismatch(format!("its git origin is not a commit: {reason}")))?; |
| 242 | match self.map.tree(&fields.tree) { |
| 243 | Some(root) if root == changeset.root => {} |
| 244 | Some(root) => { |
| 245 | return Err(mismatch(format!( |
| 246 | "its commit names tree {}, which the map links to {root}, not to its root {}", |
| 247 | fields.tree, changeset.root |
| 248 | ))); |
| 249 | } |
| 250 | None => { |
| 251 | let computed = self.tree_id(&changeset.root)?; |
| 252 | if computed != fields.tree { |
| 253 | return Err(mismatch(format!( |
| 254 | "its commit names tree {}, but its root {} exports as tree {computed}{}", |
| 255 | fields.tree, |
| 256 | changeset.root, |
| 257 | if self.map.git_tree(&changeset.root).is_some() { |
| 258 | "" |
| 259 | } else { |
| 260 | " (a git tree that is not canonical can be checked only with the map of the repository that imported it)" |
| 261 | } |
| 262 | ))); |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | if fields.parents.len() != changeset.parents.len() { |
| 267 | return Err(mismatch(format!( |
| 268 | "its commit names {} parents, the changeset has {}", |
| 269 | fields.parents.len(), |
| 270 | changeset.parents.len() |
| 271 | ))); |
| 272 | } |
| 273 | for (index, (git, braid)) in fields.parents.iter().zip(&changeset.parents).enumerate() { |
| 274 | match self.map.changeset(git) { |
| 275 | Some(known) if known == *braid => {} |
| 276 | Some(known) => { |
| 277 | return Err(mismatch(format!( |
| 278 | "parent {index} of its commit is {git}, which the map links to {known}, not to {braid}" |
| 279 | ))); |
| 280 | } |
| 281 | None => { |
| 282 | let computed = self.commit_id(braid)?; |
| 283 | if computed != *git { |
| 284 | return Err(mismatch(format!( |
| 285 | "parent {index} of its commit is {git}, but its parent {braid} exports as commit {computed}" |
| 286 | ))); |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | let oid = GitOid::for_object(GitKind::Commit, &bytes)?; |
| 292 | if let Some(known) = self.map.commit(id) |
| 293 | && known != oid |
| 294 | { |
| 295 | return Err(mismatch(format!( |
| 296 | "the map links it to commit {known}, but its git origin is commit {oid}" |
| 297 | ))); |
| 298 | } |
| 299 | Ok((oid, bytes)) |
| 300 | } |
| 301 | |
| 302 | /// The canonical git tree of a braid tree: its id and its bytes. |
| 303 | pub fn tree(&mut self, tree: &ObjectId) -> Result<(GitOid, Vec<u8>), Error> { |
| 304 | let entries = self.entries(*tree)?; |
| 305 | self.tree_of(tree, &entries) |
| 306 | } |
| 307 | |
| 308 | /// [`tree`](Self::tree) for the braid tree `tree` whose entries the caller |
| 309 | /// has already: those it was just built from, which is what reading it |
| 310 | /// back from the store gives. |
| 311 | pub(crate) fn tree_of( |
| 312 | &mut self, |
| 313 | tree: &ObjectId, |
| 314 | entries: &[Entry], |
| 315 | ) -> Result<(GitOid, Vec<u8>), Error> { |
| 316 | let bytes = self.encode_entries(tree, entries)?; |
| 317 | let oid = GitOid::for_object(GitKind::Tree, &bytes)?; |
| 318 | match self.known_tree(tree) { |
| 319 | Some(known) if known != oid => Err(Error::BadBraidObject { |
| 320 | id: *tree, |
| 321 | detail: format!("the map links it to git tree {known}, but it exports as {oid}"), |
| 322 | }), |
| 323 | Some(_) => Ok((oid, bytes)), |
| 324 | None => { |
| 325 | self.trees.insert(*tree, oid); |
| 326 | self.tree_sources.insert(oid, *tree); |
| 327 | Ok((oid, bytes)) |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | /// The id of the canonical git tree of a braid tree. |
| 333 | pub fn tree_id(&mut self, tree: &ObjectId) -> Result<GitOid, Error> { |
| 334 | if let Some(oid) = self.known_tree(tree) { |
| 335 | return Ok(oid); |
| 336 | } |
| 337 | // Directories waiting for their subdirectories: id, entries, and the |
| 338 | // index of the next entry to look at. |
| 339 | let mut stack = vec![(*tree, self.entries(*tree)?, 0usize)]; |
| 340 | while let Some((_, entries, next)) = stack.last_mut() { |
| 341 | let mut child = None; |
| 342 | while child.is_none() && *next < entries.len() { |
| 343 | if let EntryKind::Tree { tree } = &entries[*next].kind |
| 344 | && self.known_tree(tree).is_none() |
| 345 | { |
| 346 | child = Some(*tree); |
| 347 | } |
| 348 | *next += 1; |
| 349 | } |
| 350 | if let Some(child) = child { |
| 351 | let entries = self.entries(child)?; |
| 352 | stack.push((child, entries, 0)); |
| 353 | continue; |
| 354 | } |
| 355 | let (id, entries, _) = stack.pop().expect("the loop runs on a non-empty stack"); |
| 356 | if self.known_tree(&id).is_some() { |
| 357 | continue; |
| 358 | } |
| 359 | let bytes = self.encode_entries(&id, &entries)?; |
| 360 | let oid = GitOid::for_object(GitKind::Tree, &bytes)?; |
| 361 | self.trees.insert(id, oid); |
| 362 | self.tree_sources.insert(oid, id); |
| 363 | } |
| 364 | self.known_tree(tree).ok_or_else(|| Error::NotMapped { |
| 365 | what: "tree", |
| 366 | id: tree.to_hex(), |
| 367 | }) |
| 368 | } |
| 369 | |
| 370 | fn known_tree(&self, tree: &ObjectId) -> Option<GitOid> { |
| 371 | self.map |
| 372 | .git_tree(tree) |
| 373 | .or_else(|| self.trees.get(tree).copied()) |
| 374 | } |
| 375 | |
| 376 | /// The canonical bytes of a directory. Its subdirectories normally have |
| 377 | /// git ids already, so this does not recurse far. |
| 378 | fn encode_entries(&mut self, tree: &ObjectId, entries: &[Entry]) -> Result<Vec<u8>, Error> { |
| 379 | let mut items = Vec::with_capacity(entries.len()); |
| 380 | for entry in entries { |
| 381 | let (kind, oid) = match &entry.kind { |
| 382 | EntryKind::File { blob, .. } => (EntryType::File, self.blob_id(blob)?), |
| 383 | EntryKind::Executable { blob, .. } => (EntryType::Executable, self.blob_id(blob)?), |
| 384 | EntryKind::Symlink { blob, .. } => (EntryType::Symlink, self.blob_id(blob)?), |
| 385 | EntryKind::Tree { tree } => (EntryType::Tree, self.tree_id(tree)?), |
| 386 | EntryKind::Gitlink { |
| 387 | commit: GitId::Sha1(bytes), |
| 388 | } => (EntryType::Gitlink, GitOid::from_bytes(*bytes)), |
| 389 | EntryKind::Gitlink { |
| 390 | commit: GitId::Sha256(_), |
| 391 | } => { |
| 392 | return Err(Error::BadBraidObject { |
| 393 | id: *tree, |
| 394 | detail: "a SHA-256 submodule cannot be written in a SHA-1 tree".into(), |
| 395 | }); |
| 396 | } |
| 397 | }; |
| 398 | items.push(TreeItem { |
| 399 | kind, |
| 400 | name: &entry.name, |
| 401 | oid, |
| 402 | }); |
| 403 | } |
| 404 | Ok(raw::encode_tree(&mut items)) |
| 405 | } |
| 406 | |
| 407 | /// The git blob of a braid blob: its id and its content. |
| 408 | pub fn blob(&mut self, blob: &ObjectId) -> Result<(GitOid, Vec<u8>), Error> { |
| 409 | let bytes = fetch::get(self.objects, blob, Kind::Blob)?; |
| 410 | let oid = GitOid::for_object(GitKind::Blob, &bytes)?; |
| 411 | if let Some(known) = self.map.git_blob(blob) |
| 412 | && known != oid |
| 413 | { |
| 414 | return Err(Error::BadBraidObject { |
| 415 | id: *blob, |
| 416 | detail: format!("the map links it to git blob {known}, but its content is {oid}"), |
| 417 | }); |
| 418 | } |
| 419 | self.blobs.insert(*blob, (oid, bytes.len() as u64)); |
| 420 | self.blob_sources.insert(oid, *blob); |
| 421 | Ok((oid, bytes)) |
| 422 | } |
| 423 | |
| 424 | /// The id of the git blob of a braid blob. |
| 425 | pub fn blob_id(&mut self, blob: &ObjectId) -> Result<GitOid, Error> { |
| 426 | match self |
| 427 | .map |
| 428 | .git_blob(blob) |
| 429 | .or_else(|| self.blobs.get(blob).map(|(oid, _)| *oid)) |
| 430 | { |
| 431 | Some(oid) => Ok(oid), |
| 432 | None => Ok(self.blob(blob)?.0), |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | /// Any git object the map or this exporter knows, by its git id: a commit, |
| 437 | /// a tree (raw or regenerated), a blob or an annotated tag. The bytes are |
| 438 | /// checked to hash to `oid`. |
| 439 | pub fn object(&mut self, oid: &GitOid) -> Result<(GitKind, Vec<u8>), Error> { |
| 440 | let (kind, bytes) = self.object_bytes(oid)?; |
| 441 | let found = GitOid::for_object(kind, &bytes)?; |
| 442 | if found != *oid { |
| 443 | return Err(Error::Verification { |
| 444 | oid: *oid, |
| 445 | kind, |
| 446 | detail: format!("exported as {found}"), |
| 447 | }); |
| 448 | } |
| 449 | Ok((kind, bytes)) |
| 450 | } |
| 451 | |
| 452 | fn object_bytes(&mut self, oid: &GitOid) -> Result<(GitKind, Vec<u8>), Error> { |
| 453 | if let Some(changeset) = self |
| 454 | .map |
| 455 | .changeset(oid) |
| 456 | .or_else(|| self.commit_sources.get(oid).copied()) |
| 457 | { |
| 458 | return Ok((GitKind::Commit, self.commit(&changeset)?.1)); |
| 459 | } |
| 460 | if let Some(raw) = self.map.raw_tree(oid) { |
| 461 | return Ok((GitKind::Tree, fetch::get(self.objects, &raw, Kind::Blob)?)); |
| 462 | } |
| 463 | if let Some(tree) = self |
| 464 | .map |
| 465 | .tree(oid) |
| 466 | .or_else(|| self.tree_sources.get(oid).copied()) |
| 467 | { |
| 468 | return Ok((GitKind::Tree, self.tree(&tree)?.1)); |
| 469 | } |
| 470 | if let Some(blob) = self |
| 471 | .map |
| 472 | .blob(oid) |
| 473 | .map(|(id, _)| id) |
| 474 | .or_else(|| self.blob_sources.get(oid).copied()) |
| 475 | { |
| 476 | return Ok((GitKind::Blob, fetch::get(self.objects, &blob, Kind::Blob)?)); |
| 477 | } |
| 478 | if let Some(entry) = self.map.tag(oid) { |
| 479 | let bytes = fetch::get(self.objects, &entry.raw, Kind::Blob)?; |
| 480 | if raw::parse_tag(&bytes).ok() != Some(entry.target) { |
| 481 | return Err(Error::Verification { |
| 482 | oid: *oid, |
| 483 | kind: GitKind::Tag, |
| 484 | detail: format!("its raw bytes do not point to {}", entry.target), |
| 485 | }); |
| 486 | } |
| 487 | return Ok((GitKind::Tag, bytes)); |
| 488 | } |
| 489 | Err(Error::NotMapped { |
| 490 | what: "git object", |
| 491 | id: oid.to_hex(), |
| 492 | }) |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | /// The git commit of a changeset: its id and its bytes. See [`Exporter`]. |
| 497 | pub fn export_commit<O: Objects>( |
| 498 | objects: &O, |
| 499 | map: &GitMap, |
| 500 | changeset: &ObjectId, |
| 501 | ) -> Result<(GitOid, Vec<u8>), Error> { |
| 502 | Exporter::new(objects, map).commit(changeset) |
| 503 | } |
| 504 | |
| 505 | /// The canonical git tree of a braid tree: its id and its bytes. |
| 506 | pub fn export_tree<O: Objects>( |
| 507 | objects: &O, |
| 508 | map: &GitMap, |
| 509 | tree: &ObjectId, |
| 510 | ) -> Result<(GitOid, Vec<u8>), Error> { |
| 511 | Exporter::new(objects, map).tree(tree) |
| 512 | } |
| 513 | |
| 514 | /// The git blob of a braid blob: its id and its content. |
| 515 | pub fn export_blob<O: Objects>( |
| 516 | objects: &O, |
| 517 | map: &GitMap, |
| 518 | blob: &ObjectId, |
| 519 | ) -> Result<(GitOid, Vec<u8>), Error> { |
| 520 | Exporter::new(objects, map).blob(blob) |
| 521 | } |
| 522 | |
| 523 | /// An imported git object, by its git id: its kind and its exact bytes. |
| 524 | pub fn export_object<O: Objects>( |
| 525 | objects: &O, |
| 526 | map: &GitMap, |
| 527 | oid: &GitOid, |
| 528 | ) -> Result<(GitKind, Vec<u8>), Error> { |
| 529 | Exporter::new(objects, map).object(oid) |
| 530 | } |
| 531 | |
| 532 | /// What a ref written by [`write_to_repo`] points to. |
| 533 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 534 | pub enum RefTarget { |
| 535 | /// A changeset, written as a commit. |
| 536 | Changeset(ObjectId), |
| 537 | /// A git object the map knows: a commit, an annotated tag, a tree or a |
| 538 | /// blob. |
| 539 | Git(GitOid), |
| 540 | } |
| 541 | |
| 542 | /// A ref to set in [`write_to_repo`], which overwrites it without a lease. |
| 543 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 544 | pub struct RefUpdate { |
| 545 | /// The full ref name, such as `refs/heads/main`. |
| 546 | pub name: Vec<u8>, |
| 547 | /// What it points to. |
| 548 | pub target: RefTarget, |
| 549 | } |
| 550 | |
| 551 | /// What [`write_to_repo`] did. |
| 552 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 553 | pub struct WriteReport { |
| 554 | /// Commits written. |
| 555 | pub commits: usize, |
| 556 | /// Trees written. |
| 557 | pub trees: usize, |
| 558 | /// Blobs written. |
| 559 | pub blobs: usize, |
| 560 | /// Annotated tags written. |
| 561 | pub tags: usize, |
| 562 | /// Each ref and the object it points to now. |
| 563 | pub refs: Vec<(Vec<u8>, GitOid)>, |
| 564 | } |
| 565 | |
| 566 | /// Writes into the git repository at `git_repo` every object the refs need, |
| 567 | /// then points the refs at them in one transaction. |
| 568 | /// |
| 569 | /// Refs are overwritten, whatever they pointed to before: there is no lease |
| 570 | /// and no fast-forward check here. That is meant for local exports and for a |
| 571 | /// mirror; updating a shared repository with a lease, as a fast-forward, is |
| 572 | /// the job of `braid git sync`, which pushes from such a mirror. |
| 573 | /// |
| 574 | /// Objects the repository already has are not written again, and neither is |
| 575 | /// anything they reach. Objects are written after everything they reach, so an |
| 576 | /// interrupted write never leaves an object whose closure is missing. |
| 577 | /// |
| 578 | /// The map is not changed: [`write_to_repo_recording`] also records what the |
| 579 | /// export generated. |
| 580 | pub fn write_to_repo<O: Objects>( |
| 581 | git_repo: &Path, |
| 582 | objects: &O, |
| 583 | map: &GitMap, |
| 584 | refs: &[RefUpdate], |
| 585 | ) -> Result<WriteReport, Error> { |
| 586 | write(git_repo, objects, map, refs).map(|(report, _)| report) |
| 587 | } |
| 588 | |
| 589 | /// [`write_to_repo`], then records in `map` every commit, canonical tree and |
| 590 | /// blob the export generated (see [`Exporter::pairings`]), so that importing |
| 591 | /// them again, from this repository or from any other that received them, |
| 592 | /// gives back the same braid objects instead of new ones. |
| 593 | /// |
| 594 | /// Nothing is recorded when the write fails. The caller saves the map. |
| 595 | pub fn write_to_repo_recording<O: Objects>( |
| 596 | git_repo: &Path, |
| 597 | objects: &O, |
| 598 | map: &mut GitMap, |
| 599 | refs: &[RefUpdate], |
| 600 | ) -> Result<WriteReport, Error> { |
| 601 | let (report, pairings) = write(git_repo, objects, map, refs)?; |
| 602 | map.record(&pairings); |
| 603 | Ok(report) |
| 604 | } |
| 605 | |
| 606 | /// Writes the objects and the refs, and returns what the export generated. |
| 607 | fn write<O: Objects>( |
| 608 | git_repo: &Path, |
| 609 | objects: &O, |
| 610 | map: &GitMap, |
| 611 | refs: &[RefUpdate], |
| 612 | ) -> Result<(WriteReport, Pairings), Error> { |
| 613 | let mut repo = GitRepo::open(git_repo)?; |
| 614 | let mut writer = Writer { |
| 615 | exporter: Exporter::new(objects, map), |
| 616 | repo: &repo, |
| 617 | written: HashSet::new(), |
| 618 | report: WriteReport::default(), |
| 619 | }; |
| 620 | let mut targets = Vec::with_capacity(refs.len()); |
| 621 | for update in refs { |
| 622 | let oid = match update.target { |
| 623 | RefTarget::Changeset(changeset) => writer.exporter.commit_id(&changeset)?, |
| 624 | RefTarget::Git(oid) => oid, |
| 625 | }; |
| 626 | writer.write_closure(oid)?; |
| 627 | targets.push((update.name.clone(), oid)); |
| 628 | } |
| 629 | let pairings = writer.exporter.pairings(); |
| 630 | let mut report = writer.report; |
| 631 | repo.set_refs(&targets, "braid: export")?; |
| 632 | report.refs = targets; |
| 633 | Ok((report, pairings)) |
| 634 | } |
| 635 | |
| 636 | struct Writer<'r, 'a, O: Objects> { |
| 637 | exporter: Exporter<'a, O>, |
| 638 | repo: &'r GitRepo, |
| 639 | written: HashSet<GitOid>, |
| 640 | report: WriteReport, |
| 641 | } |
| 642 | |
| 643 | /// An object waiting for what it reaches to be written. |
| 644 | struct Pending { |
| 645 | oid: GitOid, |
| 646 | kind: GitKind, |
| 647 | bytes: Vec<u8>, |
| 648 | children: Vec<GitOid>, |
| 649 | next: usize, |
| 650 | } |
| 651 | |
| 652 | impl<O: Objects> Writer<'_, '_, O> { |
| 653 | fn present(&self, oid: &GitOid) -> bool { |
| 654 | self.written.contains(oid) || self.repo.contains(oid) |
| 655 | } |
| 656 | |
| 657 | fn pending(&mut self, oid: GitOid) -> Result<Pending, Error> { |
| 658 | let (kind, bytes) = self.exporter.object(&oid)?; |
| 659 | let children = reached(oid, kind, &bytes)?; |
| 660 | Ok(Pending { |
| 661 | oid, |
| 662 | kind, |
| 663 | bytes, |
| 664 | children, |
| 665 | next: 0, |
| 666 | }) |
| 667 | } |
| 668 | |
| 669 | fn write_closure(&mut self, root: GitOid) -> Result<(), Error> { |
| 670 | if self.present(&root) { |
| 671 | return Ok(()); |
| 672 | } |
| 673 | let mut stack = vec![self.pending(root)?]; |
| 674 | while let Some(top) = stack.last_mut() { |
| 675 | if top.next < top.children.len() { |
| 676 | let child = top.children[top.next]; |
| 677 | top.next += 1; |
| 678 | if !self.present(&child) { |
| 679 | let pending = self.pending(child)?; |
| 680 | stack.push(pending); |
| 681 | } |
| 682 | continue; |
| 683 | } |
| 684 | let done = stack.pop().expect("the loop runs on a non-empty stack"); |
| 685 | if self.present(&done.oid) { |
| 686 | continue; |
| 687 | } |
| 688 | let stored = self.repo.write(done.kind, &done.bytes)?; |
| 689 | if stored != done.oid { |
| 690 | return Err(Error::Verification { |
| 691 | oid: done.oid, |
| 692 | kind: done.kind, |
| 693 | detail: format!("the repository stored it as {stored}"), |
| 694 | }); |
| 695 | } |
| 696 | self.written.insert(done.oid); |
| 697 | match done.kind { |
| 698 | GitKind::Commit => self.report.commits += 1, |
| 699 | GitKind::Tree => self.report.trees += 1, |
| 700 | GitKind::Blob => self.report.blobs += 1, |
| 701 | GitKind::Tag => self.report.tags += 1, |
| 702 | } |
| 703 | } |
| 704 | Ok(()) |
| 705 | } |
| 706 | } |
| 707 | |
| 708 | /// The objects a git object names: a commit's tree and parents, a tree's |
| 709 | /// entries except submodules, a tag's target. |
| 710 | pub(crate) fn reached(oid: GitOid, kind: GitKind, bytes: &[u8]) -> Result<Vec<GitOid>, Error> { |
| 711 | let malformed = |reason| Error::Malformed { oid, kind, reason }; |
| 712 | Ok(match kind { |
| 713 | GitKind::Commit => { |
| 714 | let fields = raw::parse_commit(bytes).map_err(malformed)?; |
| 715 | let mut out = Vec::with_capacity(1 + fields.parents.len()); |
| 716 | out.push(fields.tree); |
| 717 | out.extend(fields.parents); |
| 718 | out |
| 719 | } |
| 720 | GitKind::Tree => { |
| 721 | let mut out = Vec::new(); |
| 722 | for entry in raw::parse_tree(bytes).map_err(malformed)? { |
| 723 | match EntryType::from_mode(entry.mode) { |
| 724 | Some(EntryType::Gitlink) => {} |
| 725 | Some(_) => out.push(entry.oid), |
| 726 | None => return Err(malformed("an entry has an unsupported mode")), |
| 727 | } |
| 728 | } |
| 729 | out |
| 730 | } |
| 731 | GitKind::Tag => vec![raw::parse_tag(bytes).map_err(malformed)?], |
| 732 | GitKind::Blob => Vec::new(), |
| 733 | }) |
| 734 | } |