/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/workingtree.py

  • Committer: Jelmer Vernooij
  • Date: 2017-06-10 00:06:46 UTC
  • mfrom: (6673 work)
  • mto: This revision was merged to the branch mainline in revision 6675.
  • Revision ID: jelmer@jelmer.uk-20170610000646-xj6jh277lo4xuo10
Merge trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
 
19
19
A WorkingTree represents the editable working copy of a branch.
20
20
Operations which represent the WorkingTree are also done here,
21
 
such as renaming or adding files.  The WorkingTree has an inventory
22
 
which is updated by these operations.  A commit produces a
23
 
new revision based on the workingtree and its inventory.
 
21
such as renaming or adding files.  
24
22
 
25
23
At the moment every WorkingTree has its own branch.  Remote
26
24
WorkingTrees aren't supported.
41
39
from .lazy_import import lazy_import
42
40
lazy_import(globals(), """
43
41
from bisect import bisect_left
44
 
import collections
45
42
import itertools
46
43
import operator
47
44
import stat
48
45
 
49
46
from breezy import (
50
47
    branch,
51
 
    cache_utf8,
52
48
    conflicts as _mod_conflicts,
53
49
    controldir,
54
50
    errors,
55
51
    filters as _mod_filters,
56
52
    generate_ids,
57
53
    globbing,
58
 
    graph as _mod_graph,
59
54
    ignores,
60
 
    inventory,
61
55
    merge,
62
56
    revision as _mod_revision,
63
 
    revisiontree,
64
 
    rio as _mod_rio,
65
57
    shelf,
66
58
    transform,
67
59
    transport,
68
60
    ui,
69
61
    views,
70
 
    xml5,
71
 
    xml7,
72
62
    )
73
63
""")
74
64
 
75
 
# Explicitly import breezy.bzrdir so that the BzrProber
76
 
# is guaranteed to be registered.
77
65
from . import (
78
 
    bzrdir,
79
66
    osutils,
80
67
    )
81
68
from .decorators import needs_read_lock, needs_write_lock
82
69
from .i18n import gettext
83
 
from .lock import LogicalLockResult
84
70
from . import mutabletree
85
71
from .mutabletree import needs_tree_write_lock
86
 
from .osutils import (
87
 
    file_kind,
88
 
    isdir,
89
 
    normpath,
90
 
    pathjoin,
91
 
    realpath,
92
 
    safe_unicode,
93
 
    splitpath,
94
 
    )
95
 
from .revision import CURRENT_REVISION
96
 
from .sixish import (
97
 
    BytesIO,
98
 
    )
99
72
from .trace import mutter, note
100
73
 
101
74
 
102
 
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
103
 
# TODO: Modifying the conflict objects or their type is currently nearly
104
 
# impossible as there is no clear relationship between the working tree format
105
 
# and the conflict list file format.
106
 
CONFLICT_HEADER_1 = "BZR conflict list format 1"
107
 
 
108
75
ERROR_PATH_NOT_FOUND = 3    # WindowsError errno code, equivalent to ENOENT
109
76
 
110
77
 
190
157
        if not _internal:
191
158
            raise errors.BzrError("Please use bzrdir.open_workingtree or "
192
159
                "WorkingTree.open() to obtain a WorkingTree.")
193
 
        basedir = safe_unicode(basedir)
 
160
        basedir = osutils.safe_unicode(basedir)
194
161
        mutter("opening working tree %r", basedir)
195
162
        if branch is not None:
196
163
            self._branch = branch
197
164
        else:
198
165
            self._branch = self.bzrdir.open_branch()
199
 
        self.basedir = realpath(basedir)
 
166
        self.basedir = osutils.realpath(basedir)
200
167
        self._transport = _transport
201
168
        self._rules_searcher = None
202
169
        self.views = self._make_views()
392
359
                               getattr(self, 'basedir', None))
393
360
 
394
361
    def abspath(self, filename):
395
 
        return pathjoin(self.basedir, filename)
 
362
        return osutils.pathjoin(self.basedir, filename)
396
363
 
397
364
    def basis_tree(self):
398
365
        """Return RevisionTree for the current last revision.
549
516
    def id2abspath(self, file_id):
550
517
        return self.abspath(self.id2path(file_id))
551
518
 
552
 
    def _check_for_tree_references(self, iterator):
553
 
        """See if directories have become tree-references."""
554
 
        blocked_parent_ids = set()
555
 
        for path, ie in iterator:
556
 
            if ie.parent_id in blocked_parent_ids:
557
 
                # This entry was pruned because one of its parents became a
558
 
                # TreeReference. If this is a directory, mark it as blocked.
559
 
                if ie.kind == 'directory':
560
 
                    blocked_parent_ids.add(ie.file_id)
561
 
                continue
562
 
            if ie.kind == 'directory' and self._directory_is_tree_reference(path):
563
 
                # This InventoryDirectory needs to be a TreeReference
564
 
                ie = inventory.TreeReference(ie.file_id, ie.name, ie.parent_id)
565
 
                blocked_parent_ids.add(ie.file_id)
566
 
            yield path, ie
567
 
 
568
 
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
569
 
        """See Tree.iter_entries_by_dir()"""
570
 
        # The only trick here is that if we supports_tree_reference then we
571
 
        # need to detect if a directory becomes a tree-reference.
572
 
        iterator = super(WorkingTree, self).iter_entries_by_dir(
573
 
                specific_file_ids=specific_file_ids,
574
 
                yield_parents=yield_parents)
575
 
        if not self.supports_tree_reference():
576
 
            return iterator
577
 
        else:
578
 
            return self._check_for_tree_references(iterator)
579
 
 
580
519
    def get_file_size(self, file_id):
581
520
        """See Tree.get_file_size"""
582
521
        # XXX: this returns the on-disk size; it should probably return the
594
533
        """See MutableTree._gather_kinds."""
595
534
        for pos, f in enumerate(files):
596
535
            if kinds[pos] is None:
597
 
                fullpath = normpath(self.abspath(f))
 
536
                fullpath = osutils.normpath(self.abspath(f))
598
537
                try:
599
 
                    kinds[pos] = file_kind(fullpath)
 
538
                    kinds[pos] = osutils.file_kind(fullpath)
600
539
                except OSError as e:
601
540
                    if e.errno == errno.ENOENT:
602
541
                        raise errors.NoSuchFile(fullpath)
1112
1051
        return self._ignoreglobster.match(filename)
1113
1052
 
1114
1053
    def kind(self, file_id):
1115
 
        return file_kind(self.id2abspath(file_id))
 
1054
        return osutils.file_kind(self.id2abspath(file_id))
1116
1055
 
1117
1056
    def stored_kind(self, file_id):
1118
1057
        """See Tree.stored_kind"""
1771
1710
        return ShelfManager(self, self._transport)
1772
1711
 
1773
1712
 
1774
 
class InventoryWorkingTree(WorkingTree,
1775
 
        mutabletree.MutableInventoryTree):
1776
 
    """Base class for working trees that are inventory-oriented.
1777
 
 
1778
 
    The inventory is held in the `Branch` working-inventory, and the
1779
 
    files are in a directory on disk.
1780
 
 
1781
 
    It is possible for a `WorkingTree` to have a filename which is
1782
 
    not listed in the Inventory and vice versa.
1783
 
    """
1784
 
 
1785
 
    def __init__(self, basedir='.',
1786
 
                 branch=None,
1787
 
                 _inventory=None,
1788
 
                 _control_files=None,
1789
 
                 _internal=False,
1790
 
                 _format=None,
1791
 
                 _bzrdir=None):
1792
 
        """Construct a InventoryWorkingTree instance. This is not a public API.
1793
 
 
1794
 
        :param branch: A branch to override probing for the branch.
1795
 
        """
1796
 
        super(InventoryWorkingTree, self).__init__(basedir=basedir,
1797
 
            branch=branch, _transport=_control_files._transport,
1798
 
            _internal=_internal, _format=_format, _bzrdir=_bzrdir)
1799
 
 
1800
 
        self._control_files = _control_files
1801
 
        self._detect_case_handling()
1802
 
 
1803
 
        if _inventory is None:
1804
 
            # This will be acquired on lock_read() or lock_write()
1805
 
            self._inventory_is_modified = False
1806
 
            self._inventory = None
1807
 
        else:
1808
 
            # the caller of __init__ has provided an inventory,
1809
 
            # we assume they know what they are doing - as its only
1810
 
            # the Format factory and creation methods that are
1811
 
            # permitted to do this.
1812
 
            self._set_inventory(_inventory, dirty=False)
1813
 
 
1814
 
    def _set_inventory(self, inv, dirty):
1815
 
        """Set the internal cached inventory.
