~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree_4.py

(jameinel) Allow 'bzr serve' to interpret SIGHUP as a graceful shutdown.
 (bug #795025) (John A Meinel)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2007-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
"""WorkingTree4 format and implementation.
18
18
 
28
28
 
29
29
from bzrlib.lazy_import import lazy_import
30
30
lazy_import(globals(), """
31
 
from bisect import bisect_left
32
 
import collections
33
 
from copy import deepcopy
34
31
import errno
35
 
import itertools
36
 
import operator
37
32
import stat
38
 
from time import time
39
 
import warnings
40
33
 
41
 
import bzrlib
42
34
from bzrlib import (
43
35
    bzrdir,
44
36
    cache_utf8,
 
37
    config,
45
38
    conflicts as _mod_conflicts,
46
39
    debug,
47
 
    delta,
48
40
    dirstate,
49
41
    errors,
 
42
    filters as _mod_filters,
50
43
    generate_ids,
51
 
    globbing,
52
 
    ignores,
53
 
    merge,
54
44
    osutils,
55
45
    revision as _mod_revision,
56
46
    revisiontree,
57
 
    textui,
58
47
    trace,
59
48
    transform,
60
 
    urlutils,
61
 
    xml5,
62
 
    xml6,
 
49
    views,
63
50
    )
64
 
import bzrlib.branch
65
 
from bzrlib.transport import get_transport
66
 
import bzrlib.ui
67
51
""")
68
52
 
69
 
from bzrlib import symbol_versioning
70
53
from bzrlib.decorators import needs_read_lock, needs_write_lock
71
 
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, entry_factory
72
 
import bzrlib.mutabletree
 
54
from bzrlib.inventory import Inventory, ROOT_ID, entry_factory
 
55
from bzrlib.lock import LogicalLockResult
 
56
from bzrlib.lockable_files import LockableFiles
 
57
from bzrlib.lockdir import LockDir
73
58
from bzrlib.mutabletree import needs_tree_write_lock
74
59
from bzrlib.osutils import (
75
60
    file_kind,
76
61
    isdir,
77
 
    normpath,
78
62
    pathjoin,
79
 
    rand_chars,
80
63
    realpath,
81
64
    safe_unicode,
82
 
    splitpath,
83
65
    )
84
 
from bzrlib.trace import mutter, note
85
66
from bzrlib.transport.local import LocalTransport
86
 
from bzrlib.tree import InterTree
87
 
from bzrlib.progress import DummyProgress, ProgressPhase
88
 
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
89
 
from bzrlib.rio import RioReader, rio_file, Stanza
90
 
from bzrlib.symbol_versioning import (deprecated_passed,
91
 
        deprecated_method,
92
 
        deprecated_function,
93
 
        DEPRECATED_PARAMETER,
94
 
        )
95
 
from bzrlib.tree import Tree
96
 
from bzrlib.workingtree import WorkingTree, WorkingTree3, WorkingTreeFormat3
97
 
 
98
 
 
99
 
class DirStateWorkingTree(WorkingTree3):
 
67
from bzrlib.tree import (
 
68
    InterTree,
 
69
    InventoryTree,
 
70
    )
 
71
from bzrlib.workingtree import (
 
72
    InventoryWorkingTree,
 
73
    WorkingTree,
 
74
    WorkingTreeFormat,
 
75
    )
 
76
 
 
77
 
 
78
class DirStateWorkingTree(InventoryWorkingTree):
 
79
 
100
80
    def __init__(self, basedir,
101
81
                 branch,
102
82
                 _control_files=None,
112
92
        self._format = _format
113
93
        self.bzrdir = _bzrdir
114
94
        basedir = safe_unicode(basedir)
115
 
        mutter("opening working tree %r", basedir)
 
95
        trace.mutter("opening working tree %r", basedir)
116
96
        self._branch = branch
117
97
        self.basedir = realpath(basedir)
118
98
        # if branch is at our basedir and is a format 6 or less
129
109
        self._setup_directory_is_tree_reference()
130
110
        self._detect_case_handling()
131
111
        self._rules_searcher = None
 
112
        self.views = self._make_views()
132
113
        #--- allow tests to select the dirstate iter_changes implementation
133
114
        self._iter_changes = dirstate._process_entry
134
115
 
151
132
            state.add(f, file_id, kind, None, '')
152
133
        self._make_dirty(reset_inventory=True)
153
134
 
 
135
    def _get_check_refs(self):
 
136
        """Return the references needed to perform a check of this tree."""
 
137
        return [('trees', self.last_revision())]
 
138
 
154
139
    def _make_dirty(self, reset_inventory):
155
140
        """Make the tree state dirty.
156
141
 
164
149
    @needs_tree_write_lock
165
150
    def add_reference(self, sub_tree):
166
151
        # use standard implementation, which calls back to self._add
167
 
        # 
 
152
        #
168
153
        # So we don't store the reference_revision in the working dirstate,
169
 
        # it's just recorded at the moment of commit. 
 
154
        # it's just recorded at the moment of commit.
170
155
        self._add_reference(sub_tree)
171
156
 
172
157
    def break_lock(self):
208
193
 
209
194
    def _comparison_data(self, entry, path):
210
195
        kind, executable, stat_value = \
211
 
            WorkingTree3._comparison_data(self, entry, path)
 
196
            WorkingTree._comparison_data(self, entry, path)
212
197
        # it looks like a plain directory, but it's really a reference -- see
213
198
        # also kind()
214
 
        if (self._repo_supports_tree_reference and
215
 
            kind == 'directory' and
216
 
            self._directory_is_tree_reference(path)):
 
199
        if (self._repo_supports_tree_reference and kind == 'directory'
 
200
            and entry is not None and entry.kind == 'tree-reference'):
217
201
            kind = 'tree-reference'
218
202
        return kind, executable, stat_value
219
203
 
221
205
    def commit(self, message=None, revprops=None, *args, **kwargs):
222
206
        # mark the tree as dirty post commit - commit
223
207
        # can change the current versioned list by doing deletes.
224
 
        result = WorkingTree3.commit(self, message, revprops, *args, **kwargs)
 
208
        result = WorkingTree.commit(self, message, revprops, *args, **kwargs)
225
209
        self._make_dirty(reset_inventory=True)
226
210
        return result
227
211
 
245
229
            return self._dirstate
246
230
        local_path = self.bzrdir.get_workingtree_transport(None
247
231
            ).local_abspath('dirstate')
248
 
        self._dirstate = dirstate.DirState.on_file(local_path)
 
232
        self._dirstate = dirstate.DirState.on_file(local_path,
 
233
            self._sha1_provider(), self._worth_saving_limit())
249
234
        return self._dirstate
250
235
 
 
236
    def _sha1_provider(self):
 
237
        """A function that returns a SHA1Provider suitable for this tree.
 
238
 
 
239
        :return: None if content filtering is not supported by this tree.
 
240
          Otherwise, a SHA1Provider is returned that sha's the canonical
 
241
          form of files, i.e. after read filters are applied.
 
242
        """
 
243
        if self.supports_content_filtering():
 
244
            return ContentFilterAwareSHA1Provider(self)
 
245
        else:
 
246
            return None
 
247
 
 
248
    def _worth_saving_limit(self):
 
249
        """How many hash changes are ok before we must save the dirstate.
 
250
 
 
251
        :return: an integer. -1 means never save.
 
252
        """
 
253
        # FIXME: We want a WorkingTreeStack here -- vila 20110812
 
254
        conf = config.BranchStack(self.branch)
 
255
        return conf.get('bzr.workingtree.worth_saving_limit')
 
256
 
251
257
    def filter_unversioned_files(self, paths):
252
258
        """Filter out paths that are versioned.
253
259
 
285
291
 
286
292
    def _generate_inventory(self):
287
293
        """Create and set self.inventory from the dirstate object.
288
 
        
 
294
 
289
295
        This is relatively expensive: we have to walk the entire dirstate.
290
296
        Ideally we would not, and can deprecate this function.
291
297
        """
336
342
                    parent_ies[(dirname + '/' + name).strip('/')] = inv_entry
337
343
                elif kind == 'tree-reference':
338
344
                    if not self._repo_supports_tree_reference:
339
 
                        raise AssertionError(
340
 
                            "repository of %r "
341
 
                            "doesn't support tree references "
342
 
                            "required by entry %r"
343
 
                            % (self, name))
 
345
                        raise errors.UnsupportedOperation(
 
346
                            self._generate_inventory,
 
347
                            self.branch.repository)
344
348
                    inv_entry.reference_revision = link_or_sha1 or None
345
349
                elif kind != 'symlink':
346
350
                    raise AssertionError("unknown kind %r" % kind)
361
365
        If either file_id or path is supplied, it is used as the key to lookup.
362
366
        If both are supplied, the fastest lookup is used, and an error is
363
367
        raised if they do not both point at the same row.
364
 
        
 
368
 
365
369
        :param file_id: An optional unicode file_id to be looked up.
366
370
        :param path: An optional unicode path to be looked up.
367
371
        :return: The dirstate row tuple for path/file_id, or (None, None)
385
389
        state = self.current_dirstate()
386
390
        if stat_value is None:
387
391
            try:
388
 
                stat_value = os.lstat(file_abspath)
 
392
                stat_value = osutils.lstat(file_abspath)
389
393
            except OSError, e:
390
394
                if e.errno == errno.ENOENT:
391
395
                    return None
423
427
    @needs_read_lock
424
428
    def get_parent_ids(self):
425
429
        """See Tree.get_parent_ids.
426
 
        
 
430
 
427
431
        This implementation requests the ids list from the dirstate file.
428
432
        """
429
433
        return self.current_dirstate().get_parent_ids()
451
455
        return osutils.lexists(pathjoin(
452
456
                    self.basedir, row[0].decode('utf8'), row[1].decode('utf8')))
453
457
 
 
458
    def has_or_had_id(self, file_id):
 
459
        state = self.current_dirstate()
 
460
        row, parents = self._get_entry(file_id=file_id)
 
461
        return row is not None
 
462
 
454
463
    @needs_read_lock
455
464
    def id2path(self, file_id):
456
465
        "Convert a file-id to a path."
489
498
            self._must_be_locked()
490
499
            if not path:
491
500
                path = self.id2path(file_id)
492
 
            mode = os.lstat(self.abspath(path)).st_mode
 
501
            mode = osutils.lstat(self.abspath(path)).st_mode
493
502
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
494
503
 
495
504
    def all_file_ids(self):
562
571
    def _kind(self, relpath):
563
572
        abspath = self.abspath(relpath)
564
573
        kind = file_kind(abspath)
565
 
        if (self._repo_supports_tree_reference and
566
 
            kind == 'directory' and
567
 
            self._directory_is_tree_reference(relpath)):
568
 
            kind = 'tree-reference'
 
574
        if (self._repo_supports_tree_reference and kind == 'directory'):
 
575
            entry = self._get_entry(path=relpath)
 
576
            if entry[1] is not None:
 
577
                if entry[1][0][0] == 't':
 
578
                    kind = 'tree-reference'
569
579
        return kind
570
580
 
571
581
    @needs_read_lock
578
588
            return _mod_revision.NULL_REVISION
579
589
 
580
590
    def lock_read(self):
581
 
        """See Branch.lock_read, and WorkingTree.unlock."""
 
591
        """See Branch.lock_read, and WorkingTree.unlock.
 
592
 
 
593
        :return: A bzrlib.lock.LogicalLockResult.
 
594
        """
582
595
        self.branch.lock_read()
583
596
        try:
584
597
            self._control_files.lock_read()
597
610
        except:
598
611
            self.branch.unlock()
599
612
            raise
 
613
        return LogicalLockResult(self.unlock)
600
614
 
601
615
    def _lock_self_write(self):
602
616
        """This should be called after the branch is locked."""
617
631
        except:
618
632
            self.branch.unlock()
619
633
            raise
 
634
        return LogicalLockResult(self.unlock)
620
635
 
621
636
    def lock_tree_write(self):
622
 
        """See MutableTree.lock_tree_write, and WorkingTree.unlock."""
 
637
        """See MutableTree.lock_tree_write, and WorkingTree.unlock.
 
638
 
 
639
        :return: A bzrlib.lock.LogicalLockResult.
 
640
        """
623
641
        self.branch.lock_read()
624
 
        self._lock_self_write()
 
642
        return self._lock_self_write()
625
643
 
626
644
    def lock_write(self):
627
 
        """See MutableTree.lock_write, and WorkingTree.unlock."""
 
645
        """See MutableTree.lock_write, and WorkingTree.unlock.
 
646
 
 
647
        :return: A bzrlib.lock.LogicalLockResult.
 
648
        """
628
649
        self.branch.lock_write()
629
 
        self._lock_self_write()
 
650
        return self._lock_self_write()
630
651
 
631
652
    @needs_tree_write_lock
632
653
    def move(self, from_paths, to_dir, after=False):
702
723
            from_entry = self._get_entry(path=from_rel)
703
724
            if from_entry == (None, None):
704
725
                raise errors.BzrMoveFailedError(from_rel,to_dir,
705
 
                    errors.NotVersionedError(path=str(from_rel)))
 
726
                    errors.NotVersionedError(path=from_rel))
706
727
 
707
728
            from_id = from_entry[0][2]
708
729
            to_rel = pathjoin(to_dir, from_tail)
849
870
                rollback_rename()
850
871
                raise
851
872
            result.append((from_rel, to_rel))
852
 
            state._dirblock_state = dirstate.DirState.IN_MEMORY_MODIFIED
 
873
            state._mark_modified()
853
874
            self._make_dirty(reset_inventory=False)
854
875
 
855
876
        return result
951
972
                raise errors.PathsNotVersionedError(paths)
952
973
        # -- remove redundancy in supplied paths to prevent over-scanning --
953
974
        search_paths = osutils.minimum_path_selection(paths)
954
 
        # sketch: 
 
975
        # sketch:
955
976
        # for all search_indexs in each path at or under each element of
956
977
        # search_paths, if the detail is relocated: add the id, and add the
957
978
        # relocated path as one to search if its not searched already. If the
1013
1034
 
1014
1035
    def read_working_inventory(self):
1015
1036
        """Read the working inventory.
1016
 
        
 
1037
 
1017
1038
        This is a meaningless operation for dirstate, but we obey it anyhow.
1018
1039
        """
1019
1040
        return self.inventory
1037
1058
    def set_last_revision(self, new_revision):
1038
1059
        """Change the last revision in the working tree."""
1039
1060
        parents = self.get_parent_ids()
1040
 
        if new_revision in (NULL_REVISION, None):
 
1061
        if new_revision in (_mod_revision.NULL_REVISION, None):
1041
1062
            if len(parents) >= 2:
1042
1063
                raise AssertionError(
1043
1064
                    "setting the last parent to none with a pending merge is "
1050
1071
    @needs_tree_write_lock
1051
1072
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
1052
1073
        """Set the parent ids to revision_ids.
1053
 
        
 
1074
 
1054
1075
        See also set_parent_trees. This api will try to retrieve the tree data
1055
1076
        for each element of revision_ids from the trees repository. If you have
1056
1077
        tree data already available, it is more efficient to use
1112
1133
                        _mod_revision.NULL_REVISION)))
