~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_dirstate.py

  • Committer: Colin Watson
  • Date: 2015-07-02 10:37:05 UTC
  • mto: This revision was merged to the branch mainline in revision 6605.
  • Revision ID: cjwatson@canonical.com-20150702103705-zdfslk3wb70sz37n
Avoid associating dirty patch headers with the previous file in the patch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2006-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""Tests of the dirstate functionality being built for WorkingTreeFormat4."""
18
18
 
19
 
import bisect
20
19
import os
21
 
import time
 
20
import tempfile
22
21
 
23
22
from bzrlib import (
 
23
    controldir,
24
24
    dirstate,
25
25
    errors,
 
26
    inventory,
 
27
    memorytree,
26
28
    osutils,
27
 
    )
28
 
from bzrlib.memorytree import MemoryTree
29
 
from bzrlib.tests import TestCase, TestCaseWithTransport
 
29
    revision as _mod_revision,
 
30
    revisiontree,
 
31
    tests,
 
32
    workingtree_4,
 
33
    )
 
34
from bzrlib.tests import (
 
35
    features,
 
36
    test_osutils,
 
37
    )
 
38
from bzrlib.tests.scenarios import load_tests_apply_scenarios
30
39
 
31
40
 
32
41
# TODO:
42
51
# set_path_id  setting id when state is in memory modified
43
52
 
44
53
 
45
 
class TestCaseWithDirState(TestCaseWithTransport):
 
54
load_tests = load_tests_apply_scenarios
 
55
 
 
56
 
 
57
class TestCaseWithDirState(tests.TestCaseWithTransport):
46
58
    """Helper functions for creating DirState objects with various content."""
47
59
 
 
60
    scenarios = test_osutils.dir_reader_scenarios()
 
61
 
 
62
    # Set by load_tests
 
63
    _dir_reader_class = None
 
64
    _native_to_unicode = None # Not used yet
 
65
 
 
66
    def setUp(self):
 
67
        super(TestCaseWithDirState, self).setUp()
 
68
        self.overrideAttr(osutils,
 
69
                          '_selected_dir_reader', self._dir_reader_class())
 
70
 
48
71
    def create_empty_dirstate(self):
49
72
        """Return a locked but empty dirstate"""
50
73
        state = dirstate.DirState.initialize('dirstate')
97
120
         b/g      g-file
98
121
         b/h\xc3\xa5  h-\xc3\xa5-file  #This is u'\xe5' encoded into utf-8
99
122
 
100
 
        # Notice that a/e is an empty directory.
 
123
        Notice that a/e is an empty directory.
 
124
 
 
125
        :return: The dirstate, still write-locked.
101
126
        """
102
127
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
103
128
        null_sha = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
156
181
        """
157
182
        # The state should already be write locked, since we just had to do
158
183
        # some operation to get here.
159
 
        assert state._lock_token is not None
 
184
        self.assertTrue(state._lock_token is not None)
160
185
        try:
161
186
            self.assertEqual(expected_result[0],  state.get_parent_ids())
162
187
            # there should be no ghosts in this tree.
166
191
            state.save()
167
192
        finally:
168
193
            state.unlock()
169
 
        del state # Callers should unlock
 
194
        del state
170
195
        state = dirstate.DirState.on_file('dirstate')
171
196
        state.lock_read()
172
197
        try:
174
199
        finally:
175
200
            state.unlock()
176
201
 
 
202
    def create_basic_dirstate(self):
 
203
        """Create a dirstate with a few files and directories.
 
204
 
 
205
            a
 
206
            b/
 
207
              c
 
208
              d/
 
209
                e
 
210
            b-c
 
211
            f
 
212
        """
 
213
        tree = self.make_branch_and_tree('tree')
 
214
        paths = ['a', 'b/', 'b/c', 'b/d/', 'b/d/e', 'b-c', 'f']
 
215
        file_ids = ['a-id', 'b-id', 'c-id', 'd-id', 'e-id', 'b-c-id', 'f-id']
 
216
        self.build_tree(['tree/' + p for p in paths])
 
217
        tree.set_root_id('TREE_ROOT')
 
218
        tree.add([p.rstrip('/') for p in paths], file_ids)
 
219
        tree.commit('initial', rev_id='rev-1')
 
220
        revision_id = 'rev-1'
 
221
        # a_packed_stat = dirstate.pack_stat(os.stat('tree/a'))
 
222
        t = self.get_transport('tree')
 
223
        a_text = t.get_bytes('a')
 
224
        a_sha = osutils.sha_string(a_text)
 
225
        a_len = len(a_text)
 
226
        # b_packed_stat = dirstate.pack_stat(os.stat('tree/b'))
 
227
        # c_packed_stat = dirstate.pack_stat(os.stat('tree/b/c'))
 
228
        c_text = t.get_bytes('b/c')
 
229
        c_sha = osutils.sha_string(c_text)
 
230
        c_len = len(c_text)
 
231
        # d_packed_stat = dirstate.pack_stat(os.stat('tree/b/d'))
 
232
        # e_packed_stat = dirstate.pack_stat(os.stat('tree/b/d/e'))
 
233
        e_text = t.get_bytes('b/d/e')
 
234
        e_sha = osutils.sha_string(e_text)
 
235
        e_len = len(e_text)
 
236
        b_c_text = t.get_bytes('b-c')
 
237
        b_c_sha = osutils.sha_string(b_c_text)
 
238
        b_c_len = len(b_c_text)
 
239
        # f_packed_stat = dirstate.pack_stat(os.stat('tree/f'))
 
240
        f_text = t.get_bytes('f')
 
241
        f_sha = osutils.sha_string(f_text)
 
242
        f_len = len(f_text)
 
243
        null_stat = dirstate.DirState.NULLSTAT
 
244
        expected = {
 
245
            '':(('', '', 'TREE_ROOT'), [
 
246
                  ('d', '', 0, False, null_stat),
 
247
                  ('d', '', 0, False, revision_id),
 
248
                ]),
 
249
            'a':(('', 'a', 'a-id'), [
 
250
                   ('f', '', 0, False, null_stat),
 
251
                   ('f', a_sha, a_len, False, revision_id),
 
252
                 ]),
 
253
            'b':(('', 'b', 'b-id'), [
 
254
                  ('d', '', 0, False, null_stat),
 
255
                  ('d', '', 0, False, revision_id),
 
256
                 ]),
 
257
            'b/c':(('b', 'c', 'c-id'), [
 
258
                    ('f', '', 0, False, null_stat),
 
259
                    ('f', c_sha, c_len, False, revision_id),
 
260
                   ]),
 
261
            'b/d':(('b', 'd', 'd-id'), [
 
262
                    ('d', '', 0, False, null_stat),
 
263
                    ('d', '', 0, False, revision_id),
 
264
                   ]),
 
265
            'b/d/e':(('b/d', 'e', 'e-id'), [
 
266
                      ('f', '', 0, False, null_stat),
 
267
                      ('f', e_sha, e_len, False, revision_id),
 
268
                     ]),
 
269
            'b-c':(('', 'b-c', 'b-c-id'), [
 
270
                      ('f', '', 0, False, null_stat),
 
271
                      ('f', b_c_sha, b_c_len, False, revision_id),
 
272
                     ]),
 
273
            'f':(('', 'f', 'f-id'), [
 
274
                  ('f', '', 0, False, null_stat),
 
275
                  ('f', f_sha, f_len, False, revision_id),
 
276
                 ]),
 
277
        }
 
278
        state = dirstate.DirState.from_tree(tree, 'dirstate')
 
279
        try:
 
280
            state.save()
 
281
        finally:
 
282
            state.unlock()
 
283
        # Use a different object, to make sure nothing is pre-cached in memory.
 
284
        state = dirstate.DirState.on_file('dirstate')
 
285
        state.lock_read()
 
286
        self.addCleanup(state.unlock)
 
287
        self.assertEqual(dirstate.DirState.NOT_IN_MEMORY,
 
288
                         state._dirblock_state)
 
289
        # This is code is only really tested if we actually have to make more
 
290
        # than one read, so set the page size to something smaller.
 
291
        # We want it to contain about 2.2 records, so that we have a couple
 
292
        # records that we can read per attempt
 
293
        state._bisect_page_size = 200
 
294
        return tree, state, expected
 
295
 
 
296
    def create_duplicated_dirstate(self):
 
297
        """Create a dirstate with a deleted and added entries.
 
298
 
 
299
        This grabs a basic_dirstate, and then removes and re adds every entry
 
300
        with a new file id.
 
301
        """
 
302
        tree, state, expected = self.create_basic_dirstate()
 
303
        # Now we will just remove and add every file so we get an extra entry
 
304
        # per entry. Unversion in reverse order so we handle subdirs
 
305
        tree.unversion(['f-id', 'b-c-id', 'e-id', 'd-id', 'c-id', 'b-id', 'a-id'])
 
306
        tree.add(['a', 'b', 'b/c', 'b/d', 'b/d/e', 'b-c', 'f'],
 
307
                 ['a-id2', 'b-id2', 'c-id2', 'd-id2', 'e-id2', 'b-c-id2', 'f-id2'])
 
308
 
 
309
        # Update the expected dictionary.
 
310
        for path in ['a', 'b', 'b/c', 'b/d', 'b/d/e', 'b-c', 'f']:
 
311
            orig = expected[path]
 
312
            path2 = path + '2'
 
313
            # This record was deleted in the current tree
 
314
            expected[path] = (orig[0], [dirstate.DirState.NULL_PARENT_DETAILS,
 
315
                                        orig[1][1]])
 
316
            new_key = (orig[0][0], orig[0][1], orig[0][2]+'2')
 
317
            # And didn't exist in the basis tree
 
318
            expected[path2] = (new_key, [orig[1][0],
 
319
                                         dirstate.DirState.NULL_PARENT_DETAILS])
 
320
 
 
321
        # We will replace the 'dirstate' file underneath 'state', but that is
 
322
        # okay as lock as we unlock 'state' first.
 
323
        state.unlock()
 
324
        try:
 
325
            new_state = dirstate.DirState.from_tree(tree, 'dirstate')
 
326
            try:
 
327
                new_state.save()
 
328
            finally:
 
329
                new_state.unlock()
 
330
        finally:
 
331
            # But we need to leave state in a read-lock because we already have
 
332
            # a cleanup scheduled
 
333
            state.lock_read()
 
334
        return tree, state, expected
 
335
 
 
336
    def create_renamed_dirstate(self):
 
337
        """Create a dirstate with a few internal renames.
 
338
 
 
339
        This takes the basic dirstate, and moves the paths around.
 
