Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions src/repo_smith/repo_smith.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import os
import shutil
import tempfile
from contextlib import contextmanager
from logging import shutdown
from typing import Dict, Iterator, Optional, Self, Type, TypedDict, TypeVar, Unpack
from typing import Dict, Iterator, Optional, Self, Tuple, Type, TypedDict, TypeVar, Unpack

from git.repo import Repo

Expand Down Expand Up @@ -43,18 +44,26 @@ class CreateRepoOptions(TypedDict, total=False):
clone_from: str
existing_path: str
null_repo: bool
include_remote_repo: bool


@contextmanager
def create_repo_smith(
verbose: bool, **options: Unpack[CreateRepoOptions]
) -> Iterator[RepoSmith]:
"""Creates a RepoSmith instance over a given repository."""
) -> Iterator[Tuple[RepoSmith, Optional[RepoSmith]]]:
"""Creates a RepoSmith instance over a given repository.

Returns a tuple of (local_repo_smith, remote_repo_smith).
remote_repo_smith is None unless include_remote_repo=True.
"""
clone_from = options.get("clone_from")
existing_path = options.get("existing_path")
null_repo = options.get("null_repo", False)
include_remote_repo = options.get("include_remote_repo", False)

dir = tempfile.mkdtemp() if existing_path is None else existing_path
local_remote_dir = None
remote_repo = None

if null_repo:
repo = None
Expand All @@ -63,10 +72,22 @@ def create_repo_smith(
else:
repo = Repo.init(dir, initial_branch="main")

yield RepoSmith(repo, verbose)
if include_remote_repo:
local_remote_dir = tempfile.mkdtemp()
remote_path = os.path.join(local_remote_dir, "remote.git")
remote_repo = Repo.init(remote_path, bare=True)

yield (
RepoSmith(repo, verbose),
RepoSmith(remote_repo, verbose) if remote_repo else None,
)

if existing_path is None:
# Temporary directory created, so delete it
if repo is not None:
repo.git.clear_cache()
shutil.rmtree(dir)

# Clean up bare repository if created
if local_remote_dir is not None:
shutil.rmtree(local_remote_dir, ignore_errors=True)