1113
1134
                ghosts.append(rev_id)
1114
1135
            accepted_revisions.add(rev_id)
1115
 
        dirstate.set_parent_trees(real_trees, ghosts=ghosts)
 
1136
        updated = False
 
1137
        if (len(real_trees) == 1
 
1138
            and not ghosts
 
1139
            and self.branch.repository._format.fast_deltas
 
1140
            and isinstance(real_trees[0][1],
 
1141
                revisiontree.InventoryRevisionTree)
 
1142
            and self.get_parent_ids()):
 
1143
            rev_id, rev_tree = real_trees[0]
 
1144
            basis_id = self.get_parent_ids()[0]
 
1145
            # There are times when basis_tree won't be in
 
1146
            # self.branch.repository, (switch, for example)
 
1147
            try:
 
1148
                basis_tree = self.branch.repository.revision_tree(basis_id)
 
1149
            except errors.NoSuchRevision:
 
1150
                # Fall back to the set_parent_trees(), since we can't use
 
1151
                # _make_delta if we can't get the RevisionTree
 
1152
                pass
 
1153
            else:
 
1154
                delta = rev_tree.inventory._make_delta(basis_tree.inventory)
 
1155
                dirstate.update_basis_by_delta(delta, rev_id)
 
1156
                updated = True
 