1816
 
 
1817
 
        :param inv: The inventory to set.
1818
 
        :param dirty: A boolean indicating whether the inventory is the same
1819
 
            logical inventory as whats on disk. If True the inventory is not
1820
 
            the same and should be written to disk or data will be lost, if
1821
 
            False then the inventory is the same as that on disk and any
1822
 
            serialisation would be unneeded overhead.
1823
 
        """
1824
 
        self._inventory = inv
1825
 
        self._inventory_is_modified = dirty
1826
 
 
1827
 
    def _detect_case_handling(self):
1828
 
        wt_trans = self.bzrdir.get_workingtree_transport(None)
1829
 
        try:
1830
 
            wt_trans.stat(self._format.case_sensitive_filename)
1831
 
        except errors.NoSuchFile:
1832
 
            self.case_sensitive = True
1833
 
        else:
1834
 
            self.case_sensitive = False
1835
 
 
1836
 
        self._setup_directory_is_tree_reference()
1837
 
 
1838
 
    def _serialize(self, inventory, out_file):
1839
 
        xml5.serializer_v5.write_inventory(self._inventory, out_file,
1840
 
            working=True)
1841
 
 
1842
 
    def _deserialize(selt, in_file):
1843
 
        return xml5.serializer_v5.read_inventory(in_file)
1844
 
 
1845
 
    def break_lock(self):
1846
 
        """Break a lock if one is present from another instance.
1847
 
 
1848
 
        Uses the ui factory to ask for confirmation if the lock may be from
1849
 
        an active process.
1850
 
 
1851
 
        This will probe the repository for its lock as well.
1852
 
        """
1853
 
        self._control_files.break_lock()
1854
 
        self.branch.break_lock()
1855
 
 
1856
 
    def is_locked(self):
1857
 
        return self._control_files.is_locked()
1858
 
 
1859
 
    def _must_be_locked(self):
1860
 
        if not self.is_locked():
1861
 
            raise errors.ObjectNotLocked(self)
1862
 
 
1863
 
    def lock_read(self):
1864
 
        """Lock the tree for reading.
1865
 
 
1866
 
        This also locks the branch, and can be unlocked via self.unlock().
1867
 
 
1868
 
        :return: A breezy.lock.LogicalLockResult.
1869
 
        """
1870
 
        if not self.is_locked():
1871
 
            self._reset_data()
1872
 
        self.branch.lock_read()
1873
 
        try:
1874
 
            self._control_files.lock_read()
1875
 
            return LogicalLockResult(self.unlock)
1876
 
        except:
1877
 
            self.branch.unlock()
1878
 
            raise
1879
 
 
1880
 
    def lock_tree_write(self):
1881
 
        """See MutableTree.lock_tree_write, and WorkingTree.unlock.
1882
 
 
1883
 
        :return: A breezy.lock.LogicalLockResult.
1884
 
        """
1885
 
        if not self.is_locked():
1886
 
            self._reset_data()
1887
 
        self.branch.lock_read()
1888
 
        try:
1889
 
            self._control_files.lock_write()
1890
 
            return LogicalLockResult(self.unlock)
1891
 
        except:
1892
 
            self.branch.unlock()
1893
 
            raise
1894
 
 
1895
 
    def lock_write(self):
1896
 
        """See MutableTree.lock_write, and WorkingTree.unlock.
1897
 
 
1898
 
        :return: A breezy.lock.LogicalLockResult.
1899
 
        """
1900
 
        if not self.is_locked():
1901
 
            self._reset_data()
1902
 
        self.branch.lock_write()
1903
 
        try:
1904
 
            self._control_files.lock_write()
1905
 
            return LogicalLockResult(self.unlock)
1906
 
        except:
1907
 
            self.branch.unlock()
1908
 
            raise
1909
 
 
1910
 
    def get_physical_lock_status(self):
1911
 
        return self._control_files.get_physical_lock_status()
1912
 
 
1913
 
    @needs_tree_write_lock
1914
 
    def _write_inventory(self, inv):
1915
 
        """Write inventory as the current inventory."""
1916
 
        self._set_inventory(inv, dirty=True)
1917
 
        self.flush()
1918
 
 
1919
 
    # XXX: This method should be deprecated in favour of taking in a proper
1920
 
    # new Inventory object.
1921
 
    @needs_tree_write_lock
1922
 
    def set_inventory(self, new_inventory_list):
1923
 
        from .inventory import (
1924
 
            Inventory,
1925
 
            InventoryDirectory,
1926
 
            InventoryFile,
1927
 
            InventoryLink)
1928
 
        inv = Inventory(self.get_root_id())
1929
 
        for path, file_id, parent, kind in new_inventory_list:
1930
 
            name = os.path.basename(path)
1931
 
            if name == "":
1932
 
                continue
1933
 
            # fixme, there should be a factory function inv,add_??
1934
 
            if kind == 'directory':
1935
 
                inv.add(InventoryDirectory(file_id, name, parent))
1936
 
            elif kind == 'file':
1937
 
                inv.add(InventoryFile(file_id, name, parent))
1938
 
            elif kind == 'symlink':
1939
 
                inv.add(InventoryLink(file_id, name, parent))
1940
 
            else:
1941
 
                raise errors.BzrError("unknown kind %r" % kind)
1942
 
        self._write_inventory(inv)
1943
 
 
1944
 
    def _write_basis_inventory(self, xml):
1945
 
        """Write the basis inventory XML to the basis-inventory file"""
1946
 
        path = self._basis_inventory_name()
1947
 
        sio = BytesIO(xml)
1948
 
        self._transport.put_file(path, sio,
1949
 
            mode=self.bzrdir._get_file_mode())
1950
 
 
1951
 
    def _reset_data(self):
1952
 
        """Reset transient data that cannot be revalidated."""
1953
 
        self._inventory_is_modified = False
1954
 
        f = self._transport.get('inventory')
1955
 
        try:
1956
 
            result = self._deserialize(f)
1957
 
        finally:
1958
 
            f.close()
1959
 
        self._set_inventory(result, dirty=False)
1960
 
 
1961
 
    def _set_root_id(self, file_id):
1962
 
        """Set the root id for this tree, in a format specific manner.
1963
 
 
1964
 
        :param file_id: The file id to assign to the root. It must not be
1965
 
            present in the current inventory or an error will occur. It must
1966
 
            not be None, but rather a valid file id.
