import os

import pygit2
import pytest

from gitubuntu.repo_builder import Blob, Commit, Placeholder, Repo, Tree
import gitubuntu.spec as spec
from gitubuntu.test_fixtures import repo

import gitubuntu.rich_history as target


def test_preservation(tmpdir, repo):
    """An export followed by an import should preserve rich history

    Given a minimal repository that should be able to have upload tags be
    exported, when we import the export result into a similar repository with a
    subtly different upload tag in which the rich history should still apply,
    the result should be a correctly reconstructed upload tag.

    :param py.path tmpdir: the pytest standard tmpdir fixture.
    :param repo: our standard repo fixture.
    """
    Repo(
        commits=[
            Commit(
                name='1',
                tree=Tree({
                    'a': Blob(b'a'),
                }),
            ),
            Commit(
                name='2',
                parents=[Placeholder('1')],
                tree=Tree({
                    'a': Blob(b'ab'),
                }),
            ),
            Commit(
                name='3',
                parents=[Placeholder('2')],
                tree=Tree({
                    'a': Blob(b'abc'),
                }),
            ),
        ],
        tags={
            'importer/import/1': Placeholder('1'),
            'importer/upload/2': Placeholder('3'),
        }
    ).write(repo.raw_repo)
    target.export_all(repo, str(tmpdir))
    repo.delete_tags_in_namespace('importer')
    Repo(
        commits=[
            Commit(
                name='1',
                tree=Tree({
                    'a': Blob(b'a'),
                    'b': Blob(b'b'),
                }),
            )
        ],
        tags={'importer/import/1': Placeholder('1')},
    ).write(repo.raw_repo)
    target.import_single(repo, tmpdir, '2')
    new_tag = repo.raw_repo.lookup_reference(
        'refs/tags/importer/upload/2',
    ).peel(pygit2.Tag)
    assert new_tag.tagger.name == spec.SYNTHESIZED_COMMITTER_NAME
    assert new_tag.tagger.email == spec.SYNTHESIZED_COMMITTER_EMAIL
    new_commit = new_tag.peel(pygit2.Commit)
    assert new_commit.committer.name == spec.SYNTHESIZED_COMMITTER_NAME
    assert new_commit.committer.email == spec.SYNTHESIZED_COMMITTER_EMAIL
    new_tree = new_commit.peel(pygit2.Tree)
    assert repo.raw_repo.get(new_tree['a'].id).data == b'abc'
    assert repo.raw_repo.get(new_tree['b'].id).data == b'b'


def test_preservation_multiple_parents(tmpdir, repo):
    """An export of rich history should omit multiple parent cases

    If an upload tag leads to multiple parents before we reach an import tag,
    it should be excluded from the export as this type of upload tag is not
    supported for rich history preservation. This test also serves to verify
    code paths that handle the MultipleParentError exception in the export
    code.

    :param py.path tmpdir: the pytest standard tmpdir fixture.
    :param repo: our standard repo fixture.
    """
    Repo(
        commits=[
            Commit(name='1', message='a'),
            Commit(name='2', message='b'),
            Commit(name='child', parents=[Placeholder('1'), Placeholder('2')]),
        ],
        tags={
            'importer/import/1': Placeholder('1'),
            'importer/upload/2': Placeholder('child'),
        }
    ).write(repo.raw_repo)
    upload_tag = repo.raw_repo.lookup_reference('refs/tags/importer/upload/2')
    target.export_all(repo, str(tmpdir))
    assert not os.path.exists(tmpdir.join('2.base'))


def test_preservation_no_parents(tmpdir, repo):
    """An export of rich history should omit no parent cases

    If an upload tag leads to no parents before we reach an import tag,
    it should be excluded from the export as this type of upload tag is not
    supported for rich history preservation. This test also serves to verify
    code paths that handle the NoParentError exception in the export
    code.

    :param py.path tmpdir: the pytest standard tmpdir fixture.
    :param repo: our standard repo fixture.
    """
    Repo(
        commits=[
            Commit(name='1', message='a'),
            Commit(name='2', message='b'),
        ],
        tags={
            'importer/import/1': Placeholder('1'),
            'importer/upload/2': Placeholder('2'),
        }
    ).write(repo.raw_repo)
    upload_tag = repo.raw_repo.lookup_reference('refs/tags/importer/upload/2')
    target.export_all(repo, str(tmpdir))
    assert not os.path.exists(tmpdir.join('2.base'))


def test_import_no_base(tmpdir, repo):
    """An import of rich history with a missing base should fail

    If a rich history export uses a base that doesn't exist in the target
    repository for rich history import, a BaseNotFoundError exception should be
    raised.

    :param py.path tmpdir: the pytest standard tmpdir fixture.
    :param repo: our standard repo fixture.
    """
    tmpdir.join('2.base').write("1\n")
    with pytest.raises(target.BaseNotFoundError):
        target.import_single(repo, str(tmpdir), '2')