340
        """
 
341
        tree, state, expected = self.create_basic_dirstate()
 
342
        # Rename a file
 
343
        tree.rename_one('a', 'b/g')
 
344
        # And a directory
 
345
        tree.rename_one('b/d', 'h')
 
346
 
 
347
        old_a = expected['a']
 
348
        expected['a'] = (old_a[0], [('r', 'b/g', 0, False, ''), old_a[1][1]])
 
349
        expected['b/g'] = (('b', 'g', 'a-id'), [old_a[1][0],
 
350
                                                ('r', 'a', 0, False, '')])
 
351
        old_d = expected['b/d']
 
352
        expected['b/d'] = (old_d[0], [('r', 'h', 0, False, ''), old_d[1][1]])
 
353
        expected['h'] = (('', 'h', 'd-id'), [old_d[1][0],
 
354
                                             ('r', 'b/d', 0, False, '')])
 
355
 
 
356
        old_e = expected['b/d/e']
 
357
        expected['b/d/e'] = (old_e[0], [('r', 'h/e', 0, False, ''),
 
358
                             old_e[1][1]])
 
359
        expected['h/e'] = (('h', 'e', 'e-id'), [old_e[1][0],
 
360
                                                ('r', 'b/d/e', 0, False, '')])
 
361
 
 
362
        state.unlock()
 
363
        try:
 
364
            new_state = dirstate.DirState.from_tree(tree, 'dirstate')
 
365
            try:
 
366
                new_state.save()
 
367
            finally:
 
368
                new_state.unlock()
 
369
        finally:
 
370
            state.lock_read()
 
371
        return tree, state, expected
 
372
 
177
373
 
178
374
class TestTreeToDirState(TestCaseWithDirState):
179
375
 
182
378
        # There are no files on disk and no parents
183
379
        tree = self.make_branch_and_tree('tree')
184
380
        expected_result = ([], [
185
 
            (('', '', tree.path2id('')), # common details
 
381
            (('', '', tree.get_root_id()), # common details
186
382
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
187
383
             ])])
188
384
        state = dirstate.DirState.from_tree(tree, 'dirstate')
195
391
        rev_id = tree.commit('first post').encode('utf8')
196
392
        root_stat_pack = dirstate.pack_stat(os.stat(tree.basedir))
197
393
        expected_result = ([rev_id], [
198
 
            (('', '', tree.path2id('')), # common details
 
394
            (('', '', tree.get_root_id()), # common details
199
395
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
200
396
              ('d', '', 0, False, rev_id), # first parent details
201
397
             ])])
202
398
        state = dirstate.DirState.from_tree(tree, 'dirstate')
203
399
        self.check_state_with_reopen(expected_result, state)
204
 
        state._validate()
 
400
        state.lock_read()
 
401
        try:
 
402
            state._validate()
 
403
        finally:
 
404
            state.unlock()
205
405
 
206
406
    def test_2_parents_empty_to_dirstate(self):
207
407
        # create a parent by doing a commit
211
411
        rev_id2 = tree2.commit('second post', allow_pointless=True)
212
412
        tree.merge_from_branch(tree2.branch)
213
413
        expected_result = ([rev_id, rev_id2], [
214
 
            (('', '', tree.path2id('')), # common details
 
414
            (('', '', tree.get_root_id()), # common details
215
415
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
216
416
              ('d', '', 0, False, rev_id), # first parent details
217
 
              ('d', '', 0, False, rev_id2), # second parent details
 
417
              ('d', '', 0, False, rev_id), # second parent details
218
418
             ])])
219
419
        state = dirstate.DirState.from_tree(tree, 'dirstate')
220
420
        self.check_state_with_reopen(expected_result, state)
221
 
        state._validate()
 
421
        state.lock_read()
 
422
        try:
 
423
            state._validate()
 
424
        finally:
 
425
            state.unlock()
222
426
 
223
427
    def test_empty_unknowns_are_ignored_to_dirstate(self):
224
428
        """We should be able to create a dirstate for an empty tree."""
226
430
        tree = self.make_branch_and_tree('tree')
227
431
        self.build_tree(['tree/unknown'])
228
432
        expected_result = ([], [
229
 
            (('', '', tree.path2id('')), # common details
 
433
            (('', '', tree.get_root_id()), # common details
230
434
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
231
435
             ])])
232
436
        state = dirstate.DirState.from_tree(tree, 'dirstate')
235
439
    def get_tree_with_a_file(self):
236
440
        tree = self.make_branch_and_tree('tree')
237
441
        self.build_tree(['tree/a file'])
238
 
        tree.add('a file', 'a file id')
 
442
        tree.add('a file', 'a-file-id')
239
443
        return tree
240
444
 
241
445
    def test_non_empty_no_parents_to_dirstate(self):
243
447
        # There are files on disk and no parents
244
448
        tree = self.get_tree_with_a_file()
245
449
        expected_result = ([], [
246
 
            (('', '', tree.path2id('')), # common details
 
450
            (('', '', tree.get_root_id()), # common details
247
451
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
248
452
             ]),
249
 
            (('', 'a file', 'a file id'), # common
 
453
            (('', 'a file', 'a-file-id'), # common
250
454
             [('f', '', 0, False, dirstate.DirState.NULLSTAT), # current
251
455
             ]),
252
456
            ])
261
465
        # and length:
262
466
        self.build_tree_contents([('tree/a file', 'new content\n')])
263
467
        expected_result = ([rev_id], [
264
 
            (('', '', tree.path2id('')), # common details
 
468
            (('', '', tree.get_root_id()), # common details
265
469
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
266
470
              ('d', '', 0, False, rev_id), # first parent details
267
471
             ]),
268
 
            (('', 'a file', 'a file id'), # common
 
472
            (('', 'a file', 'a-file-id'), # common
269
473
             [('f', '', 0, False, dirstate.DirState.NULLSTAT), # current
270
474
              ('f', 'c3ed76e4bfd45ff1763ca206055bca8e9fc28aa8', 24, False,
271
475
               rev_id), # first parent
288
492
        # and length again, giving us three distinct values:
289
493
        self.build_tree_contents([('tree/a file', 'new content\n')])
290
494
        expected_result = ([rev_id, rev_id2], [
291
 
            (('', '', tree.path2id('')), # common details
 
495
            (('', '', tree.get_root_id()), # common details
292
496
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
293
497
              ('d', '', 0, False, rev_id), # first parent details
294
 
              ('d', '', 0, False, rev_id2), # second parent details
 
498
              ('d', '', 0, False, rev_id), # second parent details
295
499
             ]),
296
 
            (('', 'a file', 'a file id'), # common
 
500
            (('', 'a file', 'a-file-id'), # common
297
501
             [('f', '', 0, False, dirstate.DirState.NULLSTAT), # current
298
502
              ('f', 'c3ed76e4bfd45ff1763ca206055bca8e9fc28aa8', 24, False,
299
503
               rev_id), # first parent
329
533
 
330
534
class TestDirStateOnFile(TestCaseWithDirState):
331
535
 
 
536
    def create_updated_dirstate(self):
 
537
        self.build_tree(['a-file'])
 
538
        tree = self.make_branch_and_tree('.')
 
539
        tree.add(['a-file'], ['a-id'])
 
540
        tree.commit('add a-file')
 
541
        # Save and unlock the state, re-open it in readonly mode
 
542
        state = dirstate.DirState.from_tree(tree, 'dirstate')
 
543
        state.save()
 
544
        state.unlock()
 
545
        state = dirstate.DirState.on_file('dirstate')
 
546
        state.lock_read()
 
547
        return state
 
548
 
332
549
    def test_construct_with_path(self):
333
550
        tree = self.make_branch_and_tree('tree')
334
551
        state = dirstate.DirState.from_tree(tree, 'dirstate.from_tree')
340
557
        # get a state object
341
558
        # no parents, default tree content
342
559
        expected_result = ([], [
343
 
            (('', '', tree.path2id('')), # common details
 
560
            (('', '', tree.get_root_id()), # common details
344
561
             # current tree details, but new from_tree skips statting, it
345
562
             # uses set_state_from_inventory, and thus depends on the
346
563
             # inventory state.
362
579
        finally:
363
580
            state.unlock()
364
581
 
 
582
    def test_can_save_in_read_lock(self):
 
583
        state = self.create_updated_dirstate()
 
584
        try:
 
585
            entry = state._get_entry(0, path_utf8='a-file')
 
586
            # The current size should be 0 (default)
 
587
            self.assertEqual(0, entry[1][0][2])
 
588
            # We should have a real entry.
 
589
            self.assertNotEqual((None, None), entry)
 
590
            # Set the cutoff-time into the future, so things look cacheable
 
591
            state._sha_cutoff_time()
 
592
            state._cutoff_time += 10.0
 
593
            st = os.lstat('a-file')
 
594
            sha1sum = dirstate.update_entry(state, entry, 'a-file', st)
 
595
            # We updated the current sha1sum because the file is cacheable
 
596
            self.assertEqual('ecc5374e9ed82ad3ea3b4d452ea995a5fd3e70e3',
 
597
                             sha1sum)
 
598
 
 
599
            # The dirblock has been updated
 
600
            self.assertEqual(st.st_size, entry[1][0][2])
 
601
            self.assertEqual(dirstate.DirState.IN_MEMORY_HASH_MODIFIED,
 
602
                             state._dirblock_state)
 
603
 
 
604
            del entry
 
605
            # Now, since we are the only one holding a lock, we should be able
 
606
            # to save and have it written to disk
 
607
            state.save()
 
608
        finally:
 
609
            state.unlock()
 
610
 
 
611
        # Re-open the file, and ensure that the state has been updated.
 
612
        state = dirstate.DirState.on_file('dirstate')
 
613
        state.lock_read()
 
614
        try:
 
615
            entry = state._get_entry(0, path_utf8='a-file')
 
616
            self.assertEqual(st.st_size, entry[1][0][2])
 
617
        finally:
 
618
            state.unlock()
 
619
 
 
620
    def test_save_fails_quietly_if_locked(self):
 
621
        """If dirstate is locked, save will fail without complaining."""
 
622
        state = self.create_updated_dirstate()
 
623
        try:
 
624
            entry = state._get_entry(0, path_utf8='a-file')
 
625
            # No cached sha1 yet.
 
626
            self.assertEqual('', entry[1][0][1])
 
627
            # Set the cutoff-time into the future, so things look cacheable
 
628
            state._sha_cutoff_time()
 
629
            state._cutoff_time += 10.0
 
630
            st = os.lstat('a-file')
 
631
            sha1sum = dirstate.update_entry(state, entry, 'a-file', st)
 
632
            self.assertEqual('ecc5374e9ed82ad3ea3b4d452ea995a5fd3e70e3',
 
633
                             sha1sum)
 
634
            self.assertEqual(dirstate.DirState.IN_MEMORY_HASH_MODIFIED,
 
635
                             state._dirblock_state)
 
636
 
 
637
            # Now, before we try to save, grab another dirstate, and take out a
 
638
            # read lock.
 
639
            # TODO: jam 20070315 Ideally this would be locked by another
 
640
            #       process. To make sure the file is really OS locked.
 
641
            state2 = dirstate.DirState.on_file('dirstate')
 
642
            state2.lock_read()
 
643
            try:
 
644
                # This won't actually write anything, because it couldn't grab
 
645
                # a write lock. But it shouldn't raise an error, either.
 
646
                # TODO: jam 20070315 We should probably distinguish between
 
647
                #       being dirty because of 'update_entry'. And dirty
 
648
                #       because of real modification. So that save() *does*
 
649
                #       raise a real error if it fails when we have real
 
650
                #       modifications.
 
651
                state.save()
 
652
            finally:
 
653
                state2.unlock()
 
654
        finally:
 
655
            state.unlock()
 
656
 
 
657
        # The file on disk should not be modified.
 
658
        state = dirstate.DirState.on_file('dirstate')
 
659
        state.lock_read()
 
660
        try:
 
661
            entry = state._get_entry(0, path_utf8='a-file')
 
662
            self.assertEqual('', entry[1][0][1])
 
663
        finally:
 
664
            state.unlock()
 
665
 
 
666
    def test_save_refuses_if_changes_aborted(self):
 
667
        self.build_tree(['a-file', 'a-dir/'])
 
668
        state = dirstate.DirState.initialize('dirstate')
 
669
        try:
 
670
            # No stat and no sha1 sum.
 
671
            state.add('a-file', 'a-file-id', 'file', None, '')
 
672
            state.save()
 
673
        finally:
 
674
            state.unlock()
 
675
 
 
676
        # The dirstate should include TREE_ROOT and 'a-file' and nothing else
 
677
        expected_blocks = [
 
678
            ('', [(('', '', 'TREE_ROOT'),
 
679
                   [('d', '', 0, False, dirstate.DirState.NULLSTAT)])]),
 
680
            ('', [(('', 'a-file', 'a-file-id'),
 
681
                   [('f', '', 0, False, dirstate.DirState.NULLSTAT)])]),
 
682
        ]
 
683
 
 
684
        state = dirstate.DirState.on_file('dirstate')
 
685
        state.lock_write()
 
686
        try:
 
687
            state._read_dirblocks_if_needed()
 
688
            self.assertEqual(expected_blocks, state._dirblocks)
 
689
 
 
690
            # Now modify the state, but mark it as inconsistent
 
691
            state.add('a-dir', 'a-dir-id', 'directory', None, '')
 
692
            state._changes_aborted = True
 
693
            state.save()
 
694
        finally:
 
695
            state.unlock()
 
696
 
 
697
        state = dirstate.DirState.on_file('dirstate')
 
698
        state.lock_read()
 
699
        try:
 
700
            state._read_dirblocks_if_needed()
 
701
            self.assertEqual(expected_blocks, state._dirblocks)
 
702
        finally:
 
703
            state.unlock()
 
704
 
365
705
 
366
706
class TestDirStateInitialize(TestCaseWithDirState):
367
707
 
375
715
        try:
376
716
            self.assertIsInstance(state, dirstate.DirState)
377
717
            lines = state.get_lines()
378
 
            self.assertFileEqual(''.join(state.get_lines()),
379
 
                'dirstate')
380
 
            self.check_state_with_reopen(expected_result, state)
381
 
        except:
 
718
        finally:
382
719
            state.unlock()
383
 
            raise
 
720
        # On win32 you can't read from a locked file, even within the same
 
721
        # process. So we have to unlock and release before we check the file
 
722
        # contents.
 
723
        self.assertFileEqual(''.join(lines), 'dirstate')
 
724
        state.lock_read() # check_state_with_reopen will unlock
 
725
        self.check_state_with_reopen(expected_result, state)
384
726
 
385
727
 
386
728
class TestDirStateManipulations(TestCaseWithDirState):
387
729
 
 
730
    def make_minimal_tree(self):
 
731
        tree1 = self.make_branch_and_memory_tree('tree1')
 
732
        tree1.lock_write()
 
733
        self.addCleanup(tree1.unlock)
 
734
        tree1.add('')
 
735
        revid1 = tree1.commit('foo')
 
736
        return tree1, revid1
 
737
 
 
738
    def test_update_minimal_updates_id_index(self):
 
739
        state = self.create_dirstate_with_root_and_subdir()
 
740
        self.addCleanup(state.unlock)
 
741
        id_index = state._get_id_index()
 
742
        self.assertEqual(['a-root-value', 'subdir-id'], sorted(id_index))
 
743
        state.add('file-name', 'file-id', 'file', None, '')
 
744
        self.assertEqual(['a-root-value', 'file-id', 'subdir-id'],
 
745
                         sorted(id_index))
 
746
        state.update_minimal(('', 'new-name', 'file-id'), 'f',
 
747
                             path_utf8='new-name')
 
748
        self.assertEqual(['a-root-value', 'file-id', 'subdir-id'],
 
749
                         sorted(id_index))
 
750
        self.assertEqual([('', 'new-name', 'file-id')],
 
751
                         sorted(id_index['file-id']))
 
752
        state._validate()
 
753
 
388
754
    def test_set_state_from_inventory_no_content_no_parents(self):
389
755
        # setting the current inventory is a slow but important api to support.
390
 
        tree1 = self.make_branch_and_memory_tree('tree1')
391
 
        tree1.lock_write()
392
 
        try:
393
 
            tree1.add('')
394
 
            revid1 = tree1.commit('foo').encode('utf8')
395
 
            root_id = tree1.inventory.root.file_id
396
 
            inv = tree1.inventory
397
 
        finally:
398
 
            tree1.unlock()
 
756
        tree1, revid1 = self.make_minimal_tree()
 
757
        inv = tree1.root_inventory
 
758
        root_id = inv.path2id('')
399
759
        expected_result = [], [
400
760
            (('', '', root_id), [
401
761
             ('d', '', 0, False, dirstate.DirState.NULLSTAT)])]
413
773
            # This will unlock it
414
774
            self.check_state_with_reopen(expected_result, state)
415
775
 
 
776
    def test_set_state_from_scratch_no_parents(self):
 
777
        tree1, revid1 = self.make_minimal_tree()
 
778
        inv = tree1.root_inventory
 
779
        root_id = inv.path2id('')
 
780
        expected_result = [], [
 
781
            (('', '', root_id), [
 
782
             ('d', '', 0, False, dirstate.DirState.NULLSTAT)])]
 
783
        state = dirstate.DirState.initialize('dirstate')
 
784
        try:
 
785
            state.set_state_from_scratch(inv, [], [])
 
786
            self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
 
787
                             state._header_state)
 
788
            self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
 
789
                             state._dirblock_state)
 
790
        except:
 
791
            state.unlock()
 
792
            raise
 
793
        else:
 
794
            # This will unlock it
 
795
            self.check_state_with_reopen(expected_result, state)
 
796
 
 
797
    def test_set_state_from_scratch_identical_parent(self):
 
798
        tree1, revid1 = self.make_minimal_tree()
 
799
        inv = tree1.root_inventory
 
800
        root_id = inv.path2id('')
 
801
        rev_tree1 = tree1.branch.repository.revision_tree(revid1)
 
802
        d_entry = ('d', '', 0, False, dirstate.DirState.NULLSTAT)
 
803
        parent_entry = ('d', '', 0, False, revid1)
 
804
        expected_result = [revid1], [
 
805
            (('', '', root_id), [d_entry, parent_entry])]
 
806
        state = dirstate.DirState.initialize('dirstate')
 
807
        try:
 
808
            state.set_state_from_scratch(inv, [(revid1, rev_tree1)], [])
 
809
            self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
 
810
                             state._header_state)
 
811
            self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
 
812
                             state._dirblock_state)
 
813
        except:
 
814
            state.unlock()
 
815
            raise
 
816
        else:
 
817
            # This will unlock it
 
818
            self.check_state_with_reopen(expected_result, state)
 
819
 
 
820
    def test_set_state_from_inventory_preserves_hashcache(self):
 
821
        # https://bugs.launchpad.net/bzr/+bug/146176
 
822
        # set_state_from_inventory should preserve the stat and hash value for
 
823
        # workingtree files that are not changed by the inventory.
 
824
 
 
825
        tree = self.make_branch_and_tree('.')
 
826
        # depends on the default format using dirstate...
 
827
        tree.lock_write()
 
828
        try:
 
829
            # make a dirstate with some valid hashcache data
 
830
            # file on disk, but that's not needed for this test
 
831
            foo_contents = 'contents of foo'
 
832
            self.build_tree_contents([('foo', foo_contents)])
 
833
            tree.add('foo', 'foo-id')
 
834
 
 
835
            foo_stat = os.stat('foo')
 
836
            foo_packed = dirstate.pack_stat(foo_stat)
 
837
            foo_sha = osutils.sha_string(foo_contents)
 
838
            foo_size = len(foo_contents)
 
839
 
 
840
            # should not be cached yet, because the file's too fresh
 
841
            self.assertEqual(
 
842
                (('', 'foo', 'foo-id',),
 
843
                 [('f', '', 0, False, dirstate.DirState.NULLSTAT)]),
 
844
                tree._dirstate._get_entry(0, 'foo-id'))
 
845
            # poke in some hashcache information - it wouldn't normally be
 
846
            # stored because it's too fresh
 
847
            tree._dirstate.update_minimal(
 
848
                ('', 'foo', 'foo-id'),
 
849
                'f', False, foo_sha, foo_packed, foo_size, 'foo')
 
850
            # now should be cached
 
851
            self.assertEqual(
 
852
                (('', 'foo', 'foo-id',),
 
853
                 [('f', foo_sha, foo_size, False, foo_packed)]),
 
854
                tree._dirstate._get_entry(0, 'foo-id'))
 
855
 
 
856
            # extract the inventory, and add something to it
 
857
            inv = tree._get_root_inventory()
 
858
            # should see the file we poked in...
 
859
            self.assertTrue(inv.has_id('foo-id'))
 
860
            self.assertTrue(inv.has_filename('foo'))
 
861
            inv.add_path('bar', 'file', 'bar-id')
 
862
            tree._dirstate._validate()
 
863
            # this used to cause it to lose its hashcache
 
864
            tree._dirstate.set_state_from_inventory(inv)
 
865
            tree._dirstate._validate()
 
866
        finally:
 
867
            tree.unlock()
 
868
 
 
869
        tree.lock_read()
 
870
        try:
 
871
            # now check that the state still has the original hashcache value
 
872
            state = tree._dirstate
 
873
            state._validate()
 
874
            foo_tuple = state._get_entry(0, path_utf8='foo')
 
875
            self.assertEqual(
 
876
                (('', 'foo', 'foo-id',),
 
877
                 [('f', foo_sha, len(foo_contents), False,
 
878
                   dirstate.pack_stat(foo_stat))]),
 
879
                foo_tuple)
 
880
        finally:
 
881
            tree.unlock()
 
882
 
 
883
    def test_set_state_from_inventory_mixed_paths(self):
 
884
        tree1 = self.make_branch_and_tree('tree1')
 
885
        self.build_tree(['tree1/a/', 'tree1/a/b/', 'tree1/a-b/',
 
886
                         'tree1/a/b/foo', 'tree1/a-b/bar'])
 
887
        tree1.lock_write()
 
888
        try:
 
889
            tree1.add(['a', 'a/b', 'a-b', 'a/b/foo', 'a-b/bar'],
 
890
                      ['a-id', 'b-id', 'a-b-id', 'foo-id', 'bar-id'])
 
891
            tree1.commit('rev1', rev_id='rev1')
 
892
            root_id = tree1.get_root_id()
 
893
            inv = tree1.root_inventory
 
894
        finally:
 
895
            tree1.unlock()
 
896
        expected_result1 = [('', '', root_id, 'd'),
 
897
                            ('', 'a', 'a-id', 'd'),
 
898
                            ('', 'a-b', 'a-b-id', 'd'),
 
899
                            ('a', 'b', 'b-id', 'd'),
 
900
                            ('a/b', 'foo', 'foo-id', 'f'),
 
901
                            ('a-b', 'bar', 'bar-id', 'f'),
 
902
                           ]
 
903
        expected_result2 = [('', '', root_id, 'd'),
 
904
                            ('', 'a', 'a-id', 'd'),
 
905
                            ('', 'a-b', 'a-b-id', 'd'),
 
906
                            ('a-b', 'bar', 'bar-id', 'f'),
 
907
                           ]
 
908
        state = dirstate.DirState.initialize('dirstate')
 
909
        try:
 
910
            state.set_state_from_inventory(inv)
 
911
            values = []
 
912
            for entry in state._iter_entries():
 
913
                values.append(entry[0] + entry[1][0][:1])
 
914
            self.assertEqual(expected_result1, values)
 
915
            del inv['b-id']
 
916
            state.set_state_from_inventory(inv)
 
917
            values = []
 
918
            for entry in state._iter_entries():
 
919
                values.append(entry[0] + entry[1][0][:1])
 
920
            self.assertEqual(expected_result2, values)
 
921
        finally:
 
922
            state.unlock()
 
923
 
416
924
    def test_set_path_id_no_parents(self):
417
925
        """The id of a path can be changed trivally with no parents."""
418
926
        state = dirstate.DirState.initialize('dirstate')
419
927
        try:
420
928
            # check precondition to be sure the state does change appropriately.
421
 
            self.assertEqual(
422
 
                [(('', '', 'TREE_ROOT'), [('d', '', 0, False,
423
 
                   'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')])],
424
 
                list(state._iter_entries()))
425
 
            state.set_path_id('', 'foobarbaz')
426
 
            expected_rows = [
427
 
                (('', '', 'foobarbaz'), [('d', '', 0, False,
428
 
                   'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')])]
 
929
            root_entry = (('', '', 'TREE_ROOT'), [('d', '', 0, False, 'x'*32)])
 
930
            self.assertEqual([root_entry], list(state._iter_entries()))
 
931
            self.assertEqual(root_entry, state._get_entry(0, path_utf8=''))
 
932
            self.assertEqual(root_entry,
 
933
                             state._get_entry(0, fileid_utf8='TREE_ROOT'))
 
934
            self.assertEqual((None, None),
 
935
                             state._get_entry(0, fileid_utf8='second-root-id'))
 
936
            state.set_path_id('', 'second-root-id')
 
937
            new_root_entry = (('', '', 'second-root-id'),
 
938
                              [('d', '', 0, False, 'x'*32)])
 
939
            expected_rows = [new_root_entry]
429
940
            self.assertEqual(expected_rows, list(state._iter_entries()))
 
941
            self.assertEqual(new_root_entry, state._get_entry(0, path_utf8=''))
 
942
            self.assertEqual(new_root_entry, 
 
943
                             state._get_entry(0, fileid_utf8='second-root-id'))
 
944
            self.assertEqual((None, None),
 
945
                             state._get_entry(0, fileid_utf8='TREE_ROOT'))
430
946
            # should work across save too
431
947
            state.save()
432
948
        finally:
433
949
            state.unlock()
434
950
        state = dirstate.DirState.on_file('dirstate')
435
 
        state._validate()
436
951
        state.lock_read()
437
952
        try:
 
953
            state._validate()
438
954
            self.assertEqual(expected_rows, list(state._iter_entries()))
439
955
        finally:
440
956
            state.unlock()
450
966
        state._validate()
451
967
        try:
452
968
            state.set_parent_trees([('parent-revid', rt)], ghosts=[])
453
 
            state.set_path_id('', 'foobarbaz')
 
969
            root_entry = (('', '', 'TREE_ROOT'),
 
970
                          [('d', '', 0, False, 'x'*32),
 
971
                           ('d', '', 0, False, 'parent-revid')])
 
972
            self.assertEqual(root_entry, state._get_entry(0, path_utf8=''))
 
973
            self.assertEqual(root_entry,
 
974
                             state._get_entry(0, fileid_utf8='TREE_ROOT'))
 
975
            self.assertEqual((None, None),
 
976
                             state._get_entry(0, fileid_utf8='Asecond-root-id'))
 
977
            state.set_path_id('', 'Asecond-root-id')
454
978
            state._validate()
455
979
            # now see that it is what we expected
456
 
            expected_rows = [
457
 
                (('', '', 'TREE_ROOT'),
458
 
                    [('a', '', 0, False, ''),
459
 
                     ('d', '', 0, False, 'parent-revid'),
460
 
                     ]),
461
 
                (('', '', 'foobarbaz'),
462
 
                    [('d', '', 0, False, ''),
463
 
                     ('a', '', 0, False, ''),
464
 
                     ]),
465
 
                ]
 
980
            old_root_entry = (('', '', 'TREE_ROOT'),
 
981
                              [('a', '', 0, False, ''),
 
982
                               ('d', '', 0, False, 'parent-revid')])
 
983
            new_root_entry = (('', '', 'Asecond-root-id'),
 
984
                              [('d', '', 0, False, ''),
 
985
                               ('a', '', 0, False, '')])
 
986
            expected_rows = [new_root_entry, old_root_entry]
466
987
            state._validate()
467
988
            self.assertEqual(expected_rows, list(state._iter_entries()))
 
989
            self.assertEqual(new_root_entry, state._get_entry(0, path_utf8=''))
 
990
            self.assertEqual(old_root_entry, state._get_entry(1, path_utf8=''))
 
991
            self.assertEqual((None, None),
 
992
                             state._get_entry(0, fileid_utf8='TREE_ROOT'))
 
993
            self.assertEqual(old_root_entry,
 
994
                             state._get_entry(1, fileid_utf8='TREE_ROOT'))
 
995
            self.assertEqual(new_root_entry,
 
996
                             state._get_entry(0, fileid_utf8='Asecond-root-id'))
 
997
            self.assertEqual((None, None),
 
998
                             state._get_entry(1, fileid_utf8='Asecond-root-id'))
468
999
            # should work across save too
469
1000
            state.save()
470
1001
        finally:
486
1017
        finally:
487
1018
            state.unlock()
488
1019
 
489
 
 
490
1020
    def test_set_parent_trees_no_content(self):
491
1021
        # set_parent_trees is a slow but important api to support.
492
1022
        tree1 = self.make_branch_and_memory_tree('tree1')
497
1027
        finally:
498
1028
            tree1.unlock()
499
1029
        branch2 = tree1.branch.bzrdir.clone('tree2').open_branch()
500
 
        tree2 = MemoryTree.create_on_branch(branch2)
 
1030
        tree2 = memorytree.MemoryTree.create_on_branch(branch2)
501
1031
        tree2.lock_write()
502
1032
        try:
503
1033
            revid2 = tree2.commit('foo')
504
 
            root_id = tree2.inventory.root.file_id
 
1034
            root_id = tree2.get_root_id()
505
1035
        finally:
506
1036
            tree2.unlock()
507
1037
        state = dirstate.DirState.initialize('dirstate')
535
1065
            state.set_parent_trees(
536
1066
                ((revid1, tree1.branch.repository.revision_tree(revid1)),
537
1067
                 (revid2, tree2.branch.repository.revision_tree(revid2)),
538
 
                 ('ghost-rev', tree2.branch.repository.revision_tree(None))),
 
1068
                 ('ghost-rev', tree2.branch.repository.revision_tree(
 
1069
                                   _mod_revision.NULL_REVISION))),
539
1070
                ['ghost-rev'])
540
1071
            self.assertEqual([revid1, revid2, 'ghost-rev'],
541
1072
                             state.get_parent_ids())
545
1076
                [(('', '', root_id), [
546
1077
                  ('d', '', 0, False, dirstate.DirState.NULLSTAT),
547
1078
                  ('d', '', 0, False, revid1),
548
 
                  ('d', '', 0, False, revid2)
 
1079
                  ('d', '', 0, False, revid1)
549
1080
                  ])],
550
1081
                list(state._iter_entries()))
551
1082
        finally:
566
1097
        finally:
567
1098
            tree1.unlock()
568
1099
        branch2 = tree1.branch.bzrdir.clone('tree2').open_branch()
569
 
        tree2 = MemoryTree.create_on_branch(branch2)
 
1100
        tree2 = memorytree.MemoryTree.create_on_branch(branch2)
570
1101
        tree2.lock_write()
571
1102
        try:
572
1103
            tree2.put_file_bytes_non_atomic('file-id', 'new file-content')
573
1104
            revid2 = tree2.commit('foo')
574
 
            root_id = tree2.inventory.root.file_id
 
1105
            root_id = tree2.get_root_id()
575
1106
        finally:
576
1107
            tree2.unlock()
577
1108
        # check the layout in memory
579
1110
            (('', '', root_id), [
580
1111
             ('d', '', 0, False, dirstate.DirState.NULLSTAT),
581
1112
             ('d', '', 0, False, revid1.encode('utf8')),
582
 
             ('d', '', 0, False, revid2.encode('utf8'))
 
1113
             ('d', '', 0, False, revid1.encode('utf8'))
583
1114
             ]),
584
1115
            (('', 'a file', 'file-id'), [
585
1116
             ('a', '', 0, False, ''),
617
1148
            (('', '', 'TREE_ROOT'), [
618
1149
             ('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
619
1150
             ]),
620
 
            (('', 'a file', 'a file id'), [
 
1151
            (('', 'a file', 'a-file-id'), [
621
1152
             ('f', '1'*20, 19, False, dirstate.pack_stat(stat)), # current tree
622
1153
             ]),
623
1154
            ]
624
1155
        try:
625
 
            state.add('a file', 'a file id', 'file', stat, '1'*20)
 
1156
            state.add('a file', 'a-file-id', 'file', stat, '1'*20)
626
1157
            # having added it, it should be in the output of iter_entries.
627
1158
            self.assertEqual(expected_entries, list(state._iter_entries()))
628
1159
            # saving and reloading should not affect this.
631
1162
            state.unlock()
632
1163
        state = dirstate.DirState.on_file('dirstate')
633
1164
        state.lock_read()
634
 
        try:
635
 
            self.assertEqual(expected_entries, list(state._iter_entries()))
636
 
        finally:
637
 
            state.unlock()
 
1165
        self.addCleanup(state.unlock)
 
1166
        self.assertEqual(expected_entries, list(state._iter_entries()))
638
1167
 
639
1168
    def test_add_path_to_unversioned_directory(self):
640
1169
        """Adding a path to an unversioned directory should error.