1967
 
        """
1968
 
        inv = self._inventory
1969
 
        orig_root_id = inv.root.file_id
1970
 
        # TODO: it might be nice to exit early if there was nothing
1971
 
        # to do, saving us from trigger a sync on unlock.
1972
 
        self._inventory_is_modified = True
1973
 
        # we preserve the root inventory entry object, but
1974
 
        # unlinkit from the byid index
1975
 
        del inv._byid[inv.root.file_id]
1976
 
        inv.root.file_id = file_id
1977
 
        # and link it into the index with the new changed id.
1978
 
        inv._byid[inv.root.file_id] = inv.root
1979
 
        # and finally update all children to reference the new id.
1980
 
        # XXX: this should be safe to just look at the root.children
1981
 
        # list, not the WHOLE INVENTORY.
1982
 
        for fid in inv:
1983
 
            entry = inv[fid]
1984
 
            if entry.parent_id == orig_root_id:
1985
 
                entry.parent_id = inv.root.file_id
1986
 
 
1987
 
    @needs_tree_write_lock
1988
 
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
1989
 
        """See MutableTree.set_parent_trees."""
1990
 
        parent_ids = [rev for (rev, tree) in parents_list]
1991
 
        for revision_id in parent_ids:
1992
 
            _mod_revision.check_not_reserved_id(revision_id)
1993
 
 
1994
 
        self._check_parents_for_ghosts(parent_ids,
1995
 
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
1996
 
 
1997
 
        parent_ids = self._filter_parent_ids_by_ancestry(parent_ids)
1998
 
 
1999
 
        if len(parent_ids) == 0:
2000
 
            leftmost_parent_id = _mod_revision.NULL_REVISION
2001
 
            leftmost_parent_tree = None
2002
 
        else:
2003
 
            leftmost_parent_id, leftmost_parent_tree = parents_list[0]
2004
 
 
2005
 
        if self._change_last_revision(leftmost_parent_id):
2006
 
            if leftmost_parent_tree is None:
2007
 
                # If we don't have a tree, fall back to reading the
2008
 
                # parent tree from the repository.
2009
 
                self._cache_basis_inventory(leftmost_parent_id)
2010
 
            else:
2011
 
                inv = leftmost_parent_tree.root_inventory
2012
 
                xml = self._create_basis_xml_from_inventory(
2013
 
                                        leftmost_parent_id, inv)
2014
 
                self._write_basis_inventory(xml)
2015
 
        self._set_merges_from_parent_ids(parent_ids)
2016
 
 
2017
 
    def _cache_basis_inventory(self, new_revision):
2018
 
        """Cache new_revision as the basis inventory."""
2019
 
        # TODO: this should allow the ready-to-use inventory to be passed in,
2020
 
        # as commit already has that ready-to-use [while the format is the
2021
 
        # same, that is].
2022
 
        try:
2023
 
            # this double handles the inventory - unpack and repack -
2024
 
            # but is easier to understand. We can/should put a conditional
2025
 
            # in here based on whether the inventory is in the latest format
2026
 
            # - perhaps we should repack all inventories on a repository
2027
 
            # upgrade ?
2028
 
            # the fast path is to copy the raw xml from the repository. If the
2029
 
            # xml contains 'revision_id="', then we assume the right
2030
 
            # revision_id is set. We must check for this full string, because a
2031
 
            # root node id can legitimately look like 'revision_id' but cannot
2032
 
            # contain a '"'.
2033
 
            xml = self.branch.repository._get_inventory_xml(new_revision)
2034
 
            firstline = xml.split('\n', 1)[0]
2035
 
            if (not 'revision_id="' in firstline or
2036
 
                'format="7"' not in firstline):
2037
 
                inv = self.branch.repository._serializer.read_inventory_from_string(
2038
 
                    xml, new_revision)
2039
 
                xml = self._create_basis_xml_from_inventory(new_revision, inv)
2040
 
            self._write_basis_inventory(xml)
2041
 
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
2042
 
            pass
2043
 
 
2044
 
    def _basis_inventory_name(self):
2045
 
        return 'basis-inventory-cache'
2046
 
 
2047
 
    def _create_basis_xml_from_inventory(self, revision_id, inventory):
2048
 
        """Create the text that will be saved in basis-inventory"""
2049
 
        inventory.revision_id = revision_id
2050
 
        return xml7.serializer_v7.write_inventory_to_string(inventory)
2051
 
 
2052
 
    @needs_tree_write_lock
2053
 
    def set_conflicts(self, conflicts):
2054
 
        self._put_rio('conflicts', conflicts.to_stanzas(),
2055
 
                      CONFLICT_HEADER_1)
2056
 
 
2057
 
    @needs_tree_write_lock
2058
 
    def add_conflicts(self, new_conflicts):
2059
 
        conflict_set = set(self.conflicts())
2060
 
        conflict_set.update(set(list(new_conflicts)))
2061
 
        self.set_conflicts(_mod_conflicts.ConflictList(sorted(conflict_set,
2062
 
                                       key=_mod_conflicts.Conflict.sort_key)))
2063
 
 
2064
 
    @needs_read_lock
2065
 
    def conflicts(self):
2066
 
        try:
2067
 
            confile = self._transport.get('conflicts')
2068
 
        except errors.NoSuchFile:
2069
 
            return _mod_conflicts.ConflictList()
2070
 
        try:
2071
 
            try:
2072
 
                if next(confile) != CONFLICT_HEADER_1 + '\n':
2073
 
                    raise errors.ConflictFormatError()
2074
 
            except StopIteration:
2075
 
                raise errors.ConflictFormatError()
2076
 
            reader = _mod_rio.RioReader(confile)
2077
 
            return _mod_conflicts.ConflictList.from_stanzas(reader)
2078
 
        finally:
2079
 
            confile.close()
2080
 
 
2081
 
    def read_basis_inventory(self):
2082
 
        """Read the cached basis inventory."""
2083
 
        path = self._basis_inventory_name()
2084
 
        return self._transport.get_bytes(path)
2085
 
 
2086
 
    @needs_read_lock
2087
 
    def read_working_inventory(self):
2088
 
        """Read the working inventory.
2089
 
 
2090
 
        :raises errors.InventoryModified: read_working_inventory will fail
2091
 
            when the current in memory inventory has been modified.
2092
 
        """
2093
 
        # conceptually this should be an implementation detail of the tree.
2094
 
        # XXX: Deprecate this.
2095
 
        # ElementTree does its own conversion from UTF-8, so open in
2096
 
        # binary.
2097
 
        if self._inventory_is_modified:
2098
 
            raise errors.InventoryModified(self)
2099
 
        f = self._transport.get('inventory')
2100
 
        try:
2101
 
            result = self._deserialize(f)
2102
 
        finally:
2103
 
            f.close()
2104
 
        self._set_inventory(result, dirty=False)
2105
 
        return result
2106
 
 
2107
 
    @needs_read_lock
2108
 
    def get_root_id(self):
2109
 
        """Return the id of this trees root"""
2110
 
        return self._inventory.root.file_id
2111
 
 
2112
 
    def has_id(self, file_id):
2113
 
        # files that have been deleted are excluded
2114
 
        inv, inv_file_id = self._unpack_file_id(file_id)
2115
 
        if not inv.has_id(inv_file_id):
2116
 
            return False
2117
 
        path = inv.id2path(inv_file_id)
2118
 
        return osutils.lexists(self.abspath(path))
2119
 
 
2120
 
    def has_or_had_id(self, file_id):
2121
 
        if file_id == self.get_root_id():
2122
 
            return True
2123
 
        inv, inv_file_id = self._unpack_file_id(file_id)
2124
 
        return inv.has_id(inv_file_id)
2125
 
 
2126
 
    def all_file_ids(self):
2127
 
        """Iterate through file_ids for this tree.
2128
 
 
2129
 
        file_ids are in a WorkingTree if they are in the working inventory
2130
 
        and the working file exists.
2131
 
        """
2132
 
        ret = set()
2133
 
        for path, ie in self.iter_entries_by_dir():
2134
 
            ret.add(ie.file_id)
2135
 
        return ret
2136
 
 
2137
 
    @needs_tree_write_lock
2138
 
    def set_last_revision(self, new_revision):
2139
 
        """Change the last revision in the working tree."""
2140
 
        if self._change_last_revision(new_revision):
2141
 
            self._cache_basis_inventory(new_revision)
2142
 
 
2143
 
    def _get_check_refs(self):
2144
 
        """Return the references needed to perform a check of this tree.
2145
 
        
2146
 
        The default implementation returns no refs, and is only suitable for
2147
 
        trees that have no local caching and can commit on ghosts at any time.
2148
 
 
2149
 
        :seealso: breezy.check for details about check_refs.
2150
 
        """
2151
 
        return []
2152
 
 
2153
 
    @needs_read_lock
2154
 
    def _check(self, references):
2155
 
        """Check the tree for consistency.
2156
 
 
2157
 
        :param references: A dict with keys matching the items returned by
2158
 
            self._get_check_refs(), and values from looking those keys up in
2159
 
            the repository.
2160
 
        """
2161
 
        tree_basis = self.basis_tree()
2162
 
        tree_basis.lock_read()
2163
 
        try:
2164
 
            repo_basis = references[('trees', self.last_revision())]
2165
 
            if len(list(repo_basis.iter_changes(tree_basis))) > 0:
2166
 
                raise errors.BzrCheckError(
2167
 
                    "Mismatched basis inventory content.")
2168
 
            self._validate()
2169
 
        finally:
2170
 
            tree_basis.unlock()
2171
 
 
2172
 
    @needs_read_lock
2173
 
    def check_state(self):
2174
 
        """Check that the working state is/isn't valid."""
2175
 
        check_refs = self._get_check_refs()
2176
 
        refs = {}
2177
 
        for ref in check_refs:
2178
 
            kind, value = ref
2179
 
            if kind == 'trees':
2180
 
                refs[ref] = self.branch.repository.revision_tree(value)
2181
 
        self._check(refs)
2182
 
 
2183
 
    @needs_tree_write_lock
2184
 
    def reset_state(self, revision_ids=None):
2185
 
        """Reset the state of the working tree.
2186
 
 
2187
 
        This does a hard-reset to a last-known-good state. This is a way to
2188
 
        fix if something got corrupted (like the .bzr/checkout/dirstate file)
2189
 
        """
2190
 
        if revision_ids is None:
2191
 
            revision_ids = self.get_parent_ids()
2192
 
        if not revision_ids:
2193
 
            rt = self.branch.repository.revision_tree(
2194
 
                _mod_revision.NULL_REVISION)
2195
 
        else:
2196
 
            rt = self.branch.repository.revision_tree(revision_ids[0])
2197
 
        self._write_inventory(rt.root_inventory)
