from bzrlib.diff import _patch_header_date
import bzrlib.tests
import os.path

try:
    from bzrlib.plugins.bzrtools.hunk_selector import (
        ShelveHunkSelector,
        UnshelveHunkSelector,
        )
    from bzrlib.plugins.bzrtools.errors import NoColor
except ImportError:
    from bzrtools.hunk_selector import (
        ShelveHunkSelector,
        UnshelveHunkSelector,
        )
    from bzrtools.errors import NoColor


class ShelfTests(bzrlib.tests.TestCaseWithTransport):
    ORIGINAL = '\n\nhello test world\n\n'
    MODIFIED = '\n\ngoodbye test world\n\n'
    DIFF_HEADER = "=== modified file '%(filename)s'\n"
    DIFF_1 = """--- %(filename)s\t%(old_date)s
+++ %(filename)s\t%(new_date)s
@@ -1,4 +1,4 @@
 
 
-hello test world
+goodbye test world
 
"""
    DIFF_2 = """--- test_file\t%(old_date)s
+++ test_file\t%(new_date)s
@@ -1,4 +1,4 @@
 
 
-goodbye test world
+hello test world
 
"""
    def _check_diff(self, diff=DIFF_1, filename='test_file'):
        old_tree = self.tree.basis_tree()
        old_date = _patch_header_date(old_tree, 
                                      old_tree.inventory.path2id(filename),
                                      filename)
        new_date = _patch_header_date(self.tree, 
                                      self.tree.inventory.path2id(filename),
                                      filename)
        keys = { 'filename' : filename , 'old_date': old_date, 
                 'new_date': new_date}
        hdr  = self.DIFF_HEADER % keys
        diff = diff % keys
        self.assertEqual(self.capture('diff', retcode=1), hdr + diff + '\n')

    def _check_shelf(self, idx, diff=DIFF_1, filename='test_file',
                     new_date=None):
        old_tree = self.tree.basis_tree()
        old_date = _patch_header_date(old_tree, 
                                      old_tree.inventory.path2id(filename),
                                      filename)
        diff = diff % { 'filename' : filename, 'old_date': old_date,
                        'new_date': new_date}
        shelf = open(os.path.join(self.tree.basedir,
                '.shelf/shelves/default/' + idx)).read()
        shelf = shelf[shelf.index('\n') + 1:] # skip the message
        self.assertEqual(shelf, diff)

    def test_shelf(self):
        self.__test_loop(1)

    def test_shelf_multi(self):
        self.__test_loop(10)

    def __test_loop(self, count):
        self.tree = self.make_branch_and_tree('.')
        self.__create_and_add_test_file()

        while count > 0:
            count -= 1

            # Modify the test file
            # write in binary mode because on win32 line-endings should be LF
            f = file('test_file', 'wb')
            f.write(self.MODIFIED)
            f.close()

            self._check_diff()
            
            new_date = _patch_header_date(self.tree, 
                self.tree.inventory.path2id('test_file'), 'test_file')

            # Shelve the changes
            self.run_bzr('shelve', '--all', retcode=0)

            # Make sure there is no diff anymore
            self.assertEqual(self.capture('diff', retcode=0), '')

            # Make sure the file is actually back the way it was
            self.assertEqual(file('test_file').read(), self.ORIGINAL)

            self._check_shelf('00', new_date=new_date)

            # Unshelve
            self.run_bzr('unshelve', '--all', retcode=0)

            self._check_diff()

            # Check the shelved patch was backed up
            self._check_shelf('00~', new_date=new_date)

            # Make sure the file is back the way it should be
            self.assertEqual(file('test_file').read(), self.MODIFIED)

    def test_shelf_nothing_to_shelve(self):
        import os.path
        self.tree = self.make_branch_and_tree('.')
        self.__create_and_add_test_file()

        # Shelve the changes
        self.run_bzr('shelve', '--all', retcode=3)

        if os.path.exists(os.path.join(self.tree.branch.base,
                '.shelf/shelves/default/00')):
            self.fail("Shelf exists, but it shouldn't")

    def __create_and_add_test_file(self, filename='test_file'):
        # write in binary mode because on win32 line-endings should be LF
        f = open(filename, 'wb')
        f.write(self.ORIGINAL)
        f.close()
        self.tree.add(self.tree.relpath(os.path.join(os.getcwd(), filename)))
        self.tree.commit(message='add %s' % filename)

    def test_shelf_with_revision(self):
        self.tree = self.make_branch_and_tree('.')

        self.__create_and_add_test_file()

        # Modify the test file and commit it
        self.build_tree_contents([('test_file', self.MODIFIED)])
        self.tree.commit(message='update test_file')

        # Shelve the changes
        self.run_bzr('shelve', '--all', '-r', '1', retcode=0)

        self._check_diff(self.DIFF_2)

        # Make sure the file is the way it should be
        self.assertEqual(file('test_file').read(), self.ORIGINAL)

        # Unshelve
        self.run_bzr('unshelve', '--all', retcode=0)

        # Make sure the file is back the way it should be
        self.assertEqual(file('test_file').read(), self.MODIFIED)

    def test_shelf_with_two_revisions(self):
        self.tree = self.make_branch_and_tree('.')

        cmd = 'shelve --all -r 1..2'
        (stdout, stderr) = self.run_bzr_captured(cmd.split(), retcode=None)

        self.assertEqual(stderr.split('\n')[0],
            'bzr: ERROR: shelve only accepts a single revision parameter.')

    def test_shelf_show_basic(self):
        self.tree = self.make_branch_and_tree('.')
        self.__create_and_add_test_file()
        self.__test_show(self.tree, '00')

    def __test_show(self, tree, patch):
        # Modify the test file
        self.build_tree_contents([('test_file', 'patch %s\n' % patch)])

        # Shelve the changes
        self.run_bzr('shelve', '--all', retcode=0)

        # Make sure there is no diff anymore
        self.assertEqual(self.capture('diff', retcode=0), '')

        # Check the shelf is right
        shelf = open(os.path.join(self.tree.basedir,
                    '.shelf/shelves/default', patch)).read()
        self.assertTrue('patch %s' % patch in shelf)

        # Check the shown output is right
        shown = self.capture('shelf show %s' % patch, retcode=0)
        self.assertEqual(shown, shelf)

    def test_shelf_show_multi(self):
        self.tree = self.make_branch_and_tree('.')
        self.__create_and_add_test_file()
        self.__test_show(self.tree, '00')
        self.__test_show(self.tree, '01')
        self.__test_show(self.tree, '02')

        # Now check we can show a previously shelved patch
        shelf = open(os.path.join(self.tree.basedir,
                    '.shelf/shelves/default/00')).read()
        self.assertTrue('patch 00' in shelf)

        # Check the shown output is right
        shown = self.capture('shelf show 00', retcode=0)
        self.assertEqual(shown, shelf)

    def test_shelf_show_unspecified(self):
        self.tree = self.make_branch_and_tree('.')
        self.__create_and_add_test_file()
        self.__test_show(self.tree, '00')
        self.__test_show(self.tree, '01')
        self.__test_show(self.tree, '02')

        # Check that not specifying at patch gets us the most recent
        shelf = open(os.path.join(self.tree.basedir,
                    '.shelf/shelves/default/02')).read()
        self.assertTrue('patch 02' in shelf)

        # Check the shown output is right
        shown = self.capture('shelf show', retcode=0)
        self.assertEqual(shown, shelf)

    def test_shelf_show_with_no_patch(self):
        self.tree = self.make_branch_and_tree('.')
        stderr = self.run_bzr_captured(['shelf', 'show', '00'], retcode=None)[1]
        self.assertTrue("Patch '00' doesn't exist on shelf default!" in stderr)

    def test_shelf_unshelve_failure(self):
        self.tree = self.make_branch_and_tree('.')

        self.__create_and_add_test_file()

        # Modify the test file
        file('test_file', 'w').write(self.MODIFIED)

        # Shelve the changes
        self.run_bzr('shelve', '--all', retcode=0)

        # Write an unapplyable patch into the shelf
        shelf = open(os.path.join(self.tree.basedir,
                    '.shelf/shelves/default/00'), 'w')
        shelf.write(self.DIFF_2)
        shelf.close()

        # Unshelve, should fail
        self.run_bzr('unshelve', '--all', retcode=3)

        # Make sure the patch is still there, eventhough it's broken
        shelf = open(os.path.join(self.tree.basedir,
                    '.shelf/shelves/default/00')).read()
        self.assertEqual(shelf, self.DIFF_2)

        # Working tree should be unchanged
        diff = self.capture('diff', retcode=0)
        self.assertEqual(diff, '')

    def test_shelf_unshelve_failure_two_hunks(self):
        self.tree = self.make_branch_and_tree('.')

        self.__create_and_add_test_file()
        self.__create_and_add_test_file(filename='test_file2')

        # Modify the test files
        file('test_file', 'w').write(self.MODIFIED)
        file('test_file2', 'w').write(self.MODIFIED)

        # Shelve the changes
        self.run_bzr('shelve', '--all', retcode=0)

        # Put the changes to test_file back, the shelved patch won't apply now
        file('test_file', 'w').write(self.MODIFIED)
        self.tree.commit(message='screw up test_file')

        # Unshelve, should fail
        self.run_bzr('unshelve', '--all', retcode=3)

        # Working tree should be unchanged
        diff = self.capture('diff', retcode=0)
        self.assertEqual(diff, '')

        # Force should succeed and modify test_file2, but leave shelf
        self.run_bzr('unshelve', '--force', '--all', retcode=0)
        self.assertEqual(open('test_file2').read(), self.MODIFIED)
        self.assertTrue(os.path.exists('.shelf/shelves/default/00'))

    def test_shelf_after_unshelve(self):
        self.tree = self.make_branch_and_tree('.')

        self.__create_and_add_test_file()
        self.__create_and_add_test_file(filename='test_file2')

        # Modify the test files
        file('test_file', 'w').write(self.MODIFIED)
        file('test_file2', 'w').write(self.MODIFIED)

        # Shelve the changes
        self.run_bzr('shelve', '--all', 'test_file', retcode=0)
        self.run_bzr('shelve', '--all', 'test_file2', retcode=0)

        # Unshelve
        self.run_bzr('unshelve', '--all', retcode=0)

        # We should now have 00 and 01~
        self.assertTrue(os.path.exists('.shelf/shelves/default/00'))
        self.assertTrue(os.path.exists('.shelf/shelves/default/01~'))

        # Check ls works
        lines = self.capture('shelf ls', retcode=0).split('\n')
        for line in lines:
            self.assertFalse(line.startswith(' 01'))

        # Unshelve, if unshelve is confused by the backup it will fail
        self.run_bzr('unshelve', '--all', retcode=0)

    def test_shelf_delete(self):
        self.tree = self.make_branch_and_tree('.')

        self.__create_and_add_test_file()
        self.__create_and_add_test_file(filename='test_file2')

        # Modify the test files
        # write in binary mode because on win32 line-endings should be LF
        f = file('test_file', 'wb')
        f.write(self.MODIFIED)
        f.close()
        f = file('test_file2', 'wb')
        f.write(self.MODIFIED)
        f.close()
        new_date = _patch_header_date(self.tree, 
            self.tree.inventory.path2id('test_file'), 'test_file')

        # Shelve the changes
        self.run_bzr('shelve', '--all', 'test_file', retcode=0)
        self.run_bzr('shelve', '--all', 'test_file2', retcode=0)

        self._check_shelf('00', new_date=new_date)

        # Delete 00
        self.run_bzr('shelf', 'delete', '00', retcode=0)

        # We should now have 01 but not 00, but we should have 00~
        self.assertFalse(os.path.exists('.shelf/shelves/default/00'))
        self.assertTrue(os.path.exists('.shelf/shelves/default/00~'))
        self.assertTrue(os.path.exists('.shelf/shelves/default/01'))

        # Check the backup is right
        self._check_shelf('00~', new_date=new_date)

        # Check ls works
        lines = self.capture('shelf ls', retcode=0).split('\n')
        for line in lines:
            self.assertFalse(line.startswith(' 00'))

        # Unshelve should unshelve 01
        self.run_bzr('unshelve', '--all', retcode=0)
        self.assertEqual(file('test_file2').read(), self.MODIFIED)

    def test_shelf_gaps(self):
        self.tree = self.make_branch_and_tree('.')
        self.__create_and_add_test_file()
        file('test_file', 'w').write(self.MODIFIED)
        self.run_bzr('shelve', '--all', 'test_file', retcode=0)
        file('test_file', 'w').write(self.MODIFIED)
        self.run_bzr('shelve', '--all', 'test_file', retcode=0)

        # Now delete 00, leaving 01, next shelve should go into 02
        self.run_bzr('shelf', 'delete', '0', retcode=0)
        self.assertFalse(os.path.exists('.shelf/shelves/default/00'))
        self.assertFalse(os.path.exists('.shelf/shelves/default/02'))
        file('test_file', 'w').write(self.MODIFIED)
        self.run_bzr('shelve', '--all', 'test_file', retcode=0)
        self.assertFalse(os.path.exists('.shelf/shelves/default/00'))
        self.assertTrue(os.path.exists('.shelf/shelves/default/02'))

    def test_shelf_upgrade(self):
        self.tree = self.make_branch_and_tree('.')

        self.__create_and_add_test_file()

        # Modify then shelve, so we're not upgrading to 00, just for kicks
        file('test_file', 'w').write(self.MODIFIED)
        self.run_bzr('shelve', '--all', 'test_file', retcode=0)

        open('.bzr-shelf', 'w').write('First old shelf')
        open('.bzr-shelf-1', 'w').write('Second old shelf')
        open('.bzr-shelf-3', 'w').write('Fourth old shelf')

        # shelve and unshelve should bitch and do nothing
        file('test_file', 'w').write('blah blah blah')
        self.run_bzr('shelve', '--all', retcode=3)
        self.assertFalse(os.path.exists('.shelf/shelves/default/01'))
        self.assertEqual(file('test_file').read(), 'blah blah blah')
        self.run_bzr('unshelve', '--all', retcode=3)
        self.assertTrue(os.path.exists('.shelf/shelves/default/00'))

        # Upgrade, make sure it worked
        self.run_bzr('shelf', 'upgrade', retcode=0)
        self.assertEqual(open('.shelf/shelves/default/01').read(),
                'First old shelf')
        self.assertEqual(open('.shelf/shelves/default/02').read(),
                'Second old shelf')
        self.assertEqual(open('.shelf/shelves/default/03').read(),
                'Fourth old shelf')

        # Check the old shelves got backed up right
        self.assertTrue(os.path.exists('.bzr-shelf~'))
        self.assertTrue(os.path.exists('.bzr-shelf-1~'))
        self.assertTrue(os.path.exists('.bzr-shelf-3~'))
        self.assertFalse(os.path.exists('.bzr-shelf'))
        self.assertFalse(os.path.exists('.bzr-shelf-1'))
        self.assertFalse(os.path.exists('.bzr-shelf-3'))

        # Shelve should work now
        self.run_bzr('shelve', '--all', retcode=0)

    def test_shelf_p1_patch(self):
        self.tree = self.make_branch_and_tree('.')

        self.__create_and_add_test_file()

        # Run a benign shelf command to setup .shelf for us
        self.run_bzr('shelf', 'ls', retcode=0)

        old_tree = self.tree.basis_tree()
        old_date = _patch_header_date(old_tree, 
                                      old_tree.inventory.path2id('test_file'),
                                      'test_file')
        new_date = _patch_header_date(self.tree, 
                                      self.tree.inventory.path2id('test_file'),
                                      'test_file')
        # Fake a -p0 shelved patch
        diff = self.DIFF_1 % { 'filename' : 'test_file', 'old_date': old_date,
                               'new_date' : new_date}
        diff = diff.replace('--- ', '--- a/')
        diff = diff.replace('+++ ', '+++ b/')
        open('.shelf/shelves/default/00', 'w').write(diff)

        # This should work
        self.run_bzr('unshelve', '--all', retcode=0)

        self._check_diff()

    def test_shelf_shelve_in_subdir(self):
        self.tree = self.make_branch_and_tree('.')

        subdir = 'subdir'
        os.mkdir(subdir)
        self.tree.add(subdir)
        os.chdir(subdir)

        self.__create_and_add_test_file()

        # Modify the test file
        # write in binary mode because on win32 line-endings should be LF
        f = file('test_file', 'wb')
        f.write(self.MODIFIED)
        f.close()

        # Shelve the changes
        self.run_bzr('shelve', '--all', retcode=0)

        # Working tree should be unchanged
        diff = self.capture('diff', retcode=0)
        self.assertEqual(diff, '')

        # Unshelve, should succeed
        self.run_bzr('unshelve', '--all', retcode=0)

        self._check_diff(filename='subdir/test_file')

        # Make sure relative filenames work ok
        self.run_bzr('shelve', 'test_file', '--all', retcode=0)

    def test_shelf_shelf_bogus_subcommand(self):
        self.tree = self.make_branch_and_tree('.')
        self.run_bzr('shelf', 'foo', retcode=3) # <- retcode == 3

    def test_shelf_OOO_unshelve(self):
        self.tree = self.make_branch_and_tree('.')

        for i in range(1, 5):
            self.__create_and_add_test_file(filename='test_file%d' % i)

        # Modify the test files
        for i in range(1, 5):
            file('test_file%d' % i, 'w').write(self.MODIFIED)

        # Shelve the changes
        for i in range(1, 5):
            self.run_bzr('shelve', '--all', 'test_file%d' % i, retcode=0)

        # Check shelving worked
        for i in range(1, 5):
            self.assertEqual(file('test_file%d' % i).read(), self.ORIGINAL)

        # We should now have 00-03
        for i in range(0, 4):
            self.assertTrue(os.path.exists('.shelf/shelves/default/0%d' % i))

        # Unshelve 00
        self.run_bzr('unshelve', '--all', '00', retcode=0)
        self.assertEqual(file('test_file1').read(), self.MODIFIED)

        # Check ls works
        lines = self.capture('shelf ls', retcode=0).split('\n')
        for line in lines:
            self.assertFalse(line.startswith(' 00'))

        # Check we can reshelve once we've unshelved out of order, should be 04
        self.assertFalse(os.path.exists('.shelf/shelves/default/04'))
        self.run_bzr('shelve', '--all')
        self.assertTrue(os.path.exists('.shelf/shelves/default/04'))

        # Check ls works
        text = self.capture('shelf ls', retcode=0)
        for line in text.split('\n'):
            self.assertFalse(line.startswith(' 00'))

        # We now have 01,02,03,04
        # Unshelve 02
        self.run_bzr('unshelve', '--all', '02', retcode=0)
        self.assertEqual(file('test_file3').read(), self.MODIFIED)

        # Unshelve the default, this is the reshelved 00, hence modifies file 1
        self.run_bzr('unshelve', '--all', retcode=0)
        self.assertEqual(file('test_file1').read(), self.MODIFIED)

    def test_shelf_switch_basic(self):
        self.tree = self.make_branch_and_tree('.')
        self.__create_and_add_test_file()

        # This should go to "default"
        file('test_file', 'w').write(self.MODIFIED)
        self.run_bzr('shelve', '--all', 'test_file', retcode=0)

        # Switch to "other"
        self.run_bzr('shelf', 'switch', 'other', retcode=0)
        file('test_file', 'w').write(self.MODIFIED)
        self.run_bzr('shelve', '--all', 'test_file', retcode=0)

        # Check it worked
        self.assertTrue(os.path.exists('.shelf/shelves/default/00'))
        self.assertFalse(os.path.exists('.shelf/shelves/default/01'))
        self.assertTrue(os.path.exists('.shelf/shelves/other/00'))

        # Switch back
        self.run_bzr('shelf', 'switch', 'default', retcode=0)
        file('test_file', 'w').write(self.MODIFIED)
        self.run_bzr('shelve', '--all', 'test_file', retcode=0)

        # Check that worked
        self.assertTrue(os.path.exists('.shelf/shelves/default/01'))
        self.assertFalse(os.path.exists('.shelf/shelves/other/01'))

    def test_shelf_bad_patch_arg(self):
        self.tree = self.make_branch_and_tree('.')

        # Check the bad arg handling
        stdout, error = self.run_bzr_captured(['unshelve', '01'], retcode=3)
        self.assertTrue("Patch '01' doesn't exist on shelf" in error)

        stdout, error = self.run_bzr_captured(['unshelve', 'foo'], retcode=3)
        self.assertTrue("Invalid patch name 'foo'" in error)

        # Hex and is cracky, so it shouldn't work
        stdout, error = self.run_bzr_captured(['unshelve', '0x00'], retcode=3)
        self.assertTrue("Invalid patch name '0x00'" in error)

    def test_color_hunk_selector(self):
        """Make sure NoColor is raised iff terminal.has_ansi_colors is False"""
        hs = ShelveHunkSelector([])
        hs = UnshelveHunkSelector([])
        try:
            from bzrlib.plugins.bzrtools import terminal
        except ImportError:
            from bzrtools import terminal
        old_has_ansi_colors = terminal.has_ansi_colors
        terminal.has_ansi_colors = lambda: False
        try:
            self.assertRaises(NoColor, ShelveHunkSelector, [], True)
            self.assertRaises(NoColor, UnshelveHunkSelector, [], True)
            terminal.has_ansi_colors = lambda: True
            hs = ShelveHunkSelector([], color=True)
            hs = UnshelveHunkSelector([], color=True)
        finally:
            terminal.has_ansi_colors = old_has_ansi_colors

    def test_no_color(self):
        """Ensure --no-color switch can be passed"""
        self.tree = self.make_branch_and_tree('.')

        subdir = 'subdir'
        os.mkdir(subdir)
        self.tree.add(subdir)
        os.chdir(subdir)

        self.__create_and_add_test_file()

        # Modify the test file
        # write in binary mode because on win32 line-endings should be LF
        f = file('test_file', 'wb')
        f.write(self.MODIFIED)
        f.close()
        stdout, error = self.run_bzr_captured(['shelve', '--all', 
                                               '--no-color'])
        stdout, error = self.run_bzr_captured(['unshelve', '--all', 
                                               '--no-color'])