645
1174
        """
646
1175
        self.build_tree(['unversioned/', 'unversioned/a file'])
647
1176
        state = dirstate.DirState.initialize('dirstate')
648
 
        try:
649
 
            self.assertRaises(errors.NotVersionedError, state.add,
650
 
                'unversioned/a file', 'a file id', 'file', None, None)
651
 
        finally:
652
 
            state.unlock()
 
1177
        self.addCleanup(state.unlock)
 
1178
        self.assertRaises(errors.NotVersionedError, state.add,
 
1179
                          'unversioned/a file', 'a-file-id', 'file', None, None)
653
1180
 
654
1181
    def test_add_directory_to_root_no_parents_all_data(self):
655
1182
        # The most trivial addition of a dir is when there are no parents and
675
1202
            state.unlock()
676
1203
        state = dirstate.DirState.on_file('dirstate')
677
1204
        state.lock_read()
 
1205
        self.addCleanup(state.unlock)
678
1206
        state._validate()
 
1207
        self.assertEqual(expected_entries, list(state._iter_entries()))
 
1208
 
 
1209
    def _test_add_symlink_to_root_no_parents_all_data(self, link_name, target):
 
1210
        # The most trivial addition of a symlink when there are no parents and
 
1211
        # its in the root and all data about the file is supplied
 
1212
        # bzr doesn't support fake symlinks on windows, yet.
 
1213
        self.requireFeature(features.SymlinkFeature)
 
1214
        os.symlink(target, link_name)
 
1215
        stat = os.lstat(link_name)
 
1216
        expected_entries = [
 
1217
            (('', '', 'TREE_ROOT'), [
 
1218
             ('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
 
1219
             ]),
 
1220
            (('', link_name.encode('UTF-8'), 'a link id'), [
 
1221
             ('l', target.encode('UTF-8'), stat[6],
 
1222
              False, dirstate.pack_stat(stat)), # current tree
 
1223
             ]),
 
1224
            ]
 
1225
        state = dirstate.DirState.initialize('dirstate')
679
1226
        try:
 
1227
            state.add(link_name, 'a link id', 'symlink', stat,
 
1228
                      target.encode('UTF-8'))
 
1229
            # having added it, it should be in the output of iter_entries.
680
1230
            self.assertEqual(expected_entries, list(state._iter_entries()))
 
1231
            # saving and reloading should not affect this.
 
1232
            state.save()
681
1233
        finally:
682
1234
            state.unlock()
 
1235
        state = dirstate.DirState.on_file('dirstate')
 
1236
        state.lock_read()
 
1237
        self.addCleanup(state.unlock)
 
1238
        self.assertEqual(expected_entries, list(state._iter_entries()))
683
1239
 
684
1240
    def test_add_symlink_to_root_no_parents_all_data(self):
685
 
        # The most trivial addition of a symlink when there are no parents and
686
 
        # its in the root and all data about the file is supplied
687
 
        ## TODO: windows: dont fail this test. Also, how are symlinks meant to
688
 
        # be represented on windows.
689
 
        os.symlink('target', 'a link')
690
 
        stat = os.lstat('a link')
691
 
        expected_entries = [
692
 
            (('', '', 'TREE_ROOT'), [
693
 
             ('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
694
 
             ]),
695
 
            (('', 'a link', 'a link id'), [
696
 
             ('l', 'target', 6, False, dirstate.pack_stat(stat)), # current tree
697
 
             ]),
698
 
            ]
699
 
        state = dirstate.DirState.initialize('dirstate')
700
 
        try:
701
 
            state.add('a link', 'a link id', 'symlink', stat, 'target')
702
 
            # having added it, it should be in the output of iter_entries.
703
 
            self.assertEqual(expected_entries, list(state._iter_entries()))
704
 
            # saving and reloading should not affect this.
705
 
            state.save()
706
 
        finally:
707
 
            state.unlock()
708
 
        state = dirstate.DirState.on_file('dirstate')
709
 
        state.lock_read()
710
 
        try:
711
 
            self.assertEqual(expected_entries, list(state._iter_entries()))
712
 
        finally:
713
 
            state.unlock()
 
1241
        self._test_add_symlink_to_root_no_parents_all_data('a link', 'target')
 
1242
 
 
1243
    def test_add_symlink_unicode_to_root_no_parents_all_data(self):
 
1244
        self.requireFeature(features.UnicodeFilenameFeature)
 
1245
        self._test_add_symlink_to_root_no_parents_all_data(
 
1246
            u'\N{Euro Sign}link', u'targ\N{Euro Sign}et')
714
1247
 
715
1248
    def test_add_directory_and_child_no_parents_all_data(self):
716
1249
        # after adding a directory, we should be able to add children to it.
724
1257
            (('', 'a dir', 'a dir id'), [
725
1258
             ('d', '', 0, False, dirstate.pack_stat(dirstat)), # current tree
726
1259
             ]),
727
 
            (('a dir', 'a file', 'a file id'), [
 
1260
            (('a dir', 'a file', 'a-file-id'), [
728
1261
             ('f', '1'*20, 25, False,
729
1262
              dirstate.pack_stat(filestat)), # current tree details
730
1263
             ]),
732
1265
        state = dirstate.DirState.initialize('dirstate')
733
1266
        try:
734
1267
            state.add('a dir', 'a dir id', 'directory', dirstat, None)
735
 
            state.add('a dir/a file', 'a file id', 'file', filestat, '1'*20)
 
1268
            state.add('a dir/a file', 'a-file-id', 'file', filestat, '1'*20)
736
1269
            # added it, it should be in the output of iter_entries.
737
1270
            self.assertEqual(expected_entries, list(state._iter_entries()))
738
1271
            # saving and reloading should not affect this.
741
1274
            state.unlock()
742
1275
        state = dirstate.DirState.on_file('dirstate')
743
1276
        state.lock_read()
744
 
        try:
745
 
            self.assertEqual(expected_entries, list(state._iter_entries()))
746
 
        finally:
747
 
            state.unlock()
 
1277
        self.addCleanup(state.unlock)
 
1278
        self.assertEqual(expected_entries, list(state._iter_entries()))
748
1279
 
749
1280
    def test_add_tree_reference(self):
750
1281
        # make a dirstate and add a tree reference
764
1295
            state.unlock()
765
1296
        # now check we can read it back
766
1297
        state.lock_read()
 
1298
        self.addCleanup(state.unlock)
767
1299
        state._validate()
768
 
        try:
769
 
            entry2 = state._get_entry(0, 'subdir-id', 'subdir')
770
 
            self.assertEqual(entry, entry2)
771
 
            self.assertEqual(entry, expected_entry)
772
 
            # and lookup by id should work too
773
 
            entry2 = state._get_entry(0, fileid_utf8='subdir-id')
774
 
            self.assertEqual(entry, expected_entry)
775
 
        finally:
776
 
            state.unlock()
 
1300
        entry2 = state._get_entry(0, 'subdir-id', 'subdir')
 
1301
        self.assertEqual(entry, entry2)
 
1302
        self.assertEqual(entry, expected_entry)
 
1303
        # and lookup by id should work too
 
1304
        entry2 = state._get_entry(0, fileid_utf8='subdir-id')
 
1305
        self.assertEqual(entry, expected_entry)
777
1306
 
778
1307
    def test_add_forbidden_names(self):
779
1308
        state = dirstate.DirState.initialize('dirstate')
783
1312
        self.assertRaises(errors.BzrError,
784
1313
            state.add, '..', 'ass-id', 'directory', None, None)
785
1314
 
 
1315
    def test_set_state_with_rename_b_a_bug_395556(self):
 
1316
        # bug 395556 uncovered a bug where the dirstate ends up with a false
 
1317
        # relocation record - in a tree with no parents there should be no
 
1318
        # absent or relocated records. This then leads to further corruption
 
1319
        # when a commit occurs, as the incorrect relocation gathers an
 
1320
        # incorrect absent in tree 1, and future changes go to pot.
 
1321
        tree1 = self.make_branch_and_tree('tree1')
 
1322
        self.build_tree(['tree1/b'])
 
1323
        tree1.lock_write()
 
1324
        try:
 
1325
            tree1.add(['b'], ['b-id'])
 
1326
            root_id = tree1.get_root_id()
 
1327
            inv = tree1.root_inventory
 
1328
            state = dirstate.DirState.initialize('dirstate')
 
1329
            try:
 
1330
                # Set the initial state with 'b'
 
1331
                state.set_state_from_inventory(inv)
 
1332
                inv.rename('b-id', root_id, 'a')
 
1333
                # Set the new state with 'a', which currently corrupts.
 
1334
                state.set_state_from_inventory(inv)
 
1335
                expected_result1 = [('', '', root_id, 'd'),
 
1336
                                    ('', 'a', 'b-id', 'f'),
 
1337
                                   ]
 
1338
                values = []
 
1339
                for entry in state._iter_entries():
 
1340
                    values.append(entry[0] + entry[1][0][:1])
 
1341
                self.assertEqual(expected_result1, values)
 
1342
            finally:
 
1343
                state.unlock()
 
1344
        finally:
 
1345
            tree1.unlock()
 
1346
 
 
1347
 
 
1348
class TestDirStateHashUpdates(TestCaseWithDirState):
 
1349
 
 
1350
    def do_update_entry(self, state, path):
 
1351
        entry = state._get_entry(0, path_utf8=path)
 
1352
        stat = os.lstat(path)
 
1353
        return dirstate.update_entry(state, entry, os.path.abspath(path), stat)
 
1354
 
 
1355
    def _read_state_content(self, state):
 
1356
        """Read the content of the dirstate file.
 