2198
 
        self.set_parent_ids(revision_ids)
2199
 
 
2200
 
    def flush(self):
2201
 
        """Write the in memory inventory to disk."""
2202
 
        # TODO: Maybe this should only write on dirty ?
2203
 
        if self._control_files._lock_mode != 'w':
2204
 
            raise errors.NotWriteLocked(self)
2205
 
        sio = BytesIO()
2206
 
        self._serialize(self._inventory, sio)
2207
 
        sio.seek(0)
2208
 
        self._transport.put_file('inventory', sio,
2209
 
            mode=self.bzrdir._get_file_mode())
2210
 
        self._inventory_is_modified = False
2211
 
 
2212
 
    def get_file_mtime(self, file_id, path=None):
2213
 
        """See Tree.get_file_mtime."""
2214
 
        if not path:
2215
 
            path = self.id2path(file_id)
2216
 
        try:
2217
 
            return os.lstat(self.abspath(path)).st_mtime
2218
 
        except OSError as e:
2219
 
            if e.errno == errno.ENOENT:
2220
 
                raise errors.FileTimestampUnavailable(path)
2221
 
            raise
2222
 
 
2223
 
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
2224
 
        inv, file_id = self._path2inv_file_id(path)
2225
 
        if file_id is None:
2226
 
            # For unversioned files on win32, we just assume they are not
2227
 
            # executable
2228
 
            return False
2229
 
        return inv[file_id].executable
2230
 
 
2231
 
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
2232
 
        mode = stat_result.st_mode
2233
 
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
2234
 
 
2235
 
    def is_executable(self, file_id, path=None):
2236
 
        if not self._supports_executable():
2237
 
            inv, inv_file_id = self._unpack_file_id(file_id)
2238
 
            return inv[inv_file_id].executable
2239
 
        else:
2240
 
            if not path:
2241
 
                path = self.id2path(file_id)
2242
 
            mode = os.lstat(self.abspath(path)).st_mode
2243
 
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
2244
 
 
2245
 
    def _is_executable_from_path_and_stat(self, path, stat_result):
2246
 
        if not self._supports_executable():
2247
 
            return self._is_executable_from_path_and_stat_from_basis(path, stat_result)
2248
 
        else:
2249
 
            return self._is_executable_from_path_and_stat_from_stat(path, stat_result)
2250
 
 
2251
 
    @needs_tree_write_lock
2252
 
    def _add(self, files, ids, kinds):
2253
 
        """See MutableTree._add."""
2254
 
        # TODO: Re-adding a file that is removed in the working copy
2255
 
        # should probably put it back with the previous ID.
2256
 
        # the read and write working inventory should not occur in this
2257
 
        # function - they should be part of lock_write and unlock.
2258
 
        # FIXME: nested trees
2259
 
        inv = self.root_inventory
2260
 
        for f, file_id, kind in zip(files, ids, kinds):
2261
 
            if file_id is None:
2262
 
                inv.add_path(f, kind=kind)
2263
 
            else:
2264
 
                inv.add_path(f, kind=kind, file_id=file_id)
2265
 
            self._inventory_is_modified = True
2266
 
 
2267
 
    def revision_tree(self, revision_id):
2268
 
        """See WorkingTree.revision_id."""
2269
 
        if revision_id == self.last_revision():
2270
 
            try:
2271
 
                xml = self.read_basis_inventory()
2272
 
            except errors.NoSuchFile:
2273
 
                pass
2274
 
            else:
2275
 
                try:
2276
 
                    inv = xml7.serializer_v7.read_inventory_from_string(xml)
2277
 
                    # dont use the repository revision_tree api because we want
2278
 
                    # to supply the inventory.
2279
 
                    if inv.revision_id == revision_id:
2280
 
                        return revisiontree.InventoryRevisionTree(
2281
 
                            self.branch.repository, inv, revision_id)
2282
 
                except errors.BadInventoryFormat:
2283
 
                    pass
2284
 
        # raise if there was no inventory, or if we read the wrong inventory.
2285
 
        raise errors.NoSuchRevisionInTree(self, revision_id)
2286
 
 
2287
 
    @needs_read_lock
2288
 
    def annotate_iter(self, file_id, default_revision=CURRENT_REVISION):
2289
 
        """See Tree.annotate_iter
2290
 
 
2291
 
        This implementation will use the basis tree implementation if possible.
2292
 
        Lines not in the basis are attributed to CURRENT_REVISION
2293
 
 
2294
 
        If there are pending merges, lines added by those merges will be
2295
 
        incorrectly attributed to CURRENT_REVISION (but after committing, the
2296
 
        attribution will be correct).
2297
 
        """
2298
 
        maybe_file_parent_keys = []
2299
 
        for parent_id in self.get_parent_ids():
2300
 
            try:
2301
 
                parent_tree = self.revision_tree(parent_id)
2302
 
            except errors.NoSuchRevisionInTree:
2303
 
                parent_tree = self.branch.repository.revision_tree(parent_id)
2304
 
            parent_tree.lock_read()
2305
 
            try:
2306
 
                try:
2307
 
                    kind = parent_tree.kind(file_id)
2308
 
                except errors.NoSuchId:
2309
 
                    continue
2310
 
                if kind != 'file':
2311
 
                    # Note: this is slightly unnecessary, because symlinks and
2312
 
                    # directories have a "text" which is the empty text, and we
2313
 
                    # know that won't mess up annotations. But it seems cleaner
2314
 
                    continue
2315
 
                parent_text_key = (
2316
 
                    file_id, parent_tree.get_file_revision(file_id))
2317
 
                if parent_text_key not in maybe_file_parent_keys:
2318
 
                    maybe_file_parent_keys.append(parent_text_key)
2319
 
            finally:
2320
 
                parent_tree.unlock()
2321
 
        graph = _mod_graph.Graph(self.branch.repository.texts)
2322
 
        heads = graph.heads(maybe_file_parent_keys)
2323
 
        file_parent_keys = []
2324
 
        for key in maybe_file_parent_keys:
2325
 
            if key in heads:
2326
 
                file_parent_keys.append(key)
2327
 
 
2328
 
        # Now we have the parents of this content
2329
 
        annotator = self.branch.repository.texts.get_annotator()
2330
 
        text = self.get_file_text(file_id)
2331
 
        this_key =(file_id, default_revision)
2332
 
        annotator.add_special_text(this_key, file_parent_keys, text)
2333
 
        annotations = [(key[-1], line)
2334
 
                       for key, line in annotator.annotate_flat(this_key)]
2335
 
        return annotations
2336
 
 
2337
 
    def _put_rio(self, filename, stanzas, header):
2338
 
        self._must_be_locked()
2339
 
        my_file = _mod_rio.rio_file(stanzas, header)
2340
 
        self._transport.put_file(filename, my_file,
2341
 
            mode=self.bzrdir._get_file_mode())
2342
 
 
2343
 
    @needs_tree_write_lock
2344
 
    def set_merge_modified(self, modified_hashes):
2345
 
        def iter_stanzas():
2346
 
            for file_id, hash in modified_hashes.iteritems():
2347
 
                yield _mod_rio.Stanza(file_id=file_id.decode('utf8'),
2348
 
                    hash=hash)
2349
 
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
2350
 
 
2351
 
    @needs_read_lock
2352
 
    def merge_modified(self):
2353
 
        """Return a dictionary of files modified by a merge.
2354
 
 
2355
 
        The list is initialized by WorkingTree.set_merge_modified, which is
2356
 
        typically called after we make some automatic updates to the tree
2357
 
        because of a merge.
2358
 
 
2359
 
        This returns a map of file_id->sha1, containing only files which are
2360
 
        still in the working inventory and have that text hash.
2361
 
        """
2362
 
        try:
2363
 
            hashfile = self._transport.get('merge-hashes')
2364
 
        except errors.NoSuchFile:
2365
 
            return {}
2366
 
        try:
2367
 
            merge_hashes = {}
2368
 
            try:
2369
 
                if next(hashfile) != MERGE_MODIFIED_HEADER_1 + '\n':
2370
 
                    raise errors.MergeModifiedFormatError()
2371
 
            except StopIteration:
2372
 
                raise errors.MergeModifiedFormatError()
2373
 
            for s in _mod_rio.RioReader(hashfile):
2374
 
                # RioReader reads in Unicode, so convert file_ids back to utf8
2375
 
                file_id = cache_utf8.encode(s.get("file_id"))
2376
 
                if not self.has_id(file_id):
2377
 
                    continue
2378
 
                text_hash = s.get("hash")
2379
 
                if text_hash == self.get_file_sha1(file_id):
