~bzr-pqm/bzr/bzr.dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# Copyright (C) 2004, 2005 by Martin Pool
# Copyright (C) 2005 by Canonical Ltd

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# TODO: Check ancestries are correct for every revision: includes
# every committed so far, and in a reasonable order.

# TODO: Also check non-mainline revisions mentioned as parents.

# TODO: Check for extra files in the control directory.

# TODO: Check revision, inventory and entry objects have all 
# required fields.

# TODO: Get every revision in the revision-store even if they're not
# referenced by history and make sure they're all valid.

import bzrlib.ui
from bzrlib.trace import note, warning
from bzrlib.osutils import rename, sha_string, fingerprint_file
from bzrlib.trace import mutter
from bzrlib.errors import BzrCheckError, NoSuchRevision
from bzrlib.inventory import ROOT_ID


class Check(object):
    """Check a branch"""

    def __init__(self, branch):
        self.branch = branch
        self.repository = branch.repository
        self.checked_text_cnt = 0
        self.checked_rev_cnt = 0
        self.ghosts = []
        self.repeated_text_cnt = 0
        self.missing_parent_links = {}
        self.missing_inventory_sha_cnt = 0
        self.missing_revision_cnt = 0
        # maps (file-id, version) -> sha1
        self.checked_texts = {}
        self.checked_weaves = {}

    def check(self):
        self.branch.lock_read()
        self.progress = bzrlib.ui.ui_factory.nested_progress_bar()
        try:
            self.progress.update('retrieving inventory', 0, 0)
            # do not put in init, as it should be done with progess,
            # and inside the lock.
            self.inventory_weave = self.branch.repository.get_inventory_weave()
            self.history = self.branch.revision_history()
            if not len(self.history):
                # nothing to see here
                return
            self.plan_revisions()
            revno = 0
            self.check_weaves()
            while revno < len(self.planned_revisions):
                rev_id = self.planned_revisions[revno]
                self.progress.update('checking revision', revno,
                                     len(self.planned_revisions))
                revno += 1
                self.check_one_rev(rev_id)
        finally:
            self.progress.finished()
            self.branch.unlock()

    def plan_revisions(self):
        repository = self.branch.repository
        if not repository.revision_store.listable():
            self.planned_revisions = repository.get_ancestry(self.history[-1])
            self.planned_revisions.remove(None)
            # FIXME progress bars should support this more nicely.
            self.progress.clear()
            print ("Checking reachable history -"
                   " for a complete check use a local branch.")
            return
        
        self.planned_revisions = set(repository.revision_store)
        inventoried = set(self.inventory_weave.names())
        awol = self.planned_revisions - inventoried
        if len(awol) > 0:
            raise BzrCheckError('Stored revisions missing from inventory'
                '{%s}' % ','.join([f for f in awol]))
        self.planned_revisions = list(self.planned_revisions)

    def report_results(self, verbose):
        note('checked branch %s format %s',
             self.branch.base, 
             self.branch._format)

        note('%6d revisions', self.checked_rev_cnt)
        note('%6d unique file texts', self.checked_text_cnt)
        note('%6d repeated file texts', self.repeated_text_cnt)
        note('%6d weaves', len(self.checked_weaves))
        if self.missing_inventory_sha_cnt:
            note('%6d revisions are missing inventory_sha1',
                 self.missing_inventory_sha_cnt)
        if self.missing_revision_cnt:
            note('%6d revisions are mentioned but not present',
                 self.missing_revision_cnt)
        if len(self.ghosts):
            note('%6d ghost revisions', len(self.ghosts))
            if verbose:
                for ghost in self.ghosts:
                    note('      %s', ghost)
        if len(self.missing_parent_links):
            note('%6d revisions missing parents in ancestry', 
                 len(self.missing_parent_links))
            if verbose:
                for link, linkers in self.missing_parent_links.items():
                    note('      %s should be in the ancestry for:', link)
                    for linker in linkers:
                        note('       * %s', linker)

    def check_one_rev(self, rev_id):
        """Check one revision.

        rev_id - the one to check

        last_rev_id - the previous one on the mainline, if any.
        """

        # mutter('    revision {%s}', rev_id)
        branch = self.branch
        try:
            rev_history_position = self.history.index(rev_id)
        except ValueError:
            rev_history_position = None
        last_rev_id = None
        if rev_history_position:
            rev = branch.repository.get_revision(rev_id)
            if rev_history_position > 0:
                last_rev_id = self.history[rev_history_position - 1]
        else:
            rev = branch.repository.get_revision(rev_id)
                
        if rev.revision_id != rev_id:
            raise BzrCheckError('wrong internal revision id in revision {%s}'
                                % rev_id)

        # check the previous history entry is a parent of this entry
        if rev.parent_ids:
            if last_rev_id is not None:
                for parent_id in rev.parent_ids:
                    if parent_id == last_rev_id:
                        break
                else:
                    raise BzrCheckError("previous revision {%s} not listed among "
                                        "parents of {%s}"
                                        % (last_rev_id, rev_id))
            for parent in rev.parent_ids:
                if not parent in self.planned_revisions:
                    missing_links = self.missing_parent_links.get(parent, [])
                    missing_links.append(rev_id)
                    self.missing_parent_links[parent] = missing_links
                    # list based so somewhat slow,
                    # TODO have a planned_revisions list and set.
                    if self.branch.repository.has_revision(parent):
                        missing_ancestry = self.repository.get_ancestry(parent)
                        for missing in missing_ancestry:
                            if (missing is not None 
                                and missing not in self.planned_revisions):
                                self.planned_revisions.append(missing)
                    else:
                        self.ghosts.append(rev_id)
        elif last_rev_id:
            raise BzrCheckError("revision {%s} has no parents listed "
                                "but preceded by {%s}"
                                % (rev_id, last_rev_id))

        if rev.inventory_sha1:
            inv_sha1 = branch.repository.get_inventory_sha1(rev_id)
            if inv_sha1 != rev.inventory_sha1:
                raise BzrCheckError('Inventory sha1 hash doesn\'t match'
                    ' value in revision {%s}' % rev_id)
        else:
            missing_inventory_sha_cnt += 1
            mutter("no inventory_sha1 on revision {%s}", rev_id)
        self._check_revision_tree(rev_id)
        self.checked_rev_cnt += 1

    def check_weaves(self):
        """Check all the weaves we can get our hands on.
        """
        n_weaves = 1
        weave_ids = []
        if self.branch.repository.weave_store.listable():
            weave_ids = list(self.branch.repository.weave_store)
            n_weaves = len(weave_ids)
        self.progress.update('checking weave', 0, n_weaves)
        self.inventory_weave.check(progress_bar=self.progress)
        for i, weave_id in enumerate(weave_ids):
            self.progress.update('checking weave', i, n_weaves)
            w = self.branch.repository.weave_store.get_weave(weave_id,
                    self.branch.repository.get_transaction())
            # No progress here, because it looks ugly.
            w.check()
            self.checked_weaves[weave_id] = True

    def _check_revision_tree(self, rev_id):
        tree = self.branch.repository.revision_tree(rev_id)
        inv = tree.inventory
        seen_ids = {}
        for file_id in inv:
            if file_id in seen_ids:
                raise BzrCheckError('duplicated file_id {%s} '
                                    'in inventory for revision {%s}'
                                    % (file_id, rev_id))
            seen_ids[file_id] = True
        for file_id in inv:
            ie = inv[file_id]
            ie.check(self, rev_id, inv, tree)
        seen_names = {}
        for path, ie in inv.iter_entries():
            if path in seen_names:
                raise BzrCheckError('duplicated path %s '
                                    'in inventory for revision {%s}'
                                    % (path, rev_id))
            seen_names[path] = True


def check(branch, verbose):
    """Run consistency checks on a branch."""
    checker = Check(branch)
    checker.check()
    checker.report_results(verbose)