import contextlib
import os
import tempfile

import pygit2
import pytest

import gitubuntu.git_repository


@pytest.fixture
def repo():
    """An empty GitUbuntuRepository repository fixture

    The GitUbuntuRepository class methods (other than main entry point)
    assume they are running with the current work directory set to the
    Git repository's filesystem path. Additionally, pristine-tar and
    other commands require this to be the case, so chdir in the fixture
    itself.
    """
    try:
        oldcwd = os.getcwd()
    except OSError:
        oldcwd = None

    # The git CLI requires a valid email address to be available. Normally, we
    # might expect this to be the git-ubuntu CLI caller's responsibility to
    # set. However, in tests, since GitUbuntuRepository calls the git CLI for
    # some operations that cannot currently be done through pygit2, it makes
    # sense to set EMAIL temporarily so that the test suite is independent of
    # the environment in which it is running.
    old_email = os.environ.get('EMAIL')
    os.environ['EMAIL'] = 'test@example.com'

    with tempfile.TemporaryDirectory() as path:
        os.chdir(path)
        try:
            yield gitubuntu.git_repository.GitUbuntuRepository(path)
        except:
            raise
        finally:
            if oldcwd:
                os.chdir(oldcwd)

            # Reset the EMAIL environment variable to what it was. This makes
            # little practical difference, but may prevent confusion and a
            # headache if in the future a different test is written that does
            # not use this fixture but does rely somehow on the EMAIL
            # environment variable not changing, as such a test would become
            # non-deterministic depending on whether other tests have run that
            # use this fixture.
            if old_email is None:
                del os.environ['EMAIL']
            else:
                os.environ['EMAIL'] = old_email


@pytest.fixture
def pygit2_repo():
    """An empty pygit2 repository fixture in a temporary directory"""
    with tempfile.TemporaryDirectory() as tmp_dir:
        yield pygit2.init_repository(tmp_dir)