2380
 
                    merge_hashes[file_id] = text_hash
2381
 
            return merge_hashes
2382
 
        finally:
2383
 
            hashfile.close()
2384
 
 
2385
 
    @needs_write_lock
2386
 
    def subsume(self, other_tree):
2387
 
        def add_children(inventory, entry):
2388
 
            for child_entry in entry.children.values():
2389
 
                inventory._byid[child_entry.file_id] = child_entry
2390
 
                if child_entry.kind == 'directory':
2391
 
                    add_children(inventory, child_entry)
2392
 
        if other_tree.get_root_id() == self.get_root_id():
2393
 
            raise errors.BadSubsumeSource(self, other_tree,
2394
 
                                          'Trees have the same root')
2395
 
        try:
2396
 
            other_tree_path = self.relpath(other_tree.basedir)
2397
 
        except errors.PathNotChild:
2398
 
            raise errors.BadSubsumeSource(self, other_tree,
2399
 
                'Tree is not contained by the other')
2400
 
        new_root_parent = self.path2id(osutils.dirname(other_tree_path))
2401
 
        if new_root_parent is None:
2402
 
            raise errors.BadSubsumeSource(self, other_tree,
2403
 
                'Parent directory is not versioned.')
2404
 
        # We need to ensure that the result of a fetch will have a
2405
 
        # versionedfile for the other_tree root, and only fetching into
2406
 
        # RepositoryKnit2 guarantees that.
2407
 
        if not self.branch.repository.supports_rich_root():
2408
 
            raise errors.SubsumeTargetNeedsUpgrade(other_tree)
2409
 
        other_tree.lock_tree_write()
2410
 
        try:
2411
 
            new_parents = other_tree.get_parent_ids()
2412
 
            other_root = other_tree.root_inventory.root
2413
 
            other_root.parent_id = new_root_parent
2414
 
            other_root.name = osutils.basename(other_tree_path)
2415
 
            self.root_inventory.add(other_root)
2416
 
            add_children(self.root_inventory, other_root)
2417
 
            self._write_inventory(self.root_inventory)
2418
 
            # normally we don't want to fetch whole repositories, but i think
2419
 
            # here we really do want to consolidate the whole thing.
2420
 
            for parent_id in other_tree.get_parent_ids():
2421
 
                self.branch.fetch(other_tree.branch, parent_id)
2422
 
                self.add_parent_tree_id(parent_id)
2423
 
        finally:
2424
 
            other_tree.unlock()
2425
 
        other_tree.bzrdir.retire_bzrdir()
2426
 
 
2427
 
    @needs_tree_write_lock
2428
 
    def extract(self, file_id, format=None):
2429
 
        """Extract a subtree from this tree.
2430
 
 
2431
 
        A new branch will be created, relative to the path for this tree.
2432
 
        """
2433
 
        self.flush()
2434
 
        def mkdirs(path):
2435
 
            segments = osutils.splitpath(path)
2436
 
            transport = self.branch.bzrdir.root_transport
2437
 
            for name in segments:
2438
 
                transport = transport.clone(name)
2439
 
                transport.ensure_base()
2440
 
            return transport
2441
 
 
2442
 
        sub_path = self.id2path(file_id)
2443
 
        branch_transport = mkdirs(sub_path)
2444
 
        if format is None:
2445
 
            format = self.bzrdir.cloning_metadir()
2446
 
        branch_transport.ensure_base()
2447
 
        branch_bzrdir = format.initialize_on_transport(branch_transport)
2448
 
        try:
2449
 
            repo = branch_bzrdir.find_repository()
2450
 
        except errors.NoRepositoryPresent:
2451
 
            repo = branch_bzrdir.create_repository()
2452
 
        if not repo.supports_rich_root():
2453
 
            raise errors.RootNotRich()
2454
 
        new_branch = branch_bzrdir.create_branch()
2455
 
        new_branch.pull(self.branch)
2456
 
        for parent_id in self.get_parent_ids():
2457
 
            new_branch.fetch(self.branch, parent_id)
2458
 
        tree_transport = self.bzrdir.root_transport.clone(sub_path)
2459
 
        if tree_transport.base != branch_transport.base:
2460
 
            tree_bzrdir = format.initialize_on_transport(tree_transport)
2461
 
            tree_bzrdir.set_branch_reference(new_branch)
2462
 
        else:
2463
 
            tree_bzrdir = branch_bzrdir
2464
 
        wt = tree_bzrdir.create_workingtree(_mod_revision.NULL_REVISION)
2465
 
        wt.set_parent_ids(self.get_parent_ids())
2466
 
        # FIXME: Support nested trees
2467
 
        my_inv = self.root_inventory
2468
 
        child_inv = inventory.Inventory(root_id=None)
2469
 
        new_root = my_inv[file_id]
2470
 
        my_inv.remove_recursive_id(file_id)
2471
 
        new_root.parent_id = None
2472
 
        child_inv.add(new_root)
2473
 
        self._write_inventory(my_inv)
2474
 
        wt._write_inventory(child_inv)
2475
 
        return wt
2476
 
 
2477
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
2478
 
        """List all files as (path, class, kind, id, entry).
2479
 
 
2480
 
        Lists, but does not descend into unversioned directories.
2481
 
        This does not include files that have been deleted in this
2482
 
        tree. Skips the control directory.
2483
 
 
2484
 
        :param include_root: if True, return an entry for the root
2485
 
        :param from_dir: start from this directory or None for the root
2486
 
        :param recursive: whether to recurse into subdirectories or not
2487
 
        """
2488
 
        # list_files is an iterator, so @needs_read_lock doesn't work properly
2489
 
        # with it. So callers should be careful to always read_lock the tree.
2490
 
        if not self.is_locked():
2491
 
            raise errors.ObjectNotLocked(self)
2492
 
 
2493
 
        if from_dir is None and include_root is True:
2494
 
            yield ('', 'V', 'directory', self.get_root_id(), self.root_inventory.root)
2495
 
        # Convert these into local objects to save lookup times
2496
 
        pathjoin = osutils.pathjoin
2497
 
        file_kind = self._kind
2498
 
 
2499
 
        # transport.base ends in a slash, we want the piece
2500
 
        # between the last two slashes
2501
 
        transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
2502
 
 
2503
 
        fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
2504
 
 
2505
 
        # directory file_id, relative path, absolute path, reverse sorted children
2506
 
        if from_dir is not None:
2507
 
            inv, from_dir_id = self._path2inv_file_id(from_dir)
2508
 
            if from_dir_id is None:
2509
 
                # Directory not versioned
2510
 
                return
2511
 
            from_dir_abspath = pathjoin(self.basedir, from_dir)
2512
 
        else:
2513
 
            inv = self.root_inventory
2514
 
            from_dir_id = inv.root.file_id
2515
 
            from_dir_abspath = self.basedir
2516
 
        children = sorted(os.listdir(from_dir_abspath))
2517
 
        # jam 20060527 The kernel sized tree seems equivalent whether we
2518
 
        # use a deque and popleft to keep them sorted, or if we use a plain
2519
 
        # list and just reverse() them.
2520
 
        children = collections.deque(children)
2521
 
        stack = [(from_dir_id, u'', from_dir_abspath, children)]
2522
 
        while stack:
2523
 
            from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
2524
 
 
2525
 
            while children:
2526
 
                f = children.popleft()
2527
 
                ## TODO: If we find a subdirectory with its own .bzr
2528
 
                ## directory, then that is a separate tree and we
2529
 
                ## should exclude it.
2530
 
 
2531
 
                # the bzrdir for this tree
2532
 
                if transport_base_dir == f:
2533
 
                    continue
2534
 
 
2535
 
                # we know that from_dir_relpath and from_dir_abspath never end in a slash
2536
 
                # and 'f' doesn't begin with one, we can do a string op, rather
2537
 
                # than the checks of pathjoin(), all relative paths will have an extra slash
2538
 
                # at the beginning
2539
 
                fp = from_dir_relpath + '/' + f
2540
 
 
2541
 
                # absolute path
2542
 
                fap = from_dir_abspath + '/' + f
2543
 
 
2544
 
                dir_ie = inv[from_dir_id]
2545
 
                if dir_ie.kind == 'directory':
2546
 
                    f_ie = dir_ie.children.get(f)
2547
 
                else:
2548
 
                    f_ie = None
2549
 
                if f_ie:
2550
 
                    c = 'V'
2551
 
                elif self.is_ignored(fp[1:]):
2552
 
                    c = 'I'
2553
 
                else:
2554
 
                    # we may not have found this file, because of a unicode
2555
 
                    # issue, or because the directory was actually a symlink.
