Restore one repository from a backup snapshot after its trash is purged
Browse filesOnce a deleted repository's 30 days in the trash are over, the only copy is in the snapshots. `gitv-restore find OWNER/NAME` lists the snapshots holding it, and `gitv-restore <snapshot> DIR OWNER/NAME` copies just that repository out and checks it with git fsck, without touching the live tree. `gitv import <owner> <name> <dir>` puts it back through the same private staging folder and no-replace rename as `create`, checks it again and gives it to the git account, so it can never overwrite a repository that has since taken the name. Modes and times are kept but not SELinux labels, so the copy takes the repository tree's own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 23:37
- Commit
- 96810b973871
- Parent
- 4d496f4
6 files changed +253−22
+1−1
| @@ -77,7 +77,7 @@ Three crates. `gitv` depends only on `gitv-core` and a few small crates, so buil | ||
| - Pushing to a missing name creates the repository. It is built in a private staging folder and published by rename. | ||
| - A push holds the repository's `flock` shared. The backup takes it exclusive. | ||
| - A push runs with `RECOVERY_CONFIG` (reflogs on every ref, unreachable objects kept 30 days), and appends ref changes to `gitv-push.log`. | ||
| - **Deletion** moves a repository to `<owner>/.trash/<name>.<unix time>`. `gitv purge`, run daily by a timer, removes entries older than 30 days. | ||
| - **Deletion** moves a repository to `<owner>/.trash/<name>.<unix time>`. `gitv purge`, run daily by a timer, removes entries older than 30 days. After that, `gitv-restore <snapshot> DIR OWNER/NAME` copies one repository out of a backup, and `gitv import` publishes it through the same staging and no-replace rename as `create` (`Contents::CopyOf`). | ||
| - **Logging.** SSH users only ever see generic errors. Details go to syslog, or to `$GITV_LOG` when it is set. | ||
| ### `gitv-web` | ||
+1−1
| @@ -15,5 +15,5 @@ Deferred until a second person pushes to the server: individual accounts and rep | ||
| - [x] **Compare revisions.** `/<owner>/<name>/compare?from=<rev>&to=<rev>` shows the commits in `from..to`, the changed files, and the diff against the merge base. It reuses the commit page's diff rendering, output caps and cache. Cover a release-to-release comparison and a feature branch that has diverged from its target, and the access rules for private repositories. | ||
| - [x] **Description, default branch and index filter.** Over SSH (and as root): `description <name> <text>` writes git's `description` file, and `default-branch <name> <branch>` points `HEAD` at an existing branch. The index shows descriptions and can be filtered by name with a plain GET form (`?q=`). The repository header shows its visibility to the signed-in operator. | ||
| - [x] **Tagged source archives.** The tags page links a `.tar.gz` of each tag, made by `git archive` and served through the download pool, under the repository's access rules. Tag annotations remain the release notes. Verify with a tagged GITv release that the archive matches `git archive` run locally. | ||
| - [ ] **Single-repository restore from backup.** Document restoring one repository from a retained snapshot after its trash entry was purged, and test it in `tests/backup.rs`: branches, tags, default branch and visibility come back, it can be restored under a new name, and a repository that has since taken the name is never overwritten. | ||
| - [x] **Single-repository restore from backup.** Document restoring one repository from a retained snapshot after its trash entry was purged, and test it in `tests/backup.rs`: branches, tags, default branch and visibility come back, it can be restored under a new name, and a repository that has since taken the name is never overwritten. | ||
| - [ ] **Optional: protect a repository from history rewrites.** `protect <name> on|off` sets `receive.denyNonFastForwards` and `receive.denyDeletes` for that repository. Verify that force-pushes and branch deletion are refused while ordinary pushes still work, and that the operator's push log and reflogs are unaffected. | ||
+13−2
| @@ -2,7 +2,7 @@ | ||
| Git hosting with SSH pushes, public and private repository browsing, and read-only HTTPS cloning for public repositories. | ||
| - `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `visibility`, `delete`, `add-key`, `keys`, `remove-key`, `trash`, `restore`, `purge`) | ||
| - `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `visibility`, `description`, `default-branch`, `delete`, `add-key`, `keys`, `remove-key`, `trash`, `restore`, `purge`, `import`) | ||
| - `gitv-web`: the read-only browser (repositories, tree, blob, raw, log, commit, compare, tags, archive), with Markdown rendering and syntax highlighting (`crates/gitv-web/src/render.rs`) | ||
| **Linking to code.** A file's History lists the commits that changed it, and a folder's History does the same for everything inside. Permalink opens the file at the commit you're looking at, so the link keeps showing the same content after the branch moves. Click a line number to link that line (`#L12`). To link a range, add `lines=` to the address, for example `…&lines=12-20#L12`; the server marks those lines, and Permalink keeps the range. | ||
| @@ -187,7 +187,18 @@ The backup runs daily at about 02:30. Every Sunday, `gitv-restore check` copies | ||
| ## Disaster recovery | ||
| **One repository or file.** Snapshots are plain folders, so copy what you need straight out of `/mnt/gitv-backup/gitv/snapshots/<time>/repos/<owner>/<name>.git`. For history overwritten in the last 30 days, the reflog and push log (see Storage) are quicker. | ||
| **A deleted repository.** For 30 days it waits in the trash: `gitv trash`, then `gitv restore` (see Storage). After that, bring it back from a snapshot: | ||
| ```sh | ||
| gitv-restore find um9i/my-project # the snapshots holding it, newest last | ||
| gitv-restore 2026-11-20T023000Z /srv/gitv-restore um9i/my-project | ||
| gitv import um9i my-project /srv/gitv-restore/my-project.git | ||
| rm -rf /srv/gitv-restore | ||
| ``` | ||
| `gitv-restore` copies just that repository out of the snapshot and checks it with `git fsck`, without touching the live tree. `gitv import` copies it into place, checks it again, and gives it to the `git` account. It comes back as it was in the snapshot: branches, tags, default branch, visibility, description, reflogs and push log. Import never replaces anything: if the name has been taken since, it refuses, and you can import under another name instead (`gitv import um9i my-project-restored …`). Pushes made after that snapshot are lost from the server, but every clone still has them. | ||
| **One file, or an older state.** Snapshots are plain folders, so copy what you need straight out of `/mnt/gitv-backup/gitv/snapshots/<time>/repos/<owner>/<name>.git`. For history overwritten in the last 30 days, the reflog and push log (see Storage) are quicker. | ||
| **The whole server.** On a fresh Fedora droplet: | ||
| @@ -92,6 +92,16 @@ enum Action { | ||
| #[arg(long = "as", value_parser = name)] | ||
| as_name: Option<String>, | ||
| }, | ||
| /// Copy a bare repository, such as one gitv-restore brought back, into place (root) | ||
| Import { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| /// The name to give it; anything already there is never replaced | ||
| #[arg(value_parser = name)] | ||
| name: String, | ||
| /// The restored repository's directory | ||
| source: PathBuf, | ||
| }, | ||
| /// Permanently remove trash entries deleted at least this many days ago (root) | ||
| Purge { | ||
| #[arg(long, default_value_t = TRASH_DAYS)] | ||
| @@ -211,6 +221,21 @@ fn owner_directory(owner: &str) -> Result<OwnedFd, String> { | ||
| /// out of the staging directory's own handle into the owner directory's, refusing to replace | ||
| /// anything at the name. What gets published is therefore exactly what git initialised. | ||
| fn create(owner: &str, name: &str) -> Result<Created, CreateError> { | ||
| publish_new(owner, name, Contents::Empty) | ||
| } | ||
| /// What a new repository starts as. | ||
| #[derive(Clone, Copy)] | ||
| enum Contents<'a> { | ||
| /// `git init --bare`. | ||
| Empty, | ||
| /// A copy of the bare repository at this path, outside the live tree: one restored from a | ||
| /// backup, say. | ||
| CopyOf(&'a Path), | ||
| } | ||
| /// Make `<owner>/<name>.git` from `contents`, as described for [`create`]. | ||
| fn publish_new(owner: &str, name: &str, contents: Contents) -> Result<Created, CreateError> { | ||
| let directory = owner_directory(owner).map_err(CreateError::Failed)?; | ||
| let target = format!("{name}.git"); | ||
| if kind_at(&directory, OsStr::new(&target)).is_some() { | ||
| @@ -229,7 +254,7 @@ fn create(owner: &str, name: &str) -> Result<Created, CreateError> { | ||
| if stat.st_uid != geteuid().as_raw() || stat.st_mode & 0o077 != 0 { | ||
| return Err(CreateError::Failed("the staging directory isn't private".into())); | ||
| } | ||
| build_and_publish(&directory, &staging, &target) | ||
| build_and_publish(&directory, &staging, &target, contents) | ||
| }); | ||
| // The staging directory is empty now, whether the repository was published or rolled | ||
| // back. Removing it by name only ever removes an empty directory. | ||
| @@ -305,17 +330,39 @@ fn run_privately(mut command: Command, what: &str) -> Result<(), String> { | ||
| /// Build a bare repository at `repo` inside the private `staging` directory, then move it to | ||
| /// `target` in `directory`. If anything fails after `repo` was made, it is removed again; it | ||
| /// never removes a `repo` this call didn't make. | ||
| fn build_and_publish(directory: &OwnedFd, staging: &OwnedFd, target: &str) -> Result<(), CreateError> { | ||
| fn build_and_publish( | ||
| directory: &OwnedFd, | ||
| staging: &OwnedFd, | ||
| target: &str, | ||
| contents: Contents, | ||
| ) -> Result<(), CreateError> { | ||
| let failed = |e: &dyn std::fmt::Display| CreateError::Failed(e.to_string()); | ||
| // Only once this succeeds is `repo` ours to roll back. | ||
| mkdirat(staging, "repo", Mode::from_bits_truncate(0o750)).map_err(|e| failed(&e))?; | ||
| let built = (|| { | ||
| let repo = open_dir_at(staging, OsStr::new("repo")).map_err(|e| failed(&e))?; | ||
| // A clean environment, so no caller's init.templateDir can plant hooks in it; and its | ||
| // output stays private, whoever is connected. | ||
| let mut init = git_in(&repo); | ||
| init.args(["init", "--quiet", "--bare", "--initial-branch=main", "."]); | ||
| run_privately(init, "git init").map_err(CreateError::Failed)?; | ||
| match contents { | ||
| Contents::Empty => { | ||
| // A clean environment, so no caller's init.templateDir can plant hooks in it; | ||
| // and its output stays private, whoever is connected. | ||
| let mut init = git_in(&repo); | ||
| init.args(["init", "--quiet", "--bare", "--initial-branch=main", "."]); | ||
| run_privately(init, "git init").map_err(CreateError::Failed)?; | ||
| } | ||
| Contents::CopyOf(source) => { | ||
| // Everything, the visibility marker, description and HEAD included, with modes and | ||
| // times; links are copied as links, never followed. Not owners (set below) and | ||
| // not SELinux labels: new files take the repository tree's own, not those of | ||
| // the folder a restore was staged in. | ||
| let mut copy = gitv_core::command_in(&repo, "cp"); | ||
| copy.args(["-R", "-P", "--preserve=mode,timestamps,links", "--"]).arg(source.join(".")).arg("."); | ||
| run_privately(copy, "copying the repository").map_err(CreateError::Failed)?; | ||
| // Nothing is published that git can't read whole. | ||
| let mut fsck = git_in(&repo); | ||
| fsck.args(["--git-dir=.", "fsck", "--no-progress", "--full"]); | ||
| run_privately(fsck, "git fsck").map_err(CreateError::Failed)?; | ||
| } | ||
| } | ||
| fchmod(&repo, Mode::from_bits_truncate(0o750)).map_err(|e| failed(&e))?; | ||
| if let Some((uid, gid)) = git_account().map_err(CreateError::Failed)? { | ||
| chown_tree(&repo, uid, gid).map_err(|e| failed(&e))?; | ||
| @@ -336,6 +383,29 @@ fn build_and_publish(directory: &OwnedFd, staging: &OwnedFd, target: &str) -> Re | ||
| Ok(()) | ||
| } | ||
| /// Copy the bare repository at `source` into the live tree as `<owner>/<name>.git`, never | ||
| /// replacing anything already there: how a repository restored from a backup goes back. | ||
| fn import(owner: &str, name: &str, source: &Path) -> Result<(), String> { | ||
| // Only a real bare repository is copied: a directory, not a link to one, with a HEAD file. | ||
| let from = gitv_core::open_dir(source).map_err(|e| format!("can't open {}: {e}", source.display()))?; | ||
| if kind_at(&from, OsStr::new("HEAD")) != Some(nix::sys::stat::SFlag::S_IFREG) { | ||
| return Err(format!("{} isn't a bare repository", source.display())); | ||
| } | ||
| match publish_new(owner, name, Contents::CopyOf(source)) { | ||
| Ok(created) => { | ||
| println!("imported git@{}:{owner}/{name}.git", config::host()); | ||
| if let Some(leftover) = created.leftover { | ||
| eprintln!("gitv: imported {owner}/{name}.git, but {leftover}"); | ||
| } | ||
| Ok(()) | ||
| } | ||
| Err(CreateError::Exists { .. }) => { | ||
| Err(format!("{owner}/{name}.git already exists; import under another name, or delete it first")) | ||
| } | ||
| Err(error) => Err(error.detail()), | ||
| } | ||
| } | ||
| /// Deleted repositories wait in `<owner>/.trash` for this many days before `gitv purge` removes them. | ||
| const TRASH_DAYS: u64 = 30; | ||
| /// The trash directory inside each owner's directory. Its leading dot keeps it out of every listing. | ||
| @@ -986,6 +1056,7 @@ fn run() -> Result<u8, String> { | ||
| Action::Trash => list_trash()?, | ||
| Action::Restore { owner, entry, as_name } => restore(&owner, &entry, as_name.as_deref())?, | ||
| Action::Purge { older_than_days } => purge(older_than_days)?, | ||
| Action::Import { owner, name, source } => import(&owner, &name, &source)?, | ||
| Action::Visibility { owner, name, visibility: value } => visibility(&owner, &name, &value)?, | ||
| Action::Description { owner, name, text } => description(&owner, &name, text.as_deref())?, | ||
| Action::DefaultBranch { owner, name, branch } => default_branch(&owner, &name, branch.as_deref())?, | ||
| @@ -1097,7 +1168,7 @@ mod tests { | ||
| fs::write(dir.join("owner/.staging/repo/sentinel"), "precious").unwrap(); | ||
| let owner = open_path(&dir.join("owner")); | ||
| let staging = open_path(&dir.join("owner/.staging")); | ||
| let result = build_and_publish(&owner, &staging, "new.git"); | ||
| let result = build_and_publish(&owner, &staging, "new.git", Contents::Empty); | ||
| assert!(result.is_err(), "building over an existing repo succeeded"); | ||
| assert_eq!(fs::read_to_string(dir.join("owner/.staging/repo/sentinel")).unwrap(), "precious"); | ||
| assert!(!dir.join("owner/new.git").exists(), "nothing was published"); | ||
| @@ -1112,7 +1183,10 @@ mod tests { | ||
| fs::create_dir_all(dir.join("owner/new.git")).unwrap(); | ||
| let owner = open_path(&dir.join("owner")); | ||
| let staging = open_path(&dir.join("owner/.staging")); | ||
| let error = build_and_publish(&owner, &staging, "new.git").err().map(|e| e.detail()).unwrap_or_default(); | ||
| let error = build_and_publish(&owner, &staging, "new.git", Contents::Empty) | ||
| .err() | ||
| .map(|e| e.detail()) | ||
| .unwrap_or_default(); | ||
| assert!(error.contains("already exists"), "{error}"); | ||
| assert!(fs::read_dir(dir.join("owner/.staging")).unwrap().next().is_none(), "the half-built repo is gone"); | ||
| assert!(fs::read_dir(dir.join("owner/new.git")).unwrap().next().is_none(), "the target is untouched"); | ||
| @@ -248,3 +248,87 @@ fn an_unmounted_backup_directory_is_refused() { | ||
| assert!(stderr(&out).contains("not a mounted volume"), "{}", stderr(&out)); | ||
| assert!(!setup.backups.join("gitv").exists(), "nothing was written"); | ||
| } | ||
| #[test] | ||
| fn one_repository_comes_back_from_a_snapshot_after_its_trash_is_purged() { | ||
| let setup = Setup::new("backup-one"); | ||
| let host = &setup.host; | ||
| let work = work("backup-one-work"); | ||
| git(&work, &["branch", "release"]); | ||
| git(&work, &["tag", "-a", "v1", "-m", "One"]); | ||
| git(&work, &["tag", "light"]); | ||
| let out = host.git(&work, &["push", "-q", "ada@x:ada/tools.git", "main", "release", "v1", "light"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| for args in [ | ||
| &["visibility", "ada", "tools", "public"][..], | ||
| &["default-branch", "ada", "tools", "release"], | ||
| &["description", "ada", "tools", "Tools for ada"], | ||
| ] { | ||
| let out = host.admin(args); | ||
| assert!(out.status.success(), "{args:?}: {}", stderr(&out)); | ||
| } | ||
| let refs = |repo: &Path| git(repo, &["for-each-ref", "--format=%(objectname) %(refname)"]); | ||
| let before = refs(&host.repo("ada", "tools")); | ||
| assert_eq!(before.lines().count(), 4, "{before}"); | ||
| let out = setup.backup(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let snapshot = setup.latest().file_name().unwrap().to_str().unwrap().to_string(); | ||
| // Deleted, purged from the trash, and the name since taken by a new repository. | ||
| assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success()); | ||
| let out = host.admin(&["purge", "--older-than-days", "0"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(fs::read_dir(host.repos.join("ada/.trash")).unwrap().count(), 0, "the trash was purged"); | ||
| assert!(host.admin(&["create", "ada", "tools"]).status.success()); | ||
| let out = setup.run(RESTORE, &["find", "ada/tools"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), snapshot); | ||
| assert!(!setup.run(RESTORE, &["find", "ada/missing"]).status.success()); | ||
| let target = scratch("backup-one-restored"); | ||
| let out = setup.run(RESTORE, &["latest", target.to_str().unwrap(), "ada/tools"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stderr(&out).contains("gitv import ada tools"), "{}", stderr(&out)); | ||
| let restored = target.join("tools.git"); | ||
| assert_eq!(fs::read_dir(&target).unwrap().count(), 1, "only that repository was copied"); | ||
| // The new repository at the name is never replaced. | ||
| let out = host.admin(&["import", "ada", "tools", restored.to_str().unwrap()]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("already exists"), "{}", stderr(&out)); | ||
| assert_eq!(refs(&host.repo("ada", "tools")), "", "the new repository is untouched"); | ||
| let leftovers: Vec<_> = fs::read_dir(host.repos.join("ada")) | ||
| .unwrap() | ||
| .map(|e| e.unwrap().file_name().into_string().unwrap()) | ||
| .filter(|n| n.starts_with(".create")) | ||
| .collect(); | ||
| assert!(leftovers.is_empty(), "{leftovers:?}"); | ||
| // Under another name it comes back whole: refs, default branch, visibility, description. | ||
| let out = host.admin(&["import", "ada", "tools-restored", restored.to_str().unwrap()]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let back = host.repo("ada", "tools-restored"); | ||
| assert_eq!(refs(&back), before); | ||
| assert_eq!(git(&back, &["symbolic-ref", "HEAD"]), "refs/heads/release"); | ||
| assert!(back.join("gitv-public").is_file(), "still public"); | ||
| assert_eq!(fs::read_to_string(back.join("description")).unwrap(), "Tools for ada\n"); | ||
| let out = host.ssh("ada", "list"); | ||
| assert!(String::from_utf8_lossy(&out.stdout).contains("ada/tools-restored.git")); | ||
| let clone = scratch("backup-one-clone"); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:ada/tools-restored.git", "copy"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(git(&clone.join("copy"), &["branch", "--show-current"]), "release"); | ||
| // Names that aren't OWNER/NAME, and repositories a snapshot doesn't hold, copy nothing. | ||
| let elsewhere = host.dir.join("not-restored"); | ||
| for repo in ["ada/../etc", "ada", "ada/tools/x", "Ada/tools", "ada/missing"] { | ||
| let out = setup.run(RESTORE, &["latest", elsewhere.to_str().unwrap(), repo]); | ||
| assert!(!out.status.success(), "{repo} was restored"); | ||
| assert!(!elsewhere.exists(), "{repo} copied something"); | ||
| } | ||
| // Only a bare repository is imported. | ||
| let out = host.admin(&["import", "ada", "other", work.to_str().unwrap()]); | ||
| assert!(!out.status.success(), "a working copy was imported"); | ||
| assert!(!host.repo("ada", "other").exists()); | ||
| } | ||
+71−9
| @@ -3,7 +3,11 @@ | ||
| # into the live tree: move what you need into place afterwards (see the README's recovery steps). | ||
| # | ||
| # gitv-restore list the snapshots, newest last | ||
| # gitv-restore find OWNER/NAME the snapshots holding that repository, newest last | ||
| # gitv-restore <snapshot|latest> DIR copy it to DIR (which must be empty or absent) and check it | ||
| # gitv-restore <snapshot|latest> DIR OWNER/NAME | ||
| # copy just that repository to DIR/NAME.git and check it; | ||
| # put it back with: gitv import OWNER NAME DIR/NAME.git | ||
| # gitv-restore check restore latest to a scratch folder on the volume, check | ||
| # it, and remove it: a drill proving backups restore | ||
| # | ||
| @@ -23,19 +27,46 @@ snapshot_dir() { | ||
| echo "$base/snapshots/$name" | ||
| } | ||
| # Never copy anything but a snapshot: an empty or wrong source must not become `rsync /`. | ||
| check_snapshot() { | ||
| [[ -n $1 && -d $1/repos && -f $1/MANIFEST ]] || die "not a snapshot: '$1'" | ||
| } | ||
| # A restore goes only into a folder that is empty or absent, so it never mixes with anything. | ||
| check_target() { | ||
| if [[ -e $1 ]] && [[ -n $(ls -A "$1") ]]; then die "$1 isn't empty"; fi | ||
| } | ||
| # Whether git can read the whole repository, with no user or system configuration. | ||
| verify() { | ||
| env -i PATH=/usr/bin:/bin HOME=/nonexistent GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null \ | ||
| git -c safe.directory='*' --git-dir="$1" fsck --no-progress --full >/dev/null | ||
| } | ||
| # OWNER/NAME, checked against gitv's name rule, into $owner and $name. | ||
| parse_repo() { | ||
| local part='[a-z0-9][a-z0-9_-]{0,62}' | ||
| [[ $1 =~ ^($part)/($part)$ ]] || die "name the repository as OWNER/NAME: $1" | ||
| owner=${BASH_REMATCH[1]} name=${BASH_REMATCH[2]} | ||
| } | ||
| # The repository in a snapshot, if it holds one: real directories only, never links. | ||
| snapshot_repo() { | ||
| local dir=$1/repos/$owner | ||
| [[ -d $dir && ! -L $dir && -d $dir/$name.git && ! -L $dir/$name.git ]] && echo "$dir/$name.git" | ||
| } | ||
| # Copy a snapshot to an empty target with owners and modes kept, then fsck every repository. | ||
| restore() { | ||
| local from=$1 to=$2 | ||
| # Never copy anything but a snapshot: an empty or wrong source must not become `rsync /`. | ||
| [[ -n $from && -d $from/repos && -f $from/MANIFEST ]] || die "not a snapshot: '$from'" | ||
| if [[ -e $to ]] && [[ -n $(ls -A "$to") ]]; then die "$to isn't empty"; fi | ||
| check_snapshot "$from" | ||
| check_target "$to" | ||
| mkdir -p "$to" | ||
| rsync -a "$from/" "$to/" | ||
| local count=0 failed=0 repo | ||
| while IFS= read -r -d '' repo; do | ||
| count=$((count + 1)) | ||
| if ! env -i PATH=/usr/bin:/bin HOME=/nonexistent GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null \ | ||
| git -c safe.directory='*' --git-dir="$repo" fsck --no-progress --full >/dev/null; then | ||
| if ! verify "$repo"; then | ||
| say "fsck failed for ${repo#"$to"/repos/}" | ||
| failed=$((failed + 1)) | ||
| fi | ||
| @@ -44,8 +75,21 @@ restore() { | ||
| say "restored $(basename "$from") to $to: $count repositories verified" | ||
| } | ||
| # Copy one repository out of a snapshot to TARGET/NAME.git, owners and modes kept, and fsck it. | ||
| restore_one() { | ||
| local from=$1 to=$2 source | ||
| check_snapshot "$from" | ||
| source=$(snapshot_repo "$from") || die "$(basename "$from") doesn't hold $owner/$name (see: gitv-restore find $owner/$name)" | ||
| check_target "$to" | ||
| mkdir -p "$to" | ||
| rsync -a "$source" "$to/" | ||
| verify "$to/$name.git" || die "fsck failed for the restored $owner/$name" | ||
| say "restored $owner/$name from $(basename "$from") to $to/$name.git and verified it" | ||
| say "put it back with: gitv import $owner $name $to/$name.git (or another name)" | ||
| } | ||
| if (($# == 0)); then | ||
| sed -n '2,10p' "$0" | ||
| sed -n '2,13p' "$0" | ||
| exit 0 | ||
| fi | ||
| @@ -61,12 +105,30 @@ check) | ||
| trap 'rm -rf "$scratch"' EXIT | ||
| restore "$from" "$scratch" | ||
| ;; | ||
| find) | ||
| [[ $# == 2 ]] || die "usage: gitv-restore find OWNER/NAME" | ||
| parse_repo "$2" | ||
| found=0 | ||
| for snapshot in "$base"/snapshots/*/; do | ||
| snapshot=${snapshot%/} | ||
| if snapshot_repo "$snapshot" >/dev/null; then | ||
| basename "$snapshot" | ||
| found=1 | ||
| fi | ||
| done | ||
| ((found)) || die "no snapshot holds $owner/$name" | ||
| ;; | ||
| -h | --help) | ||
| sed -n '2,10p' "$0" | ||
| sed -n '2,13p' "$0" | ||
| ;; | ||
| *) | ||
| [[ $# == 2 ]] || die "usage: gitv-restore <snapshot|latest> DIR" | ||
| [[ $# == 2 || $# == 3 ]] || die "usage: gitv-restore <snapshot|latest> DIR [OWNER/NAME]" | ||
| from=$(snapshot_dir "$1") || exit 1 | ||
| restore "$from" "$2" | ||
| if [[ $# == 3 ]]; then | ||
| parse_repo "$3" | ||
| restore_one "$from" "$2" | ||
| else | ||
| restore "$from" "$2" | ||
| fi | ||
| ;; | ||
| esac | ||