datalad-core/datalad_core/clone/clone_repo.py

134 lines
4.9 KiB
Python

import re
from pathlib import Path
from datasalad.itertools import itemize
from datasalad.progress import ProgressHandler
from datalad_core.runners import (
CommandError,
call_git,
iter_git_subproc,
)
progress_line = re.compile(
# we can only match using the structure of the messages,
# I18N changes all the language
b'(?P<task>.*): .*\\((?P<completed>\\d+)/(?P<total>\\d+)\\)[ ,](?P<info>.*)'
)
def clone_repo(
source: str | Path,
destination: Path,
*,
bare: bool = False,
depth: int | None = None,
branch: str | None = None,
quiet: bool = False,
progress_handler: ProgressHandler | None = None,
):
"""Clone a repository into a new/empty directory"""
cmd = ['clone']
if progress_handler:
cmd.append('--progress')
if bare:
cmd.append('--bare')
if depth:
cmd.extend(('--depth', str(depth)))
if branch:
cmd.extend(('--branch', branch))
if quiet:
cmd.append('--quiet')
cmd.extend((str(source), str(destination)))
if not progress_handler:
# no output capture whatsoever. Will barf on stderr and
# raise exception if anything goes wrong
call_git(cmd)
return None
# register an overall task that wraps the individual clone
# steps
clone_task_id = progress_handler.register_task(
description=f"Cloning repository into '{destination}'",
)
# the first update kicks off the task
progress_handler.update_task(
clone_task_id,
# there may be credential prompting before the fetching starts
expect_nonprogress_output=True,
)
current_task_label = None
current_task_id = None
stderr_lines: list[bytes] = []
try:
with iter_git_subproc(
cmd,
# we use a small buffer and chunk sizes to avoid progress
# message to get stuck in a buffer
bufsize=50,
chunk_size=50,
# git-clone reports progress via stderr, and this
# is what we mostly care about here
swap_stderr=True,
) as gitclone:
# we use '\r', because that is what separates the
# progress messages
for item in itemize(gitclone, b'\r', keep_ends=False):
# each progress item could still have multiple lines
# (the non-progress summary lines). This next loop
# ensures we really have a single line
for line in item.splitlines():
# capture stderr to report it, in case something goes wrong
stderr_lines.append(line)
pm = progress_line.match(line)
if not pm:
continue
pmd = pm.groupdict()
description = f'{pmd["task"].decode("utf-8")}{pmd["info"].decode("utf-8") if pmd["info"].rstrip() else ""}'
total = int(pmd['total'])
if pmd['task'] != current_task_label:
if current_task_id is not None:
progress_handler.remove_completed_task(current_task_id)
# with the first fetch task running any
# chance for prompting is gone
progress_handler.update_task(
clone_task_id,
expect_nonprogress_output=False,
)
current_task_id = progress_handler.register_task(
total=total,
description=description,
)
current_task_label = pmd['task']
progress_handler.update_task(
current_task_id,
completed=int(pmd['completed']),
total=total,
description=description,
)
if current_task_id:
progress_handler.remove_completed_task(current_task_id)
progress_handler.remove_completed_task(
clone_task_id,
message=f"Cloned repository into '{destination}'",
)
# signal to finally that nothing needs to be done
clone_task_id = None
current_task_id = None
except CommandError as e:
# the CommandError won't have any meaningful stderr, because we
# diverted it for progress tracking. Inject it here to allow for
# a standard exception handling behavior that is independent of
# any (particular) progress handling approach
e.stderr = b'\n'.join(stderr_lines)
raise
finally:
if current_task_id:
progress_handler.remove_incomplete_task(current_task_id)
if clone_task_id:
progress_handler.remove_incomplete_task(
clone_task_id,
message=f"Failed to clone into '{destination}'",
)