# Path: gg/main.py
# class Config:
#     def __init__(self):
#         self.verbose = False  # default
#         self.configfile = DEFAULT_CONFIGFILE
#         try:
#             self.repo = get_repo()
#         except git.InvalidGitRepositoryError as exception:
#             error_out(f"{exception.args[0]} is not a git repository")
# 
# Path: gg/builtins/branches/gg_branches.py
# @cli.command()
# @click.option(
#     "-y",
#     "--yes",
#     default=False,
#     is_flag=True,
#     help="Immediately say yes to any questions",
# )
# @click.option(
#     "-n",
#     "--cutoff",
#     default=DEFAULT_CUTOFF,
#     help="Max. number of branches to show",
#     show_default=True,
# )
# @click.argument("searchstring", default="")
# @pass_config
# def branches(config, yes=False, searchstring="", cutoff=DEFAULT_CUTOFF):
#     """List all branches. And if exactly 1 found, offer to check it out."""
#     repo = config.repo
# 
#     try:
#         branches_ = list(find(repo, searchstring))
#     except InvalidRemoteName as exception:
#         remote_search_name = searchstring.split(":")[0]
#         if remote_search_name in [x.name for x in repo.remotes]:
#             error_out(f"Invalid remote name {exception!r}")
# 
#         (repo_name,) = [
#             x.url.split("/")[-1].split(".git")[0]
#             for x in repo.remotes
#             if x.name == "origin"
#         ]
#         # Add it and start again
#         remote_url = f"https://github.com/{remote_search_name}/{repo_name}.git"
#         if not click.confirm(
#             f"Add remote {remote_search_name!r} ({remote_url})", default=True
#         ):
#             error_out("Unable to find or create remote")
# 
#         repo.create_remote(remote_search_name, remote_url)
#         branches_ = list(find(repo, searchstring))
# 
#     if branches_:
#         merged = get_merged_branches(repo)
#         info_out("Found existing branches...")
#         print_list(branches_, merged, cutoff=cutoff)
#         if len(branches_) == 1 and searchstring:
#             # If the found branch is the current one, error
#             active_branch = repo.active_branch
#             if active_branch == branches_[0]:
#                 error_out(f"You're already on {branches_[0].name!r}")
#             branch_name = branches_[0].name
#             if len(branch_name) > 50:
#                 branch_name = branch_name[:47] + "…"
# 
#             if not yes:
#                 check_it_out = (
#                     input(f"Check out {branch_name!r}? [Y/n] ").lower().strip() != "n"
#                 )
#             if yes or check_it_out:
#                 branches_[0].checkout()
#     elif searchstring:
#         warning_out(f"Found no branches matching {searchstring!r}.")
#     else:
#         warning_out("Found no branches.")


import json
import os
import tempfile
import shutil
import pytest
import requests_mock
from click.testing import CliRunner
from gg.main import Config
from gg.builtins.branches.gg_branches import branches
@pytest.fixture(autouse=True)
def requestsmock():
    """Return a context where requests are all mocked.
    Usage::

        def test_something(requestsmock):
            requestsmock.get(
                'https://example.com/path'
                content=b'The content'
            )
            # Do stuff that involves requests.get('http://example.com/path')
    """
    with requests_mock.mock() as m:
        yield m


@pytest.yield_fixture
def temp_configfile():
    tmp_dir = tempfile.mkdtemp("gg-start")
    fp = os.path.join(tmp_dir, "state.json")
    with open(fp, "w") as f:
        json.dump({}, f)
    yield fp
    shutil.rmtree(tmp_dir)


def test_branches(temp_configfile, mocker):
    mocked_git = mocker.patch("git.Repo")
    mocked_git().working_dir = "gg-start-test"
    mocked_git().git.branch.return_value = """

# Path: gg/main.py
# class Config:
#     def __init__(self):
#         self.verbose = False  # default
#         self.configfile = DEFAULT_CONFIGFILE
#         try:
#             self.repo = get_repo()
#         except git.InvalidGitRepositoryError as exception:
#             error_out(f"{exception.args[0]} is not a git repository")
# 
# Path: gg/builtins/branches/gg_branches.py
# @cli.command()
# @click.option(
#     "-y",
#     "--yes",
#     default=False,
#     is_flag=True,
#     help="Immediately say yes to any questions",
# )
# @click.option(
#     "-n",
#     "--cutoff",
#     default=DEFAULT_CUTOFF,
#     help="Max. number of branches to show",
#     show_default=True,
# )
# @click.argument("searchstring", default="")
# @pass_config
# def branches(config, yes=False, searchstring="", cutoff=DEFAULT_CUTOFF):
#     """List all branches. And if exactly 1 found, offer to check it out."""
#     repo = config.repo
# 
#     try:
#         branches_ = list(find(repo, searchstring))
#     except InvalidRemoteName as exception:
#         remote_search_name = searchstring.split(":")[0]
#         if remote_search_name in [x.name for x in repo.remotes]:
#             error_out(f"Invalid remote name {exception!r}")
# 
#         (repo_name,) = [
#             x.url.split("/")[-1].split(".git")[0]
#             for x in repo.remotes
#             if x.name == "origin"
#         ]
#         # Add it and start again
#         remote_url = f"https://github.com/{remote_search_name}/{repo_name}.git"
#         if not click.confirm(
#             f"Add remote {remote_search_name!r} ({remote_url})", default=True
#         ):
#             error_out("Unable to find or create remote")
# 
#         repo.create_remote(remote_search_name, remote_url)
#         branches_ = list(find(repo, searchstring))
# 
#     if branches_:
#         merged = get_merged_branches(repo)
#         info_out("Found existing branches...")
#         print_list(branches_, merged, cutoff=cutoff)
#         if len(branches_) == 1 and searchstring:
#             # If the found branch is the current one, error
#             active_branch = repo.active_branch
#             if active_branch == branches_[0]:
#                 error_out(f"You're already on {branches_[0].name!r}")
#             branch_name = branches_[0].name
#             if len(branch_name) > 50:
#                 branch_name = branch_name[:47] + "…"
# 
#             if not yes:
#                 check_it_out = (
#                     input(f"Check out {branch_name!r}? [Y/n] ").lower().strip() != "n"
#                 )
#             if yes or check_it_out:
#                 branches_[0].checkout()
#     elif searchstring:
#         warning_out(f"Found no branches matching {searchstring!r}.")
#     else:
#         warning_out("Found no branches.")


# Path: gg/builtins/branches/tests/test_gg_branches.py
import json
import os
import tempfile
import shutil
import pytest
import requests_mock
from click.testing import CliRunner
from gg.main import Config
from gg.builtins.branches.gg_branches import branches

@pytest.fixture(autouse=True)
def requestsmock():
    """Return a context where requests are all mocked.
    Usage::

        def test_something(requestsmock):
            requestsmock.get(
                'https://example.com/path'
                content=b'The content'
            )
            # Do stuff that involves requests.get('http://example.com/path')
    """
    with requests_mock.mock() as m:
        yield m


@pytest.yield_fixture
def temp_configfile():
    tmp_dir = tempfile.mkdtemp("gg-start")
    fp = os.path.join(tmp_dir, "state.json")
    with open(fp, "w") as f:
        json.dump({}, f)
    yield fp
    shutil.rmtree(tmp_dir)


def test_branches(temp_configfile, mocker):
    mocked_git = mocker.patch("git.Repo")
    mocked_git().working_dir = "gg-start-test"
    mocked_git().git.branch.return_value = """

    * this-branch