git-annex-mirror-orchestrator/gamo/annex_ref_mirror.py
Michael Hanke a0d4a2d94d
rf: process-task -> update-refs
This makes room for a helper that deals with annex-key syncing.
2026-11-07 12:51:48 +01:00

271 lines
8.5 KiB
Python

"""
Synchronize Git branch references and git-annex metadata from a configured
Git remote into an existing local bare git-annex repository.
This command does not transfer annexed file content. It fetches Git objects
and metadata only; it does not run git-annex get, copy, or move.
It is a Python reimplementation of the ``git-annex-ref-mirror`` shell script
(https://hub.datalad.org/git-annex/git-annex-mirror-action).
"""
import argparse
import os
import shutil
import signal
import sys
from datetime import datetime
from pathlib import Path
from datalad_core.runners import (
CommandError,
call_git,
call_git_lines,
call_git_oneline,
)
_ANNEX_BRANCH = 'git-annex'
def _log(message: str, *, quiet: bool) -> None:
"""Write an informational line to STDERR, unless *quiet* is set."""
if quiet:
return
timestamp = datetime.now().astimezone().strftime('%Y-%m-%d %H:%M:%S')
sys.stderr.write(f'[{timestamp}] {message}\n')
def _die(message: str) -> None:
"""Write an error to STDERR and exit with status 1."""
sys.stderr.write(f'error: {message}\n')
sys.exit(1)
def _on_signal(signum: int, _frame: object) -> None:
# translate handled signals into a SystemExit so the lock directory is
# released by the caller's ``finally`` block. 128 + signum matches the
# conventional shell exit statuses (130 for INT, 143 for TERM).
raise SystemExit(128 + signum)
def _lock_path(repo: Path) -> Path:
return Path(f'{repo}.mirror.lock')
def _write_lock_metadata(lock: Path, remote: str) -> None:
(lock / 'pid').write_text(f'{os.getpid()}\n', encoding='utf-8')
start_time = datetime.now().astimezone().strftime('%Y-%m-%d %H:%M:%S')
(lock / 'start-time').write_text(f'{start_time}\n', encoding='utf-8')
(lock / 'remote').write_text(f'{remote}\n', encoding='utf-8')
def _mirror(
repo: Path,
remote: str,
*,
prune: bool,
force_tags: bool,
quiet: bool,
) -> None:
"""Perform the mirror operation on *repo* from *remote*."""
_log(f"fetching branches from '{remote}'", quiet=quiet)
fetch_args = ['fetch', '--no-tags']
if prune:
fetch_args.append('--prune')
if quiet:
fetch_args.append('--quiet')
fetch_args += [remote, f'+refs/heads/*:refs/remotes/{remote}/*']
call_git(fetch_args, cwd=repo)
if force_tags:
_log(f"force-updating tags from '{remote}'", quiet=quiet)
tag_args = ['fetch', '--no-tags']
if quiet:
tag_args.append('--quiet')
# deliberately no --prune: local-only tags are retained.
tag_args += [remote, '+refs/tags/*:refs/tags/*']
call_git(tag_args, cwd=repo)
_log('merging git-annex metadata', quiet=quiet)
merge_args = ['annex', 'merge']
if quiet:
merge_args.append('--quiet')
call_git(merge_args, cwd=repo)
_log('synchronizing ordinary branches', quiet=quiet)
remote_prefix = f'refs/remotes/{remote}/'
remote_refs = call_git_lines(
[
'for-each-ref',
'--format=%(refname) %(objectname)',
f'refs/remotes/{remote}/',
],
cwd=repo,
)
remote_suffixes = set()
for line in remote_refs:
if not line.strip():
continue
source_ref, object_id = line.split()
suffix = source_ref[len(remote_prefix) :]
remote_suffixes.add(suffix)
# the git-annex branch is merged separately and HEAD is a symref,
# not a branch. Neither is written to refs/heads/.
if suffix in (_ANNEX_BRANCH, 'HEAD'):
continue
call_git(['update-ref', f'refs/heads/{suffix}', object_id], cwd=repo)
if prune:
_log('pruning deleted branches', quiet=quiet)
local_refs = call_git_lines(
['for-each-ref', '--format=%(refname)', 'refs/heads/'],
cwd=repo,
)
for destination_ref in local_refs:
if not destination_ref.strip():
continue
# the local git-annex branch is an aggregate and never pruned.
if destination_ref == f'refs/heads/{_ANNEX_BRANCH}':
continue
suffix = destination_ref[len('refs/heads/') :]
if suffix not in remote_suffixes:
call_git(['update-ref', '-d', destination_ref], cwd=repo)
_log('mirror completed', quiet=quiet)
def mirror(
repo: str | Path,
remote: str,
*,
prune: bool = False,
force_tags: bool = False,
quiet: bool = False,
) -> None:
"""Validate, lock, and mirror *repo* from *remote*.
Raises on failure (instead of exiting) so it can be embedded in other
commands such as ``git-gamo-update-refs``.
"""
repo = Path(repo)
# -- validation ---------------------------------------------------------
if not repo.is_dir():
msg = f'repository does not exist: {repo}'
raise ValueError(msg)
try:
call_git(['rev-parse', '--git-dir'], cwd=repo, capture_output=True)
except CommandError as e:
msg = f'not a Git repository: {repo}'
raise ValueError(msg) from e
try:
is_bare = call_git_oneline(
['rev-parse', '--is-bare-repository'],
cwd=repo,
).strip()
except CommandError as e:
msg = f'cannot inspect repository: {repo}'
raise ValueError(msg) from e
if is_bare != 'true':
msg = f'repository is not bare: {repo}'
raise ValueError(msg)
try:
annex_uuid = call_git_oneline(
['config', '--local', '--get', 'annex.uuid'],
cwd=repo,
).strip()
except CommandError:
annex_uuid = ''
if not annex_uuid:
msg = f'repository does not appear to be git-annex initialized: {repo}'
raise ValueError(msg)
try:
call_git(['remote', 'get-url', remote], cwd=repo, capture_output=True)
except CommandError as e:
msg = f'remote is not configured in repository: {remote}'
raise ValueError(msg) from e
# -- locking and execution ----------------------------------------------
# the lock is released on every exit path: the ``finally`` block runs
# both for exceptions and for the SystemExit raised by the signal
# handlers (SIGINT/SIGTERM) installed in main() -- see _on_signal.
lock = _lock_path(repo)
acquired = False
try:
try:
lock.mkdir()
except FileExistsError as e:
msg = f'another mirror operation appears to be running: {lock}'
raise ValueError(msg) from e
acquired = True
_write_lock_metadata(lock, remote)
_mirror(
repo,
remote,
prune=prune,
force_tags=force_tags,
quiet=quiet,
)
finally:
if acquired:
shutil.rmtree(lock, ignore_errors=True)
def main() -> None:
parser = argparse.ArgumentParser(
description=(
'Synchronize Git branch references and git-annex metadata from '
'a configured remote into an existing local bare git-annex '
'repository. Annexed file content is not transferred.'
),
)
parser.add_argument(
'--prune',
'-p',
action='store_true',
help='delete local branches absent from REMOTE (except git-annex)',
)
parser.add_argument(
'--force-tags',
action='store_true',
help=(
'force-update same-named local tags from REMOTE; local-only '
'tags are retained'
),
)
parser.add_argument(
'--quiet',
'-q',
action='store_true',
help='suppress informational logging and normal Git/git-annex output',
)
parser.add_argument(
'repository',
type=Path,
metavar='REPOSITORY',
help='path to an existing local bare git-annex repository',
)
parser.add_argument(
'remote',
metavar='REMOTE',
help='name of a configured Git remote in REPOSITORY',
)
args = parser.parse_args()
os.umask(0o077)
# translate signals into SystemExit so the lock directory is released
# by mirror()'s ``finally`` block. 128 + signum matches the conventional
# shell exit statuses (130 for INT, 143 for TERM).
signal.signal(signal.SIGINT, _on_signal)
signal.signal(signal.SIGTERM, _on_signal)
try:
mirror(
args.repository,
args.remote,
prune=args.prune,
force_tags=args.force_tags,
quiet=args.quiet,
)
except (ValueError, CommandError) as e:
_die(str(e))