1157
        if not updated:
 
1158
            dirstate.set_parent_trees(real_trees, ghosts=ghosts)
1116
1159
        self._make_dirty(reset_inventory=False)
1117
1160
 
1118
1161
    def _set_root_id(self, file_id):
1138
1181
 
1139
1182
    def unlock(self):
1140
1183
        """Unlock in format 4 trees needs to write the entire dirstate."""
1141
 
        # do non-implementation specific cleanup
1142
 
        self._cleanup()
1143
 
 
1144
1184
        if self._control_files._lock_count == 1:
 
1185
            # do non-implementation specific cleanup
 
1186
            self._cleanup()
 
1187
 
1145
1188
            # eventually we should do signature checking during read locks for
1146
1189
            # dirstate updates.
1147
1190
            if self._control_files._lock_mode == 'w':
1210
1253
                # just forget the whole block.
1211
1254
                entry_index = 0
1212
1255
                while entry_index < len(block[1]):
1213
 
                    # Mark this file id as having been removed
1214
1256
                    entry = block[1][entry_index]
1215
 
                    ids_to_unversion.discard(entry[0][2])
1216
 
                    if (entry[1][0][0] in 'ar' # don't remove absent or renamed
1217
 
                                               # entries
1218
 
                        or not state._make_absent(entry)):
 
