| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | use std::{ |
| 11 | cmp::Ordering, |
| 12 | ffi::OsStr, |
| 13 | fs::{self, File}, |
| 14 | io::{self, Read, Write}, |
| 15 | path::{Path, PathBuf}, |
| 16 | sync::{Arc, Mutex}, |
| 17 | time::{SystemTime, UNIX_EPOCH}, |
| 18 | }; |
| 19 | |
| 20 | use flate2::{Compression, read::GzDecoder, write::GzEncoder}; |
| 21 | use sqlx::SqlitePool; |
| 22 | |
| 23 | use crate::application::{ |
| 24 | backup::BackupManifest, |
| 25 | port::{ |
| 26 | BACKUP_DATA_PREFIX, BACKUP_DATABASE, BACKUP_MANIFEST, BackupArchive, BackupError, |
| 27 | BackupPlan, DatabaseSnapshot, ExistingData, RestorePlan, |
| 28 | }, |
| 29 | }; |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | #[must_use] |
| 38 | pub fn database_file(url: &str) -> Option<PathBuf> { |
| 39 | let rest = url |
| 40 | .strip_prefix("sqlite://") |
| 41 | .or_else(|| url.strip_prefix("sqlite:")) |
| 42 | .unwrap_or(url); |
| 43 | |
| 44 | |
| 45 | |
| 46 | let path = rest.split('?').next().unwrap_or_default(); |
| 47 | |
| 48 | (!path.is_empty() && path != ":memory:").then(|| PathBuf::from(path)) |
| 49 | } |
| 50 | |
| 51 | |
| 52 | #[derive(Debug, Clone)] |
| 53 | pub struct SqliteDatabaseSnapshot { |
| 54 | pool: SqlitePool, |
| 55 | |
| 56 | |
| 57 | database: PathBuf, |
| 58 | } |
| 59 | |
| 60 | impl SqliteDatabaseSnapshot { |
| 61 | pub fn new(pool: SqlitePool, database: impl Into<PathBuf>) -> Self { |
| 62 | Self { |
| 63 | pool, |
| 64 | database: database.into(), |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | impl DatabaseSnapshot for SqliteDatabaseSnapshot { |
| 70 | async fn snapshot(&self, workspace: &Path) -> Result<PathBuf, BackupError> { |
| 71 | let destination = workspace.join(format!("steid-snapshot-{}.db", uuid::Uuid::new_v4())); |
| 72 | |
| 73 | let target = destination |
| 74 | .to_str() |
| 75 | .ok_or_else(|| BackupError::backend("the workspace path is not valid UTF-8"))?; |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | sqlx::query("vacuum into ?") |
| 84 | .bind(target) |
| 85 | .execute(&self.pool) |
| 86 | .await |
| 87 | .map_err(BackupError::backend)?; |
| 88 | |
| 89 | Ok(destination) |
| 90 | } |
| 91 | |
| 92 | async fn replace(&self, source: &Path) -> Result<(), BackupError> { |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | self.pool.close().await; |
| 98 | |
| 99 | let source = source.to_path_buf(); |
| 100 | let database = self.database.clone(); |
| 101 | |
| 102 | blocking(move || { |
| 103 | |
| 104 | |
| 105 | |
| 106 | for suffix in ["-wal", "-shm"] { |
| 107 | let sibling = sibling(&database, suffix); |
| 108 | if sibling.exists() { |
| 109 | fs::remove_file(&sibling).map_err(BackupError::backend)?; |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | move_file(&source, &database) |
| 114 | }) |
| 115 | .await |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | #[derive(Debug, Clone, Copy, Default)] |
| 124 | pub struct TarGzBackupArchive; |
| 125 | |
| 126 | impl TarGzBackupArchive { |
| 127 | #[must_use] |
| 128 | pub fn new() -> Self { |
| 129 | Self |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | impl BackupArchive for TarGzBackupArchive { |
| 134 | async fn pack(&self, plan: BackupPlan) -> Result<u64, BackupError> { |
| 135 | blocking(move || pack(&plan)).await |
| 136 | } |
| 137 | |
| 138 | async fn manifest(&self, archive: &Path) -> Result<BackupManifest, BackupError> { |
| 139 | let archive = archive.to_path_buf(); |
| 140 | blocking(move || read_manifest(&archive)).await |
| 141 | } |
| 142 | |
| 143 | async fn unpack(&self, plan: RestorePlan) -> Result<(), BackupError> { |
| 144 | blocking(move || unpack(&plan)).await |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | |
| 149 | async fn blocking<T, F>(work: F) -> Result<T, BackupError> |
| 150 | where |
| 151 | F: FnOnce() -> Result<T, BackupError> + Send + 'static, |
| 152 | T: Send + 'static, |
| 153 | { |
| 154 | tokio::task::spawn_blocking(work) |
| 155 | .await |
| 156 | .map_err(BackupError::backend)? |
| 157 | } |
| 158 | |
| 159 | |
| 160 | fn sibling(database: &Path, suffix: &str) -> PathBuf { |
| 161 | let mut name = database.as_os_str().to_os_string(); |
| 162 | name.push(suffix); |
| 163 | PathBuf::from(name) |
| 164 | } |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | fn move_file(source: &Path, destination: &Path) -> Result<(), BackupError> { |
| 171 | if let Some(parent) = destination.parent() { |
| 172 | fs::create_dir_all(parent).map_err(BackupError::backend)?; |
| 173 | } |
| 174 | |
| 175 | match fs::rename(source, destination) { |
| 176 | Ok(()) => Ok(()), |
| 177 | Err(_) => { |
| 178 | fs::copy(source, destination).map_err(BackupError::backend)?; |
| 179 | |
| 180 | |
| 181 | let _ = fs::remove_file(source); |
| 182 | Ok(()) |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | fn pack(plan: &BackupPlan) -> Result<u64, BackupError> { |
| 193 | pack_with(plan, &mut |_, _| {}) |
| 194 | } |
| 195 | |
| 196 | |
| 197 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 198 | enum Moment { |
| 199 | |
| 200 | Reaching, |
| 201 | |
| 202 | |
| 203 | Copying, |
| 204 | } |
| 205 | |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | |
| 211 | |
| 212 | fn pack_with(plan: &BackupPlan, watch: &mut dyn FnMut(Moment, &Path)) -> Result<u64, BackupError> { |
| 213 | if plan.destination.exists() { |
| 214 | return Err(BackupError::refused(format!( |
| 215 | "{} already exists", |
| 216 | plan.destination.display() |
| 217 | ))); |
| 218 | } |
| 219 | |
| 220 | if let Some(parent) = plan |
| 221 | .destination |
| 222 | .parent() |
| 223 | .filter(|parent| !parent.as_os_str().is_empty()) |
| 224 | { |
| 225 | fs::create_dir_all(parent).map_err(BackupError::backend)?; |
| 226 | } |
| 227 | |
| 228 | let partial = sibling(&plan.destination, ".partial"); |
| 229 | let file = File::create(&partial).map_err(BackupError::backend)?; |
| 230 | let mut builder = tar::Builder::new(GzEncoder::new(file, Compression::default())); |
| 231 | |
| 232 | |
| 233 | builder.follow_symlinks(false); |
| 234 | |
| 235 | let manifest = serde_json::to_vec_pretty(&plan.manifest).map_err(BackupError::backend)?; |
| 236 | let mut header = tar::Header::new_gnu(); |
| 237 | header.set_size(manifest.len() as u64); |
| 238 | header.set_mode(0o600); |
| 239 | header.set_mtime(epoch_seconds()); |
| 240 | header.set_cksum(); |
| 241 | builder |
| 242 | .append_data(&mut header, BACKUP_MANIFEST, manifest.as_slice()) |
| 243 | .map_err(BackupError::backend)?; |
| 244 | |
| 245 | builder |
| 246 | .append_path_with_name(&plan.database, BACKUP_DATABASE) |
| 247 | .map_err(BackupError::backend)?; |
| 248 | |
| 249 | append_data_dir(&mut builder, &plan.data_dir, watch)?; |
| 250 | |
| 251 | let encoder = builder.into_inner().map_err(BackupError::backend)?; |
| 252 | let mut file = encoder.finish().map_err(BackupError::backend)?; |
| 253 | file.flush().map_err(BackupError::backend)?; |
| 254 | drop(file); |
| 255 | |
| 256 | let bytes = fs::metadata(&partial).map_err(BackupError::backend)?.len(); |
| 257 | fs::rename(&partial, &plan.destination).map_err(BackupError::backend)?; |
| 258 | |
| 259 | Ok(bytes) |
| 260 | } |
| 261 | |
| 262 | fn epoch_seconds() -> u64 { |
| 263 | SystemTime::now() |
| 264 | .duration_since(UNIX_EPOCH) |
| 265 | .map(|since| since.as_secs()) |
| 266 | .unwrap_or_default() |
| 267 | } |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | |
| 286 | |
| 287 | |
| 288 | fn append_data_dir<W: Write>( |
| 289 | builder: &mut tar::Builder<W>, |
| 290 | data_dir: &Path, |
| 291 | watch: &mut dyn FnMut(Moment, &Path), |
| 292 | ) -> Result<(), BackupError> { |
| 293 | |
| 294 | |
| 295 | let mut root = tar::Header::new_gnu(); |
| 296 | root.set_entry_type(tar::EntryType::Directory); |
| 297 | root.set_size(0); |
| 298 | root.set_mode(0o750); |
| 299 | root.set_mtime(epoch_seconds()); |
| 300 | root.set_cksum(); |
| 301 | builder |
| 302 | .append_data(&mut root, format!("{BACKUP_DATA_PREFIX}/"), io::empty()) |
| 303 | .map_err(BackupError::backend)?; |
| 304 | |
| 305 | if !data_dir.is_dir() { |
| 306 | return Ok(()); |
| 307 | } |
| 308 | |
| 309 | walk(builder, data_dir, data_dir, Place::Top, watch) |
| 310 | } |
| 311 | |
| 312 | |
| 313 | const PACKED_REFS: &str = "packed-refs"; |
| 314 | |
| 315 | |
| 316 | const OBJECTS: &str = "objects"; |
| 317 | |
| 318 | |
| 319 | const PACKS: &str = "pack"; |
| 320 | |
| 321 | |
| 322 | |
| 323 | |
| 324 | |
| 325 | |
| 326 | |
| 327 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 328 | enum Place { |
| 329 | |
| 330 | Top, |
| 331 | |
| 332 | Handle, |
| 333 | |
| 334 | Repository, |
| 335 | |
| 336 | InRepository, |
| 337 | |
| 338 | Objects, |
| 339 | |
| 340 | Packs, |
| 341 | |
| 342 | InObjects, |
| 343 | |
| 344 | |
| 345 | Elsewhere, |
| 346 | } |
| 347 | |
| 348 | impl Place { |
| 349 | |
| 350 | fn below(self, name: &str) -> Self { |
| 351 | match self { |
| 352 | Self::Top => Self::Handle, |
| 353 | Self::Handle if name.ends_with(".git") => Self::Repository, |
| 354 | Self::Handle | Self::Elsewhere => Self::Elsewhere, |
| 355 | Self::Repository if name == OBJECTS => Self::Objects, |
| 356 | Self::Repository | Self::InRepository => Self::InRepository, |
| 357 | Self::Objects if name == PACKS => Self::Packs, |
| 358 | Self::Objects | Self::Packs | Self::InObjects => Self::InObjects, |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | |
| 363 | fn is_objects(self) -> bool { |
| 364 | matches!(self, Self::Objects | Self::Packs | Self::InObjects) |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 384 | |
| 385 | |
| 386 | fn walk_order(a: &Path, b: &Path) -> Ordering { |
| 387 | fn rank(path: &Path) -> u8 { |
| 388 | match path.file_name().and_then(OsStr::to_str) { |
| 389 | Some(PACKED_REFS) => 1, |
| 390 | Some(OBJECTS) => 2, |
| 391 | _ => 0, |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | rank(a).cmp(&rank(b)).then_with(|| a.cmp(b)) |
| 396 | } |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | |
| 408 | |
| 409 | |
| 410 | |
| 411 | |
| 412 | |
| 413 | |
| 414 | |
| 415 | |
| 416 | |
| 417 | |
| 418 | |
| 419 | |
| 420 | |
| 421 | |
| 422 | |
| 423 | |
| 424 | |
| 425 | fn is_scratch(place: Place, name: &str) -> bool { |
| 426 | name.ends_with(".lock") |
| 427 | || (place.is_objects() && name.starts_with("tmp_")) |
| 428 | || (place == Place::Packs && name.ends_with(".keep")) |
| 429 | } |
| 430 | |
| 431 | |
| 432 | |
| 433 | |
| 434 | |
| 435 | |
| 436 | |
| 437 | |
| 438 | |
| 439 | fn unreadable(path: &Path, error: &io::Error) -> BackupError { |
| 440 | if error.kind() == io::ErrorKind::NotFound { |
| 441 | BackupError::backend(format!( |
| 442 | "{} vanished while the backup was copying it, so the archive would have been \ |
| 443 | missing it and was not finished. Something changed the data directory \ |
| 444 | mid-backup — a push, or git's own housekeeping; run the backup again", |
| 445 | path.display() |
| 446 | )) |
| 447 | } else { |
| 448 | BackupError::backend(format!("could not back up {}: {error}", path.display())) |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | fn walk<W: Write>( |
| 453 | builder: &mut tar::Builder<W>, |
| 454 | data_dir: &Path, |
| 455 | dir: &Path, |
| 456 | place: Place, |
| 457 | watch: &mut dyn FnMut(Moment, &Path), |
| 458 | ) -> Result<(), BackupError> { |
| 459 | let mut entries: Vec<PathBuf> = fs::read_dir(dir) |
| 460 | .map_err(|error| unreadable(dir, &error))? |
| 461 | .map(|entry| entry.map(|entry| entry.path())) |
| 462 | .collect::<Result<_, _>>() |
| 463 | .map_err(|error| unreadable(dir, &error))?; |
| 464 | |
| 465 | |
| 466 | |
| 467 | |
| 468 | |
| 469 | |
| 470 | let mut looked_for = None; |
| 471 | |
| 472 | |
| 473 | |
| 474 | |
| 475 | if place == Place::Repository { |
| 476 | let packed_refs = dir.join(PACKED_REFS); |
| 477 | if !entries.contains(&packed_refs) { |
| 478 | entries.push(packed_refs.clone()); |
| 479 | looked_for = Some(packed_refs); |
| 480 | } |
| 481 | |
| 482 | entries.sort_by(|a, b| walk_order(a, b)); |
| 483 | } else { |
| 484 | entries.sort(); |
| 485 | } |
| 486 | |
| 487 | for path in entries { |
| 488 | watch(Moment::Reaching, &path); |
| 489 | |
| 490 | let name = path |
| 491 | .file_name() |
| 492 | .and_then(|name| name.to_str()) |
| 493 | .ok_or_else(|| { |
| 494 | BackupError::backend(format!("{} is not a valid UTF-8 name", path.display())) |
| 495 | })?; |
| 496 | |
| 497 | if (place == Place::Top && name.starts_with('.')) || is_scratch(place, name) { |
| 498 | continue; |
| 499 | } |
| 500 | |
| 501 | let metadata = match fs::symlink_metadata(&path) { |
| 502 | Ok(metadata) => metadata, |
| 503 | |
| 504 | |
| 505 | Err(error) |
| 506 | if error.kind() == io::ErrorKind::NotFound |
| 507 | && looked_for.as_ref() == Some(&path) => |
| 508 | { |
| 509 | continue; |
| 510 | } |
| 511 | Err(error) => return Err(unreadable(&path, &error)), |
| 512 | }; |
| 513 | |
| 514 | let relative = path.strip_prefix(data_dir).map_err(BackupError::backend)?; |
| 515 | let entry = format!("{BACKUP_DATA_PREFIX}/{}", relative.to_string_lossy()); |
| 516 | |
| 517 | if metadata.is_symlink() { |
| 518 | eprintln!("steid: backup skipped the symlink {}", path.display()); |
| 519 | continue; |
| 520 | } |
| 521 | |
| 522 | if metadata.is_dir() { |
| 523 | builder |
| 524 | .append_dir(format!("{entry}/"), &path) |
| 525 | .map_err(|error| unreadable(&path, &error))?; |
| 526 | walk(builder, data_dir, &path, place.below(name), watch)?; |
| 527 | } else if metadata.is_file() { |
| 528 | copy_file(builder, &entry, &path, watch)?; |
| 529 | } else { |
| 530 | eprintln!( |
| 531 | "steid: backup skipped {}, which is not a file", |
| 532 | path.display() |
| 533 | ); |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | Ok(()) |
| 538 | } |
| 539 | |
| 540 | |
| 541 | |
| 542 | |
| 543 | |
| 544 | |
| 545 | |
| 546 | |
| 547 | |
| 548 | |
| 549 | |
| 550 | |
| 551 | |
| 552 | |
| 553 | |
| 554 | |
| 555 | |
| 556 | |
| 557 | fn copy_file<W: Write>( |
| 558 | builder: &mut tar::Builder<W>, |
| 559 | entry: &str, |
| 560 | path: &Path, |
| 561 | watch: &mut dyn FnMut(Moment, &Path), |
| 562 | ) -> Result<(), BackupError> { |
| 563 | let file = File::open(path).map_err(|error| unreadable(path, &error))?; |
| 564 | let stat = file.metadata().map_err(|error| unreadable(path, &error))?; |
| 565 | let size = stat.len(); |
| 566 | |
| 567 | let mut header = tar::Header::new_gnu(); |
| 568 | header.set_metadata_in_mode(&stat, tar::HeaderMode::Complete); |
| 569 | watch(Moment::Copying, path); |
| 570 | |
| 571 | let mut bytes = file.take(size); |
| 572 | builder |
| 573 | .append_data(&mut header, entry, &mut bytes) |
| 574 | .map_err(|error| unreadable(path, &error))?; |
| 575 | |
| 576 | |
| 577 | |
| 578 | match bytes.limit() { |
| 579 | 0 => Ok(()), |
| 580 | missing => Err(shrank(path, size, size - missing)), |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | |
| 585 | fn shrank(path: &Path, size: u64, copied: u64) -> BackupError { |
| 586 | BackupError::backend(format!( |
| 587 | "{} shrank while the backup was copying it, from {size} bytes to {copied}, so the \ |
| 588 | archive would have held a broken copy of it and was not finished. Git only ever \ |
| 589 | appends to a file in place, so something else rewrote it mid-backup; run the \ |
| 590 | backup again", |
| 591 | path.display() |
| 592 | )) |
| 593 | } |
| 594 | |
| 595 | |
| 596 | fn read_manifest(archive: &Path) -> Result<BackupManifest, BackupError> { |
| 597 | |
| 598 | |
| 599 | const MAX: u64 = 64 * 1024; |
| 600 | |
| 601 | for entry in open(archive)?.entries().map_err(BackupError::backend)? { |
| 602 | let mut entry = entry.map_err(BackupError::backend)?; |
| 603 | let path = entry.path().map_err(BackupError::backend)?.into_owned(); |
| 604 | |
| 605 | if path != Path::new(BACKUP_MANIFEST) { |
| 606 | continue; |
| 607 | } |
| 608 | |
| 609 | let mut json = String::new(); |
| 610 | entry |
| 611 | .by_ref() |
| 612 | .take(MAX) |
| 613 | .read_to_string(&mut json) |
| 614 | .map_err(|error| { |
| 615 | BackupError::malformed(format!("the manifest is unreadable: {error}")) |
| 616 | })?; |
| 617 | |
| 618 | return serde_json::from_str(&json).map_err(|error| { |
| 619 | BackupError::malformed(format!("the manifest does not parse: {error}")) |
| 620 | }); |
| 621 | } |
| 622 | |
| 623 | Err(BackupError::malformed( |
| 624 | "there is no manifest.json in it, so it is not a Steid backup", |
| 625 | )) |
| 626 | } |
| 627 | |
| 628 | fn open(archive: &Path) -> Result<tar::Archive<GzDecoder<File>>, BackupError> { |
| 629 | let file = File::open(archive).map_err(|error| { |
| 630 | BackupError::malformed(format!( |
| 631 | "{} could not be opened: {error}", |
| 632 | archive.display() |
| 633 | )) |
| 634 | })?; |
| 635 | |
| 636 | Ok(tar::Archive::new(GzDecoder::new(file))) |
| 637 | } |
| 638 | |
| 639 | |
| 640 | |
| 641 | |
| 642 | |
| 643 | |
| 644 | |
| 645 | |
| 646 | |
| 647 | |
| 648 | |
| 649 | |
| 650 | |
| 651 | fn unpack(plan: &RestorePlan) -> Result<(), BackupError> { |
| 652 | let mut database = false; |
| 653 | |
| 654 | |
| 655 | |
| 656 | let data_dir = match &plan.existing { |
| 657 | ExistingData::Refuse => plan.data_dir.clone(), |
| 658 | ExistingData::Replace { staging, .. } => { |
| 659 | if staging.exists() { |
| 660 | return Err(BackupError::refused(format!( |
| 661 | "{} already exists, and a restore stages into a fresh directory", |
| 662 | staging.display() |
| 663 | ))); |
| 664 | } |
| 665 | |
| 666 | staging.clone() |
| 667 | } |
| 668 | }; |
| 669 | |
| 670 | for entry in open(&plan.archive)? |
| 671 | .entries() |
| 672 | .map_err(BackupError::backend)? |
| 673 | { |
| 674 | let mut entry = entry.map_err(BackupError::backend)?; |
| 675 | let path = entry.path().map_err(BackupError::backend)?.into_owned(); |
| 676 | |
| 677 | let kind = entry.header().entry_type(); |
| 678 | if !(kind.is_file() || kind.is_dir()) { |
| 679 | return Err(BackupError::malformed(format!( |
| 680 | "{} is a {kind:?}, and a backup holds only files and directories", |
| 681 | path.display() |
| 682 | ))); |
| 683 | } |
| 684 | |
| 685 | let Some(relative) = safe(&path) else { |
| 686 | return Err(BackupError::malformed(format!( |
| 687 | "{} is not a path a backup may contain", |
| 688 | path.display() |
| 689 | ))); |
| 690 | }; |
| 691 | |
| 692 | let destination = if relative == Path::new(BACKUP_MANIFEST) { |
| 693 | |
| 694 | continue; |
| 695 | } else if relative == Path::new(BACKUP_DATABASE) { |
| 696 | database = true; |
| 697 | plan.database.clone() |
| 698 | } else if let Ok(rest) = relative.strip_prefix(BACKUP_DATA_PREFIX) { |
| 699 | data_dir.join(rest) |
| 700 | } else { |
| 701 | return Err(BackupError::malformed(format!( |
| 702 | "{} is not part of a Steid backup", |
| 703 | path.display() |
| 704 | ))); |
| 705 | }; |
| 706 | |
| 707 | if kind.is_dir() { |
| 708 | fs::create_dir_all(&destination).map_err(BackupError::backend)?; |
| 709 | continue; |
| 710 | } |
| 711 | |
| 712 | |
| 713 | |
| 714 | if destination.exists() { |
| 715 | return Err(BackupError::refused(format!( |
| 716 | "{} already exists", |
| 717 | destination.display() |
| 718 | ))); |
| 719 | } |
| 720 | |
| 721 | if let Some(parent) = destination.parent() { |
| 722 | fs::create_dir_all(parent).map_err(BackupError::backend)?; |
| 723 | } |
| 724 | |
| 725 | entry.unpack(&destination).map_err(BackupError::backend)?; |
| 726 | } |
| 727 | |
| 728 | if !database { |
| 729 | return Err(BackupError::malformed( |
| 730 | "there is no steid.db in it, so it is not a Steid backup", |
| 731 | )); |
| 732 | } |
| 733 | |
| 734 | |
| 735 | |
| 736 | if let ExistingData::Replace { staging, aside } = &plan.existing { |
| 737 | swap(&plan.data_dir, staging, aside)?; |
| 738 | } |
| 739 | |
| 740 | Ok(()) |
| 741 | } |
| 742 | |
| 743 | |
| 744 | |
| 745 | |
| 746 | |
| 747 | |
| 748 | |
| 749 | |
| 750 | |
| 751 | |
| 752 | |
| 753 | |
| 754 | |
| 755 | |
| 756 | fn swap(data_dir: &Path, staging: &Path, aside: &Path) -> Result<(), BackupError> { |
| 757 | fs::create_dir_all(aside).map_err(BackupError::backend)?; |
| 758 | |
| 759 | for path in entries(data_dir)? { |
| 760 | let name = file_name(&path)?; |
| 761 | |
| 762 | if name.starts_with('.') { |
| 763 | continue; |
| 764 | } |
| 765 | |
| 766 | fs::rename(&path, aside.join(name)).map_err(|error| { |
| 767 | BackupError::backend(format!( |
| 768 | "could not move {} aside to {}: {error}", |
| 769 | path.display(), |
| 770 | aside.display() |
| 771 | )) |
| 772 | })?; |
| 773 | } |
| 774 | |
| 775 | for path in entries(staging)? { |
| 776 | let name = file_name(&path)?; |
| 777 | |
| 778 | fs::rename(&path, data_dir.join(name)).map_err(|error| { |
| 779 | BackupError::backend(format!( |
| 780 | "could not move the restored {} into {}: {error}", |
| 781 | path.display(), |
| 782 | data_dir.display() |
| 783 | )) |
| 784 | })?; |
| 785 | } |
| 786 | |
| 787 | |
| 788 | let _ = fs::remove_dir(staging); |
| 789 | |
| 790 | Ok(()) |
| 791 | } |
| 792 | |
| 793 | |
| 794 | fn entries(dir: &Path) -> Result<Vec<PathBuf>, BackupError> { |
| 795 | let mut found: Vec<PathBuf> = fs::read_dir(dir) |
| 796 | .map_err(|error| { |
| 797 | BackupError::backend(format!("could not read {}: {error}", dir.display())) |
| 798 | })? |
| 799 | .map(|entry| entry.map(|entry| entry.path())) |
| 800 | .collect::<Result<_, _>>() |
| 801 | .map_err(BackupError::backend)?; |
| 802 | |
| 803 | found.sort(); |
| 804 | |
| 805 | Ok(found) |
| 806 | } |
| 807 | |
| 808 | fn file_name(path: &Path) -> Result<&str, BackupError> { |
| 809 | path.file_name() |
| 810 | .and_then(|name| name.to_str()) |
| 811 | .ok_or_else(|| { |
| 812 | BackupError::backend(format!("{} is not a valid UTF-8 name", path.display())) |
| 813 | }) |
| 814 | } |
| 815 | |
| 816 | |
| 817 | |
| 818 | |
| 819 | |
| 820 | |
| 821 | fn safe(path: &Path) -> Option<&Path> { |
| 822 | use std::path::Component; |
| 823 | |
| 824 | let ordinary = path |
| 825 | .components() |
| 826 | .all(|component| matches!(component, Component::Normal(_))); |
| 827 | |
| 828 | (ordinary && path.components().next().is_some()).then_some(path) |
| 829 | } |
| 830 | |
| 831 | |
| 832 | |
| 833 | |
| 834 | |
| 835 | #[derive(Debug, Default, Clone)] |
| 836 | pub struct InMemoryDatabaseSnapshot { |
| 837 | taken: Arc<Mutex<u64>>, |
| 838 | installed: Arc<Mutex<Vec<PathBuf>>>, |
| 839 | } |
| 840 | |
| 841 | impl InMemoryDatabaseSnapshot { |
| 842 | #[must_use] |
| 843 | pub fn new() -> Self { |
| 844 | Self::default() |
| 845 | } |
| 846 | |
| 847 | |
| 848 | #[must_use] |
| 849 | pub fn taken(&self) -> u64 { |
| 850 | *self.taken.lock().expect("lock poisoned") |
| 851 | } |
| 852 | |
| 853 | |
| 854 | #[must_use] |
| 855 | pub fn installed(&self) -> Vec<PathBuf> { |
| 856 | self.installed.lock().expect("lock poisoned").clone() |
| 857 | } |
| 858 | } |
| 859 | |
| 860 | impl DatabaseSnapshot for InMemoryDatabaseSnapshot { |
| 861 | async fn snapshot(&self, workspace: &Path) -> Result<PathBuf, BackupError> { |
| 862 | let mut taken = self.taken.lock().expect("lock poisoned"); |
| 863 | *taken += 1; |
| 864 | |
| 865 | Ok(workspace.join(format!("snapshot-{taken}.db"))) |
| 866 | } |
| 867 | |
| 868 | async fn replace(&self, source: &Path) -> Result<(), BackupError> { |
| 869 | self.installed |
| 870 | .lock() |
| 871 | .expect("lock poisoned") |
| 872 | .push(source.to_path_buf()); |
| 873 | |
| 874 | Ok(()) |
| 875 | } |
| 876 | } |
| 877 | |
| 878 | |
| 879 | |
| 880 | |
| 881 | |
| 882 | |
| 883 | #[derive(Debug, Default, Clone)] |
| 884 | pub struct InMemoryBackupArchive { |
| 885 | manifests: Arc<Mutex<Vec<(PathBuf, BackupManifest)>>>, |
| 886 | packed: Arc<Mutex<Vec<BackupPlan>>>, |
| 887 | unpacked: Arc<Mutex<Vec<RestorePlan>>>, |
| 888 | } |
| 889 | |
| 890 | impl InMemoryBackupArchive { |
| 891 | #[must_use] |
| 892 | pub fn new() -> Self { |
| 893 | Self::default() |
| 894 | } |
| 895 | |
| 896 | |
| 897 | |
| 898 | pub fn plant(&self, path: impl Into<PathBuf>, manifest: BackupManifest) { |
| 899 | self.manifests |
| 900 | .lock() |
| 901 | .expect("lock poisoned") |
| 902 | .push((path.into(), manifest)); |
| 903 | } |
| 904 | |
| 905 | #[must_use] |
| 906 | pub fn packed(&self) -> Vec<BackupPlan> { |
| 907 | self.packed.lock().expect("lock poisoned").clone() |
| 908 | } |
| 909 | |
| 910 | #[must_use] |
| 911 | pub fn unpacked(&self) -> Vec<RestorePlan> { |
| 912 | self.unpacked.lock().expect("lock poisoned").clone() |
| 913 | } |
| 914 | } |
| 915 | |
| 916 | impl BackupArchive for InMemoryBackupArchive { |
| 917 | async fn pack(&self, plan: BackupPlan) -> Result<u64, BackupError> { |
| 918 | self.plant(plan.destination.clone(), plan.manifest.clone()); |
| 919 | self.packed.lock().expect("lock poisoned").push(plan); |
| 920 | |
| 921 | Ok(1024) |
| 922 | } |
| 923 | |
| 924 | async fn manifest(&self, archive: &Path) -> Result<BackupManifest, BackupError> { |
| 925 | self.manifests |
| 926 | .lock() |
| 927 | .expect("lock poisoned") |
| 928 | .iter() |
| 929 | .find(|(path, _)| path == archive) |
| 930 | .map(|(_, manifest)| manifest.clone()) |
| 931 | .ok_or_else(|| BackupError::malformed(format!("no archive at {}", archive.display()))) |
| 932 | } |
| 933 | |
| 934 | async fn unpack(&self, plan: RestorePlan) -> Result<(), BackupError> { |
| 935 | |
| 936 | |
| 937 | self.manifest(&plan.archive).await?; |
| 938 | self.unpacked.lock().expect("lock poisoned").push(plan); |
| 939 | |
| 940 | Ok(()) |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | #[cfg(test)] |
| 945 | mod tests { |
| 946 | use super::*; |
| 947 | use crate::application::backup::BackupCounts; |
| 948 | |
| 949 | fn manifest() -> BackupManifest { |
| 950 | BackupManifest { |
| 951 | version: "0.4.0".to_owned(), |
| 952 | taken_at: "2026-09-08T14:25:30Z".to_owned(), |
| 953 | counts: BackupCounts { |
| 954 | users: 1, |
| 955 | organisations: 1, |
| 956 | repositories: 2, |
| 957 | }, |
| 958 | } |
| 959 | } |
| 960 | |
| 961 | |
| 962 | fn fixture(root: &Path) -> PathBuf { |
| 963 | let data = root.join("repos"); |
| 964 | fs::create_dir_all(data.join("james/steid.git/refs/heads")).expect("mkdir"); |
| 965 | fs::write(data.join("james/steid.git/HEAD"), b"ref: refs/heads/main\n").expect("write"); |
| 966 | fs::write(data.join("james/steid.git/refs/heads/main"), b"abc123\n").expect("write"); |
| 967 | data |
| 968 | } |
| 969 | |
| 970 | fn plan(root: &Path, data: &Path) -> BackupPlan { |
| 971 | let database = root.join("snapshot.db"); |
| 972 | fs::write(&database, b"SQLite format 3\0not really").expect("write"); |
| 973 | |
| 974 | BackupPlan { |
| 975 | destination: root.join("out.tar.gz"), |
| 976 | database, |
| 977 | data_dir: data.to_path_buf(), |
| 978 | manifest: manifest(), |
| 979 | } |
| 980 | } |
| 981 | |
| 982 | #[test] |
| 983 | fn a_database_url_names_a_file() { |
| 984 | assert_eq!( |
| 985 | database_file("sqlite:/var/lib/steid/steid.db?mode=rwc"), |
| 986 | Some(PathBuf::from("/var/lib/steid/steid.db")) |
| 987 | ); |
| 988 | assert_eq!( |
| 989 | database_file("sqlite://steid.db"), |
| 990 | Some(PathBuf::from("steid.db")) |
| 991 | ); |
| 992 | assert_eq!(database_file("steid.db"), Some(PathBuf::from("steid.db"))); |
| 993 | assert_eq!(database_file("sqlite::memory:"), None); |
| 994 | } |
| 995 | |
| 996 | #[test] |
| 997 | fn an_archive_round_trips_the_database_and_every_repository() { |
| 998 | let root = tempfile::tempdir().expect("tempdir"); |
| 999 | let data = fixture(root.path()); |
| 1000 | let plan = plan(root.path(), &data); |
| 1001 | |
| 1002 | let bytes = pack(&plan).expect("should pack"); |
| 1003 | assert!(bytes > 0); |
| 1004 | assert_eq!( |
| 1005 | read_manifest(&plan.destination).expect("manifest"), |
| 1006 | manifest() |
| 1007 | ); |
| 1008 | |
| 1009 | let into = root.path().join("restored"); |
| 1010 | unpack(&RestorePlan { |
| 1011 | archive: plan.destination.clone(), |
| 1012 | database: into.join("steid.db"), |
| 1013 | data_dir: into.join("repos"), |
| 1014 | existing: ExistingData::Refuse, |
| 1015 | }) |
| 1016 | .expect("should unpack"); |
| 1017 | |
| 1018 | assert_eq!( |
| 1019 | fs::read(into.join("steid.db")).expect("read"), |
| 1020 | b"SQLite format 3\0not really" |
| 1021 | ); |
| 1022 | assert_eq!( |
| 1023 | fs::read_to_string(into.join("repos/james/steid.git/HEAD")).expect("read"), |
| 1024 | "ref: refs/heads/main\n" |
| 1025 | ); |
| 1026 | assert!(into.join("repos/james/steid.git/refs/heads/main").is_file()); |
| 1027 | } |
| 1028 | |
| 1029 | #[test] |
| 1030 | fn a_replace_swaps_the_tree_in_and_leaves_the_old_one_beside_it() { |
| 1031 | |
| 1032 | |
| 1033 | |
| 1034 | let root = tempfile::tempdir().expect("tempdir"); |
| 1035 | let plan = plan(root.path(), &fixture(root.path())); |
| 1036 | pack(&plan).expect("should pack"); |
| 1037 | |
| 1038 | let live = root.path().join("live"); |
| 1039 | fs::create_dir_all(live.join("bob/notes.git")).expect("mkdir"); |
| 1040 | fs::write(live.join("bob/notes.git/HEAD"), b"mine\n").expect("write"); |
| 1041 | let workspace = live.join(".backup"); |
| 1042 | fs::create_dir_all(&workspace).expect("mkdir"); |
| 1043 | fs::write(workspace.join("keep-me"), b"scratch\n").expect("write"); |
| 1044 | |
| 1045 | let aside = live.join(".replaced-20260908T142530Z"); |
| 1046 | unpack(&RestorePlan { |
| 1047 | archive: plan.destination.clone(), |
| 1048 | database: workspace.join("steid.db"), |
| 1049 | data_dir: live.clone(), |
| 1050 | existing: ExistingData::Replace { |
| 1051 | staging: workspace.join("incoming"), |
| 1052 | aside: aside.clone(), |
| 1053 | }, |
| 1054 | }) |
| 1055 | .expect("should unpack and swap"); |
| 1056 | |
| 1057 | assert_eq!( |
| 1058 | fs::read_to_string(live.join("james/steid.git/HEAD")).expect("read"), |
| 1059 | "ref: refs/heads/main\n", |
| 1060 | "the archive's tree is not in place" |
| 1061 | ); |
| 1062 | assert!( |
| 1063 | !live.join("bob").exists(), |
| 1064 | "the old tree is still where it was" |
| 1065 | ); |
| 1066 | assert_eq!( |
| 1067 | fs::read_to_string(aside.join("bob/notes.git/HEAD")).expect("read"), |
| 1068 | "mine\n", |
| 1069 | "the old tree was not moved aside intact" |
| 1070 | ); |
| 1071 | assert!( |
| 1072 | fs::read_to_string(workspace.join("keep-me")).expect("read") == "scratch\n", |
| 1073 | "the swap moved the workspace it is running out of" |
| 1074 | ); |
| 1075 | assert!( |
| 1076 | !workspace.join("incoming").exists(), |
| 1077 | "the staging directory survived the swap" |
| 1078 | ); |
| 1079 | } |
| 1080 | |
| 1081 | #[test] |
| 1082 | fn a_failed_replace_leaves_the_live_directory_exactly_as_it_was() { |
| 1083 | |
| 1084 | |
| 1085 | let root = tempfile::tempdir().expect("tempdir"); |
| 1086 | let truncated = root.path().join("half.tar.gz"); |
| 1087 | fs::write(&truncated, b"not a gzip at all").expect("write"); |
| 1088 | |
| 1089 | let live = root.path().join("live"); |
| 1090 | fs::create_dir_all(live.join("bob/notes.git")).expect("mkdir"); |
| 1091 | fs::write(live.join("bob/notes.git/HEAD"), b"mine\n").expect("write"); |
| 1092 | let workspace = live.join(".backup"); |
| 1093 | fs::create_dir_all(&workspace).expect("mkdir"); |
| 1094 | |
| 1095 | let refused = unpack(&RestorePlan { |
| 1096 | archive: truncated, |
| 1097 | database: workspace.join("steid.db"), |
| 1098 | data_dir: live.clone(), |
| 1099 | existing: ExistingData::Replace { |
| 1100 | staging: workspace.join("incoming"), |
| 1101 | aside: live.join(".replaced-20260908T142530Z"), |
| 1102 | }, |
| 1103 | }); |
| 1104 | |
| 1105 | assert!(refused.is_err(), "a truncated archive is not a restore"); |
| 1106 | assert_eq!( |
| 1107 | fs::read_to_string(live.join("bob/notes.git/HEAD")).expect("read"), |
| 1108 | "mine\n", |
| 1109 | "the instance lost its state to a failed restore" |
| 1110 | ); |
| 1111 | assert!( |
| 1112 | !live.join(".replaced-20260908T142530Z").exists(), |
| 1113 | "nothing should have been moved aside" |
| 1114 | ); |
| 1115 | } |
| 1116 | |
| 1117 | #[test] |
| 1118 | fn a_replace_refuses_to_stage_into_a_directory_that_already_exists() { |
| 1119 | |
| 1120 | |
| 1121 | let root = tempfile::tempdir().expect("tempdir"); |
| 1122 | let plan = plan(root.path(), &fixture(root.path())); |
| 1123 | pack(&plan).expect("should pack"); |
| 1124 | |
| 1125 | let live = root.path().join("live"); |
| 1126 | let workspace = live.join(".backup"); |
| 1127 | fs::create_dir_all(workspace.join("incoming")).expect("mkdir"); |
| 1128 | |
| 1129 | let refused = unpack(&RestorePlan { |
| 1130 | archive: plan.destination.clone(), |
| 1131 | database: workspace.join("steid.db"), |
| 1132 | data_dir: live.clone(), |
| 1133 | existing: ExistingData::Replace { |
| 1134 | staging: workspace.join("incoming"), |
| 1135 | aside: live.join(".replaced-20260908T142530Z"), |
| 1136 | }, |
| 1137 | }); |
| 1138 | |
| 1139 | assert!( |
| 1140 | matches!(refused, Err(BackupError::Refused(_))), |
| 1141 | "{refused:?}" |
| 1142 | ); |
| 1143 | } |
| 1144 | |
| 1145 | #[test] |
| 1146 | fn an_empty_data_directory_still_restores_as_a_directory() { |
| 1147 | let root = tempfile::tempdir().expect("tempdir"); |
| 1148 | let data = root.path().join("repos"); |
| 1149 | fs::create_dir_all(&data).expect("mkdir"); |
| 1150 | |
| 1151 | let plan = plan(root.path(), &data); |
| 1152 | pack(&plan).expect("should pack"); |
| 1153 | |
| 1154 | let into = root.path().join("restored"); |
| 1155 | unpack(&RestorePlan { |
| 1156 | archive: plan.destination.clone(), |
| 1157 | database: into.join("steid.db"), |
| 1158 | data_dir: into.join("repos"), |
| 1159 | existing: ExistingData::Refuse, |
| 1160 | }) |
| 1161 | .expect("should unpack"); |
| 1162 | |
| 1163 | assert!(into.join("repos").is_dir()); |
| 1164 | } |
| 1165 | |
| 1166 | #[test] |
| 1167 | fn no_entry_names_a_path_outside_the_data_directory() { |
| 1168 | let root = tempfile::tempdir().expect("tempdir"); |
| 1169 | let data = fixture(root.path()); |
| 1170 | |
| 1171 | |
| 1172 | |
| 1173 | let secret = root.path().join("secret.txt"); |
| 1174 | fs::write(&secret, b"not yours").expect("write"); |
| 1175 | std::os::unix::fs::symlink(&secret, data.join("james/escape")).expect("symlink"); |
| 1176 | |
| 1177 | |
| 1178 | fs::create_dir_all(data.join(".backup/whatever")).expect("mkdir"); |
| 1179 | fs::write(data.join(".backup/whatever/big.db"), b"scratch").expect("write"); |
| 1180 | |
| 1181 | let plan = plan(root.path(), &data); |
| 1182 | pack(&plan).expect("should pack"); |
| 1183 | |
| 1184 | let names = entry_names(&plan.destination); |
| 1185 | |
| 1186 | for name in &names { |
| 1187 | let path = Path::new(name); |
| 1188 | assert!( |
| 1189 | safe(path).is_some(), |
| 1190 | "{name} is not a path a restore would accept" |
| 1191 | ); |
| 1192 | assert!( |
| 1193 | name == BACKUP_MANIFEST |
| 1194 | || name == BACKUP_DATABASE |
| 1195 | || name.starts_with(&format!("{BACKUP_DATA_PREFIX}/")), |
| 1196 | "{name} is outside the archive's three destinations" |
| 1197 | ); |
| 1198 | } |
| 1199 | |
| 1200 | assert!( |
| 1201 | !names.iter().any(|name| name.contains("escape")), |
| 1202 | "the symlink was archived: {names:?}" |
| 1203 | ); |
| 1204 | assert!( |
| 1205 | !names.iter().any(|name| name.contains(".backup")), |
| 1206 | "the scratch directory was archived: {names:?}" |
| 1207 | ); |
| 1208 | } |
| 1209 | |
| 1210 | #[test] |
| 1211 | fn a_restore_refuses_an_entry_that_climbs_out() { |
| 1212 | assert!(safe(Path::new("data/james/steid.git/HEAD")).is_some()); |
| 1213 | assert!(safe(Path::new("../etc/passwd")).is_none()); |
| 1214 | assert!(safe(Path::new("data/../../etc/passwd")).is_none()); |
| 1215 | assert!(safe(Path::new("/etc/passwd")).is_none()); |
| 1216 | assert!(safe(Path::new("")).is_none()); |
| 1217 | } |
| 1218 | |
| 1219 | #[test] |
| 1220 | fn a_restore_refuses_to_overwrite_what_is_already_there() { |
| 1221 | let root = tempfile::tempdir().expect("tempdir"); |
| 1222 | let data = fixture(root.path()); |
| 1223 | let plan = plan(root.path(), &data); |
| 1224 | pack(&plan).expect("should pack"); |
| 1225 | |
| 1226 | let into = root.path().join("restored"); |
| 1227 | fs::create_dir_all(into.join("repos/james/steid.git")).expect("mkdir"); |
| 1228 | fs::write(into.join("repos/james/steid.git/HEAD"), b"mine\n").expect("write"); |
| 1229 | |
| 1230 | let refused = unpack(&RestorePlan { |
| 1231 | archive: plan.destination.clone(), |
| 1232 | database: into.join("steid.db"), |
| 1233 | data_dir: into.join("repos"), |
| 1234 | existing: ExistingData::Refuse, |
| 1235 | }); |
| 1236 | |
| 1237 | assert!( |
| 1238 | matches!(refused, Err(BackupError::Refused(_))), |
| 1239 | "{refused:?}" |
| 1240 | ); |
| 1241 | assert_eq!( |
| 1242 | fs::read_to_string(into.join("repos/james/steid.git/HEAD")).expect("read"), |
| 1243 | "mine\n", |
| 1244 | "the existing file was left alone" |
| 1245 | ); |
| 1246 | } |
| 1247 | |
| 1248 | #[test] |
| 1249 | fn something_that_is_not_a_backup_is_said_to_be_one() { |
| 1250 | let root = tempfile::tempdir().expect("tempdir"); |
| 1251 | let not = root.path().join("holiday.tar.gz"); |
| 1252 | fs::write(¬, b"not a gzip at all").expect("write"); |
| 1253 | |
| 1254 | assert!(matches!( |
| 1255 | read_manifest(¬), |
| 1256 | Err(BackupError::Malformed(_) | BackupError::Backend(_)) |
| 1257 | )); |
| 1258 | } |
| 1259 | |
| 1260 | #[test] |
| 1261 | fn packing_refuses_to_overwrite_an_existing_archive() { |
| 1262 | let root = tempfile::tempdir().expect("tempdir"); |
| 1263 | let data = fixture(root.path()); |
| 1264 | let plan = plan(root.path(), &data); |
| 1265 | fs::write(&plan.destination, b"someone else's").expect("write"); |
| 1266 | |
| 1267 | assert!(matches!(pack(&plan), Err(BackupError::Refused(_)))); |
| 1268 | } |
| 1269 | |
| 1270 | |
| 1271 | |
| 1272 | |
| 1273 | |
| 1274 | |
| 1275 | |
| 1276 | |
| 1277 | |
| 1278 | |
| 1279 | |
| 1280 | struct Live { |
| 1281 | root: tempfile::TempDir, |
| 1282 | data: PathBuf, |
| 1283 | repo: PathBuf, |
| 1284 | work: PathBuf, |
| 1285 | } |
| 1286 | |
| 1287 | fn live() -> Live { |
| 1288 | let root = tempfile::tempdir().expect("tempdir"); |
| 1289 | let data = root.path().join("repos"); |
| 1290 | let repo = data.join("james/steid.git"); |
| 1291 | let work = root.path().join("work"); |
| 1292 | |
| 1293 | |
| 1294 | git( |
| 1295 | root.path(), |
| 1296 | &[ |
| 1297 | "init", |
| 1298 | "--bare", |
| 1299 | "--quiet", |
| 1300 | "--template=", |
| 1301 | "--initial-branch=main", |
| 1302 | path_str(&repo), |
| 1303 | ], |
| 1304 | ); |
| 1305 | git(&repo, &["config", "core.logAllRefUpdates", "true"]); |
| 1306 | |
| 1307 | git( |
| 1308 | root.path(), |
| 1309 | &["init", "--quiet", "--initial-branch=main", path_str(&work)], |
| 1310 | ); |
| 1311 | fs::write(work.join("README"), "one\n").expect("write"); |
| 1312 | git(&work, &["add", "README"]); |
| 1313 | git(&work, &["commit", "--quiet", "-m", "one"]); |
| 1314 | git(&work, &["remote", "add", "origin", path_str(&repo)]); |
| 1315 | git(&work, &["push", "--quiet", "origin", "main"]); |
| 1316 | |
| 1317 | fs::write(work.join("README"), "two\n").expect("write"); |
| 1318 | git(&work, &["commit", "--quiet", "-am", "two"]); |
| 1319 | |
| 1320 | Live { |
| 1321 | root, |
| 1322 | data, |
| 1323 | repo, |
| 1324 | work, |
| 1325 | } |
| 1326 | } |
| 1327 | |
| 1328 | impl Live { |
| 1329 | |
| 1330 | fn plan(&self, name: &str) -> BackupPlan { |
| 1331 | BackupPlan { |
| 1332 | destination: self.root.path().join(name), |
| 1333 | ..plan(self.root.path(), &self.data) |
| 1334 | } |
| 1335 | } |
| 1336 | |
| 1337 | |
| 1338 | fn restore(&self, archive: &Path, into: &str) -> PathBuf { |
| 1339 | let into = self.root.path().join(into); |
| 1340 | unpack(&RestorePlan { |
| 1341 | archive: archive.to_path_buf(), |
| 1342 | database: into.join("steid.db"), |
| 1343 | data_dir: into.join("repos"), |
| 1344 | existing: ExistingData::Refuse, |
| 1345 | }) |
| 1346 | .expect("should unpack"); |
| 1347 | |
| 1348 | into.join("repos/james/steid.git") |
| 1349 | } |
| 1350 | } |
| 1351 | |
| 1352 | |
| 1353 | fn reaching(mut hook: impl FnMut(&Path)) -> impl FnMut(Moment, &Path) { |
| 1354 | move |moment, path| { |
| 1355 | if moment == Moment::Reaching { |
| 1356 | hook(path); |
| 1357 | } |
| 1358 | } |
| 1359 | } |
| 1360 | |
| 1361 | |
| 1362 | |
| 1363 | |
| 1364 | |
| 1365 | |
| 1366 | fn repository_entries() -> Vec<String> { |
| 1367 | let fixture = live(); |
| 1368 | let mut seen = Vec::new(); |
| 1369 | |
| 1370 | pack_with( |
| 1371 | &fixture.plan("probe.tar.gz"), |
| 1372 | &mut reaching(|path| { |
| 1373 | if path.parent() == Some(fixture.repo.as_path()) { |
| 1374 | seen.push(path_str(path.file_name().expect("a name").as_ref()).to_owned()); |
| 1375 | } |
| 1376 | }), |
| 1377 | ) |
| 1378 | .expect("should pack"); |
| 1379 | |
| 1380 | seen |
| 1381 | } |
| 1382 | |
| 1383 | #[test] |
| 1384 | fn a_push_during_a_backup_never_leaves_a_ref_without_its_objects() { |
| 1385 | let entries = repository_entries(); |
| 1386 | assert!(entries.contains(&"refs".to_owned()), "{entries:?}"); |
| 1387 | |
| 1388 | |
| 1389 | for entry in &entries { |
| 1390 | let fixture = live(); |
| 1391 | let plan = fixture.plan("out.tar.gz"); |
| 1392 | let mut pushed = false; |
| 1393 | |
| 1394 | pack_with( |
| 1395 | &plan, |
| 1396 | &mut reaching(|path| { |
| 1397 | if !pushed && path == fixture.repo.join(entry) { |
| 1398 | git(&fixture.work, &["push", "--quiet", "origin", "main"]); |
| 1399 | pushed = true; |
| 1400 | } |
| 1401 | }), |
| 1402 | ) |
| 1403 | .expect("should pack"); |
| 1404 | assert!(pushed, "the push never ran before {entry}"); |
| 1405 | |
| 1406 | let restored = fixture.restore(&plan.destination, "restored"); |
| 1407 | let fsck = git_output(&restored, &["fsck", "--connectivity-only"]); |
| 1408 | assert!( |
| 1409 | fsck.status.success(), |
| 1410 | "a push just before {entry} left the archive inconsistent: {}", |
| 1411 | String::from_utf8_lossy(&fsck.stderr) |
| 1412 | ); |
| 1413 | } |
| 1414 | } |
| 1415 | |
| 1416 | #[test] |
| 1417 | fn a_pack_refs_during_a_backup_never_drops_a_branch() { |
| 1418 | let entries = repository_entries(); |
| 1419 | |
| 1420 | for entry in &entries { |
| 1421 | let fixture = live(); |
| 1422 | let main = git(&fixture.repo, &["rev-parse", "refs/heads/main"]); |
| 1423 | let plan = fixture.plan("out.tar.gz"); |
| 1424 | let mut packed = false; |
| 1425 | |
| 1426 | pack_with( |
| 1427 | &plan, |
| 1428 | &mut reaching(|path| { |
| 1429 | if !packed && path == fixture.repo.join(entry) { |
| 1430 | git(&fixture.repo, &["pack-refs", "--all", "--prune"]); |
| 1431 | packed = true; |
| 1432 | } |
| 1433 | }), |
| 1434 | ) |
| 1435 | .expect("should pack"); |
| 1436 | assert!(packed, "pack-refs never ran before {entry}"); |
| 1437 | |
| 1438 | let restored = fixture.restore(&plan.destination, "restored"); |
| 1439 | let found = git_output(&restored, &["rev-parse", "--verify", "refs/heads/main"]); |
| 1440 | assert!( |
| 1441 | found.status.success(), |
| 1442 | "a pack-refs just before {entry} dropped main: {}", |
| 1443 | String::from_utf8_lossy(&found.stderr) |
| 1444 | ); |
| 1445 | assert_eq!(String::from_utf8_lossy(&found.stdout).trim(), main); |
| 1446 | git(&restored, &["fsck", "--connectivity-only"]); |
| 1447 | } |
| 1448 | } |
| 1449 | |
| 1450 | #[test] |
| 1451 | fn git_lock_files_are_never_archived_and_may_vanish_mid_walk() { |
| 1452 | let fixture = live(); |
| 1453 | let held = fixture.repo.join("refs/heads/main.lock"); |
| 1454 | let released = fixture.repo.join("refs/heads/topic.lock"); |
| 1455 | let plan = fixture.plan("out.tar.gz"); |
| 1456 | |
| 1457 | pack_with( |
| 1458 | &plan, |
| 1459 | &mut reaching(|path| { |
| 1460 | |
| 1461 | if path == fixture.repo.join("refs") { |
| 1462 | fs::write(&held, b"locked\n").expect("write"); |
| 1463 | fs::write(&released, b"locked\n").expect("write"); |
| 1464 | } |
| 1465 | |
| 1466 | if path == released { |
| 1467 | fs::remove_file(&released).expect("remove"); |
| 1468 | } |
| 1469 | }), |
| 1470 | ) |
| 1471 | .expect("a lock that vanishes must not fail the backup"); |
| 1472 | |
| 1473 | let names = entry_names(&plan.destination); |
| 1474 | assert!( |
| 1475 | !names.iter().any(|name| name.ends_with(".lock")), |
| 1476 | "a lock file was archived: {names:?}" |
| 1477 | ); |
| 1478 | |
| 1479 | |
| 1480 | let restored = fixture.restore(&plan.destination, "restored"); |
| 1481 | git( |
| 1482 | &fixture.work, |
| 1483 | &["push", "--quiet", path_str(&restored), "main"], |
| 1484 | ); |
| 1485 | } |
| 1486 | |
| 1487 | #[test] |
| 1488 | fn the_push_quarantine_and_gits_temporary_files_are_never_archived() { |
| 1489 | let fixture = live(); |
| 1490 | let quarantine = fixture.repo.join("objects/tmp_objdir-incoming-AbC123"); |
| 1491 | let partial = fixture.repo.join("objects/pack/tmp_pack_XyZ789"); |
| 1492 | let plan = fixture.plan("out.tar.gz"); |
| 1493 | |
| 1494 | pack_with( |
| 1495 | &plan, |
| 1496 | &mut reaching(|path| { |
| 1497 | |
| 1498 | if path == fixture.repo.join("objects") { |
| 1499 | fs::create_dir_all(quarantine.join("pack")).expect("mkdir"); |
| 1500 | fs::write(quarantine.join("pack/tmp_pack_1"), b"half a pack").expect("write"); |
| 1501 | fs::write(&partial, b"half a pack").expect("write"); |
| 1502 | } |
| 1503 | |
| 1504 | if path == partial { |
| 1505 | fs::remove_file(&partial).expect("remove"); |
| 1506 | } |
| 1507 | }), |
| 1508 | ) |
| 1509 | .expect("git's scratch vanishing must not fail the backup"); |
| 1510 | |
| 1511 | let names = entry_names(&plan.destination); |
| 1512 | assert!( |
| 1513 | !names.iter().any(|name| name.contains("tmp_")), |
| 1514 | "git's temporary files were archived: {names:?}" |
| 1515 | ); |
| 1516 | } |
| 1517 | |
| 1518 | #[test] |
| 1519 | fn a_pack_deleted_mid_walk_fails_the_backup_and_names_it() { |
| 1520 | let fixture = live(); |
| 1521 | git(&fixture.repo, &["repack", "-a", "-d", "-q"]); |
| 1522 | let plan = fixture.plan("out.tar.gz"); |
| 1523 | let mut deleted = None; |
| 1524 | |
| 1525 | let failed = pack_with( |
| 1526 | &plan, |
| 1527 | &mut reaching(|path| { |
| 1528 | |
| 1529 | if deleted.is_none() && path.extension().is_some_and(|ext| ext == "pack") { |
| 1530 | fs::remove_file(path).expect("remove"); |
| 1531 | deleted = Some(path.to_path_buf()); |
| 1532 | } |
| 1533 | }), |
| 1534 | ); |
| 1535 | |
| 1536 | let deleted = deleted.expect("the fixture should hold a pack"); |
| 1537 | let error = failed |
| 1538 | .expect_err("a pack that vanished must fail the backup") |
| 1539 | .to_string(); |
| 1540 | assert!( |
| 1541 | error.contains(&deleted.display().to_string()) && error.contains("vanished"), |
| 1542 | "the failure does not say which file went: {error}" |
| 1543 | ); |
| 1544 | assert!(!plan.destination.exists(), "an archive was written anyway"); |
| 1545 | } |
| 1546 | |
| 1547 | #[test] |
| 1548 | fn a_pushed_packs_keep_marker_is_never_archived_and_may_vanish_mid_walk() { |
| 1549 | |
| 1550 | |
| 1551 | |
| 1552 | |
| 1553 | let fixture = live(); |
| 1554 | let parked = fixture.root.path().join("parked"); |
| 1555 | let release = fixture.root.path().join("release"); |
| 1556 | park_pushes(&fixture, &parked, &release); |
| 1557 | |
| 1558 | |
| 1559 | for n in 0..150 { |
| 1560 | fs::write(fixture.work.join(format!("file-{n}")), format!("{n}\n")).expect("write"); |
| 1561 | } |
| 1562 | git(&fixture.work, &["add", "."]); |
| 1563 | git(&fixture.work, &["commit", "--quiet", "-m", "big"]); |
| 1564 | |
| 1565 | let pack_dir = fixture.repo.join("objects/pack"); |
| 1566 | let plan = fixture.plan("out.tar.gz"); |
| 1567 | let mut push = None; |
| 1568 | let mut keep = None; |
| 1569 | |
| 1570 | let packed = pack_with( |
| 1571 | &plan, |
| 1572 | &mut reaching(|path| { |
| 1573 | |
| 1574 | |
| 1575 | if push.is_none() && keep.is_none() && path == pack_dir { |
| 1576 | let child = git_command(&fixture.work, &["push", "--quiet", "origin", "main"]) |
| 1577 | .stdout(std::process::Stdio::null()) |
| 1578 | .stderr(std::process::Stdio::piped()) |
| 1579 | .spawn() |
| 1580 | .expect("git should be on PATH"); |
| 1581 | push = Some(child); |
| 1582 | wait_for(&parked); |
| 1583 | } |
| 1584 | |
| 1585 | if keep.is_none() && path.extension().is_some_and(|ext| ext == "keep") { |
| 1586 | fs::write(&release, b"").expect("write"); |
| 1587 | let pushed = push |
| 1588 | .take() |
| 1589 | .expect("a .keep with no push running") |
| 1590 | .wait_with_output() |
| 1591 | .expect("wait"); |
| 1592 | assert!( |
| 1593 | pushed.status.success(), |
| 1594 | "the push failed: {}", |
| 1595 | String::from_utf8_lossy(&pushed.stderr) |
| 1596 | ); |
| 1597 | assert!(!path.exists(), "receive-pack left its .keep behind"); |
| 1598 | keep = Some(path.to_path_buf()); |
| 1599 | } |
| 1600 | }), |
| 1601 | ); |
| 1602 | |
| 1603 | let keep = keep.expect("the walk never listed the push's .keep"); |
| 1604 | packed.expect("a .keep that vanishes must not fail the backup"); |
| 1605 | |
| 1606 | let names = entry_names(&plan.destination); |
| 1607 | assert!( |
| 1608 | !names.iter().any(|name| name.ends_with(".keep")), |
| 1609 | "a .keep was archived: {names:?}" |
| 1610 | ); |
| 1611 | |
| 1612 | let pack = keep.with_extension("pack"); |
| 1613 | let relative = pack |
| 1614 | .strip_prefix(&fixture.data) |
| 1615 | .expect("inside the data directory"); |
| 1616 | let pack_entry = format!("{BACKUP_DATA_PREFIX}/{}", path_str(relative)); |
| 1617 | assert!( |
| 1618 | names.contains(&pack_entry), |
| 1619 | "{pack_entry} is not in {names:?}" |
| 1620 | ); |
| 1621 | |
| 1622 | let restored = fixture.restore(&plan.destination, "restored"); |
| 1623 | git(&restored, &["fsck", "--connectivity-only"]); |
| 1624 | } |
| 1625 | |
| 1626 | #[test] |
| 1627 | fn a_file_that_grows_while_it_is_copied_is_archived_as_it_was_when_opened() { |
| 1628 | |
| 1629 | |
| 1630 | |
| 1631 | let fixture = live(); |
| 1632 | let reflog = fixture.repo.join("logs/refs/heads/main"); |
| 1633 | let plan = fixture.plan("out.tar.gz"); |
| 1634 | let mut opened = None; |
| 1635 | |
| 1636 | pack_with(&plan, &mut |moment, path| { |
| 1637 | if moment == Moment::Copying && path == reflog && opened.is_none() { |
| 1638 | opened = Some(fs::read(&reflog).expect("read")); |
| 1639 | for n in 0..4 { |
| 1640 | fs::write(fixture.work.join("README"), format!("{n}\n")).expect("write"); |
| 1641 | git(&fixture.work, &["commit", "--quiet", "-am", "more"]); |
| 1642 | git(&fixture.work, &["push", "--quiet", "origin", "main"]); |
| 1643 | } |
| 1644 | } |
| 1645 | }) |
| 1646 | .expect("should pack"); |
| 1647 | |
| 1648 | let opened = opened.expect("the walk never copied the reflog"); |
| 1649 | let grown = fs::read(&reflog).expect("read"); |
| 1650 | assert!(grown.starts_with(&opened), "git rewrote the reflog"); |
| 1651 | |
| 1652 | |
| 1653 | assert!( |
| 1654 | grown.len().div_ceil(512) > opened.len().div_ceil(512), |
| 1655 | "the pushes grew the reflog from {} to {} bytes, inside one block", |
| 1656 | opened.len(), |
| 1657 | grown.len() |
| 1658 | ); |
| 1659 | |
| 1660 | let restored = fixture.restore(&plan.destination, "restored"); |
| 1661 | assert_eq!( |
| 1662 | fs::read(restored.join("logs/refs/heads/main")).expect("read"), |
| 1663 | opened, |
| 1664 | "the archive does not hold exactly the first {} bytes", |
| 1665 | opened.len() |
| 1666 | ); |
| 1667 | git(&restored, &["fsck", "--connectivity-only"]); |
| 1668 | } |
| 1669 | |
| 1670 | #[test] |
| 1671 | fn a_file_that_shrinks_while_it_is_copied_fails_the_backup_and_names_it() { |
| 1672 | |
| 1673 | |
| 1674 | let fixture = live(); |
| 1675 | let reflog = fixture.repo.join("logs/refs/heads/main"); |
| 1676 | let plan = fixture.plan("out.tar.gz"); |
| 1677 | let mut cut = false; |
| 1678 | |
| 1679 | let failed = pack_with(&plan, &mut |moment, path| { |
| 1680 | if moment == Moment::Copying && path == reflog && !cut { |
| 1681 | let file = fs::OpenOptions::new() |
| 1682 | .write(true) |
| 1683 | .open(&reflog) |
| 1684 | .expect("open"); |
| 1685 | let len = file.metadata().expect("stat").len(); |
| 1686 | file.set_len(len / 2).expect("truncate"); |
| 1687 | cut = true; |
| 1688 | } |
| 1689 | }); |
| 1690 | |
| 1691 | assert!(cut, "the walk never copied the reflog"); |
| 1692 | let error = failed |
| 1693 | .expect_err("a file that shrank must fail the backup") |
| 1694 | .to_string(); |
| 1695 | assert!( |
| 1696 | error.contains(&reflog.display().to_string()) && error.contains("shrank"), |
| 1697 | "the failure does not say which file shrank: {error}" |
| 1698 | ); |
| 1699 | assert!(!plan.destination.exists(), "an archive was written anyway"); |
| 1700 | } |
| 1701 | |
| 1702 | #[test] |
| 1703 | fn a_branch_named_like_gits_scratch_is_still_archived() { |
| 1704 | |
| 1705 | |
| 1706 | |
| 1707 | let fixture = live(); |
| 1708 | let branches = ["refs/heads/objects/tmp_x", "refs/heads/objects/pack/x.keep"]; |
| 1709 | for branch in branches { |
| 1710 | git(&fixture.repo, &["update-ref", branch, "refs/heads/main"]); |
| 1711 | } |
| 1712 | let plan = fixture.plan("out.tar.gz"); |
| 1713 | pack(&plan).expect("should pack"); |
| 1714 | |
| 1715 | let restored = fixture.restore(&plan.destination, "restored"); |
| 1716 | for branch in branches { |
| 1717 | git(&restored, &["rev-parse", "--verify", branch]); |
| 1718 | } |
| 1719 | } |
| 1720 | |
| 1721 | #[test] |
| 1722 | fn two_backups_of_one_state_hold_the_same_entries_in_the_same_order() { |
| 1723 | let fixture = live(); |
| 1724 | git(&fixture.repo, &["tag", "v1", "main"]); |
| 1725 | git(&fixture.repo, &["pack-refs", "--all"]); |
| 1726 | git(&fixture.repo, &["repack", "-a", "-d", "-q"]); |
| 1727 | |
| 1728 | let first = fixture.plan("first.tar.gz"); |
| 1729 | let second = fixture.plan("second.tar.gz"); |
| 1730 | pack(&first).expect("should pack"); |
| 1731 | pack(&second).expect("should pack"); |
| 1732 | |
| 1733 | let names = entry_names(&first.destination); |
| 1734 | assert_eq!(names, entry_names(&second.destination)); |
| 1735 | |
| 1736 | |
| 1737 | let position = |wanted: &str| { |
| 1738 | names |
| 1739 | .iter() |
| 1740 | .position(|name| name == wanted) |
| 1741 | .unwrap_or_else(|| panic!("{wanted} is not in {names:?}")) |
| 1742 | }; |
| 1743 | let repo = format!("{BACKUP_DATA_PREFIX}/james/steid.git"); |
| 1744 | assert!( |
| 1745 | position(&format!("{repo}/refs/heads/")) < position(&format!("{repo}/packed-refs")) |
| 1746 | ); |
| 1747 | assert!(position(&format!("{repo}/packed-refs")) < position(&format!("{repo}/objects/"))); |
| 1748 | } |
| 1749 | |
| 1750 | |
| 1751 | |
| 1752 | fn git(dir: &Path, args: &[&str]) -> String { |
| 1753 | let output = git_output(dir, args); |
| 1754 | assert!( |
| 1755 | output.status.success(), |
| 1756 | "git {args:?} failed: {}", |
| 1757 | String::from_utf8_lossy(&output.stderr) |
| 1758 | ); |
| 1759 | |
| 1760 | String::from_utf8_lossy(&output.stdout).trim().to_owned() |
| 1761 | } |
| 1762 | |
| 1763 | fn git_output(dir: &Path, args: &[&str]) -> std::process::Output { |
| 1764 | git_command(dir, args) |
| 1765 | .output() |
| 1766 | .expect("git should be on PATH") |
| 1767 | } |
| 1768 | |
| 1769 | |
| 1770 | fn git_command(dir: &Path, args: &[&str]) -> std::process::Command { |
| 1771 | let mut command = std::process::Command::new("git"); |
| 1772 | command |
| 1773 | .arg("-C") |
| 1774 | .arg(dir) |
| 1775 | .args(args) |
| 1776 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 1777 | .env("GIT_CONFIG_SYSTEM", "/dev/null") |
| 1778 | .env("GIT_AUTHOR_NAME", "Ada") |
| 1779 | .env("GIT_AUTHOR_EMAIL", "ada@example.com") |
| 1780 | .env("GIT_COMMITTER_NAME", "Ada") |
| 1781 | .env("GIT_COMMITTER_EMAIL", "ada@example.com") |
| 1782 | .env("GIT_AUTHOR_DATE", "2026-10-07T12:00:00Z") |
| 1783 | .env("GIT_COMMITTER_DATE", "2026-10-07T12:00:00Z"); |
| 1784 | |
| 1785 | for variable in [ |
| 1786 | "GIT_ALTERNATE_OBJECT_DIRECTORIES", |
| 1787 | "GIT_DIR", |
| 1788 | "GIT_INDEX_FILE", |
| 1789 | "GIT_OBJECT_DIRECTORY", |
| 1790 | "GIT_WORK_TREE", |
| 1791 | ] { |
| 1792 | command.env_remove(variable); |
| 1793 | } |
| 1794 | |
| 1795 | command |
| 1796 | } |
| 1797 | |
| 1798 | |
| 1799 | |
| 1800 | |
| 1801 | |
| 1802 | |
| 1803 | |
| 1804 | |
| 1805 | fn park_pushes(fixture: &Live, parked: &Path, release: &Path) { |
| 1806 | use std::os::unix::fs::PermissionsExt; |
| 1807 | |
| 1808 | let hooks = fixture.root.path().join("hooks"); |
| 1809 | fs::create_dir_all(&hooks).expect("mkdir"); |
| 1810 | let hook = hooks.join("reference-transaction"); |
| 1811 | fs::write( |
| 1812 | &hook, |
| 1813 | format!( |
| 1814 | "#!/bin/sh\n\ |
| 1815 | [ \"$1\" = committed ] || exit 0\n\ |
| 1816 | : > '{parked}'\n\ |
| 1817 | tries=0\n\ |
| 1818 | while [ ! -e '{release}' ]; do\n\ |
| 1819 | \x20 tries=$((tries + 1))\n\ |
| 1820 | \x20 [ \"$tries\" -gt 600 ] && exit 1\n\ |
| 1821 | \x20 sleep 0.1\n\ |
| 1822 | done\n", |
| 1823 | parked = path_str(parked), |
| 1824 | release = path_str(release), |
| 1825 | ), |
| 1826 | ) |
| 1827 | .expect("write"); |
| 1828 | fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).expect("chmod"); |
| 1829 | git( |
| 1830 | &fixture.repo, |
| 1831 | &["config", "core.hooksPath", path_str(&hooks)], |
| 1832 | ); |
| 1833 | } |
| 1834 | |
| 1835 | |
| 1836 | fn wait_for(path: &Path) { |
| 1837 | use std::time::{Duration, Instant}; |
| 1838 | |
| 1839 | let deadline = Instant::now() + Duration::from_secs(60); |
| 1840 | while !path.exists() { |
| 1841 | assert!( |
| 1842 | Instant::now() < deadline, |
| 1843 | "{} never appeared", |
| 1844 | path.display() |
| 1845 | ); |
| 1846 | std::thread::sleep(Duration::from_millis(10)); |
| 1847 | } |
| 1848 | } |
| 1849 | |
| 1850 | fn path_str(path: &Path) -> &str { |
| 1851 | path.to_str().expect("a UTF-8 temp path") |
| 1852 | } |
| 1853 | |
| 1854 | |
| 1855 | fn entry_names(archive: &Path) -> Vec<String> { |
| 1856 | open(archive) |
| 1857 | .expect("open") |
| 1858 | .entries() |
| 1859 | .expect("entries") |
| 1860 | .map(|entry| { |
| 1861 | entry |
| 1862 | .expect("entry") |
| 1863 | .path() |
| 1864 | .expect("path") |
| 1865 | .to_string_lossy() |
| 1866 | .into_owned() |
| 1867 | }) |
| 1868 | .collect() |
| 1869 | } |
| 1870 | } |