All checks were successful
Codespell / Check for spelling errors (pull_request) Successful in 58s
Conventional commits / check-messages (pull_request) Successful in 1m4s
Ruff / Code linting (pull_request) Successful in 1m9s
Type annotation (PR) / check (pull_request) Successful in 1m29s
Unit tests (Linux) / check (pull_request) Successful in 2m29s
Codespell / Check for spelling errors (push) Successful in 31s
Ruff / Code linting (push) Successful in 39s
Type annotation (project) / check (push) Successful in 1m38s
Unit tests (Linux) / check (push) Successful in 2m23s
This changeset brings three variants of a function to clone a repository. `clone_repo()` is a low-level helper, and a thin frontend to `git clone`. It main purpose is to orchestrate progress reporting via the `ProgressHandler` interface. `clone_repo_mirror()` is a similarly low-level variant, focused on wrapping `git clone --mirror`. it is implemented as a dedicated function, because the `--mirror` flag determines much of the parameter values of `clone_repo()`. A dedicated function appears cleaner than a sophisticated parameter combination validation. `clone_annexrepo()` is envisioned to be the standard workhorse. It wraps `clone_repo()` and supports the initialization of a local annex. The dependency on datasalad is bumped to 0.7, which introduced the ability to have `iter_subproc()` yield `stderr` -- which is used for reading and processing `git clone` progress reports.
219 lines
7.3 KiB
Python
219 lines
7.3 KiB
Python
import re
|
|
from collections.abc import (
|
|
Hashable,
|
|
)
|
|
from pathlib import Path
|
|
|
|
from datasalad.itertools import itemize
|
|
from datasalad.progress import ProgressHandler
|
|
|
|
from datalad_core.repo import (
|
|
Repo,
|
|
Worktree,
|
|
)
|
|
from datalad_core.runners import (
|
|
CommandError,
|
|
call_git,
|
|
iter_git_subproc,
|
|
)
|
|
|
|
from .utils import git_url_basename # noqa TID252
|
|
|
|
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,
|
|
directory: Path | None,
|
|
*,
|
|
bare: bool = False,
|
|
depth: int | None = None,
|
|
branch: str | None = None,
|
|
quiet: bool = False,
|
|
progress_handler: ProgressHandler | None = None,
|
|
) -> Repo | Worktree:
|
|
"""Clone a repository into a new/empty directory
|
|
|
|
This is a thin frontend for the ``git-clone`` command. All parameters
|
|
except ``progress_handler`` correspond exactly to the ``git-clone`` CLI
|
|
arguments. Values for ``source`` can be in any form that Git can handle,
|
|
and can also be ``Path`` instances. If ``directory`` is ``None``, a target
|
|
directory name is derived from ``source``, in the same way Git does.
|
|
|
|
When a ``progress_handler`` is given, the ``git-clone`` execution is
|
|
wrapped with a parser that reports Git's progress messages through the
|
|
progress handler.
|
|
|
|
Depending on the ``bare`` parameter, a ``Repo`` or ``Worktree`` instance
|
|
is returned.
|
|
"""
|
|
dest = (
|
|
Path(git_url_basename(str(source), is_bare=bare))
|
|
if directory is None
|
|
else directory
|
|
)
|
|
cmd: list[str] = ['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(dest)))
|
|
_call_gitclone(cmd, dest, progress_handler)
|
|
return Repo(dest) if bare else Worktree(dest)
|
|
|
|
|
|
def clone_repo_mirror(
|
|
source: str | Path,
|
|
directory: Path,
|
|
*,
|
|
quiet: bool = False,
|
|
progress_handler: ProgressHandler | None = None,
|
|
) -> Repo:
|
|
"""Clone a repository into a new/empty directory in mirror mode
|
|
|
|
This function closely matches :func:`clone_repo` in behavior. The only
|
|
difference is that ``--mirror`` is passed to ``git-clone``, and all
|
|
parameters that are predetermined by this flag are not available.
|
|
"""
|
|
cmd: list[str] = ['clone', '--mirror']
|
|
if progress_handler:
|
|
cmd.append('--progress')
|
|
if quiet:
|
|
cmd.append('--quiet')
|
|
cmd.extend((str(source), str(directory)))
|
|
_call_gitclone(cmd, directory, progress_handler)
|
|
return Repo(directory)
|
|
|
|
|
|
def _call_gitclone(
|
|
cmd: list[str],
|
|
directory: Path,
|
|
progress_handler: ProgressHandler | None,
|
|
) -> None:
|
|
if not progress_handler:
|
|
# no output capture whatsoever. Will barf on stderr and
|
|
# raise exception if anything goes wrong
|
|
call_git(cmd)
|
|
return None
|
|
_call_gitclone_w_progresstracking(cmd, directory, progress_handler)
|
|
|
|
|
|
def _call_gitclone_w_progresstracking(
|
|
cmd: list[str],
|
|
directory: Path,
|
|
progress_handler: ProgressHandler,
|
|
) -> None:
|
|
# register an overall task that wraps the individual clone
|
|
# steps
|
|
clone_task_id = progress_handler.register_task(
|
|
description=f"Cloning repository into '{directory}'",
|
|
)
|
|
# 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: bytes | None = None
|
|
current_task_id: Hashable | None = 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):
|
|
current_task_id, current_task_label = _handle_progress_chunk(
|
|
progress_handler,
|
|
item,
|
|
stderr_lines,
|
|
clone_task_id,
|
|
current_task_id,
|
|
current_task_label,
|
|
)
|
|
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 '{directory}'",
|
|
)
|
|
# 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) # pragma: no cover
|
|
if clone_task_id:
|
|
progress_handler.remove_incomplete_task(
|
|
clone_task_id,
|
|
message=f"Failed to clone into '{directory}'",
|
|
) # pragma: no cover
|
|
|
|
|
|
def _handle_progress_chunk(
|
|
progress_handler: ProgressHandler,
|
|
item: bytes,
|
|
stderr_lines: list,
|
|
clone_task_id: Hashable,
|
|
current_task_id: Hashable | None,
|
|
current_task_label: bytes | None,
|
|
) -> tuple[Hashable | None, bytes | None]:
|
|
# 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,
|
|
)
|
|
return current_task_id, current_task_label
|