1257
                    if entry[1][0][0] in 'ar':
 
1258
                        # don't remove absent or renamed entries
1219
1259
                        entry_index += 1
 
1260
                    else:
 
1261
                        # Mark this file id as having been removed
 
1262
                        ids_to_unversion.discard(entry[0][2])
 
1263
                        if not state._make_absent(entry):
 
1264
                            # The block has not shrunk.
 
1265
                            entry_index += 1
1220
1266
                # go to the next block. (At the moment we dont delete empty
1221
1267
                # dirblocks)
1222
1268
                block_index += 1
1243
1289
        # have to change the legacy inventory too.
1244
1290
        if self._inventory is not None:
1245
1291
            for file_id in file_ids:
1246
 
                self._inventory.remove_recursive_id(file_id)
 
1292
                if self._inventory.has_id(file_id):
 
1293
                    self._inventory.remove_recursive_id(file_id)
1247
1294
 
1248
1295
    @needs_tree_write_lock
1249
1296
    def rename_one(self, from_rel, to_rel, after=False):
1250
1297
        """See WorkingTree.rename_one"""
1251
1298
        self.flush()
1252
 
        WorkingTree.rename_one(self, from_rel, to_rel, after)
 
1299
        super(DirStateWorkingTree, self).rename_one(from_rel, to_rel, after)
1253
1300
 
1254
1301
    @needs_tree_write_lock
1255
1302
    def apply_inventory_delta(self, changes):
1274
1321
        if self._dirty:
1275
1322
            raise AssertionError("attempting to write an inventory when the "
1276
1323
                "dirstate is dirty will lose pending changes")
1277
 
        self.current_dirstate().set_state_from_inventory(inv)
1278
 
        self._make_dirty(reset_inventory=False)
1279
 
        if self._inventory is not None:
 
1324
        had_inventory = self._inventory is not None
 
1325
        # Setting self._inventory = None forces the dirstate to regenerate the
 
1326
        # working inventory. We do this because self.inventory may be inv, or
 
1327
        # may have been modified, and either case would prevent a clean delta
 
1328
        # being created.
 
1329
        self._inventory = None
 
1330
        # generate a delta,
 
1331
        delta = inv._make_delta(self.inventory)
 
1332
        # and apply it.
 
1333
        self.apply_inventory_delta(delta)
 
1334
        if had_inventory:
1280
1335
            self._inventory = inv
1281
1336
        self.flush()
1282
1337
 
 
1338
    @needs_tree_write_lock
 
1339
    def reset_state(self, revision_ids=None):
 
1340
        """Reset the state of the working tree.
 
1341
 
 
1342
        This does a hard-reset to a last-known-good state. This is a way to
 
1343
        fix if something got corrupted (like the .bzr/checkout/dirstate file)
 
1344
        """
 
1345
        if revision_ids is None:
 
1346
            revision_ids = self.get_parent_ids()
 
1347
        if not revision_ids:
 
1348
            base_tree = self.branch.repository.revision_tree(
 
1349
                _mod_revision.NULL_REVISION)
 
1350
            trees = []
 
1351
        else:
 
1352
            trees = zip(revision_ids,
 
1353
                        self.branch.repository.revision_trees(revision_ids))
 
1354
            base_tree = trees[0][1]
 
1355
        state = self.current_dirstate()
 
1356
        # We don't support ghosts yet
 
1357
        state.set_state_from_scratch(base_tree.inventory, trees, [])
 
1358
 
 
1359
 
 
1360
class ContentFilterAwareSHA1Provider(dirstate.SHA1Provider):
 
1361
 
 
1362
    def __init__(self, tree):
 
1363
        self.tree = tree
 
1364
 
 
1365
    def sha1(self, abspath):
 
1366
        """See dirstate.SHA1Provider.sha1()."""
 
1367
        filters = self.tree._content_filter_stack(
 
1368
            self.tree.relpath(osutils.safe_unicode(abspath)))
 
1369
        return _mod_filters.internal_size_sha_file_byname(abspath, filters)[1]
 
1370
 
 
1371
    def stat_and_sha1(self, abspath):
 
1372
        """See dirstate.SHA1Provider.stat_and_sha1()."""
 
1373
        filters = self.tree._content_filter_stack(
 
1374
            self.tree.relpath(osutils.safe_unicode(abspath)))
 
1375
        file_obj = file(abspath, 'rb', 65000)
 
1376
        try:
 
1377
            statvalue = os.fstat(file_obj.fileno())
 
1378
            if filters:
 
1379
                file_obj = _mod_filters.filtered_input_file(file_obj, filters)
 
1380
            sha1 = osutils.size_sha_file(file_obj)[1]
 
1381
        finally:
 
1382
            file_obj.close()
 
1383
        return statvalue, sha1
 
1384
 
 
1385
 
 
1386
class ContentFilteringDirStateWorkingTree(DirStateWorkingTree):
 
1387
    """Dirstate working tree that supports content filtering.
 
1388
 
 
1389
    The dirstate holds the hash and size of the canonical form of the file, 
 
1390
    and most methods must return that.
 
1391
    """
 
1392
 
 
1393
    def _file_content_summary(self, path, stat_result):
 
1394
        # This is to support the somewhat obsolete path_content_summary method
 
1395
        # with content filtering: see
 
1396
        # <https://bugs.launchpad.net/bzr/+bug/415508>.
 
1397
        #
 
1398
        # If the dirstate cache is up to date and knows the hash and size,
 
1399
        # return that.
 
1400
        # Otherwise if there are no content filters, return the on-disk size
 
1401
        # and leave the hash blank.
 
1402
        # Otherwise, read and filter the on-disk file and use its size and
 
1403
        # hash.
 
1404
        #
 
1405
        # The dirstate doesn't store the size of the canonical form so we
 
1406
        # can't trust it for content-filtered trees.  We just return None.
 
1407
        dirstate_sha1 = self._dirstate.sha1_from_stat(path, stat_result)
 