1357
 
 
1358
        On Windows when one process locks a file, you can't even open() the
 
1359
        file in another process (to read it). So we go directly to
 
1360
        state._state_file. This should always be the exact disk representation,
 
1361
        so it is reasonable to do so.
 
1362
        DirState also always seeks before reading, so it doesn't matter if we
 
1363
        bump the file pointer.
 
1364
        """
 
1365
        state._state_file.seek(0)
 
1366
        return state._state_file.read()
 
1367
 
 
1368
    def test_worth_saving_limit_avoids_writing(self):
 
1369
        tree = self.make_branch_and_tree('.')
 
1370
        self.build_tree(['c', 'd'])
 
1371
        tree.lock_write()
 
1372
        tree.add(['c', 'd'], ['c-id', 'd-id'])
 
1373
        tree.commit('add c and d')
 
1374
        state = InstrumentedDirState.on_file(tree.current_dirstate()._filename,
 
1375
                                             worth_saving_limit=2)
 
1376
        tree.unlock()
 
1377
        state.lock_write()
 
1378
        self.addCleanup(state.unlock)
 
1379
        state._read_dirblocks_if_needed()
 
1380
        state.adjust_time(+20) # Allow things to be cached
 
1381
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
 
1382
                         state._dirblock_state)
 
1383
        content = self._read_state_content(state)
 
1384
        self.do_update_entry(state, 'c')
 
1385
        self.assertEqual(1, len(state._known_hash_changes))
 
1386
        self.assertEqual(dirstate.DirState.IN_MEMORY_HASH_MODIFIED,
 
1387
                         state._dirblock_state)
 
1388
        state.save()
 
1389
        # It should not have set the state to IN_MEMORY_UNMODIFIED because the
 
1390
        # hash values haven't been written out.
 
1391
        self.assertEqual(dirstate.DirState.IN_MEMORY_HASH_MODIFIED,
 
1392
                         state._dirblock_state)
 
1393
        self.assertEqual(content, self._read_state_content(state))
 
1394
        self.assertEqual(dirstate.DirState.IN_MEMORY_HASH_MODIFIED,
 
1395
                         state._dirblock_state)
 
1396
        self.do_update_entry(state, 'd')
 
1397
        self.assertEqual(2, len(state._known_hash_changes))
 
1398
        state.save()
 
1399
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
 
1400
                         state._dirblock_state)
 
1401
        self.assertEqual(0, len(state._known_hash_changes))
 
1402
 
786
1403
 
787
1404
class TestGetLines(TestCaseWithDirState):
788
1405
 
1001
1618
            state.unlock()
1002
1619
 
1003
1620
 
1004
 
class TestDirstateSortOrder(TestCaseWithTransport):
 
1621
class TestIterChildEntries(TestCaseWithDirState):
 
1622
 
 
1623
    def create_dirstate_with_two_trees(self):
 
1624
        """This dirstate contains multiple files and directories.
 
1625
 
 
1626
         /        a-root-value
 
1627
         a/       a-dir
 
1628
         b/       b-dir
 
1629
         c        c-file
 
1630
         d        d-file
 
1631
         a/e/     e-dir
 
1632
         a/f      f-file
 
1633
         b/g      g-file
 
1634
         b/h\xc3\xa5  h-\xc3\xa5-file  #This is u'\xe5' encoded into utf-8
 
1635
 
 
1636
        Notice that a/e is an empty directory.
 
1637
 
 
1638
        There is one parent tree, which has the same shape with the following variations:
 
1639
        b/g in the parent is gone.
 
1640
        b/h in the parent has a different id
 
1641
        b/i is new in the parent
 
1642
        c is renamed to b/j in the parent
 
1643
 
 
1644
        :return: The dirstate, still write-locked.
 
1645
        """
 
1646
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
 
1647
        null_sha = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
 
1648
        NULL_PARENT_DETAILS = dirstate.DirState.NULL_PARENT_DETAILS
 
1649
        root_entry = ('', '', 'a-root-value'), [
 
1650
            ('d', '', 0, False, packed_stat),
 
1651
            ('d', '', 0, False, 'parent-revid'),
 
1652
            ]
 
1653
        a_entry = ('', 'a', 'a-dir'), [
 
1654
            ('d', '', 0, False, packed_stat),
 
1655
            ('d', '', 0, False, 'parent-revid'),
 
1656
            ]
 
1657
        b_entry = ('', 'b', 'b-dir'), [
 
1658
            ('d', '', 0, False, packed_stat),
 
1659
            ('d', '', 0, False, 'parent-revid'),
 
1660
            ]
 
1661
        c_entry = ('', 'c', 'c-file'), [
 
1662
            ('f', null_sha, 10, False, packed_stat),
 
1663
            ('r', 'b/j', 0, False, ''),
 
1664
            ]
 
1665
        d_entry = ('', 'd', 'd-file'), [
 
1666
            ('f', null_sha, 20, False, packed_stat),
 
1667
            ('f', 'd', 20, False, 'parent-revid'),
 
1668
            ]
 
1669
        e_entry = ('a', 'e', 'e-dir'), [
 
1670
            ('d', '', 0, False, packed_stat),
 
1671
            ('d', '', 0, False, 'parent-revid'),
 
1672
            ]
 
1673
        f_entry = ('a', 'f', 'f-file'), [
 
1674
            ('f', null_sha, 30, False, packed_stat),
 
1675
            ('f', 'f', 20, False, 'parent-revid'),
 
1676
            ]
 
1677
        g_entry = ('b', 'g', 'g-file'), [
 
1678
            ('f', null_sha, 30, False, packed_stat),
 
1679
            NULL_PARENT_DETAILS,
 
1680
            ]
 
1681
        h_entry1 = ('b', 'h\xc3\xa5', 'h-\xc3\xa5-file1'), [
 
1682
            ('f', null_sha, 40, False, packed_stat),
 
1683
            NULL_PARENT_DETAILS,
 
1684
            ]
 
1685
        h_entry2 = ('b', 'h\xc3\xa5', 'h-\xc3\xa5-file2'), [
 
1686
            NULL_PARENT_DETAILS,
 
1687
            ('f', 'h', 20, False, 'parent-revid'),
 
1688
            ]
 
1689
        i_entry = ('b', 'i', 'i-file'), [
 
1690
            NULL_PARENT_DETAILS,
 
1691
            ('f', 'h', 20, False, 'parent-revid'),
 
1692
            ]
 
1693
        j_entry = ('b', 'j', 'c-file'), [
 
1694
            ('r', 'c', 0, False, ''),
 
1695
            ('f', 'j', 20, False, 'parent-revid'),
 
1696
            ]
 
1697
        dirblocks = []
 
1698
        dirblocks.append(('', [root_entry]))
 
1699
        dirblocks.append(('', [a_entry, b_entry, c_entry, d_entry]))
 
1700
        dirblocks.append(('a', [e_entry, f_entry]))
 
1701
        dirblocks.append(('b', [g_entry, h_entry1, h_entry2, i_entry, j_entry]))
 
1702
        state = dirstate.DirState.initialize('dirstate')
 
1703
        state._validate()
 
1704
        try:
 
1705
            state._set_data(['parent'], dirblocks)
 
1706
        except:
 
1707
            state.unlock()
 
1708
            raise
 
1709
        return state, dirblocks
 
1710
 
 
1711
    def test_iter_children_b(self):
 
1712
        state, dirblocks = self.create_dirstate_with_two_trees()
 
1713
        self.addCleanup(state.unlock)
 
1714
        expected_result = []
 
1715
        expected_result.append(dirblocks[3][1][2]) # h2
 
1716
        expected_result.append(dirblocks[3][1][3]) # i
 
1717
        expected_result.append(dirblocks[3][1][4]) # j
 
1718
        self.assertEqual(expected_result,
 
1719
            list(state._iter_child_entries(1, 'b')))
 
1720
 
 
1721
    def test_iter_child_root(self):
 
1722
        state, dirblocks = self.create_dirstate_with_two_trees()
 
1723
        self.addCleanup(state.unlock)
 
1724
        expected_result = []
 
1725
        expected_result.append(dirblocks[1][1][0]) # a
 
1726
        expected_result.append(dirblocks[1][1][1]) # b
 
1727
        expected_result.append(dirblocks[1][1][3]) # d
 
1728
        expected_result.append(dirblocks[2][1][0]) # e
 
1729
        expected_result.append(dirblocks[2][1][1]) # f
 
1730
        expected_result.append(dirblocks[3][1][2]) # h2
 
1731
        expected_result.append(dirblocks[3][1][3]) # i
 
1732
        expected_result.append(dirblocks[3][1][4]) # j
 
1733
        self.assertEqual(expected_result,
 
1734
            list(state._iter_child_entries(1, '')))
 
1735
 
 
1736
 
 
1737
class TestDirstateSortOrder(tests.TestCaseWithTransport):
1005
1738
    """Test that DirState adds entries in the right order."""
1006
1739
 
1007
1740
    def test_add_sorting(self):
1056
1789
 
1057
1790
        # *really* cheesy way to just get an empty tree
1058
1791
        repo = self.make_repository('repo')
1059
 
        empty_tree = repo.revision_tree(None)
 
1792
        empty_tree = repo.revision_tree(_mod_revision.NULL_REVISION)
1060
1793
        state.set_parent_trees([('null:', empty_tree)], [])
1061
1794
 
1062
1795
        dirblock_names = [d[0] for d in state._dirblocks]
1066
1799
class InstrumentedDirState(dirstate.DirState):
1067
1800
    """An DirState with instrumented sha1 functionality."""
1068
1801
 
1069
 
    def __init__(self, path):
1070
 
        super(InstrumentedDirState, self).__init__(path)
 
1802
    def __init__(self, path, sha1_provider, worth_saving_limit=0):
 
1803
        super(InstrumentedDirState, self).__init__(path, sha1_provider,
 
1804
            worth_saving_limit=worth_saving_limit)
1071
1805
        self._time_offset = 0
1072
1806
        self._log = []
 
1807
        # member is dynamically set in DirState.__init__ to turn on trace
 
1808
        self._sha1_provider = sha1_provider
 
1809
        self._sha1_file = self._sha1_file_and_log
1073
1810
 
1074
1811
    def _sha_cutoff_time(self):
1075
1812
        timestamp = super(InstrumentedDirState, self)._sha_cutoff_time()
1076
1813
        self._cutoff_time = timestamp + self._time_offset
1077
1814
 
1078
 
    def _sha1_file(self, abspath, entry):
 
1815
    def _sha1_file_and_log(self, abspath):
1079
1816
        self._log.append(('sha1', abspath))
1080
 
        return super(InstrumentedDirState, self)._sha1_file(abspath, entry)
 
1817
        return self._sha1_provider.sha1(abspath)
1081
1818
 
1082
1819
    def _read_link(self, abspath, old_link):
1083
1820
        self._log.append(('read_link', abspath, old_link))
1114
1851
        self.st_ino = ino
1115
1852
        self.st_mode = mode
1116
1853
 
1117
 
 
1118
 
class TestUpdateEntry(TestCaseWithDirState):
1119
 
    """Test the DirState.update_entry functions"""
1120
 
 
1121
 
    def get_state_with_a(self):
1122
 
        """Create a DirState tracking a single object named 'a'"""
1123
 
        state = InstrumentedDirState.initialize('dirstate')
1124
 
        self.addCleanup(state.unlock)
1125
 
        state.add('a', 'a-id', 'file', None, '')
1126
 
        entry = state._get_entry(0, path_utf8='a')
1127
 
        return state, entry
1128
 
 
1129
 
    def test_update_entry(self):
1130
 
        state, entry = self.get_state_with_a()
1131
 
        self.build_tree(['a'])
1132
 
        # Add one where we don't provide the stat or sha already
1133
 
        self.assertEqual(('', 'a', 'a-id'), entry[0])
1134
 
        self.assertEqual([('f', '', 0, False, dirstate.DirState.NULLSTAT)],
1135
 
                         entry[1])
1136
 
        # Flush the buffers to disk
1137
 
        state.save()
1138
 
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1139
 
                         state._dirblock_state)
1140
 
 
1141
 
        stat_value = os.lstat('a')
1142
 
        packed_stat = dirstate.pack_stat(stat_value)
1143
 
        link_or_sha1 = state.update_entry(entry, abspath='a',
1144
 
                                          stat_value=stat_value)
1145
 
        self.assertEqual('b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6',
1146
 
                         link_or_sha1)
1147
 
 
1148
 
        # The dirblock entry should be updated with the new info
1149
 
        self.assertEqual([('f', link_or_sha1, 14, False, packed_stat)],
1150
 
                         entry[1])
1151
 
        self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
1152
 
                         state._dirblock_state)
1153
 
        mode = stat_value.st_mode
1154
 
        self.assertEqual([('sha1', 'a'), ('is_exec', mode, False)], state._log)
1155
 
 
1156
 
        state.save()
1157
 
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1158
 
                         state._dirblock_state)
1159
 
 
1160
 
        # If we do it again right away, we don't know if the file has changed
1161
 
        # so we will re-read the file. Roll the clock back so the file is
1162
 
        # guaranteed to look too new.
1163
 
        state.adjust_time(-10)
1164
 
 
1165
 
        link_or_sha1 = state.update_entry(entry, abspath='a',
1166
 
                                          stat_value=stat_value)
1167
 
        self.assertEqual([('sha1', 'a'), ('is_exec', mode, False),
1168
 
                          ('sha1', 'a'), ('is_exec', mode, False),
1169
 
                         ], state._log)
1170
 
        self.assertEqual('b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6',
1171
 
                         link_or_sha1)
1172
 
        self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
1173
 
                         state._dirblock_state)
1174
 
        state.save()
1175
 
 
1176
 
        # However, if we move the clock forward so the file is considered
1177
 
        # "stable", it should just returned the cached value.
1178
 
        state.adjust_time(20)
1179
 
        link_or_sha1 = state.update_entry(entry, abspath='a',
1180
 
                                          stat_value=stat_value)
1181
 
        self.assertEqual('b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6',
1182
 
                         link_or_sha1)
1183
 
        self.assertEqual([('sha1', 'a'), ('is_exec', mode, False),
1184
 
                          ('sha1', 'a'), ('is_exec', mode, False),
1185
 
                         ], state._log)
1186
 
 
1187
 
    def test_update_entry_no_stat_value(self):
1188
 
        """Passing the stat_value is optional."""
1189
 
        state, entry = self.get_state_with_a()
1190
 
        state.adjust_time(-10) # Make sure the file looks new
1191
 
        self.build_tree(['a'])
1192
 
        # Add one where we don't provide the stat or sha already
1193
 
        link_or_sha1 = state.update_entry(entry, abspath='a')
1194
 
        self.assertEqual('b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6',
1195
 
                         link_or_sha1)
1196
 
        stat_value = os.lstat('a')
1197
 
        self.assertEqual([('lstat', 'a'), ('sha1', 'a'),
1198
 
                          ('is_exec', stat_value.st_mode, False),
1199
 
                         ], state._log)
1200
 
 
1201
 
    def test_update_entry_symlink(self):
1202
 
        """Update entry should read symlinks."""
1203
 
        if not osutils.has_symlinks():
1204
 
            return # PlatformDeficiency / TestSkipped
1205
 
        state, entry = self.get_state_with_a()
1206
 
        state.save()
1207
 
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1208
 
                         state._dirblock_state)
1209
 
        os.symlink('target', 'a')
1210
 
 
1211
 
        state.adjust_time(-10) # Make the symlink look new
1212
 
        stat_value = os.lstat('a')
1213
 
        packed_stat = dirstate.pack_stat(stat_value)
1214
 
        link_or_sha1 = state.update_entry(entry, abspath='a',
1215
 
                                          stat_value=stat_value)
1216
 
        self.assertEqual('target', link_or_sha1)
1217
 
        self.assertEqual([('read_link', 'a', '')], state._log)
1218
 
        # Dirblock is updated
1219
 
        self.assertEqual([('l', link_or_sha1, 6, False, packed_stat)],
1220
 
                         entry[1])
1221
 
        self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
1222
 
                         state._dirblock_state)
1223
 
 
1224
 
        # Because the stat_value looks new, we should re-read the target
1225
 
        link_or_sha1 = state.update_entry(entry, abspath='a',
1226
 
                                          stat_value=stat_value)
1227
 
        self.assertEqual('target', link_or_sha1)
1228
 
        self.assertEqual([('read_link', 'a', ''),
1229
 
                          ('read_link', 'a', 'target'),
1230
 
                         ], state._log)
1231
 
        state.adjust_time(+20) # Skip into the future, all files look old
1232
 
        link_or_sha1 = state.update_entry(entry, abspath='a',
1233
 
                                          stat_value=stat_value)
1234
 
        self.assertEqual('target', link_or_sha1)
1235
 
        # There should not be a new read_link call.
1236
 
        # (this is a weak assertion, because read_link is fairly inexpensive,
1237
 
        # versus the number of symlinks that we would have)
1238
 
        self.assertEqual([('read_link', 'a', ''),
1239
 
                          ('read_link', 'a', 'target'),
1240
 
                         ], state._log)
1241
 
 
1242
 
    def test_update_entry_dir(self):
1243
 
        state, entry = self.get_state_with_a()
1244
 
        self.build_tree(['a/'])
1245
 
        self.assertIs(None, state.update_entry(entry, 'a'))
1246
 
 
1247
 
    def create_and_test_file(self, state, entry):
1248
 
        """Create a file at 'a' and verify the state finds it.