2556
 
                    f_norm, can_access = osutils.normalized_filename(f)
2557
 
                    if f == f_norm or not can_access:
2558
 
                        # No change, so treat this file normally
2559
 
                        c = '?'
2560
 
                    else:
2561
 
                        # this file can be accessed by a normalized path
2562
 
                        # check again if it is versioned
2563
 
                        # these lines are repeated here for performance
2564
 
                        f = f_norm
2565
 
                        fp = from_dir_relpath + '/' + f
2566
 
                        fap = from_dir_abspath + '/' + f
2567
 
                        f_ie = inv.get_child(from_dir_id, f)
2568
 
                        if f_ie:
2569
 
                            c = 'V'
2570
 
                        elif self.is_ignored(fp[1:]):
2571
 
                            c = 'I'
2572
 
                        else:
2573
 
                            c = '?'
2574
 
 
2575
 
                fk = file_kind(fap)
2576
 
 
2577
 
                # make a last minute entry
2578
 
                if f_ie:
2579
 
                    yield fp[1:], c, fk, f_ie.file_id, f_ie
2580
 
                else:
2581
 
                    try:
2582
 
                        yield fp[1:], c, fk, None, fk_entries[fk]()
2583
 
                    except KeyError:
2584
 
                        yield fp[1:], c, fk, None, TreeEntry()
2585
 
                    continue
2586
 
 
2587
 
                if fk != 'directory':
2588
 
                    continue
2589
 
 
2590
 
                # But do this child first if recursing down
2591
 
                if recursive:
2592
 
                    new_children = sorted(os.listdir(fap))
2593
 
                    new_children = collections.deque(new_children)
2594
 
                    stack.append((f_ie.file_id, fp, fap, new_children))
2595
 
                    # Break out of inner loop,
2596
 
                    # so that we start outer loop with child
2597
 
                    break
2598
 
            else:
2599
 
                # if we finished all children, pop it off the stack
2600
 
                stack.pop()
2601
 
 
2602
 
    @needs_tree_write_lock
2603
 
    def move(self, from_paths, to_dir=None, after=False):
2604
 
        """Rename files.
2605
 
 
2606
 
        to_dir must exist in the inventory.
2607
 
 
2608
 
        If to_dir exists and is a directory, the files are moved into
2609
 
        it, keeping their old names.
2610
 
 
2611
 
        Note that to_dir is only the last component of the new name;
2612
 
        this doesn't change the directory.
2613
 
 
2614
 
        For each entry in from_paths the move mode will be determined
2615
 
        independently.
2616
 
 
2617
 
        The first mode moves the file in the filesystem and updates the
2618
 
        inventory. The second mode only updates the inventory without
2619
 
        touching the file on the filesystem.
2620
 
 
2621
 
        move uses the second mode if 'after == True' and the target is
2622
 
        either not versioned or newly added, and present in the working tree.
2623
 
 
2624
 
        move uses the second mode if 'after == False' and the source is
2625
 
        versioned but no longer in the working tree, and the target is not
2626
 
        versioned but present in the working tree.
2627
 
 
2628
 
        move uses the first mode if 'after == False' and the source is
2629
 
        versioned and present in the working tree, and the target is not
2630
 
        versioned and not present in the working tree.
2631
 
 
2632
 
        Everything else results in an error.
2633
 
 
2634
 
        This returns a list of (from_path, to_path) pairs for each
2635
 
        entry that is moved.
2636
 
        """
2637
 
        rename_entries = []
2638
 
        rename_tuples = []
2639
 
 
2640
 
        invs_to_write = set()
2641
 
 
2642
 
        # check for deprecated use of signature
2643
 
        if to_dir is None:
2644
 
            raise TypeError('You must supply a target directory')
2645
 
        # check destination directory
2646
 
        if isinstance(from_paths, basestring):
2647
 
            raise ValueError()
2648
 
        to_abs = self.abspath(to_dir)
2649
 
        if not isdir(to_abs):
2650
 
            raise errors.BzrMoveFailedError('',to_dir,
2651
 
                errors.NotADirectory(to_abs))
2652
 
        if not self.has_filename(to_dir):
2653
 
            raise errors.BzrMoveFailedError('',to_dir,
2654
 
                errors.NotInWorkingDirectory(to_dir))
2655
 
        to_inv, to_dir_id = self._path2inv_file_id(to_dir)
2656
 
        if to_dir_id is None:
2657
 
            raise errors.BzrMoveFailedError('',to_dir,
2658
 
                errors.NotVersionedError(path=to_dir))
2659
 
 
2660
 
        to_dir_ie = to_inv[to_dir_id]
2661
 
        if to_dir_ie.kind != 'directory':
2662
 
            raise errors.BzrMoveFailedError('',to_dir,
2663
 
                errors.NotADirectory(to_abs))
2664
 
 
2665
 
        # create rename entries and tuples
2666
 
        for from_rel in from_paths:
2667
 
            from_tail = splitpath(from_rel)[-1]
2668
 
            from_inv, from_id = self._path2inv_file_id(from_rel)
2669
 
            if from_id is None:
2670
 
                raise errors.BzrMoveFailedError(from_rel,to_dir,
2671
 
                    errors.NotVersionedError(path=from_rel))
2672
 
 
2673
 
            from_entry = from_inv[from_id]
2674
 
            from_parent_id = from_entry.parent_id
2675
 
            to_rel = pathjoin(to_dir, from_tail)
2676
 
            rename_entry = InventoryWorkingTree._RenameEntry(
2677
 
                from_rel=from_rel,
2678
 
                from_id=from_id,
2679
 
                from_tail=from_tail,
2680
 
                from_parent_id=from_parent_id,
2681
 
                to_rel=to_rel, to_tail=from_tail,
2682
 
                to_parent_id=to_dir_id)
2683
 
            rename_entries.append(rename_entry)
2684
 
            rename_tuples.append((from_rel, to_rel))
2685
 
 
2686
 
        # determine which move mode to use. checks also for movability
2687
 
        rename_entries = self._determine_mv_mode(rename_entries, after)
2688
 
 
2689
 
        original_modified = self._inventory_is_modified
2690
 
        try:
2691
 
            if len(from_paths):
2692
 
                self._inventory_is_modified = True
2693
 
            self._move(rename_entries)
2694
 
        except:
2695
 
            # restore the inventory on error
2696
 
            self._inventory_is_modified = original_modified
2697
 
            raise
2698
 
        #FIXME: Should potentially also write the from_invs
2699
 
        self._write_inventory(to_inv)
2700
 
        return rename_tuples
2701
 
 
2702
 
    @needs_tree_write_lock
2703
 
    def rename_one(self, from_rel, to_rel, after=False):
2704
 
        """Rename one file.
2705
 
 
2706
 
        This can change the directory or the filename or both.
2707
 
 
2708
 
        rename_one has several 'modes' to work. First, it can rename a physical
2709
 
        file and change the file_id. That is the normal mode. Second, it can
2710
 
        only change the file_id without touching any physical file.
2711
 
 
2712
 
        rename_one uses the second mode if 'after == True' and 'to_rel' is not
2713
 
        versioned but present in the working tree.
2714
 
 
2715
 
        rename_one uses the second mode if 'after == False' and 'from_rel' is
2716
 
        versioned but no longer in the working tree, and 'to_rel' is not
2717
 
        versioned but present in the working tree.
2718
 
 
2719
 
        rename_one uses the first mode if 'after == False' and 'from_rel' is
2720
 
        versioned and present in the working tree, and 'to_rel' is not
2721
 
        versioned and not present in the working tree.
2722
 
 
2723
 
        Everything else results in an error.
2724
 
        """
2725
 
        rename_entries = []
2726
 
 
2727
 
        # create rename entries and tuples
2728
 
        from_tail = splitpath(from_rel)[-1]
2729
 
        from_inv, from_id = self._path2inv_file_id(from_rel)
2730
 
        if from_id is None:
2731
 
            # if file is missing in the inventory maybe it's in the basis_tree
2732
 
            basis_tree = self.branch.basis_tree()
2733
 
            from_id = basis_tree.path2id(from_rel)
2734
 
            if from_id is None:
2735
 
                raise errors.BzrRenameFailedError(from_rel,to_rel,
2736
 
                    errors.NotVersionedError(path=from_rel))
2737
 
            # put entry back in the inventory so we can rename it
2738
 
            from_entry = basis_tree.root_inventory[from_id].copy()
2739
 
            from_inv.add(from_entry)
2740
 
        else:
2741
 
            from_inv, from_inv_id = self._unpack_file_id(from_id)