1408
        executable = self._is_executable_from_path_and_stat(path, stat_result)
 
1409
        return ('file', None, executable, dirstate_sha1)
 
1410
 
1283
1411
 
1284
1412
class WorkingTree4(DirStateWorkingTree):
1285
1413
    """This is the Format 4 working tree.
1286
1414
 
1287
 
    This differs from WorkingTree3 by:
 
1415
    This differs from WorkingTree by:
1288
1416
     - Having a consolidated internal dirstate, stored in a
1289
1417
       randomly-accessible sorted file on disk.
1290
 
     - Not having a regular inventory attribute.  One can be synthesized 
 
1418
     - Not having a regular inventory attribute.  One can be synthesized
1291
1419
       on demand but this is expensive and should be avoided.
1292
1420
 
1293
1421
    This is new in bzr 0.15.
1294
1422
    """
1295
1423
 
1296
1424
 
1297
 
class WorkingTree5(DirStateWorkingTree):
 
1425
class WorkingTree5(ContentFilteringDirStateWorkingTree):
1298
1426
    """This is the Format 5 working tree.
1299
1427
 
1300
1428
    This differs from WorkingTree4 by:
1301
1429
     - Supporting content filtering.
 
1430
 
 
1431
    This is new in bzr 1.11.
 
1432
    """
 
1433
 
 
1434
 
 
1435
class WorkingTree6(ContentFilteringDirStateWorkingTree):
 
1436
    """This is the Format 6 working tree.
 
1437
 
 
1438
    This differs from WorkingTree5 by:
1302
1439
     - Supporting a current view that may mask the set of files in a tree
1303
1440
       impacted by most user operations.
1304
1441
 
1305
 
    This is new in bzr 1.11.
 
1442
    This is new in bzr 1.14.
1306
1443
    """
1307
1444
 
1308
 
 
1309
 
class DirStateWorkingTreeFormat(WorkingTreeFormat3):
 
1445
    def _make_views(self):
 
1446
        return views.PathBasedViews(self)
 
1447
 
 
1448
 
 
1449
class DirStateWorkingTreeFormat(WorkingTreeFormat):
 
1450
 
 
1451
    missing_parent_conflicts = True
 
1452
 
 
1453
    supports_versioned_directories = True
 
1454
 
 
1455
    _lock_class = LockDir
 
1456
    _lock_file_name = 'lock'
 
1457
 
 
1458
    def _open_control_files(self, a_bzrdir):
 
1459
        transport = a_bzrdir.get_workingtree_transport(None)
 
1460
        return LockableFiles(transport, self._lock_file_name,
 
1461
                             self._lock_class)
 
1462
 
1310
1463
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
1311
1464
                   accelerator_tree=None, hardlink=False):
1312
1465
        """See WorkingTreeFormat.initialize().
1313
1466
 
1314
1467
        :param revision_id: allows creating a working tree at a different
1315
 
        revision than the branch is at.
 
1468
            revision than the branch is at.
1316
1469
        :param accelerator_tree: A tree which can be used for retrieving file
1317
1470
            contents more quickly than the revision tree, i.e. a workingtree.
1318
1471
            The revision tree will be used for cases where accelerator_tree's
1351
1504
        wt.lock_tree_write()
1352
1505
        try:
1353
1506
            self._init_custom_control_files(wt)
1354
 
            if revision_id in (None, NULL_REVISION):
 
1507
            if revision_id in (None, _mod_revision.NULL_REVISION):
1355
1508
                if branch.repository.supports_rich_root():
1356
1509
                    wt._set_root_id(generate_ids.gen_root_id())
1357
1510
                else:
1368
1521
                    pass
1369
1522
            if basis is None:
1370
1523
                basis = branch.repository.revision_tree(revision_id)
1371
 
            if revision_id == NULL_REVISION:
 
1524
            if revision_id == _mod_revision.NULL_REVISION:
1372
1525
                parents_list = []
1373
1526
            else:
1374
1527
                parents_list = [(revision_id, basis)]
1382
1535
                if basis_root_id is not None:
1383
1536
                    wt._set_root_id(basis_root_id)
1384
1537
                    wt.flush()
 
1538
                if wt.supports_content_filtering():
 
1539
                    # The original tree may not have the same content filters
 
1540
                    # applied so we can't safely build the inventory delta from
 
1541
                    # the source tree.
 
1542
                    delta_from_tree = False
 
1543
                else:
 
1544
                    delta_from_tree = True
1385
1545
                # delta_from_tree is safe even for DirStateRevisionTrees,
1386
1546
                # because wt4.apply_inventory_delta does not mutate the input
1387
1547
                # inventory entries.
1388
1548
                transform.build_tree(basis, wt, accelerator_tree,
1389
 
                                     hardlink=hardlink, delta_from_tree=True)
 
1549
                                     hardlink=hardlink,
 
1550
                                     delta_from_tree=delta_from_tree)
1390
1551
            finally:
1391
1552
                basis.unlock()
1392
1553
        finally:
1396
1557
 
1397
1558
    def _init_custom_control_files(self, wt):
1398
1559
        """Subclasses with custom control files should override this method.
1399
 
        
 
1560
 
1400
1561
        The working tree and control files are locked for writing when this
1401
1562
        method is called.
1402
 
        
 
1563
 
1403
1564
        :param wt: the WorkingTree object
1404
1565
        """
1405
1566
 
 
1567
    def open(self, a_bzrdir, _found=False):
 
1568
        """Return the WorkingTree object for a_bzrdir
 
1569
 
 
1570
        _found is a private parameter, do not use it. It is used to indicate
 
1571
               if format probing has already been done.
 
1572
        """
 
1573
        if not _found:
 
1574
            # we are being called directly and must probe.
 
1575
            raise NotImplementedError
 
1576
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
1577
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
1578
        wt = self._open(a_bzrdir, self._open_control_files(a_bzrdir))
 
1579
        return wt
 
1580
 
1406
1581
    def _open(self, a_bzrdir, control_files):
1407
1582
        """Open the tree itself.