1249
 
 
1250
 
        The state should already be versioning *something* at 'a'. This makes
1251
 
        sure that state.update_entry recognizes it as a file.
1252
 
        """
1253
 
        self.build_tree(['a'])
1254
 
        stat_value = os.lstat('a')
1255
 
        packed_stat = dirstate.pack_stat(stat_value)
1256
 
 
1257
 
        link_or_sha1 = state.update_entry(entry, abspath='a')
1258
 
        self.assertEqual('b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6',
1259
 
                         link_or_sha1)
1260
 
        self.assertEqual([('f', link_or_sha1, 14, False, packed_stat)],
1261
 
                         entry[1])
1262
 
        return packed_stat
1263
 
 
1264
 
    def create_and_test_dir(self, state, entry):
1265
 
        """Create a directory at 'a' and verify the state finds it.
1266
 
 
1267
 
        The state should already be versioning *something* at 'a'. This makes
1268
 
        sure that state.update_entry recognizes it as a directory.
1269
 
        """
1270
 
        self.build_tree(['a/'])
1271
 
        stat_value = os.lstat('a')
1272
 
        packed_stat = dirstate.pack_stat(stat_value)
1273
 
 
1274
 
        link_or_sha1 = state.update_entry(entry, abspath='a')
1275
 
        self.assertIs(None, link_or_sha1)
1276
 
        self.assertEqual([('d', '', 0, False, packed_stat)], entry[1])
1277
 
 
1278
 
        return packed_stat
1279
 
 
1280
 
    def create_and_test_symlink(self, state, entry):
1281
 
        """Create a symlink at 'a' and verify the state finds it.
1282
 
 
1283
 
        The state should already be versioning *something* at 'a'. This makes
1284
 
        sure that state.update_entry recognizes it as a symlink.
1285
 
 
1286
 
        This should not be called if this platform does not have symlink
1287
 
        support.
1288
 
        """
1289
 
        os.symlink('path/to/foo', 'a')
1290
 
 
1291
 
        stat_value = os.lstat('a')
1292
 
        packed_stat = dirstate.pack_stat(stat_value)
1293
 
 
1294
 
        link_or_sha1 = state.update_entry(entry, abspath='a')
1295
 
        self.assertEqual('path/to/foo', link_or_sha1)
1296
 
        self.assertEqual([('l', 'path/to/foo', 11, False, packed_stat)],
1297
 
                         entry[1])
1298
 
        return packed_stat
1299
 
 
1300
 
    def test_update_missing_file(self):
1301
 
        state, entry = self.get_state_with_a()
1302
 
        packed_stat = self.create_and_test_file(state, entry)
1303
 
        # Now if we delete the file, update_entry should recover and
1304
 
        # return None.
1305
 
        os.remove('a')
1306
 
        self.assertIs(None, state.update_entry(entry, abspath='a'))
1307
 
        # And the record shouldn't be changed.
1308
 
        digest = 'b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6'
1309
 
        self.assertEqual([('f', digest, 14, False, packed_stat)],
1310
 
                         entry[1])
1311
 
 
1312
 
    def test_update_missing_dir(self):
1313
 
        state, entry = self.get_state_with_a()
1314
 
        packed_stat = self.create_and_test_dir(state, entry)
1315
 
        # Now if we delete the directory, update_entry should recover and
1316
 
        # return None.
1317
 
        os.rmdir('a')
1318
 
        self.assertIs(None, state.update_entry(entry, abspath='a'))
1319
 
        self.assertEqual([('d', '', 0, False, packed_stat)], entry[1])
1320
 
 
1321
 
    def test_update_missing_symlink(self):
1322
 
        if not osutils.has_symlinks():
1323
 
            return # PlatformDeficiency / TestSkipped
1324
 
        state, entry = self.get_state_with_a()
1325
 
        packed_stat = self.create_and_test_symlink(state, entry)
1326
 
        os.remove('a')
1327
 
        self.assertIs(None, state.update_entry(entry, abspath='a'))
1328
 
        # And the record shouldn't be changed.
1329
 
        self.assertEqual([('l', 'path/to/foo', 11, False, packed_stat)],
1330
 
                         entry[1])
1331
 
 
1332
 
    def test_update_file_to_dir(self):
1333
 
        """If a file changes to a directory we return None for the sha.
1334
 
        We also update the inventory record.
1335
 
        """
1336
 
        state, entry = self.get_state_with_a()
1337
 
        self.create_and_test_file(state, entry)
1338
 
        os.remove('a')
1339
 
        self.create_and_test_dir(state, entry)
1340
 
 
1341
 
    def test_update_file_to_symlink(self):
1342
 
        """File becomes a symlink"""
1343
 
        if not osutils.has_symlinks():
1344
 
            return # PlatformDeficiency / TestSkipped
1345
 
        state, entry = self.get_state_with_a()
1346
 
        self.create_and_test_file(state, entry)
1347
 
        os.remove('a')
1348
 
        self.create_and_test_symlink(state, entry)
1349
 
 
1350
 
    def test_update_dir_to_file(self):
1351
 
        """Directory becoming a file updates the entry."""
1352
 
        state, entry = self.get_state_with_a()
1353
 
        self.create_and_test_dir(state, entry)
1354
 
        os.rmdir('a')
1355
 
        self.create_and_test_file(state, entry)
1356
 
 
1357
 
    def test_update_dir_to_symlink(self):
1358
 
        """Directory becomes a symlink"""
1359
 
        if not osutils.has_symlinks():
1360
 
            return # PlatformDeficiency / TestSkipped
1361
 
        state, entry = self.get_state_with_a()
1362
 
        self.create_and_test_dir(state, entry)
1363
 
        os.rmdir('a')
1364
 
        self.create_and_test_symlink(state, entry)
1365
 
 
1366
 
    def test_update_symlink_to_file(self):
1367
 
        """Symlink becomes a file"""
1368
 
        state, entry = self.get_state_with_a()
1369
 
        self.create_and_test_symlink(state, entry)
1370
 
        os.remove('a')
1371
 
        self.create_and_test_file(state, entry)
1372
 
 
1373
 
    def test_update_symlink_to_dir(self):
1374
 
        """Symlink becomes a directory"""
1375
 
        state, entry = self.get_state_with_a()
1376
 
        self.create_and_test_symlink(state, entry)
1377
 
        os.remove('a')
1378
 
        self.create_and_test_dir(state, entry)
1379
 
 
1380
 
    def test__is_executable_win32(self):
1381
 
        state, entry = self.get_state_with_a()
1382
 
        self.build_tree(['a'])
1383
 
 
1384
 
        # Make sure we are using the win32 implementation of _is_executable
1385
 
        state._is_executable = state._is_executable_win32
1386
 
 
1387
 
        # The file on disk is not executable, but we are marking it as though
1388
 
        # it is. With _is_executable_win32 we ignore what is on disk.
1389
 
        entry[1][0] = ('f', '', 0, True, dirstate.DirState.NULLSTAT)
1390
 
 
1391
 
        stat_value = os.lstat('a')
1392
 
        packed_stat = dirstate.pack_stat(stat_value)
1393
 
 
1394
 
        state.adjust_time(-10) # Make sure everything is new
1395
 
        # Make sure it wants to kkkkkkkk
1396
 
        state.update_entry(entry, abspath='a', stat_value=stat_value)
1397
 
 
1398
 
        # The row is updated, but the executable bit stays set.
1399
 
        digest = 'b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6'
1400
 
        self.assertEqual([('f', digest, 14, True, packed_stat)], entry[1])
1401
 
 
1402
 
 
1403
 
class TestPackStat(TestCaseWithTransport):
 
1854
    @staticmethod
 
1855
    def from_stat(st):
 
1856
        return _FakeStat(st.st_size, st.st_mtime, st.st_ctime, st.st_dev,
 
1857
            st.st_ino, st.st_mode)
 
1858
 
 
1859
 
 
1860
class TestPackStat(tests.TestCaseWithTransport):
1404
1861
 
1405
1862
    def assertPackStat(self, expected, stat_value):
1406
1863
        """Check the packed and serialized form of a stat value."""
1452
1909
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADCQBjLNIAAIGk', st)
1453
1910
 
1454
1911
 
1455
 
class TestBisect(TestCaseWithTransport):
 
1912
class TestBisect(TestCaseWithDirState):
1456
1913
    """Test the ability to bisect into the disk format."""
1457
1914
 
1458
 
    def create_basic_dirstate(self):
1459
 
        """Create a dirstate with a few files and directories.
1460
 
 
1461
 
            a
1462
 
            b/
1463
 
              c
1464
 
              d/
1465
 
                e
1466
 
            f
1467
 
        """
1468
 
        tree = self.make_branch_and_tree('tree')
1469
 
        paths = ['a', 'b/', 'b/c', 'b/d/', 'b/d/e', 'f']
1470
 
        file_ids = ['a-id', 'b-id', 'c-id', 'd-id', 'e-id', 'f-id']
1471
 
        self.build_tree(['tree/' + p for p in paths])
1472
 
        tree.set_root_id('TREE_ROOT')
1473
 
        tree.add([p.rstrip('/') for p in paths], file_ids)
1474
 
        tree.commit('initial', rev_id='rev-1')
1475
 
        revision_id = 'rev-1'
1476
 
        # a_packed_stat = dirstate.pack_stat(os.stat('tree/a'))
1477
 
        t = self.get_transport().clone('tree')
1478
 
        a_text = t.get_bytes('a')
1479
 
        a_sha = osutils.sha_string(a_text)
1480
 
        a_len = len(a_text)
1481
 
        # b_packed_stat = dirstate.pack_stat(os.stat('tree/b'))
1482
 
        # c_packed_stat = dirstate.pack_stat(os.stat('tree/b/c'))
1483
 
        c_text = t.get_bytes('b/c')
1484
 
        c_sha = osutils.sha_string(c_text)
1485
 
        c_len = len(c_text)
1486
 
        # d_packed_stat = dirstate.pack_stat(os.stat('tree/b/d'))
1487
 
        # e_packed_stat = dirstate.pack_stat(os.stat('tree/b/d/e'))
1488
 
        e_text = t.get_bytes('b/d/e')
1489
 
        e_sha = osutils.sha_string(e_text)
1490
 
        e_len = len(e_text)
1491
 
        # f_packed_stat = dirstate.pack_stat(os.stat('tree/f'))
1492
 
        f_text = t.get_bytes('f')
1493
 
        f_sha = osutils.sha_string(f_text)
1494
 
        f_len = len(f_text)
1495
 
        null_stat = dirstate.DirState.NULLSTAT
1496
 
        expected = {
1497
 
            '':(('', '', 'TREE_ROOT'), [
1498
 
                  ('d', '', 0, False, null_stat),
1499
 
                  ('d', '', 0, False, revision_id),
1500
 
                ]),
1501
 
            'a':(('', 'a', 'a-id'), [
1502
 
                   ('f', '', 0, False, null_stat),
1503
 
                   ('f', a_sha, a_len, False, revision_id),
1504
 
                 ]),
1505
 
            'b':(('', 'b', 'b-id'), [
1506
 
                  ('d', '', 0, False, null_stat),
1507
 
                  ('d', '', 0, False, revision_id),
1508
 
                 ]),
1509
 
            'b/c':(('b', 'c', 'c-id'), [
1510
 
                    ('f', '', 0, False, null_stat),
1511
 
                    ('f', c_sha, c_len, False, revision_id),
1512
 
                   ]),
1513
 
            'b/d':(('b', 'd', 'd-id'), [
1514
 
                    ('d', '', 0, False, null_stat),
1515
 
                    ('d', '', 0, False, revision_id),
1516
 
                   ]),
1517
 
            'b/d/e':(('b/d', 'e', 'e-id'), [
1518
 
                      ('f', '', 0, False, null_stat),
1519
 
                      ('f', e_sha, e_len, False, revision_id),
1520
 
                     ]),
1521
 
            'f':(('', 'f', 'f-id'), [
1522
 
                  ('f', '', 0, False, null_stat),
1523
 
                  ('f', f_sha, f_len, False, revision_id),
1524
 
                 ]),
1525
 
        }
1526
 
        state = dirstate.DirState.from_tree(tree, 'dirstate')
1527
 
        try:
1528
 
            state.save()
1529
 
        finally:
1530
 
            state.unlock()
1531
 
        # Use a different object, to make sure nothing is pre-cached in memory.
1532
 
        state = dirstate.DirState.on_file('dirstate')
1533
 
        state.lock_read()
1534
 
        self.addCleanup(state.unlock)
1535
 
        self.assertEqual(dirstate.DirState.NOT_IN_MEMORY,
1536
 
                         state._dirblock_state)
1537
 
        # This is code is only really tested if we actually have to make more
1538
 
        # than one read, so set the page size to something smaller.
1539
 
        # We want it to contain about 2.2 records, so that we have a couple
1540
 
        # records that we can read per attempt
1541
 
        state._bisect_page_size = 200
1542
 
        return tree, state, expected
1543
 
 
1544
 
    def create_duplicated_dirstate(self):
1545
 
        """Create a dirstate with a deleted and added entries.
1546
 
 
1547
 
        This grabs a basic_dirstate, and then removes and re adds every entry
1548
 
        with a new file id.
1549
 
        """
1550
 
        tree, state, expected = self.create_basic_dirstate()
1551
 
        # Now we will just remove and add every file so we get an extra entry
1552
 
        # per entry. Unversion in reverse order so we handle subdirs
1553
 
        tree.unversion(['f-id', 'e-id', 'd-id', 'c-id', 'b-id', 'a-id'])
1554
 
        tree.add(['a', 'b', 'b/c', 'b/d', 'b/d/e', 'f'],
1555
 
                 ['a-id2', 'b-id2', 'c-id2', 'd-id2', 'e-id2', 'f-id2'])
1556
 
 
1557
 
        # Update the expected dictionary.
1558
 
        for path in ['a', 'b', 'b/c', 'b/d', 'b/d/e', 'f']:
1559
 
            orig = expected[path]
1560
 
            path2 = path + '2'
1561
 
            # This record was deleted in the current tree
1562
 
            expected[path] = (orig[0], [dirstate.DirState.NULL_PARENT_DETAILS,
1563
 
                                        orig[1][1]])
1564
 
            new_key = (orig[0][0], orig[0][1], orig[0][2]+'2')
1565
 
            # And didn't exist in the basis tree
1566
 
            expected[path2] = (new_key, [orig[1][0],
1567
 
                                         dirstate.DirState.NULL_PARENT_DETAILS])
1568
 
 
1569
 
        # We will replace the 'dirstate' file underneath 'state', but that is
1570
 
        # okay as lock as we unlock 'state' first.
1571
 
        state.unlock()
1572
 
        try:
1573
 
            new_state = dirstate.DirState.from_tree(tree, 'dirstate')
1574
 
            try:
1575
 
                new_state.save()
1576
 
            finally:
1577
 
                new_state.unlock()
1578
 
        finally:
1579
 
            # But we need to leave state in a read-lock because we already have
1580
 
            # a cleanup scheduled
1581
 
            state.lock_read()
1582
 
        return tree, state, expected
1583
 
 
1584
 
    def create_renamed_dirstate(self):
1585
 
        """Create a dirstate with a few internal renames.
1586
 
 
1587
 
        This takes the basic dirstate, and moves the paths around.
