from bzrlib import revision, transform
from bzrlib.tests import TestCaseWithTransport

from bzrlib.plugins.bzrtools.mirror import create_mirror

class TestMirror(TestCaseWithTransport):

    def commit_transform(self, branch, tt):
        base_revno, base_revision = branch.last_revision_info()
        if base_revision == revision.NULL_REVISION:
            parents = []
        else:
            parents = [base_revision]
        preview = tt.get_preview_tree()
        preview.set_parent_ids(parents)
        changes = tt.iter_changes()
        builder = branch.get_commit_builder(parents)
        try:
            list(builder.record_iter_changes(preview, base_revision, changes))
            builder.finish_inventory()
            revision_id = builder.commit('message')
        except:
            builder.abort()
            raise
        branch.set_last_revision_info(base_revno + 1, revision_id)

    def make_transform(self, branch):
        base = branch.basis_tree()
        tt = transform.TransformPreview(base)
        self.addCleanup(tt.finalize)
        root = tt.new_directory('', transform.ROOT_PARENT, 'root-id')
        tt._new_root = root
        return tt

    def test_create_mirror(self):
        source = self.make_branch('source')
        source.lock_write()
        self.addCleanup(source.unlock)
        source.nick = 'my special nick'
        source.set_submit_branch(':submit:')
        source.get_config().set_user_option('child_submit_to', 'a@b.com')
        self.commit_transform(source, self.make_transform(source))
        mirror = create_mirror(source, 'target', [])
        self.assertEqual(source.last_revision(), mirror.last_revision())
        self.assertEqual(source.base, mirror.get_public_branch())
        self.assertEqual(source.base, mirror.get_parent())
        self.assertEqual('my special nick', mirror.nick)
        self.assertEqual(':submit:', mirror.get_submit_branch())
        self.assertEqual('a@b.com', mirror.get_config().get_user_option(
                         'child_submit_to'))

    def test_nonexplict_nick(self):
        source = self.make_branch('source')
        mirror = create_mirror(source, 'target', [])
        self.assertEqual('target', mirror.nick)