1408
1583
 
1416
1591
                           _control_files=control_files)
1417
1592
 
1418
1593
    def __get_matchingbzrdir(self):
 
1594
        return self._get_matchingbzrdir()
 
1595
 
 
1596
    def _get_matchingbzrdir(self):
 
1597
        """Overrideable method to get a bzrdir for testing."""
1419
1598
        # please test against something that will let us do tree references
1420
1599
        return bzrdir.format_registry.make_bzrdir(
1421
1600
            'dirstate-with-subtree')
1449
1628
 
1450
1629
 
1451
1630
class WorkingTreeFormat5(DirStateWorkingTreeFormat):
1452
 
    """WorkingTree format supporting views.
 
1631
    """WorkingTree format supporting content filtering.
1453
1632
    """
1454
1633
 
1455
1634
    upgrade_recommended = False
1464
1643
        """See WorkingTreeFormat.get_format_description()."""
1465
1644
        return "Working tree format 5"
1466
1645
 
 
1646
    def supports_content_filtering(self):
 
1647
        return True
 
1648
 
 
1649
 
 
1650
class WorkingTreeFormat6(DirStateWorkingTreeFormat):
 
1651
    """WorkingTree format supporting views.
 
1652
    """
 
1653
 
 
1654
    upgrade_recommended = False
 
1655
 
 
1656
    _tree_class = WorkingTree6
 
1657
 
 
1658
    def get_format_string(self):
 
1659
        """See WorkingTreeFormat.get_format_string()."""
 
1660
        return "Bazaar Working Tree Format 6 (bzr 1.14)\n"
 
1661
 
 
1662
    def get_format_description(self):
 
1663
        """See WorkingTreeFormat.get_format_description()."""
 
1664
        return "Working tree format 6"
 
1665
 
1467
1666
    def _init_custom_control_files(self, wt):
1468
1667
        """Subclasses with custom control files should override this method."""
1469
1668
        wt._transport.put_bytes('views', '', mode=wt.bzrdir._get_file_mode())
1475
1674
        return True
1476
1675
 
1477
1676
 
1478
 
class DirStateRevisionTree(Tree):
1479
 
    """A revision tree pulling the inventory from a dirstate."""
 
1677
class DirStateRevisionTree(InventoryTree):
 
1678
    """A revision tree pulling the inventory from a dirstate.
 
1679
    
 
1680
    Note that this is one of the historical (ie revision) trees cached in the
 
1681
    dirstate for easy access, not the workingtree.
 
1682
    """
1480
1683
 
1481
1684
    def __init__(self, dirstate, revision_id, repository):
1482
1685
        self._dirstate = dirstate
1496
1699
    def annotate_iter(self, file_id,
1497
1700
                      default_revision=_mod_revision.CURRENT_REVISION):
1498
1701
        """See Tree.annotate_iter"""
1499
 
        text_key = (file_id, self.inventory[file_id].revision)
 
1702
        text_key = (file_id, self.get_file_revision(file_id))
1500
1703
        annotations = self._repository.texts.annotate(text_key)
1501
1704
        return [(key[-1], line) for (key, line) in annotations]
1502
1705
 
1503
 
    def _get_ancestors(self, default_revision):
1504
 
        return set(self._repository.get_ancestry(self._revision_id,
1505
 
                                                 topo_sorted=False))
1506
1706
    def _comparison_data(self, entry, path):
1507
1707
        """See Tree._comparison_data."""
1508
1708
        if entry is None:
1551
1751
        If either file_id or path is supplied, it is used as the key to lookup.
1552
1752
        If both are supplied, the fastest lookup is used, and an error is
1553
1753
        raised if they do not both point at the same row.
1554
 
        
 
1754
 
1555
1755
        :param file_id: An optional unicode file_id to be looked up.
1556
1756
        :param path: An optional unicode path to be looked up.
1557
1757
        :return: The dirstate row tuple for path/file_id, or (None, None)
1624
1824
                elif kind == 'directory':
1625
1825
                    parent_ies[(dirname + '/' + name).strip('/')] = inv_entry
1626
1826
                elif kind == 'symlink':
1627
 
                    inv_entry.executable = False
1628
 
                    inv_entry.text_size = None
1629
1827
                    inv_entry.symlink_target = utf8_decode(fingerprint)[0]
1630
1828
                elif kind == 'tree-reference':
1631
1829
                    inv_entry.reference_revision = fingerprint or None
1651
1849
        # Make sure the file exists
1652
1850
        entry = self._get_entry(file_id, path=path)
1653
1851
        if entry == (None, None): # do we raise?
1654
 
            return None
 
1852
            raise errors.NoSuchId(self, file_id)
1655
1853
        parent_index = self._get_parent_index()
1656
1854
        last_changed_revision = entry[1][parent_index][4]
1657
 
        return self._repository.get_revision(last_changed_revision).timestamp
 
1855
        try:
 
1856
            rev = self._repository.get_revision(last_changed_revision)
 
1857
        except errors.NoSuchRevision:
 
1858
            raise errors.FileTimestampUnavailable(self.id2path(file_id))
 
1859
        return rev.timestamp
1658
1860
 
1659
1861
    def get_file_sha1(self, file_id, path=None, stat_value=None):
1660
1862
        entry = self._get_entry(file_id=file_id, path=path)
1664
1866
            return parent_details[1]
1665
1867
        return None
1666
1868
 
 
1869
    @needs_read_lock
 
1870
    def get_file_revision(self, file_id):
 
1871
        return self.inventory[file_id].revision
 
1872
 
1667
1873
    def get_file(self, file_id, path=None):
1668
1874
        return StringIO(self.get_file_text(file_id))
1669
1875
 
1672
1878
        return self.inventory[file_id].text_size
1673
1879
 
1674
1880
    def get_file_text(self, file_id, path=None):
1675
 
        return list(self.iter_files_bytes([(file_id, None)]))[0][1]
 
1881
        _, content = list(self.iter_files_bytes([(file_id, None)]))[0]
 
1882
        return ''.join(content)
1676
1883
 
1677
1884
    def get_reference_revision(self, file_id, path=None):
1678
1885
        return self.inventory[file_id].reference_revision
1691
1898
                                       identifier))
1692
1899
        return self._repository.iter_files_bytes(repo_desired_files)
1693
1900
 
1694
 
    def get_symlink_target(self, file_id):
 
1901
    def get_symlink_target(self, file_id, path=None):
1695
1902
        entry = self._get_entry(file_id=file_id)
1696
1903
        parent_index = self._get_parent_index()
1697
1904
        if entry[1][parent_index][0] != 'l':
1698
1905
            return None
1699
1906
        else:
1700
 
            # At present, none of the tree implementations supports non-ascii
1701
 
            # symlink targets. So we will just assume that the dirstate path is
1702
 
            # correct.
1703
 
            return entry[1][parent_index][1]
 
1907
            target = entry[1][parent_index][1]
 
1908
            target = target.decode('utf8')
 
1909
            return target
1704
1910
 
1705
1911
    def get_revision_id(self):
1706
1912
        """Return the revision id for this tree."""
1727
1933
        entry = self._get_entry(file_id=file_id)[1]
1728
1934
        if entry is None:
1729
1935
            raise errors.NoSuchId(tree=self, file_id=file_id)
1730
 
        return dirstate.DirState._minikind_to_kind[entry[1][0]]
 
1936
        parent_index = self._get_parent_index()
 
1937
        return dirstate.DirState._minikind_to_kind[entry[parent_index][0]]
1731
1938
 
1732
1939
    def stored_kind(self, file_id):
1733
1940
        """See Tree.stored_kind"""
1750
1957
    def is_executable(self, file_id, path=None):
1751
1958
        ie = self.inventory[file_id]
1752
1959
        if ie.kind != "file":
1753
 
            return None
 
1960
            return False
1754
1961
        return ie.executable
1755
1962
 
1756
 
    def list_files(self, include_root=False):
 
1963
    def is_locked(self):
 
1964
        return self._locked
 
1965
 
 
1966
    def list_files(self, include_root=False, from_dir=None, recursive=True):
1757
1967
        # We use a standard implementation, because DirStateRevisionTree is
1758
1968
        # dealing with one of the parents of the current state
1759
1969
        inv = self._get_inventory()
1760
 
        entries = inv.iter_entries()
1761
 
        if self.inventory.root is not None and not include_root:
 
1970
        if from_dir is None:
 
1971
            from_dir_id = None
 
1972
        else:
 
1973
            from_dir_id = inv.path2id(from_dir)
 
1974
            if from_dir_id is None:
 
1975
                # Directory not versioned
 
1976
                return
 
1977
        entries = inv.iter_entries(from_dir=from_dir_id, recursive=recursive)
 
1978
        if inv.root is not None and not include_root and from_dir is None:
1762
1979
            entries.next()
1763
1980
        for path, entry in entries:
1764
1981
            yield path, 'V', entry.kind, entry.file_id, entry
1765
1982
 
1766
1983
    def lock_read(self):
1767
 
        """Lock the tree for a set of operations."""
 
1984
        """Lock the tree for a set of operations.
 