1588
 
        """
1589
 
        tree, state, expected = self.create_basic_dirstate()
1590
 
        # Rename a file
1591
 
        tree.rename_one('a', 'b/g')
1592
 
        # And a directory
1593
 
        tree.rename_one('b/d', 'h')
1594
 
 
1595
 
        old_a = expected['a']
1596
 
        expected['a'] = (old_a[0], [('r', 'b/g', 0, False, ''), old_a[1][1]])
1597
 
        expected['b/g'] = (('b', 'g', 'a-id'), [old_a[1][0],
1598
 
                                                ('r', 'a', 0, False, '')])
1599
 
        old_d = expected['b/d']
1600
 
        expected['b/d'] = (old_d[0], [('r', 'h', 0, False, ''), old_d[1][1]])
1601
 
        expected['h'] = (('', 'h', 'd-id'), [old_d[1][0],
1602
 
                                             ('r', 'b/d', 0, False, '')])
1603
 
 
1604
 
        old_e = expected['b/d/e']
1605
 
        expected['b/d/e'] = (old_e[0], [('r', 'h/e', 0, False, ''),
1606
 
                             old_e[1][1]])
1607
 
        expected['h/e'] = (('h', 'e', 'e-id'), [old_e[1][0],
1608
 
                                                ('r', 'b/d/e', 0, False, '')])
1609
 
 
1610
 
        state.unlock()
1611
 
        try:
1612
 
            new_state = dirstate.DirState.from_tree(tree, 'dirstate')
1613
 
            try:
1614
 
                new_state.save()
1615
 
            finally:
1616
 
                new_state.unlock()
1617
 
        finally:
1618
 
            state.lock_read()
1619
 
        return tree, state, expected
1620
 
 
1621
1915
    def assertBisect(self, expected_map, map_keys, state, paths):
1622
1916
        """Assert that bisecting for paths returns the right result.
1623
1917
 
1628
1922
                      (dir, name) tuples, and sorted according to how _bisect
1629
1923
                      requires.
1630
1924
        """
1631
 
        dir_names = sorted(osutils.split(p) for p in paths)
1632
 
        result = state._bisect(dir_names)
 
1925
        result = state._bisect(paths)
1633
1926
        # For now, results are just returned in whatever order we read them.
1634
1927
        # We could sort by (dir, name, file_id) or something like that, but in
1635
1928
        # the end it would still be fairly arbitrary, and we don't want the
1636
1929
        # extra overhead if we can avoid it. So sort everything to make sure
1637
1930
        # equality is true
1638
 
        assert len(map_keys) == len(dir_names)
 
1931
        self.assertEqual(len(map_keys), len(paths))
1639
1932
        expected = {}
1640
 
        for dir_name, keys in zip(dir_names, map_keys):
 
1933
        for path, keys in zip(paths, map_keys):
1641
1934
            if keys is None:
1642
1935
                # This should not be present in the output
1643
1936
                continue
1644
 
            expected[dir_name] = sorted(expected_map[k] for k in keys)
 
1937
            expected[path] = sorted(expected_map[k] for k in keys)
1645
1938
 
1646
 
        for dir_name in result:
1647
 
            result[dir_name].sort()
 
1939
        # The returned values are just arranged randomly based on when they
 
1940
        # were read, for testing, make sure it is properly sorted.
 
1941
        for path in result:
 
1942
            result[path].sort()
1648
1943
 
1649
1944
        self.assertEqual(expected, result)
1650
1945
 
1658
1953
        :param paths: A list of directories
1659
1954
        """
1660
1955
        result = state._bisect_dirblocks(paths)
1661
 
        assert len(map_keys) == len(paths)
1662
 
 
 
1956
        self.assertEqual(len(map_keys), len(paths))
1663
1957
        expected = {}
1664
1958
        for path, keys in zip(paths, map_keys):
1665
1959
            if keys is None:
1687
1981
            dir_name_id, trees_info = entry
1688
1982
            expected[dir_name_id] = trees_info
1689
1983
 
1690
 
        dir_names = sorted(osutils.split(p) for p in paths)
1691
 
        result = state._bisect_recursive(dir_names)
 
1984
        result = state._bisect_recursive(paths)
1692
1985
 
1693
1986
        self.assertEqual(expected, result)
1694
1987
 
1703
1996
        self.assertBisect(expected, [['b/c']], state, ['b/c'])
1704
1997
        self.assertBisect(expected, [['b/d']], state, ['b/d'])
1705
1998
        self.assertBisect(expected, [['b/d/e']], state, ['b/d/e'])
 
1999
        self.assertBisect(expected, [['b-c']], state, ['b-c'])
1706
2000
        self.assertBisect(expected, [['f']], state, ['f'])
1707
2001
 
1708
2002
    def test_bisect_multi(self):
1711
2005
        # Bisect should be capable of finding multiple entries at the same time
1712
2006
        self.assertBisect(expected, [['a'], ['b'], ['f']],
1713
2007
                          state, ['a', 'b', 'f'])
1714
 
        # ('', 'f') sorts before the others
1715
2008
        self.assertBisect(expected, [['f'], ['b/d'], ['b/d/e']],
1716
 
                          state, ['b/d', 'b/d/e', 'f'])
 
2009
                          state, ['f', 'b/d', 'b/d/e'])
 
2010
        self.assertBisect(expected, [['b'], ['b-c'], ['b/c']],
 
2011
                          state, ['b', 'b-c', 'b/c'])
1717
2012
 
1718
2013
    def test_bisect_one_page(self):
1719
2014
        """Test bisect when there is only 1 page to read"""
1725
2020
        self.assertBisect(expected,[['b/c']], state, ['b/c'])
1726
2021
        self.assertBisect(expected,[['b/d']], state, ['b/d'])
1727
2022
        self.assertBisect(expected,[['b/d/e']], state, ['b/d/e'])
 
2023
        self.assertBisect(expected,[['b-c']], state, ['b-c'])
1728
2024
        self.assertBisect(expected,[['f']], state, ['f'])
1729
2025
        self.assertBisect(expected,[['a'], ['b'], ['f']],
1730
2026
                          state, ['a', 'b', 'f'])
1731
 
        # ('', 'f') sorts before the others
1732
 
        self.assertBisect(expected, [['f'], ['b/d'], ['b/d/e']],
 
2027
        self.assertBisect(expected, [['b/d'], ['b/d/e'], ['f']],
1733
2028
                          state, ['b/d', 'b/d/e', 'f'])
 
2029
        self.assertBisect(expected, [['b'], ['b/c'], ['b-c']],
 
2030
                          state, ['b', 'b/c', 'b-c'])
1734
2031
 
1735
2032
    def test_bisect_duplicate_paths(self):
1736
2033
        """When bisecting for a path, handle multiple entries."""
1744
2041
        self.assertBisect(expected, [['b/d', 'b/d2']], state, ['b/d'])
1745
2042
        self.assertBisect(expected, [['b/d/e', 'b/d/e2']],
1746
2043
                          state, ['b/d/e'])
 
2044
        self.assertBisect(expected, [['b-c', 'b-c2']], state, ['b-c'])
1747
2045
        self.assertBisect(expected, [['f', 'f2']], state, ['f'])
1748
2046
 
1749
2047
    def test_bisect_page_size_too_small(self):
1756
2054
        self.assertBisect(expected, [['b/c']], state, ['b/c'])
1757
2055
        self.assertBisect(expected, [['b/d']], state, ['b/d'])
1758
2056
        self.assertBisect(expected, [['b/d/e']], state, ['b/d/e'])
 
2057
        self.assertBisect(expected, [['b-c']], state, ['b-c'])
1759
2058
        self.assertBisect(expected, [['f']], state, ['f'])
1760
2059
 
1761
2060
    def test_bisect_missing(self):
1764
2063
        self.assertBisect(expected, [None], state, ['foo'])
1765
2064
        self.assertBisect(expected, [None], state, ['b/foo'])
1766
2065
        self.assertBisect(expected, [None], state, ['bar/foo'])
 
2066
        self.assertBisect(expected, [None], state, ['b-c/foo'])
1767
2067
 
1768
2068
        self.assertBisect(expected, [['a'], None, ['b/d']],
1769
2069
                          state, ['a', 'foo', 'b/d'])
1785
2085
    def test_bisect_dirblocks(self):
1786
2086
        tree, state, expected = self.create_duplicated_dirstate()
1787
2087
        self.assertBisectDirBlocks(expected,
1788
 
            [['', 'a', 'a2', 'b', 'b2', 'f', 'f2']], state, [''])
 
2088
            [['', 'a', 'a2', 'b', 'b2', 'b-c', 'b-c2', 'f', 'f2']],
 
2089
            state, [''])
1789
2090
        self.assertBisectDirBlocks(expected,
1790
2091
            [['b/c', 'b/c2', 'b/d', 'b/d2']], state, ['b'])
1791
2092
        self.assertBisectDirBlocks(expected,
1792
2093
            [['b/d/e', 'b/d/e2']], state, ['b/d'])