2742
 
            from_entry = from_inv[from_inv_id]
2743
 
        from_parent_id = from_entry.parent_id
2744
 
        to_dir, to_tail = os.path.split(to_rel)
2745
 
        to_inv, to_dir_id = self._path2inv_file_id(to_dir)
2746
 
        rename_entry = InventoryWorkingTree._RenameEntry(from_rel=from_rel,
2747
 
                                     from_id=from_id,
2748
 
                                     from_tail=from_tail,
2749
 
                                     from_parent_id=from_parent_id,
2750
 
                                     to_rel=to_rel, to_tail=to_tail,
2751
 
                                     to_parent_id=to_dir_id)
2752
 
        rename_entries.append(rename_entry)
2753
 
 
2754
 
        # determine which move mode to use. checks also for movability
2755
 
        rename_entries = self._determine_mv_mode(rename_entries, after)
2756
 
 
2757
 
        # check if the target changed directory and if the target directory is
2758
 
        # versioned
2759
 
        if to_dir_id is None:
2760
 
            raise errors.BzrMoveFailedError(from_rel,to_rel,
2761
 
                errors.NotVersionedError(path=to_dir))
2762
 
 
2763
 
        # all checks done. now we can continue with our actual work
2764
 
        mutter('rename_one:\n'
2765
 
               '  from_id   {%s}\n'
2766
 
               '  from_rel: %r\n'
2767
 
               '  to_rel:   %r\n'
2768
 
               '  to_dir    %r\n'
2769
 
               '  to_dir_id {%s}\n',
2770
 
               from_id, from_rel, to_rel, to_dir, to_dir_id)
2771
 
 
2772
 
        self._move(rename_entries)
2773
 
        self._write_inventory(to_inv)
2774
 
 
2775
 
    class _RenameEntry(object):
2776
 
        def __init__(self, from_rel, from_id, from_tail, from_parent_id,
2777
 
                     to_rel, to_tail, to_parent_id, only_change_inv=False,
2778
 
                     change_id=False):
2779
 
            self.from_rel = from_rel
2780
 
            self.from_id = from_id
2781
 
            self.from_tail = from_tail
2782
 
            self.from_parent_id = from_parent_id
2783
 
            self.to_rel = to_rel
2784
 
            self.to_tail = to_tail
2785
 
            self.to_parent_id = to_parent_id
2786
 
            self.change_id = change_id
2787
 
            self.only_change_inv = only_change_inv
2788
 
 
2789
 
    def _determine_mv_mode(self, rename_entries, after=False):
2790
 
        """Determines for each from-to pair if both inventory and working tree
2791
 
        or only the inventory has to be changed.
2792
 
 
2793
 
        Also does basic plausability tests.
2794
 
        """
2795
 
        # FIXME: Handling of nested trees
2796
 
        inv = self.root_inventory
2797
 
 
2798
 
        for rename_entry in rename_entries:
2799
 
            # store to local variables for easier reference
2800
 
            from_rel = rename_entry.from_rel
2801
 
            from_id = rename_entry.from_id
2802
 
            to_rel = rename_entry.to_rel
2803
 
            to_id = inv.path2id(to_rel)
2804
 
            only_change_inv = False
2805
 
            change_id = False
2806
 
 
2807
 
            # check the inventory for source and destination
2808
 
            if from_id is None:
2809
 
                raise errors.BzrMoveFailedError(from_rel,to_rel,
2810
 
                    errors.NotVersionedError(path=from_rel))
2811
 
            if to_id is not None:
2812
 
                allowed = False
2813
 
                # allow it with --after but only if dest is newly added
2814
 
                if after:
2815
 
                    basis = self.basis_tree()
2816
 
                    basis.lock_read()
2817
 
                    try:
2818
 
                        if not basis.has_id(to_id):
2819
 
                            rename_entry.change_id = True
2820
 
                            allowed = True
2821
 
                    finally:
2822
 
                        basis.unlock()
2823
 
                if not allowed:
2824
 
                    raise errors.BzrMoveFailedError(from_rel,to_rel,
2825
 
                        errors.AlreadyVersionedError(path=to_rel))
2826
 
 
2827
 
            # try to determine the mode for rename (only change inv or change
2828
 
            # inv and file system)
2829
 
            if after:
2830
 
                if not self.has_filename(to_rel):
2831
 
                    raise errors.BzrMoveFailedError(from_id,to_rel,
2832
 
                        errors.NoSuchFile(path=to_rel,
2833
 
                        extra="New file has not been created yet"))
2834
 
                only_change_inv = True
2835
 
            elif not self.has_filename(from_rel) and self.has_filename(to_rel):
2836
 
                only_change_inv = True
2837
 
            elif self.has_filename(from_rel) and not self.has_filename(to_rel):
2838
 
                only_change_inv = False
2839
 
            elif (not self.case_sensitive
2840
 
                  and from_rel.lower() == to_rel.lower()
2841
 
                  and self.has_filename(from_rel)):
2842
 
                only_change_inv = False
2843
 
            else:
2844
 
                # something is wrong, so lets determine what exactly
2845
 
                if not self.has_filename(from_rel) and \
2846
 
                   not self.has_filename(to_rel):
2847
 
                    raise errors.BzrRenameFailedError(from_rel, to_rel,
2848
 
                        errors.PathsDoNotExist(paths=(from_rel, to_rel)))
2849
 
                else:
2850
 
                    raise errors.RenameFailedFilesExist(from_rel, to_rel)
2851
 
            rename_entry.only_change_inv = only_change_inv
2852
 
        return rename_entries
2853
 
 
2854
 
    def _move(self, rename_entries):
2855
 
        """Moves a list of files.
2856
 
 
2857
 
        Depending on the value of the flag 'only_change_inv', the
2858
 
        file will be moved on the file system or not.
2859
 
        """
2860
 
        moved = []
2861
 
 
2862
 
        for entry in rename_entries:
2863
 
            try:
2864
 
                self._move_entry(entry)
2865
 
            except:
2866
 
                self._rollback_move(moved)
2867
 
                raise
2868
 
            moved.append(entry)
2869
 
 
2870
 
    def _rollback_move(self, moved):
2871
 
        """Try to rollback a previous move in case of an filesystem error."""
2872
 
        for entry in moved:
2873
 
            try:
2874
 
                self._move_entry(WorkingTree._RenameEntry(
2875
 
                    entry.to_rel, entry.from_id,
2876
 
                    entry.to_tail, entry.to_parent_id, entry.from_rel,
2877
 
                    entry.from_tail, entry.from_parent_id,
2878
 
                    entry.only_change_inv))
2879
 
            except errors.BzrMoveFailedError as e:
2880
 
                raise errors.BzrMoveFailedError( '', '', "Rollback failed."
2881
 
                        " The working tree is in an inconsistent state."
2882
 
                        " Please consider doing a 'bzr revert'."
2883
 
                        " Error message is: %s" % e)
2884
 
 
2885
 
    def _move_entry(self, entry):
2886
 
        inv = self.root_inventory
2887
 
        from_rel_abs = self.abspath(entry.from_rel)
2888
 
        to_rel_abs = self.abspath(entry.to_rel)
2889
 
        if from_rel_abs == to_rel_abs:
2890
 
            raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
2891
 
                "Source and target are identical.")
2892
 
 
2893
 
        if not entry.only_change_inv:
2894
 
            try:
2895
 
                osutils.rename(from_rel_abs, to_rel_abs)
2896
 
            except OSError as e:
2897
 
                raise errors.BzrMoveFailedError(entry.from_rel,
2898
 
                    entry.to_rel, e[1])
2899
 
        if entry.change_id:
2900
 
            to_id = inv.path2id(entry.to_rel)
2901
 
            inv.remove_recursive_id(to_id)
2902
 
        inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
2903
 
 
2904
 
    @needs_tree_write_lock
2905
 
    def unversion(self, file_ids):
2906
 
        """Remove the file ids in file_ids from the current versioned set.
2907
 
 
2908
 
        When a file_id is unversioned, all of its children are automatically
2909
 
        unversioned.
2910
 
 
2911
 
        :param file_ids: The file ids to stop versioning.
2912
 
        :raises: NoSuchId if any fileid is not currently versioned.
2913
 
        """
2914
 
        for file_id in file_ids:
2915
 
            if not self._inventory.has_id(file_id):
2916
 
                raise errors.NoSuchId(self, file_id)
2917
 
        for file_id in file_ids:
2918
 
            if self._inventory.has_id(file_id):
2919
 
                self._inventory.remove_recursive_id(file_id)
2920
 
        if len(file_ids):
2921
 
            # in the future this should just set a dirty bit to wait for the