1985
 
 
1986
        :return: A bzrlib.lock.LogicalLockResult.
 
1987
        """
1768
1988
        if not self._locked:
1769
1989
            self._repository.lock_read()
1770
1990
            if self._dirstate._lock_token is None:
1771
1991
                self._dirstate.lock_read()
1772
1992
                self._dirstate_locked = True
1773
1993
        self._locked += 1
 
1994
        return LogicalLockResult(self.unlock)
1774
1995
 
1775
1996
    def _must_be_locked(self):
1776
1997
        if not self._locked:
1803
2024
 
1804
2025
    def walkdirs(self, prefix=""):
1805
2026
        # TODO: jam 20070215 This is the lazy way by using the RevisionTree
1806
 
        # implementation based on an inventory.  
 
2027
        # implementation based on an inventory.
1807
2028
        # This should be cleaned up to use the much faster Dirstate code
1808
2029
        # So for now, we just build up the parent inventory, and extract
1809
2030
        # it the same way RevisionTree does.
1838
2059
 
1839
2060
class InterDirStateTree(InterTree):
1840
2061
    """Fast path optimiser for changes_from with dirstate trees.
1841
 
    
1842
 
    This is used only when both trees are in the dirstate working file, and 
1843
 
    the source is any parent within the dirstate, and the destination is 
 
2062
 
 
2063
    This is used only when both trees are in the dirstate working file, and
 
2064
    the source is any parent within the dirstate, and the destination is
1844
2065
    the current working tree of the same dirstate.
1845
2066
    """
1846
2067
    # this could be generalized to allow comparisons between any trees in the
1855
2076
    def make_source_parent_tree(source, target):
1856
2077
        """Change the source tree into a parent of the target."""
1857
2078
        revid = source.commit('record tree')
1858
 
        target.branch.repository.fetch(source.branch.repository, revid)
 
2079
        target.branch.fetch(source.branch, revid)
1859
2080
        target.set_parent_ids([revid])
1860
2081
        return target.basis_tree(), target
1861
2082
 
1866
2087
        return result
1867
2088
 
1868
2089
    @classmethod
1869
 
    def make_source_parent_tree_compiled_dirstate(klass, test_case, source, target):
 
2090
    def make_source_parent_tree_compiled_dirstate(klass, test_case, source,
 
2091
                                                  target):
1870
2092
        from bzrlib.tests.test__dirstate_helpers import \
1871
 
            CompiledDirstateHelpersFeature
1872
 
        if not CompiledDirstateHelpersFeature.available():
1873
 
            from bzrlib.tests import UnavailableFeature
1874
 
            raise UnavailableFeature(CompiledDirstateHelpersFeature)
1875
 
        from bzrlib._dirstate_helpers_c import ProcessEntryC
 
2093
            compiled_dirstate_helpers_feature
 
2094
        test_case.requireFeature(compiled_dirstate_helpers_feature)
 
2095
        from bzrlib._dirstate_helpers_pyx import ProcessEntryC
1876
2096
        result = klass.make_source_parent_tree(source, target)
1877
2097
        result[1]._iter_changes = ProcessEntryC
1878
2098
        return result
1908
2128
            output. An unversioned file is defined as one with (False, False)
1909
2129
            for the versioned pair.
1910
2130
        """