1793
2094
        self.assertBisectDirBlocks(expected,
1794
 
            [['', 'a', 'a2', 'b', 'b2', 'f', 'f2'],
 
2095
            [['', 'a', 'a2', 'b', 'b2', 'b-c', 'b-c2', 'f', 'f2'],
1795
2096
             ['b/c', 'b/c2', 'b/d', 'b/d2'],
1796
2097
             ['b/d/e', 'b/d/e2'],
1797
2098
            ], state, ['', 'b', 'b/d'])
1812
2113
        self.assertBisectRecursive(expected, ['a'], state, ['a'])
1813
2114
        self.assertBisectRecursive(expected, ['b/c'], state, ['b/c'])
1814
2115
        self.assertBisectRecursive(expected, ['b/d/e'], state, ['b/d/e'])
 
2116
        self.assertBisectRecursive(expected, ['b-c'], state, ['b-c'])
1815
2117
        self.assertBisectRecursive(expected, ['b/d', 'b/d/e'],
1816
2118
                                   state, ['b/d'])
1817
2119
        self.assertBisectRecursive(expected, ['b', 'b/c', 'b/d', 'b/d/e'],
1818
2120
                                   state, ['b'])
1819
 
        self.assertBisectRecursive(expected, ['', 'a', 'b', 'f', 'b/c',
 
2121
        self.assertBisectRecursive(expected, ['', 'a', 'b', 'b-c', 'f', 'b/c',
1820
2122
                                              'b/d', 'b/d/e'],
1821
2123
                                   state, [''])
1822
2124
 
1846
2148
                                   state, ['b'])
1847
2149
 
1848
2150
 
1849
 
class TestBisectDirblock(TestCase):
1850
 
    """Test that bisect_dirblock() returns the expected values.
1851
 
 
1852
 
    bisect_dirblock is intended to work like bisect.bisect_left() except it
1853
 
    knows it is working on dirblocks and that dirblocks are sorted by ('path',
1854
 
    'to', 'foo') chunks rather than by raw 'path/to/foo'.
1855
 
    """
1856
 
 
1857
 
    def assertBisect(self, dirblocks, split_dirblocks, path, *args, **kwargs):
1858
 
        """Assert that bisect_split works like bisect_left on the split paths.
1859
 
 
1860
 
        :param dirblocks: A list of (path, [info]) pairs.
1861
 
        :param split_dirblocks: A list of ((split, path), [info]) pairs.
1862
 
        :param path: The path we are indexing.
1863
 
 
1864
 
        All other arguments will be passed along.
1865
 
        """
1866
 
        bisect_split_idx = dirstate.bisect_dirblock(dirblocks, path,
1867
 
                                                 *args, **kwargs)
1868
 
        split_dirblock = (path.split('/'), [])
1869
 
        bisect_left_idx = bisect.bisect_left(split_dirblocks, split_dirblock,
1870
 
                                             *args)
1871
 
        self.assertEqual(bisect_left_idx, bisect_split_idx,
1872
 
                         'bisect_split disagreed. %s != %s'
1873
 
                         ' for key %s'
1874
 
                         % (bisect_left_idx, bisect_split_idx, path)
1875
 
                         )
1876
 
 
1877
 
    def paths_to_dirblocks(self, paths):
1878
 
        """Convert a list of paths into dirblock form.
1879
 
 
1880
 
        Also, ensure that the paths are in proper sorted order.
1881
 
        """
1882
 
        dirblocks = [(path, []) for path in paths]
1883
 
        split_dirblocks = [(path.split('/'), []) for path in paths]
1884
 
        self.assertEqual(sorted(split_dirblocks), split_dirblocks)
1885
 
        return dirblocks, split_dirblocks
1886
 
 
1887
 
    def test_simple(self):
1888
 
        """In the simple case it works just like bisect_left"""
1889
 
        paths = ['', 'a', 'b', 'c', 'd']
1890
 
        dirblocks, split_dirblocks = self.paths_to_dirblocks(paths)
1891
 
        for path in paths:
1892
 
            self.assertBisect(dirblocks, split_dirblocks, path)
1893
 
        self.assertBisect(dirblocks, split_dirblocks, '_')
1894
 
        self.assertBisect(dirblocks, split_dirblocks, 'aa')
1895
 
        self.assertBisect(dirblocks, split_dirblocks, 'bb')
1896
 
        self.assertBisect(dirblocks, split_dirblocks, 'cc')
1897
 
        self.assertBisect(dirblocks, split_dirblocks, 'dd')
1898
 
        self.assertBisect(dirblocks, split_dirblocks, 'a/a')
1899
 
        self.assertBisect(dirblocks, split_dirblocks, 'b/b')
1900
 
        self.assertBisect(dirblocks, split_dirblocks, 'c/c')
1901
 
        self.assertBisect(dirblocks, split_dirblocks, 'd/d')
1902
 
 
1903
 
    def test_involved(self):
1904
 
        """This is where bisect_left diverges slightly."""
1905
 
        paths = ['', 'a',
1906
 
                 'a/a', 'a/a/a', 'a/a/z', 'a/a-a', 'a/a-z',
1907
 
                 'a/z', 'a/z/a', 'a/z/z', 'a/z-a', 'a/z-z',
1908
 
                 'a-a', 'a-z',
1909
 
                 'z', 'z/a/a', 'z/a/z', 'z/a-a', 'z/a-z',
1910
 
                 'z/z', 'z/z/a', 'z/z/z', 'z/z-a', 'z/z-z',
1911
 
                 'z-a', 'z-z',
1912
 
                ]
1913
 
        dirblocks, split_dirblocks = self.paths_to_dirblocks(paths)
1914
 
        for path in paths:
1915
 
            self.assertBisect(dirblocks, split_dirblocks, path)
1916
 
 
1917
 
    def test_involved_cached(self):
1918
 
        """This is where bisect_left diverges slightly."""
1919
 
        paths = ['', 'a',
1920
 
                 'a/a', 'a/a/a', 'a/a/z', 'a/a-a', 'a/a-z',
1921
 
                 'a/z', 'a/z/a', 'a/z/z', 'a/z-a', 'a/z-z',
1922
 
                 'a-a', 'a-z',
1923
 
                 'z', 'z/a/a', 'z/a/z', 'z/a-a', 'z/a-z',
1924
 
                 'z/z', 'z/z/a', 'z/z/z', 'z/z-a', 'z/z-z',
1925
 
                 'z-a', 'z-z',
1926
 
                ]
1927
 
        cache = {}
1928
 
        dirblocks, split_dirblocks = self.paths_to_dirblocks(paths)
1929
 
        for path in paths:
1930
 
            self.assertBisect(dirblocks, split_dirblocks, path, cache=cache)
1931
 
 
 
2151
class TestDirstateValidation(TestCaseWithDirState):
 
2152
 
 
2153
    def test_validate_correct_dirstate(self):
 
2154
        state = self.create_complex_dirstate()
 
2155
        state._validate()
 
2156
        state.unlock()
 
2157
        # and make sure we can also validate with a read lock
 
2158
        state.lock_read()
 
2159
        try:
 
2160
            state._validate()
 
2161
        finally:
 
2162
            state.unlock()
 
2163
 
 
2164
    def test_dirblock_not_sorted(self):
 
2165
        tree, state, expected = self.create_renamed_dirstate()
 
2166
        state._read_dirblocks_if_needed()
 
2167
        last_dirblock = state._dirblocks[-1]
 
2168
        # we're appending to the dirblock, but this name comes before some of
 
2169
        # the existing names; that's wrong
 
2170
        last_dirblock[1].append(
 
2171
            (('h', 'aaaa', 'a-id'),
 
2172
             [('a', '', 0, False, ''),
 
2173
              ('a', '', 0, False, '')]))
 
2174
        e = self.assertRaises(AssertionError,
 
2175
            state._validate)
 
2176
        self.assertContainsRe(str(e), 'not sorted')
 
2177
 
 
2178
    def test_dirblock_name_mismatch(self):
 
2179
        tree, state, expected = self.create_renamed_dirstate()
 
2180
        state._read_dirblocks_if_needed()
 
2181
        last_dirblock = state._dirblocks[-1]
 
2182
        # add an entry with the wrong directory name
 
2183
        last_dirblock[1].append(
 
2184
            (('', 'z', 'a-id'),
 
2185
             [('a', '', 0, False, ''),
 
2186
              ('a', '', 0, False, '')]))
 
2187
        e = self.assertRaises(AssertionError,
 
2188
            state._validate)
 
2189
        self.assertContainsRe(str(e),
 
2190
            "doesn't match directory name")
 
2191
 
 
2192
    def test_dirblock_missing_rename(self):
 
2193
        tree, state, expected = self.create_renamed_dirstate()
 
2194
        state._read_dirblocks_if_needed()
 
2195
        last_dirblock = state._dirblocks[-1]
 
2196
        # make another entry for a-id, without a correct 'r' pointer to
 
2197
        # the real occurrence in the working tree
 
2198
        last_dirblock[1].append(
 
2199
            (('h', 'z', 'a-id'),
 
2200
             [('a', '', 0, False, ''),
 
2201
              ('a', '', 0, False, '')]))
 
2202
        e = self.assertRaises(AssertionError,
 
2203
            state._validate)
 
2204
        self.assertContainsRe(str(e),
 
2205
            'file a-id is absent in row')
 
2206
 
 
2207
 
 
2208
class TestDirstateTreeReference(TestCaseWithDirState):
 
2209
 
 
2210
    def test_reference_revision_is_none(self):
 
2211
        tree = self.make_branch_and_tree('tree', format='development-subtree')
 
2212
        subtree = self.make_branch_and_tree('tree/subtree',
 
2213
                            format='development-subtree')
 
2214
        subtree.set_root_id('subtree')
 
2215
        tree.add_reference(subtree)
 
2216
        tree.add('subtree')
 
2217
        state = dirstate.DirState.from_tree(tree, 'dirstate')
 
2218
        key = ('', 'subtree', 'subtree')
 
2219
        expected = ('', [(key,
 
2220
            [('t', '', 0, False, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')])])
 
2221
 
 
2222
        try:
 
2223
            self.assertEqual(expected, state._find_block(key))
 
2224
        finally:
 
2225
            state.unlock()
 
2226
 
 
2227
 
 
2228
class TestDiscardMergeParents(TestCaseWithDirState):
 
2229
 
 
2230
    def test_discard_no_parents(self):
 
2231
        # This should be a no-op
 
2232
        state = self.create_empty_dirstate()
 
2233
        self.addCleanup(state.unlock)
 
2234
        state._discard_merge_parents()
 
2235
        state._validate()
 
2236
 
 
2237
    def test_discard_one_parent(self):
 
2238
        # No-op
 
2239
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
 
2240
        root_entry_direntry = ('', '', 'a-root-value'), [
 
2241
            ('d', '', 0, False, packed_stat),
 
2242
            ('d', '', 0, False, packed_stat),
 
2243
            ]
 
2244
        dirblocks = []
 
2245
        dirblocks.append(('', [root_entry_direntry]))
 
2246
        dirblocks.append(('', []))
 
2247
 
 
2248
        state = self.create_empty_dirstate()
 
2249
        self.addCleanup(state.unlock)
 
2250
        state._set_data(['parent-id'], dirblocks[:])
 
2251
        state._validate()
 
2252
 
 
2253
        state._discard_merge_parents()
 
2254
        state._validate()
 
2255
        self.assertEqual(dirblocks, state._dirblocks)
 
2256
 
 
2257
    def test_discard_simple(self):
 
2258
        # No-op
 
2259
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
 
2260
        root_entry_direntry = ('', '', 'a-root-value'), [
 
2261
            ('d', '', 0, False, packed_stat),
 
2262
            ('d', '', 0, False, packed_stat),
 
2263
            ('d', '', 0, False, packed_stat),
 
2264
            ]
 
2265
        expected_root_entry_direntry = ('', '', 'a-root-value'), [
 
2266
            ('d', '', 0, False, packed_stat),
 
2267
            ('d', '', 0, False, packed_stat),
 
2268
            ]
 
2269
        dirblocks = []
 
2270
        dirblocks.append(('', [root_entry_direntry]))
 
2271
        dirblocks.append(('', []))
 
2272
 
 
2273
        state = self.create_empty_dirstate()
 
2274
        self.addCleanup(state.unlock)
 
2275
        state._set_data(['parent-id', 'merged-id'], dirblocks[:])
 
2276
        state._validate()
 
2277
 
 
2278
        # This should strip of the extra column
 
2279
        state._discard_merge_parents()
 
2280
        state._validate()
 
2281
        expected_dirblocks = [('', [expected_root_entry_direntry]), ('', [])]
 
2282
        self.assertEqual(expected_dirblocks, state._dirblocks)
 
2283
 
 
2284
    def test_discard_absent(self):
 
2285
        """If entries are only in a merge, discard should remove the entries"""
 
2286
        null_stat = dirstate.DirState.NULLSTAT
 
2287
        present_dir = ('d', '', 0, False, null_stat)
 
2288
        present_file = ('f', '', 0, False, null_stat)
 
2289
        absent = dirstate.DirState.NULL_PARENT_DETAILS
 
2290
        root_key = ('', '', 'a-root-value')
 
2291
        file_in_root_key = ('', 'file-in-root', 'a-file-id')
 
2292
        file_in_merged_key = ('', 'file-in-merged', 'b-file-id')
 
2293
        dirblocks = [('', [(root_key, [present_dir, present_dir, present_dir])]),
 
2294
                     ('', [(file_in_merged_key,
 
2295
                            [absent, absent, present_file]),
 
2296
                           (file_in_root_key,
 
2297
                            [present_file, present_file, present_file]),
 
2298
                          ]),
 
2299
                    ]
 
2300
 
 
2301
        state = self.create_empty_dirstate()
 
2302
        self.addCleanup(state.unlock)
 
2303
        state._set_data(['parent-id', 'merged-id'], dirblocks[:])
 
2304
        state._validate()
 
2305
 
 
2306
        exp_dirblocks = [('', [(root_key, [present_dir, present_dir])]),
 
2307
                         ('', [(file_in_root_key,
 
2308
                                [present_file, present_file]),
 
2309
                              ]),
 
2310
                        ]
 
2311
        state._discard_merge_parents()
 
2312
        state._validate()
 
2313
        self.assertEqual(exp_dirblocks, state._dirblocks)
 
2314
 
 
2315
    def test_discard_renamed(self):
 
2316
        null_stat = dirstate.DirState.NULLSTAT
 
2317
        present_dir = ('d', '', 0, False, null_stat)
 
2318
        present_file = ('f', '', 0, False, null_stat)
 
2319
        absent = dirstate.DirState.NULL_PARENT_DETAILS
 
2320
        root_key = ('', '', 'a-root-value')
 
2321
        file_in_root_key = ('', 'file-in-root', 'a-file-id')
 
2322
        # Renamed relative to parent
 
2323
        file_rename_s_key = ('', 'file-s', 'b-file-id')
 
2324
        file_rename_t_key = ('', 'file-t', 'b-file-id')
 
2325
        # And one that is renamed between the parents, but absent in this
 
2326
        key_in_1 = ('', 'file-in-1', 'c-file-id')
 
2327
        key_in_2 = ('', 'file-in-2', 'c-file-id')
 
2328
 
 
2329
        dirblocks = [
 
2330
            ('', [(root_key, [present_dir, present_dir, present_dir])]),
 
2331
            ('', [(key_in_1,
 
2332
                   [absent, present_file, ('r', 'file-in-2', 'c-file-id')]),
 
2333
                  (key_in_2,
 
2334
                   [absent, ('r', 'file-in-1', 'c-file-id'), present_file]),
 
2335
                  (file_in_root_key,
 
2336
                   [present_file, present_file, present_file]),
 
2337
                  (file_rename_s_key,
 
2338
                   [('r', 'file-t', 'b-file-id'), absent, present_file]),
 
2339
                  (file_rename_t_key,
 
2340
                   [present_file, absent, ('r', 'file-s', 'b-file-id')]),
 
2341
                 ]),
 
2342
        ]
 
2343
        exp_dirblocks = [
 
2344
            ('', [(root_key, [present_dir, present_dir])]),
 
2345
            ('', [(key_in_1, [absent, present_file]),
 
2346
                  (file_in_root_key, [present_file, present_file]),
 
2347
                  (file_rename_t_key, [present_file, absent]),
 
2348
                 ]),
 
2349
        ]
 
2350
        state = self.create_empty_dirstate()
 
2351
        self.addCleanup(state.unlock)
 
2352
        state._set_data(['parent-id', 'merged-id'], dirblocks[:])
 
2353
        state._validate()
 
2354
 
 
2355
        state._discard_merge_parents()
 
2356
        state._validate()
 
2357
        self.assertEqual(exp_dirblocks, state._dirblocks)
 
2358
 
 
2359
    def test_discard_all_subdir(self):
 
2360
        null_stat = dirstate.DirState.NULLSTAT
 
2361
        present_dir = ('d', '', 0, False, null_stat)
 
2362
        present_file = ('f', '', 0, False, null_stat)
 
2363
        absent = dirstate.DirState.NULL_PARENT_DETAILS
 
2364
        root_key = ('', '', 'a-root-value')
 
2365
        subdir_key = ('', 'sub', 'dir-id')
 
2366
        child1_key = ('sub', 'child1', 'child1-id')
 
2367
        child2_key = ('sub', 'child2', 'child2-id')
 
2368
        child3_key = ('sub', 'child3', 'child3-id')
 
2369
 
 
2370
        dirblocks = [
 
2371
            ('', [(root_key, [present_dir, present_dir, present_dir])]),
 
2372
            ('', [(subdir_key, [present_dir, present_dir, present_dir])]),
 
2373
            ('sub', [(child1_key, [absent, absent, present_file]),
 
2374
                     (child2_key, [absent, absent, present_file]),
 
2375
                     (child3_key, [absent, absent, present_file]),
 
2376
                    ]),
 
2377
        ]
 
2378
        exp_dirblocks = [
 
2379
            ('', [(root_key, [present_dir, present_dir])]),
 
2380
            ('', [(subdir_key, [present_dir, present_dir])]),
 
2381
            ('sub', []),
 
2382
        ]
 
2383
        state = self.create_empty_dirstate()
 
2384
        self.addCleanup(state.unlock)
 
2385
        state._set_data(['parent-id', 'merged-id'], dirblocks[:])
 
2386
        state._validate()
 
2387
 
 
2388
        state._discard_merge_parents()
 
2389
        state._validate()
 
2390
        self.assertEqual(exp_dirblocks, state._dirblocks)
 
2391
 
 
2392
 
 
2393
class Test_InvEntryToDetails(tests.TestCase):
 
2394
 
 
2395
    def assertDetails(self, expected, inv_entry):
 
2396
        details = dirstate.DirState._inv_entry_to_details(inv_entry)
 
2397
        self.assertEqual(expected, details)
 
2398
        # details should always allow join() and always be a plain str when
 
2399
        # finished
 
2400
        (minikind, fingerprint, size, executable, tree_data) = details
 
2401
        self.assertIsInstance(minikind, str)
 
2402
        self.assertIsInstance(fingerprint, str)
 
2403
        self.assertIsInstance(tree_data, str)
 
2404
 
 
2405
    def test_unicode_symlink(self):
 
2406
        inv_entry = inventory.InventoryLink('link-file-id',
 
2407
                                            u'nam\N{Euro Sign}e',
 
2408
                                            'link-parent-id')
 
2409
        inv_entry.revision = 'link-revision-id'
 
2410
        target = u'link-targ\N{Euro Sign}t'
 
2411
        inv_entry.symlink_target = target
 
2412
        self.assertDetails(('l', target.encode('UTF-8'), 0, False,
 
2413
                            'link-revision-id'), inv_entry)
 
2414
 
 
2415
 
 
2416
class TestSHA1Provider(tests.TestCaseInTempDir):
 
2417
 
 
2418
    def test_sha1provider_is_an_interface(self):
 
2419
        p = dirstate.SHA1Provider()
 
2420
        self.assertRaises(NotImplementedError, p.sha1, "foo")
 
2421
        self.assertRaises(NotImplementedError, p.stat_and_sha1, "foo")
 
2422
 
 
2423
    def test_defaultsha1provider_sha1(self):
 
2424
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
 
2425
        self.build_tree_contents([('foo', text)])
 
2426
        expected_sha = osutils.sha_string(text)
 
2427
        p = dirstate.DefaultSHA1Provider()
 
2428
        self.assertEqual(expected_sha, p.sha1('foo'))
 
2429
 
 
2430
    def test_defaultsha1provider_stat_and_sha1(self):
 
2431
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
 
2432
        self.build_tree_contents([('foo', text)])
 
2433
        expected_sha = osutils.sha_string(text)
 
2434
        p = dirstate.DefaultSHA1Provider()
 
2435
        statvalue, sha1 = p.stat_and_sha1('foo')
 
2436
        self.assertTrue(len(statvalue) >= 10)
 
2437
        self.assertEqual(len(text), statvalue.st_size)
 
2438
        self.assertEqual(expected_sha, sha1)
 
2439
 
 
2440
 
 
2441
class _Repo(object):
 
2442
    """A minimal api to get InventoryRevisionTree to work."""
 
2443
 
 
2444
    def __init__(self):
 
2445
        default_format = controldir.format_registry.make_bzrdir('default')
 
2446
        self._format = default_format.repository_format
 
2447
 
 
2448
    def lock_read(self):
 
2449
        pass
 
2450
 
 
2451
    def unlock(self):
 
2452
        pass
 
2453
 
 
2454
 
 
2455
class TestUpdateBasisByDelta(tests.TestCase):
 
2456
 
 
2457
    def path_to_ie(self, path, file_id, rev_id, dir_ids):
 
2458
        if path.endswith('/'):
 
2459
            is_dir = True
 
2460
            path = path[:-1]
 
2461
        else:
 
2462
            is_dir = False
 
2463
        dirname, basename = osutils.split(path)
 
2464
        try:
 
2465
            dir_id = dir_ids[dirname]
 
2466
        except KeyError:
 
2467
            dir_id = osutils.basename(dirname) + '-id'
 
2468
        if is_dir:
 
2469
            ie = inventory.InventoryDirectory(file_id, basename, dir_id)
 
2470
            dir_ids[path] = file_id
 
2471
        else:
 
2472
            ie = inventory.InventoryFile(file_id, basename, dir_id)
 
2473
            ie.text_size = 0
 
2474
            ie.text_sha1 = ''
 
2475
        ie.revision = rev_id
 
2476
        return ie
 
2477
 
 
2478
    def create_tree_from_shape(self, rev_id, shape):
 
2479
        dir_ids = {'': 'root-id'}
 
2480
        inv = inventory.Inventory('root-id', rev_id)
 
2481
        for info in shape:
 
2482
            if len(info) == 2:
 
2483
                path, file_id = info
 
2484
                ie_rev_id = rev_id
 
2485
            else:
 
2486
                path, file_id, ie_rev_id = info
 
2487
            if path == '':
 
2488
                # Replace the root entry
 
2489
                del inv._byid[inv.root.file_id]
 
2490
                inv.root.file_id = file_id
 
2491
                inv._byid[file_id] = inv.root
 
2492
                dir_ids[''] = file_id
 
2493
                continue
 
2494
            inv.add(self.path_to_ie(path, file_id, ie_rev_id, dir_ids))
 
2495
        return revisiontree.InventoryRevisionTree(_Repo(), inv, rev_id)
 
2496
 
 
2497
    def create_empty_dirstate(self):
 
2498
        fd, path = tempfile.mkstemp(prefix='bzr-dirstate')
 
2499
        self.addCleanup(os.remove, path)
 
2500
        os.close(fd)
 
2501
        state = dirstate.DirState.initialize(path)
 
2502
        self.addCleanup(state.unlock)
 
2503
        return state
 
2504
 
 
2505
    def create_inv_delta(self, delta, rev_id):
 
2506
        """Translate a 'delta shape' into an actual InventoryDelta"""
 
2507
        dir_ids = {'': 'root-id'}
 
2508
        inv_delta = []
 
2509
        for old_path, new_path, file_id in delta:
 
2510
            if old_path is not None and old_path.endswith('/'):
 
2511
                # Don't have to actually do anything for this, because only
 
2512
                # new_path creates InventoryEntries
 
2513
                old_path = old_path[:-1]
 
2514
            if new_path is None: # Delete
 
2515
                inv_delta.append((old_path, None, file_id, None))
 
2516
                continue
 
2517
            ie = self.path_to_ie(new_path, file_id, rev_id, dir_ids)
 
2518
            inv_delta.append((old_path, new_path, file_id, ie))
 
2519
        return inv_delta
 
2520
 
 
2521
    def assertUpdate(self, active, basis, target):
 
2522
        """Assert that update_basis_by_delta works how we want.
 
2523
 
 
2524
        Set up a DirState object with active_shape for tree 0, basis_shape for
 
2525
        tree 1. Then apply the delta from basis_shape to target_shape,
 
2526
        and assert that the DirState is still valid, and that its stored
 
2527
        content matches the target_shape.
 
2528
        """
 
2529
        active_tree = self.create_tree_from_shape('active', active)
 
2530
        basis_tree = self.create_tree_from_shape('basis', basis)
 
2531
        target_tree = self.create_tree_from_shape('target', target)
 
2532
        state = self.create_empty_dirstate()
 
2533
        state.set_state_from_scratch(active_tree.root_inventory,
 
2534
            [('basis', basis_tree)], [])
 
2535
        delta = target_tree.root_inventory._make_delta(
 
2536
            basis_tree.root_inventory)
 
2537
        state.update_basis_by_delta(delta, 'target')
 
2538
        state._validate()
 
2539
        dirstate_tree = workingtree_4.DirStateRevisionTree(state,
 
2540
            'target', _Repo())
 
2541
        # The target now that delta has been applied should match the
 
2542
        # RevisionTree
 
2543
        self.assertEqual([], list(dirstate_tree.iter_changes(target_tree)))
 
2544
        # And the dirblock state should be identical to the state if we created
 
2545
        # it from scratch.
 
2546
        state2 = self.create_empty_dirstate()
 
2547
        state2.set_state_from_scratch(active_tree.root_inventory,
 
2548
            [('target', target_tree)], [])
 
2549
        self.assertEqual(state2._dirblocks, state._dirblocks)
 
2550
        return state
 
2551
 
 
2552
    def assertBadDelta(self, active, basis, delta):
 
2553
        """Test that we raise InconsistentDelta when appropriate.
 
2554
 
 
2555
        :param active: The active tree shape
 
2556
        :param basis: The basis tree shape
 
2557
        :param delta: A description of the delta to apply. Similar to the form
 
2558
            for regular inventory deltas, but omitting the InventoryEntry.
 
2559
            So adding a file is: (None, 'path', 'file-id')
 
2560
            Adding a directory is: (None, 'path/', 'dir-id')
 
2561
            Renaming a dir is: ('old/', 'new/', 'dir-id')
 
2562
            etc.
 
2563
        """
 
2564
        active_tree = self.create_tree_from_shape('active', active)
 
2565
        basis_tree = self.create_tree_from_shape('basis', basis)
 
2566
        inv_delta = self.create_inv_delta(delta, 'target')
 
2567
        state = self.create_empty_dirstate()
 
2568
        state.set_state_from_scratch(active_tree.root_inventory,
 
2569
            [('basis', basis_tree)], [])
 
2570
        self.assertRaises(errors.InconsistentDelta,
 
2571
            state.update_basis_by_delta, inv_delta, 'target')
 
2572
        ## try:
 
2573
        ##     state.update_basis_by_delta(inv_delta, 'target')
 
2574
        ## except errors.InconsistentDelta, e:
 
2575
        ##     import pdb; pdb.set_trace()
 
2576
        ## else:
 
2577
        ##     import pdb; pdb.set_trace()
 
2578
        self.assertTrue(state._changes_aborted)
 
2579
 
 
2580
    def test_remove_file_matching_active_state(self):
 
2581
        state = self.assertUpdate(
 
2582
            active=[],
 
2583
            basis =[('file', 'file-id')],
 
2584
            target=[],
 
2585
            )
 
2586
 
 
2587
    def test_remove_file_present_in_active_state(self):
 
2588
        state = self.assertUpdate(
 
2589
            active=[('file', 'file-id')],
 
2590
            basis =[('file', 'file-id')],
 
2591
            target=[],
 
2592
            )
 
2593
 
 
2594
    def test_remove_file_present_elsewhere_in_active_state(self):
 
2595
        state = self.assertUpdate(
 
2596
            active=[('other-file', 'file-id')],
 
2597
            basis =[('file', 'file-id')],
 
2598
            target=[],
 
2599
            )
 
2600
 
 
2601
    def test_remove_file_active_state_has_diff_file(self):
 
2602
        state = self.assertUpdate(
 
2603
            active=[('file', 'file-id-2')],
 
2604
            basis =[('file', 'file-id')],
 
2605
            target=[],
 
2606
            )
 
2607
 
 
2608
    def test_remove_file_active_state_has_diff_file_and_file_elsewhere(self):
 
2609
        state = self.assertUpdate(
 
2610
            active=[('file', 'file-id-2'),
 
2611
                    ('other-file', 'file-id')],
 
2612
            basis =[('file', 'file-id')],
 
2613
            target=[],
 
2614
            )
 
2615
 
 
2616
    def test_add_file_matching_active_state(self):
 
2617
        state = self.assertUpdate(
 
2618
            active=[('file', 'file-id')],
 
2619
            basis =[],
 
2620
            target=[('file', 'file-id')],
 
2621
            )
 
2622
 
 
2623
    def test_add_file_in_empty_dir_not_matching_active_state(self):
 
2624
        state = self.assertUpdate(
 
2625
                active=[],
 
2626
                basis=[('dir/', 'dir-id')],
 
2627
                target=[('dir/', 'dir-id', 'basis'), ('dir/file', 'file-id')],
 
2628
                )
 
2629
 
 
2630
    def test_add_file_missing_in_active_state(self):
 
2631
        state = self.assertUpdate(
 
2632
            active=[],
 
2633
            basis =[],
 
2634
            target=[('file', 'file-id')],
 
2635
            )
 
2636
 
 
2637
    def test_add_file_elsewhere_in_active_state(self):
 
2638
        state = self.assertUpdate(
 
2639
            active=[('other-file', 'file-id')],
 
2640
            basis =[],
 
2641
            target=[('file', 'file-id')],
 
2642
            )
 
2643
 
 
2644
    def test_add_file_active_state_has_diff_file_and_file_elsewhere(self):
 
2645
        state = self.assertUpdate(
 
2646
            active=[('other-file', 'file-id'),
 
2647
                    ('file', 'file-id-2')],
 
2648
            basis =[],
 
2649
            target=[('file', 'file-id')],
 
2650
            )
 
2651
 
 
2652
    def test_rename_file_matching_active_state(self):
 
2653
        state = self.assertUpdate(
 
2654
            active=[('other-file', 'file-id')],
 
2655
            basis =[('file', 'file-id')],
 
2656
            target=[('other-file', 'file-id')],
 
2657
            )
 
2658
 
 
2659
    def test_rename_file_missing_in_active_state(self):
 
2660
        state = self.assertUpdate(
 
2661
            active=[],
 
2662
            basis =[('file', 'file-id')],
 
2663
            target=[('other-file', 'file-id')],
 
2664
            )
 
2665
 
 
2666
    def test_rename_file_present_elsewhere_in_active_state(self):
 
2667
        state = self.assertUpdate(
 
2668
            active=[('third', 'file-id')],
 
2669
            basis =[('file', 'file-id')],
 
2670
            target=[('other-file', 'file-id')],
 
2671
            )
 
2672
 
 
2673
    def test_rename_file_active_state_has_diff_source_file(self):
 
2674
        state = self.assertUpdate(
 
2675
            active=[('file', 'file-id-2')],
 
2676
            basis =[('file', 'file-id')],
 
2677
            target=[('other-file', 'file-id')],
 
2678
            )
 
2679
 
 
2680
    def test_rename_file_active_state_has_diff_target_file(self):
 
2681
        state = self.assertUpdate(
 
2682
            active=[('other-file', 'file-id-2')],
 
2683
            basis =[('file', 'file-id')],
 
2684
            target=[('other-file', 'file-id')],
 
2685
            )
 
2686
 
 
2687
    def test_rename_file_active_has_swapped_files(self):
 
2688
        state = self.assertUpdate(
 
2689
            active=[('file', 'file-id'),
 
2690
                    ('other-file', 'file-id-2')],
 
2691
            basis= [('file', 'file-id'),
 
2692
                    ('other-file', 'file-id-2')],
 
2693
            target=[('file', 'file-id-2'),
 
2694
                    ('other-file', 'file-id')])
 
2695
 
 
2696
    def test_rename_file_basis_has_swapped_files(self):
 
2697
        state = self.assertUpdate(
 
2698
            active=[('file', 'file-id'),
 
2699
                    ('other-file', 'file-id-2')],
 
2700
            basis= [('file', 'file-id-2'),
 
2701
                    ('other-file', 'file-id')],
 
2702
            target=[('file', 'file-id'),
 
2703
                    ('other-file', 'file-id-2')])
 
2704
 
 
2705
    def test_rename_directory_with_contents(self):
 
2706
        state = self.assertUpdate( # active matches basis
 
2707
            active=[('dir1/', 'dir-id'),
 
2708
                    ('dir1/file', 'file-id')],
 
2709
            basis= [('dir1/', 'dir-id'),
 
2710
                    ('dir1/file', 'file-id')],
 
2711
            target=[('dir2/', 'dir-id'),
 
2712
                    ('dir2/file', 'file-id')])
 
2713
        state = self.assertUpdate( # active matches target
 
2714
            active=[('dir2/', 'dir-id'),
 
2715
                    ('dir2/file', 'file-id')],
 
2716
            basis= [('dir1/', 'dir-id'),
 
2717
                    ('dir1/file', 'file-id')],
 
2718
            target=[('dir2/', 'dir-id'),
 
2719
                    ('dir2/file', 'file-id')])
 
2720
        state = self.assertUpdate( # active empty
 
2721
            active=[],
 
2722
            basis= [('dir1/', 'dir-id'),
 
2723
                    ('dir1/file', 'file-id')],
 
2724
            target=[('dir2/', 'dir-id'),
 
2725
                    ('dir2/file', 'file-id')])
 
2726
        state = self.assertUpdate( # active present at other location
 
2727
            active=[('dir3/', 'dir-id'),
 
2728
                    ('dir3/file', 'file-id')],
 
2729
            basis= [('dir1/', 'dir-id'),
 
2730
                    ('dir1/file', 'file-id')],
 
2731
            target=[('dir2/', 'dir-id'),
 
2732
                    ('dir2/file', 'file-id')])
 
2733
        state = self.assertUpdate( # active has different ids
 
2734
            active=[('dir1/', 'dir1-id'),
 
2735
                    ('dir1/file', 'file1-id'),
 
2736
                    ('dir2/', 'dir2-id'),
 
2737
                    ('dir2/file', 'file2-id')],
 
2738
            basis= [('dir1/', 'dir-id'),
 
2739
                    ('dir1/file', 'file-id')],
 
2740
            target=[('dir2/', 'dir-id'),
 
2741
                    ('dir2/file', 'file-id')])
 
2742
 
 
2743
    def test_invalid_file_not_present(self):
 
2744
        state = self.assertBadDelta(
 
2745
            active=[('file', 'file-id')],
 
2746
            basis= [('file', 'file-id')],
 
2747
            delta=[('other-file', 'file', 'file-id')])
 
2748
 
 
2749
    def test_invalid_new_id_same_path(self):
 
2750
        # The bad entry comes after
 
2751
        state = self.assertBadDelta(
 
2752
            active=[('file', 'file-id')],
 
2753
            basis= [('file', 'file-id')],
 
2754
            delta=[(None, 'file', 'file-id-2')])
 
2755
        # The bad entry comes first
 
2756
        state = self.assertBadDelta(
 
2757
            active=[('file', 'file-id-2')],
 
2758
            basis=[('file', 'file-id-2')],
 
2759
            delta=[(None, 'file', 'file-id')])
 
2760
 
 
2761
    def test_invalid_existing_id(self):
 
2762
        state = self.assertBadDelta(
 
2763
            active=[('file', 'file-id')],
 
2764
            basis= [('file', 'file-id')],
 
2765
            delta=[(None, 'file', 'file-id')])
 
2766
 
 
2767
    def test_invalid_parent_missing(self):
 
2768
        state = self.assertBadDelta(
 
2769
            active=[],
 
2770
            basis= [],
 
2771
            delta=[(None, 'path/path2', 'file-id')])
 
2772
        # Note: we force the active tree to have the directory, by knowing how
 
2773
        #       path_to_ie handles entries with missing parents
 
2774
        state = self.assertBadDelta(
 
2775
            active=[('path/', 'path-id')],
 
2776
            basis= [],
 
2777
            delta=[(None, 'path/path2', 'file-id')])
 
2778
        state = self.assertBadDelta(
 
2779
            active=[('path/', 'path-id'),
 
2780
                    ('path/path2', 'file-id')],
 
2781
            basis= [],
 
2782
            delta=[(None, 'path/path2', 'file-id')])
 
2783
 
 
2784
    def test_renamed_dir_same_path(self):
 
2785
        # We replace the parent directory, with another parent dir. But the C
 
2786
        # file doesn't look like it has been moved.
 
2787
        state = self.assertUpdate(# Same as basis
 
2788
            active=[('dir/', 'A-id'),
 
2789
                    ('dir/B', 'B-id')],
 
2790
            basis= [('dir/', 'A-id'),
 
2791
                    ('dir/B', 'B-id')],
 
2792
            target=[('dir/', 'C-id'),
 
2793
                    ('dir/B', 'B-id')])
 
2794
        state = self.assertUpdate(# Same as target
 
2795
            active=[('dir/', 'C-id'),
 
2796
                    ('dir/B', 'B-id')],
 
2797
            basis= [('dir/', 'A-id'),
 
2798
                    ('dir/B', 'B-id')],
 
2799
            target=[('dir/', 'C-id'),
 
2800
                    ('dir/B', 'B-id')])
 
2801
        state = self.assertUpdate(# empty active
 
2802
            active=[],
 
2803
            basis= [('dir/', 'A-id'),
 
2804
                    ('dir/B', 'B-id')],
 
2805
            target=[('dir/', 'C-id'),
 
2806
                    ('dir/B', 'B-id')])
 
2807
        state = self.assertUpdate(# different active
 
2808
            active=[('dir/', 'D-id'),
 
2809
                    ('dir/B', 'B-id')],
 
2810
            basis= [('dir/', 'A-id'),
 
2811
                    ('dir/B', 'B-id')],
 
2812
            target=[('dir/', 'C-id'),
 
2813
                    ('dir/B', 'B-id')])
 
2814
 
 
2815
    def test_parent_child_swap(self):
 
2816
        state = self.assertUpdate(# Same as basis
 
2817
            active=[('A/', 'A-id'),
 
2818
                    ('A/B/', 'B-id'),
 
2819
                    ('A/B/C', 'C-id')],
 
2820
            basis= [('A/', 'A-id'),
 
2821
                    ('A/B/', 'B-id'),
 
2822
                    ('A/B/C', 'C-id')],
 
2823
            target=[('A/', 'B-id'),
 
2824
                    ('A/B/', 'A-id'),
 
2825
                    ('A/B/C', 'C-id')])
 
2826
        state = self.assertUpdate(# Same as target
 
2827
            active=[('A/', 'B-id'),
 
2828
                    ('A/B/', 'A-id'),
 
2829
                    ('A/B/C', 'C-id')],
 
2830
            basis= [('A/', 'A-id'),
 
2831
                    ('A/B/', 'B-id'),
 
2832
                    ('A/B/C', 'C-id')],
 
2833
            target=[('A/', 'B-id'),
 
2834
                    ('A/B/', 'A-id'),
 
2835
                    ('A/B/C', 'C-id')])
 
2836
        state = self.assertUpdate(# empty active
 
2837
            active=[],
 
2838
            basis= [('A/', 'A-id'),
 
2839
                    ('A/B/', 'B-id'),
 
2840
                    ('A/B/C', 'C-id')],
 
2841
            target=[('A/', 'B-id'),
 
2842
                    ('A/B/', 'A-id'),
 
2843
                    ('A/B/C', 'C-id')])
 
2844
        state = self.assertUpdate(# different active
 
2845
            active=[('D/', 'A-id'),
 
2846
                    ('D/E/', 'B-id'),
 
2847
                    ('F', 'C-id')],
 
2848
            basis= [('A/', 'A-id'),
 
2849
                    ('A/B/', 'B-id'),
 
2850
                    ('A/B/C', 'C-id')],
 
2851
            target=[('A/', 'B-id'),
 
2852
                    ('A/B/', 'A-id'),
 
2853
                    ('A/B/C', 'C-id')])
 
2854
 
 
2855
    def test_change_root_id(self):
 
2856
        state = self.assertUpdate( # same as basis
 
2857
            active=[('', 'root-id'),
 
2858
                    ('file', 'file-id')],
 
2859
            basis= [('', 'root-id'),
 
2860
                    ('file', 'file-id')],
 
2861
            target=[('', 'target-root-id'),
 
2862
                    ('file', 'file-id')])
 
2863
        state = self.assertUpdate( # same as target
 
2864
            active=[('', 'target-root-id'),
 
2865
                    ('file', 'file-id')],
 
2866
            basis= [('', 'root-id'),
 
2867
                    ('file', 'file-id')],
 
2868
            target=[('', 'target-root-id'),
 
2869
                    ('file', 'root-id')])
 
2870
        state = self.assertUpdate( # all different
 
2871
            active=[('', 'active-root-id'),
 
2872
                    ('file', 'file-id')],
 
2873
            basis= [('', 'root-id'),
 
2874
                    ('file', 'file-id')],
 
2875
            target=[('', 'target-root-id'),
 
2876
                    ('file', 'root-id')])
 
2877
 
 
2878
    def test_change_file_absent_in_active(self):
 
2879
        state = self.assertUpdate(
 
2880
            active=[],
 
2881
            basis= [('file', 'file-id')],
 
2882
            target=[('file', 'file-id')])
 
2883
 
 
2884
    def test_invalid_changed_file(self):
 
2885
        state = self.assertBadDelta( # Not present in basis
 
2886
            active=[('file', 'file-id')],
 
2887
            basis= [],
 
2888
            delta=[('file', 'file', 'file-id')])
 
2889
        state = self.assertBadDelta( # present at another location in basis
 
2890
            active=[('file', 'file-id')],
 
2891
            basis= [('other-file', 'file-id')],
 
2892
            delta=[('file', 'file', 'file-id')])