2922
 
            # final unlock. However, until all methods of workingtree start
2923
 
            # with the current in -memory inventory rather than triggering
2924
 
            # a read, it is more complex - we need to teach read_inventory
2925
 
            # to know when to read, and when to not read first... and possibly
2926
 
            # to save first when the in memory one may be corrupted.
2927
 
            # so for now, we just only write it if it is indeed dirty.
2928
 
            # - RBC 20060907
2929
 
            self._write_inventory(self._inventory)
2930
 
 
2931
 
    def stored_kind(self, file_id):
2932
 
        """See Tree.stored_kind"""
2933
 
        inv, inv_file_id = self._unpack_file_id(file_id)
2934
 
        return inv[inv_file_id].kind
2935
 
 
2936
 
    def extras(self):
2937
 
        """Yield all unversioned files in this WorkingTree.
2938
 
 
2939
 
        If there are any unversioned directories then only the directory is
2940
 
        returned, not all its children.  But if there are unversioned files
2941
 
        under a versioned subdirectory, they are returned.
2942
 
 
2943
 
        Currently returned depth-first, sorted by name within directories.
2944
 
        This is the same order used by 'osutils.walkdirs'.
2945
 
        """
2946
 
        ## TODO: Work from given directory downwards
2947
 
        for path, dir_entry in self.iter_entries_by_dir():
2948
 
            if dir_entry.kind != 'directory':
2949
 
                continue
2950
 
            # mutter("search for unknowns in %r", path)
2951
 
            dirabs = self.abspath(path)
2952
 
            if not isdir(dirabs):
2953
 
                # e.g. directory deleted
2954
 
                continue
2955
 
 
2956
 
            fl = []
2957
 
            for subf in os.listdir(dirabs):
2958
 
                if self.bzrdir.is_control_filename(subf):
2959
 
                    continue
2960
 
                if subf not in dir_entry.children:
2961
 
                    try:
2962
 
                        (subf_norm,
2963
 
                         can_access) = osutils.normalized_filename(subf)
2964
 
                    except UnicodeDecodeError:
2965
 
                        path_os_enc = path.encode(osutils._fs_enc)
2966
 
                        relpath = path_os_enc + '/' + subf
2967
 
                        raise errors.BadFilenameEncoding(relpath,
2968
 
                                                         osutils._fs_enc)
2969
 
                    if subf_norm != subf and can_access:
2970
 
                        if subf_norm not in dir_entry.children:
2971
 
                            fl.append(subf_norm)
2972
 
                    else:
2973
 
                        fl.append(subf)
2974
 
 
2975
 
            fl.sort()
2976
 
            for subf in fl:
2977
 
                subp = pathjoin(path, subf)
2978
 
                yield subp
2979
 
 
2980
 
    def _walkdirs(self, prefix=""):
2981
 
        """Walk the directories of this tree.
2982
 
 
2983
 
        :param prefix: is used as the directrory to start with.
2984
 
        :returns: a generator which yields items in the form::
2985
 
 
2986
 
            ((curren_directory_path, fileid),
2987
 
             [(file1_path, file1_name, file1_kind, None, file1_id,
2988
 
               file1_kind), ... ])
2989
 
        """
2990
 
        _directory = 'directory'
2991
 
        # get the root in the inventory
2992
 
        inv, top_id = self._path2inv_file_id(prefix)
2993
 
        if top_id is None:
2994
 
            pending = []
2995
 
        else:
2996
 
            pending = [(prefix, '', _directory, None, top_id, None)]
2997
 
        while pending:
2998
 
            dirblock = []
2999
 
            currentdir = pending.pop()
3000
 
            # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
3001
 
            top_id = currentdir[4]
3002
 
            if currentdir[0]:
3003
 
                relroot = currentdir[0] + '/'
3004
 
            else:
3005
 
                relroot = ""
3006
 
            # FIXME: stash the node in pending
3007
 
            entry = inv[top_id]
3008
 
            if entry.kind == 'directory':
3009
 
                for name, child in entry.sorted_children():
3010
 
                    dirblock.append((relroot + name, name, child.kind, None,
3011
 
                        child.file_id, child.kind
3012
 
                        ))
3013
 
            yield (currentdir[0], entry.file_id), dirblock
3014
 
            # push the user specified dirs from dirblock
3015
 
            for dir in reversed(dirblock):
3016
 
                if dir[2] == _directory:
3017
 
                    pending.append(dir)
3018
 
 
3019
 
    @needs_write_lock
3020
 
    def update_feature_flags(self, updated_flags):
3021
 
        """Update the feature flags for this branch.
3022
 
 
3023
 
        :param updated_flags: Dictionary mapping feature names to necessities
3024
 
            A necessity can be None to indicate the feature should be removed
3025
 
        """
3026
 
        self._format._update_feature_flags(updated_flags)
3027
 
        self.control_transport.put_bytes('format', self._format.as_string())
3028
 
 
3029
 
 
3030
1713
class WorkingTreeFormatRegistry(controldir.ControlComponentFormatRegistry):
3031
1714
    """Registry for working tree formats."""
3032
1715
 
3140
1823
        return self._matchingbzrdir
3141
1824
 
3142
1825
 
3143
 
class WorkingTreeFormatMetaDir(bzrdir.BzrFormat, WorkingTreeFormat):
3144
 
    """Base class for working trees that live in bzr meta directories."""
3145
 
 
3146
 
    def __init__(self):
3147
 
        WorkingTreeFormat.__init__(self)
3148
 
        bzrdir.BzrFormat.__init__(self)
3149
 
 
3150
 
    @classmethod
3151
 
    def find_format_string(klass, controldir):
3152
 
        """Return format name for the working tree object in controldir."""
3153
 
        try:
3154
 
            transport = controldir.get_workingtree_transport(None)
3155
 
            return transport.get_bytes("format")
3156
 
        except errors.NoSuchFile:
3157
 
            raise errors.NoWorkingTree(base=transport.base)
3158
 
 
3159
 
    @classmethod
3160
 
    def find_format(klass, controldir):
3161
 
        """Return the format for the working tree object in controldir."""
3162
 
        format_string = klass.find_format_string(controldir)
3163
 
        return klass._find_format(format_registry, 'working tree',
3164
 
                format_string)
3165
 
 
3166
 
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
3167
 
            basedir=None):
3168
 
        WorkingTreeFormat.check_support_status(self,
3169
 
            allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
3170
 
            basedir=basedir)
3171
 
        bzrdir.BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
3172
 
            recommend_upgrade=recommend_upgrade, basedir=basedir)
3173
 
 
3174
 
    def get_controldir_for_branch(self):
3175
 
        """Get the control directory format for creating branches.
3176
 
 
3177
 
        This is to support testing of working tree formats that can not exist
3178
 
        in the same control directory as a branch.
3179
 
        """
3180
 
        return self._matchingbzrdir
3181
 
 
3182
 
 
3183
 
class WorkingTreeFormatMetaDir(bzrdir.BzrFormat, WorkingTreeFormat):
3184
 
    """Base class for working trees that live in bzr meta directories."""
3185
 
 
3186
 
    def __init__(self):
3187
 
        WorkingTreeFormat.__init__(self)
3188
 
        bzrdir.BzrFormat.__init__(self)
3189
 
 
3190
 
    @classmethod
3191
 
    def find_format_string(klass, controldir):
3192
 
        """Return format name for the working tree object in controldir."""
3193
 
        try:
3194
 
            transport = controldir.get_workingtree_transport(None)
3195
 
            return transport.get_bytes("format")
3196
 
        except errors.NoSuchFile:
3197
 
            raise errors.NoWorkingTree(base=transport.base)
3198
 
 
3199
 
    @classmethod
3200
 
    def find_format(klass, controldir):
3201
 
        """Return the format for the working tree object in controldir."""
3202
 
        format_string = klass.find_format_string(controldir)
3203
 
        return klass._find_format(format_registry, 'working tree',
3204
 
                format_string)
3205
 
 
3206
 
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
3207
 
            basedir=None):
3208
 
        WorkingTreeFormat.check_support_status(self,
3209
 
            allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
3210
 
            basedir=basedir)
3211
 
        bzrdir.BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
3212
 
            recommend_upgrade=recommend_upgrade, basedir=basedir)
3213
 
 
3214
 
 
3215
1826
format_registry.register_lazy("Bazaar Working Tree Format 4 (bzr 0.15)\n",
3216
1827
    "breezy.workingtree_4", "WorkingTreeFormat4")
3217
1828
format_registry.register_lazy("Bazaar Working Tree Format 5 (bzr 1.11)\n",