import os
import os.path
from unittest import makeSuite

from bzrlib import branch, osutils, workingtree
from bzrlib.config import LocationConfig
from bzrlib.transport import get_transport
from bzrlib.tests import (
    TestCaseWithTransport,
    )
from bzrlib.plugins.bzrtools import command

try:
    from bzrlib.tests.features import (
        HardlinkFeature,
        ModuleAvailableFeature,
        )
except ImportError: # bzr < 2.5
    from bzrlib.tests import (
        HardlinkFeature,
        ModuleAvailableFeature,
        )


LzmaFeature = ModuleAvailableFeature("lzma")


class TestBzrTools(TestCaseWithTransport):

    def setUp(self):
        TestCaseWithTransport.setUp(self)
        command._testing = True
        self.addCleanup(command._stop_testing)

    @staticmethod
    def touch(filename):
        file(filename, 'wb').write('')

    def test_shelve(self):
        self.run_bzr('init')
        self.run_bzr('commit -m uc --unchanged')
        self.run_bzr('shelve1 -r 1 -m foo --all', retcode=3)
        file('foo', 'wb').write('foo')
        self.run_bzr('add foo')
        self.run_bzr('commit -m foo')
        self.run_bzr('shelve1 -r 1 -m foo --all', retcode=0)

    def test_fetch_ghosts(self):
        self.run_bzr('init')
        self.run_bzr('fetch-ghosts .')

    def test_fetch_ghosts_with_saved(self):
        wt = self.make_branch_and_tree('.')
        wt.branch.set_parent('.')
        self.run_bzr('fetch-ghosts')

    def test_patch(self):
        self.run_bzr('init')
        file('myfile', 'wb').write('hello')
        self.run_bzr('add')
        self.run_bzr('commit -m hello')
        file('myfile', 'wb').write('goodbye')
        file('mypatch', 'wb').write(self.run_bzr('diff', retcode=1)[0])
        self.run_bzr('revert')
        assert file('myfile', 'rb').read() == 'hello'
        self.run_bzr('patch --silent mypatch')
        assert file('myfile', 'rb').read() == 'goodbye'

    def test_branch_history(self):
        self.run_bzr('init')
        file('myfile', 'wb').write('hello')
        self.run_bzr('add')
        self.run_bzr('commit -m hello')
        self.run_bzr('branch-history')

    def test_branch_history(self):
        self.run_bzr('init')
        file('myfile', 'wb').write('hello')
        self.run_bzr('add')
        self.run_bzr('commit -m hello')
        self.run_bzr('graph-ancestry . graph.dot')
        self.run_bzr('branch . my_branch')
        self.run_bzr('graph-ancestry . graph.dot --merge-branch my_branch')

    def test_fetch_ghosts(self):
        self.run_bzr('init')
        file('myfile', 'wb').write('hello')
        self.run_bzr('add')
        self.run_bzr('commit -m hello')
        self.run_bzr('branch . my_branch')
        self.run_bzr('fetch-ghosts my_branch')

    def test_zap(self):
        self.run_bzr('init source')
        self.run_bzr('checkout --lightweight source checkout')
        self.run_bzr('zap checkout')
        self.assertIs(False, os.path.exists('checkout'))
        self.assertIs(True, os.path.exists('source'))

    def test_zap_modified(self):
        tree = self.make_branch_and_tree('source')
        checkout = tree.branch.create_checkout('checkout', lightweight=True)
        self.build_tree(['checkout/file'])
        checkout.add('file')
        self.run_bzr_error(('This checkout has uncommitted changes',),
                           'zap checkout')
        self.assertPathExists('checkout')
        self.run_bzr('zap checkout --force')
        self.assertPathDoesNotExist('checkout')
        self.assertPathExists('source')

    def test_zap_branch(self):
        self.run_bzr('init source')
        self.run_bzr('checkout --lightweight source checkout')
        self.run_bzr('zap --branch checkout', retcode=3)
        self.assertIs(True, os.path.exists('checkout'))
        self.assertIs(True, os.path.exists('source'))
        self.run_bzr('branch source source2')
        self.run_bzr('checkout --lightweight source2 checkout2')
        self.run_bzr('zap --branch checkout2')
        self.assertIs(False, os.path.exists('checkout2'))
        self.assertIs(False, os.path.exists('source2'))

    def test_list_branches(self):
        self.run_bzr('init source')
        self.run_bzr('init source/subsource')
        self.run_bzr('checkout --lightweight source checkout')
        self.run_bzr('init checkout/subcheckout')
        self.run_bzr('init checkout/.bzr/subcheckout')
        out = self.run_bzr('list-branches')[0]
        lines = out.split('\n')
        self.assertIs(True, 'source' in lines)
        self.assertIs(True, 'source/subsource' in lines)
        self.assertIs(True, 'checkout/subcheckout' in lines)
        self.assertIs(True, 'checkout' not in lines)

    def test_import_upstream(self):
        self.run_bzr('init source')
        os.mkdir('source/src')
        f = file('source/src/myfile', 'wb')
        f.write('hello?')
        f.close()
        os.chdir('source')
        self.run_bzr('add')
        self.run_bzr('commit -m hello')
        self.run_bzr('export ../source-0.1.tar.gz')
        self.run_bzr('export ../source-0.1.tar.bz2')
        self.run_bzr('export ../source-0.1')
        self.run_bzr('init ../import')
        os.chdir('../import')
        self.run_bzr('import ../source-0.1.tar.gz')
        self.assertPathExists('src/myfile')
        result = self.run_bzr('import ../source-0.1.tar.gz', retcode=3)[1]
        self.assertContainsRe(result, 'Working tree has uncommitted changes')
        self.run_bzr('commit -m commit')
        self.run_bzr('import ../source-0.1.tar.gz')
        os.chdir('..')
        self.run_bzr('init import2')
        self.run_bzr('import source-0.1.tar.gz import2')
        self.assertPathExists('import2/src/myfile')
        self.run_bzr('import source-0.1.tar.gz import3')
        self.assertPathExists('import3/src/myfile')
        self.run_bzr('import source-0.1.tar.bz2 import4')
        self.assertPathExists('import4/src/myfile')
        self.run_bzr('import source-0.1 import5')
        self.assertPathExists('import5/src/myfile')

    def test_import_upstream_lzma(self):
        self.requireFeature(LzmaFeature)
        self.run_bzr('init source')
        os.mkdir('source/src')
        f = file('source/src/myfile', 'wb')
        f.write('hello?')
        f.close()
        os.chdir('source')
        self.run_bzr('add')
        self.run_bzr('commit -m hello')
        self.run_bzr('export ../source-0.1.tar.lzma')
        self.run_bzr('export ../source-0.1.tar.xz')
        os.chdir('..')
        self.run_bzr('import source-0.1.tar.lzma import1')
        self.assertPathExists('import1/src/myfile')
        self.run_bzr('import source-0.1.tar.xz import2')
        self.assertPathExists('import2/src/myfile')

    def test_cbranch(self):
        source = self.make_branch_and_tree('source')
        config = LocationConfig(osutils.abspath('target'))
        config.set_user_option('cbranch_target', 'target_branch')
        self.run_bzr('cbranch source target')
        checkout = workingtree.WorkingTree.open('target')
        self.assertEqual(checkout.branch.base,
                         get_transport('target').base)
        self.assertEqual(checkout.branch.get_master_branch().base,
                         get_transport('target_branch').base)
        self.assertEqual(checkout.branch.get_master_branch().get_parent(),
                         get_transport('source').base)

    def test_cbranch_hardlink(self):
        self.requireFeature(HardlinkFeature)
        # Later formats don't support hardlinks.  Boo!
        source = self.make_branch_and_tree('source', format='1.9')
        self.build_tree(['source/file'])
        source.add('file')
        source.commit('added file')
        config = LocationConfig(osutils.abspath('target'))
        config.set_user_option('cbranch_target', 'target_branch')
        self.run_bzr('cbranch source target --lightweight')
        checkout = workingtree.WorkingTree.open('target')
        self.assertNotEqual(os.lstat(checkout.abspath('file')).st_ino,
                            os.lstat(source.abspath('file')).st_ino)
        config = LocationConfig(osutils.abspath('target2'))
        config.set_user_option('cbranch_target', 'target_branch2')
        self.run_bzr('cbranch source target2 --lightweight --hardlink')
        checkout2 = workingtree.WorkingTree.open('target2')
        self.assertEqual(os.lstat(checkout2.abspath('file')).st_ino,
                         os.lstat(source.abspath('file')).st_ino)

    def test_create_mirror(self):
        source = self.make_branch_and_tree('source')
        source.commit('message')
        self.run_bzr('create-mirror source target')
        target = branch.Branch.open('target')
        self.assertEqual(source.last_revision(), target.last_revision())
        self.assertEqual(source.branch.base, target.get_public_branch())


def test_suite():
    return makeSuite(TestBzrTools)
