import os
from contextlib import contextmanager
from typing import Generator

import pkg_resources

import gitubuntu.git_repository


def get_test_changelog(name):
    """Create a Changelog object from a test case pkg_resources file

    Find the test case file in the source tree or shipped with the package,
    read it into a Changelog object, and return that object.

    :param str name: the name of the test case changelog file from the
        gitubuntu/changelog_tests/ directory in the source tree.
    :returns: the Changelog object constructed from the test case input file
    :rtype: gitubuntu.git_repository.Changelog
    """
    return gitubuntu.git_repository.Changelog.from_path(os.path.join(
        pkg_resources.resource_filename('gitubuntu', 'changelog_tests'),
        name,
    ))



@contextmanager
def cwd_excursion(target: 'str | None' = None) -> Generator[str, None, None]:
    """Context which restores the working directory after exit.

    :param Optional[str] target: where to switch the cwd to
    :yields: cwd the program is in the context (the target directory)

    To be used as context manager:

    with cwd_excursion():
        os.chdir(somewhere)
        # do stuff
    # now the cwd is restored.

    or, if target is given:

    with cwd_excursion(target=os.path.join(tmpdir, "candyland"):
        print(os.getcwd())  # -> /tmp/somewhere/candyland
    # returned to previous cwd

    """
    prevcwd = os.getcwd()

    try:
        if target is not None:
            os.chdir(target)
            yield target
        else:
            yield prevcwd
    finally:
        os.chdir(prevcwd)