@pytest.mark.parametrize(['before_export', 'before_import'], [
    (
        # Commit messages with patch-like contents should not fail

        # If a commit message in rich history contains text in a patch-like
        # format (such as a diff of some file), it should not prevent correct
        # round-tripping. "git format-patch" followed by "git am" fails this
        # test, for example.
        {
            'commits': [
                Commit(name='1', message='a', tree=Tree({'a': Blob(b'a')})),
                Commit(
                    name='2',
                    message='''First line

Inline patch that isn't part of the real patch starts here

--- a/foo
+++ b/foo
@@ -1 +1,2 @@
 foo
+bar
''',
                    tree=Tree({'a': Blob(b'ab')}),
                    parents=[Placeholder('1')],
                ),
            ],
            'tags': {
                'importer/import/1': Placeholder('1'),
                'importer/upload/2': Placeholder('2'),
            }
        },
        {
            'commits': [
                Commit(name='b1', message='c', tree=Tree({'a': Blob(b'a')})),
            ],
            'tags': {'importer/import/1': Placeholder('b1')},
        },
    ),
    (
        # Commits that have no changes should round trip
        {
            'commits': [
                Commit(
                    name='1',
                    message='a',
                ),
                Commit(
                    name='2',
                    message='b',
                    parents=[Placeholder('1')],
                ),
            ],
            'tags': {
                'importer/import/1': Placeholder('1'),
                'importer/upload/2': Placeholder('2'),
            },
        },
        {
            'commits':  [Commit(name='b1', message='c')],
            'tags': {'importer/import/1': Placeholder('b1')},
        },
    ),
    (
        # Commits that have no commit message should round trip
        {
            'commits': [
                Commit(
                    name='1',
                    message='a',
                ),
                Commit(
                    name='2',
                    message='',
                    tree=Tree({'a': Blob(b'a')}),
                    parents=[Placeholder('1')],
                ),
            ],
            'tags': {
                'importer/import/1': Placeholder('1'),
                'importer/upload/2': Placeholder('2'),
            }
        },
        {
            'commits': [Commit(name='b1', message='c')],
            'tags': {'importer/import/1': Placeholder('b1')},
        },
    ),
])
def test_input_edge_cases(tmpdir, repo, before_export, before_import):
    """
    Edge cases in input rich history should reimport without failure

    Check that rich history preservation completes without an exception in
    various cases. Details of each case are described in comments in the test
    parameters above.

    Since these tests generally cover the mutated case (where rich history has
    to be ported forward because parent commits have mutated), we must remove
    and recreate the 'importer/import/1' tag so that it is different before
    attempting reimport. This is done by deleting all ('importer/*') tags and
    then using the before_import parameter to recreate it again.

    :param py.path tmpdir: the pytest standard tmpdir fixture.
    :param GitUbuntuRepository repo: our standard repo fixture.
    :param dict before_export: the parameters to supply to Repo() to construct
        the repository that will be exported.
    :param dict before_import: the parametsrs to supply to Repo() to add to the
        repository before attempting reimport.
    """
    Repo(**before_export).write(repo.raw_repo)
    target.export_all(repo, str(tmpdir))
    repo.delete_tags_in_namespace('importer')
    Repo(**before_import).write(repo.raw_repo)

    # We already test in test_rich_history_preservation() that the import works
    # correctly; this test solely checks that the following call does not raise
    # an exception, so no further assertion is required.
    target.import_single(repo, tmpdir, '2')


def test_preservation_fast_forwards(tmpdir, repo):
    """Rich history that can be fast forwarded should not mutate

    :param py.path tmpdir: the pytest standard tmpdir fixture.
    :param GitUbuntuRepository repo: our standard repo fixture.
    """
    Repo(
        commits=[
            Commit(
                name='1',
                message='a',
            ),
            Commit(
                name='2',
                message='',
                tree=Tree({'a': Blob(b'a')}),
                parents=[Placeholder('1')],
            ),
        ],
        tags={
            'importer/import/1': Placeholder('1'),
            'importer/upload/2': Placeholder('2'),
        }
    ).write(repo.raw_repo)
    target.export_all(repo, str(tmpdir))
    old_upload_ref = repo.raw_repo.lookup_reference(
        'refs/tags/importer/upload/2',
    )
    old_upload_id = old_upload_ref.peel().id
    old_upload_ref.delete()
    target.import_single(repo, tmpdir, '2')
    new_upload_ref = repo.raw_repo.lookup_reference(
        'refs/tags/importer/upload/2',
    )
    new_upload_id = new_upload_ref.peel().id
    assert old_upload_id == new_upload_id