1911
 
        # NB: show_status depends on being able to pass in non-versioned files
1912
 
        # and report them as unknown
1913
2131
        # TODO: handle extra trees in the dirstate.
1914
2132
        if (extra_trees or specific_files == []):
1915
2133
            # we can't fast-path these cases (yet)
1918
2136
                require_versioned, want_unversioned=want_unversioned)
1919
2137
        parent_ids = self.target.get_parent_ids()
1920
2138
        if not (self.source._revision_id in parent_ids
1921
 
                or self.source._revision_id == NULL_REVISION):
 
2139
                or self.source._revision_id == _mod_revision.NULL_REVISION):
1922
2140
            raise AssertionError(
1923
2141
                "revision {%s} is not stored in {%s}, but %s "
1924
2142
                "can only be used for trees stored in the dirstate"
1925
2143
                % (self.source._revision_id, self.target, self.iter_changes))
1926
2144
        target_index = 0
1927
 
        if self.source._revision_id == NULL_REVISION:
 
2145
        if self.source._revision_id == _mod_revision.NULL_REVISION:
1928
2146
            source_index = None
1929
2147
            indices = (target_index,)
1930
2148
        else:
1945
2163
        else:
1946
2164
            specific_files = set([''])
1947
2165
        # -- specific_files is now a utf8 path set --
1948
 
        search_specific_files = set()
 
2166
 
1949
2167
        # -- get the state object and prepare it.
1950
2168
        state = self.target.current_dirstate()
1951
2169
        state._read_dirblocks_if_needed()
1952
2170
        if require_versioned:
1953
2171
            # -- check all supplied paths are versioned in a search tree. --
1954
 
            all_versioned = True
 
2172
            not_versioned = []
1955
2173
            for path in specific_files:
1956
2174
                path_entries = state._entries_for_path(path)
1957
2175
                if not path_entries:
1958
2176
                    # this specified path is not present at all: error
1959
 
                    all_versioned = False
1960
 
                    break
 
2177
                    not_versioned.append(path)
 
2178
                    continue
1961
2179
                found_versioned = False
1962
2180
                # for each id at this path
1963
2181
                for entry in path_entries:
1970
2188
                if not found_versioned:
1971
2189
                    # none of the indexes was not 'absent' at all ids for this
1972
2190
                    # path.
1973
 
                    all_versioned = False
1974
 
                    break
1975
 
            if not all_versioned:
1976
 
                raise errors.PathsNotVersionedError(specific_files)
 
2191
                    not_versioned.append(path)
 
2192
            if len(not_versioned) > 0:
 
2193
                raise errors.PathsNotVersionedError(not_versioned)
1977
2194
        # -- remove redundancy in supplied specific_files to prevent over-scanning --
1978
 
        for path in specific_files:
1979
 
            other_specific_files = specific_files.difference(set([path]))
1980
 
            if not osutils.is_inside_any(other_specific_files, path):
1981
 
                # this is a top level path, we must check it.
1982
 
                search_specific_files.add(path)
 
2195
        search_specific_files = osutils.minimum_path_selection(specific_files)
1983
2196
 
1984
2197
        use_filesystem_for_exec = (sys.platform != 'win32')
1985
2198
        iter_changes = self.target._iter_changes(include_unchanged,
1997
2210
            (revisiontree.RevisionTree, DirStateRevisionTree)):
1998
2211
            return False
1999
2212
        # the source revid must be in the target dirstate
2000
 
        if not (source._revision_id == NULL_REVISION or
 
2213
        if not (source._revision_id == _mod_revision.NULL_REVISION or
2001
2214
            source._revision_id in target.get_parent_ids()):
2002
 
            # TODO: what about ghosts? it may well need to 
 
2215
            # TODO: what about ghosts? it may well need to
2003
2216
            # check for them explicitly.
2004
2217
            return False
2005
2218
        return True
2015
2228
 
2016
2229
    def convert(self, tree):
2017
2230
        # lock the control files not the tree, so that we dont get tree
2018
 
        # on-unlock behaviours, and so that noone else diddles with the 
 
2231
        # on-unlock behaviours, and so that noone else diddles with the
2019
2232
        # tree during upgrade.
2020
2233
        tree._control_files.lock_write()
2021
2234
        try:
2060
2273
 
2061
2274
    def convert(self, tree):
2062
2275
        # lock the control files not the tree, so that we don't get tree
2063
 
        # on-unlock behaviours, and so that no-one else diddles with the 
 
2276
        # on-unlock behaviours, and so that no-one else diddles with the
 
2277
        # tree during upgrade.
 
2278
        tree._control_files.lock_write()
 
2279
        try:
 
2280
            self.update_format(tree)
 
2281
        finally:
 
2282
            tree._control_files.unlock()
 
2283
 
 
2284
    def update_format(self, tree):
 
2285
        """Change the format marker."""
 
2286
        tree._transport.put_bytes('format',
 
2287
            self.target_format.get_format_string(),
 
2288
            mode=tree.bzrdir._get_file_mode())
 
2289
 
 
2290
 
 
2291
class Converter4or5to6(object):
 
2292
    """Perform an in-place upgrade of format 4 or 5 to format 6 trees."""
 
2293
 
 
2294
    def __init__(self):
 
2295
        self.target_format = WorkingTreeFormat6()
 
2296
 
 
2297
    def convert(self, tree):
 
2298
        # lock the control files not the tree, so that we don't get tree
 
2299
        # on-unlock behaviours, and so that no-one else diddles with the
2064
2300
        # tree during upgrade.
2065
2301
        tree._control_files.lock_write()
2066
2302
        try: