/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 bzrlib/upgrade.py

  • Committer: Martin Pool
  • Date: 2005-09-22 11:57:15 UTC
  • Revision ID: mbp@sourcefrog.net-20050922115715-5c756ae94451c66f
- run conversion to weaves from the 'bzr upgrade' command

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#! /usr/bin/python
 
2
#
 
3
# Copyright (C) 2005 Canonical Ltd
 
4
#
 
5
# This program is free software; you can redistribute it and/or modify
 
6
# it under the terms of the GNU General Public License as published by
 
7
# the Free Software Foundation; either version 2 of the License, or
 
8
# (at your option) any later version.
 
9
#
 
10
# This program is distributed in the hope that it will be useful,
 
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
# GNU General Public License for more details.
 
14
#
 
15
# You should have received a copy of the GNU General Public License
 
16
# along with this program; if not, write to the Free Software
 
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
18
 
 
19
"""Experiment in converting existing bzr branches to weaves."""
 
20
 
 
21
# To make this properly useful
 
22
#
 
23
# 1. assign text version ids, and put those text versions into
 
24
#    the inventory as they're converted.
 
25
#
 
26
# 2. keep track of the previous version of each file, rather than
 
27
#    just using the last one imported
 
28
#
 
29
# 3. assign entry versions when files are added, renamed or moved.
 
30
#
 
31
# 4. when merged-in versions are observed, walk down through them
 
32
#    to discover everything, then commit bottom-up
 
33
#
 
34
# 5. track ancestry as things are merged in, and commit that in each
 
35
#    revision
 
36
#
 
37
# Perhaps it's best to first walk the whole graph and make a plan for
 
38
# what should be imported in what order?  Need a kind of topological
 
39
# sort of all revisions.  (Or do we, can we just before doing a revision
 
40
# see that all its parents have either been converted or abandoned?)
 
41
 
 
42
 
 
43
# Cannot import a revision until all its parents have been
 
44
# imported.  in other words, we can only import revisions whose
 
45
# parents have all been imported.  the first step must be to
 
46
# import a revision with no parents, of which there must be at
 
47
# least one.  (So perhaps it's useful to store forward pointers
 
48
# from a list of parents to their children?)
 
49
#
 
50
# Another (equivalent?) approach is to build up the ordered
 
51
# ancestry list for the last revision, and walk through that.  We
 
52
# are going to need that.
 
53
#
 
54
# We don't want to have to recurse all the way back down the list.
 
55
#
 
56
# Suppose we keep a queue of the revisions able to be processed at
 
57
# any point.  This starts out with all the revisions having no
 
58
# parents.
 
59
#
 
60
# This seems like a generally useful algorithm...
 
61
#
 
62
# The current algorithm is dumb (O(n**2)?) but will do the job, and
 
63
# takes less than a second on the bzr.dev branch.
 
64
 
 
65
# This currently does a kind of lazy conversion of file texts, where a
 
66
# new text is written in every version.  That's unnecessary but for
 
67
# the moment saves us having to worry about when files need new
 
68
# versions.
 
69
 
 
70
 
 
71
if False:
 
72
    try:
 
73
        import psyco
 
74
        psyco.full()
 
75
    except ImportError:
 
76
        pass
 
77
 
 
78
 
 
79
import os
 
80
import tempfile
 
81
import hotshot, hotshot.stats
 
82
import sys
 
83
import logging
 
84
import shutil
 
85
 
 
86
from bzrlib.branch import Branch, find_branch, BZR_BRANCH_FORMAT_5
 
87
from bzrlib.revfile import Revfile
 
88
from bzrlib.weave import Weave
 
89
from bzrlib.weavefile import read_weave, write_weave
 
90
from bzrlib.progress import ProgressBar
 
91
from bzrlib.atomicfile import AtomicFile
 
92
from bzrlib.xml4 import serializer_v4
 
93
from bzrlib.xml5 import serializer_v5
 
94
from bzrlib.trace import mutter, note, warning, enable_default_logging
 
95
from bzrlib.osutils import sha_strings, sha_string
 
96
from bzrlib.commit import merge_ancestry_lines
 
97
 
 
98
 
 
99
class Convert(object):
 
100
    def __init__(self, base_dir):
 
101
        self.base = base_dir
 
102
        self.converted_revs = set()
 
103
        self.absent_revisions = set()
 
104
        self.text_count = 0
 
105
        self.revisions = {}
 
106
        self.inventories = {}
 
107
        self.convert()
 
108
 
 
109
 
 
110
    def convert(self):
 
111
        note('starting upgrade of %s', self.base)
 
112
        self._backup_control_dir()
 
113
        note('starting upgrade')
 
114
        note('note: upgrade will be faster if all store files are ungzipped first')
 
115
        self.pb = ProgressBar()
 
116
        if not os.path.isdir(self.base + '/.bzr/weaves'):
 
117
            os.mkdir(self.base + '/.bzr/weaves')
 
118
        self.inv_weave = Weave('__inventory')
 
119
        self.anc_weave = Weave('__ancestry')
 
120
        self.ancestries = {}
 
121
        # holds in-memory weaves for all files
 
122
        self.text_weaves = {}
 
123
        self.branch = Branch(self.base, relax_version_check=True)
 
124
        if self.branch._branch_format == 5:
 
125
            note('this branch is already in the most current format')
 
126
            return
 
127
        if self.branch._branch_format != 4:
 
128
            raise BzrError("cannot upgrade from branch format %r" %
 
129
                           self.branch._branch_format)
 
130
        os.remove(self.branch.controlfilename('branch-format'))
 
131
        self._convert_working_inv()
 
132
        rev_history = self.branch.revision_history()
 
133
        # to_read is a stack holding the revisions we still need to process;
 
134
        # appending to it adds new highest-priority revisions
 
135
        self.known_revisions = set(rev_history)
 
136
        self.to_read = [rev_history[-1]]
 
137
        while self.to_read:
 
138
            rev_id = self.to_read.pop()
 
139
            if (rev_id not in self.revisions
 
140
                and rev_id not in self.absent_revisions):
 
141
                self._load_one_rev(rev_id)
 
142
        self.pb.clear()
 
143
        to_import = self._make_order()
 
144
        for i, rev_id in enumerate(to_import):
 
145
            self.pb.update('converting revision', i, len(to_import))
 
146
            self._convert_one_rev(rev_id)
 
147
        self.pb.clear()
 
148
        note('upgraded to weaves:')
 
149
        note('  %6d revisions and inventories' % len(self.revisions))
 
150
        note('  %6d absent revisions removed' % len(self.absent_revisions))
 
151
        note('  %6d texts' % self.text_count)
 
152
        self._write_all_weaves()
 
153
        self._write_all_revs()
 
154
        self._set_new_format()
 
155
        self._cleanup_spare_files()
 
156
 
 
157
 
 
158
    def _set_new_format(self):
 
159
        f = self.branch.controlfile('branch-format', 'wb')
 
160
        try:
 
161
            f.write(BZR_BRANCH_FORMAT_5)
 
162
        finally:
 
163
            f.close()
 
164
 
 
165
 
 
166
    def _cleanup_spare_files(self):
 
167
        for n in 'merged-patches', 'pending-merged-patches':
 
168
            p = self.branch.controlfilename(n)
 
169
            if not os.path.exists(p):
 
170
                continue
 
171
            assert os.path.getsize(p) == 0
 
172
            os.remove(p)
 
173
        os.remove(self.base + '/.bzr/allow-upgrade')
 
174
        shutil.rmtree(self.base + '/.bzr/inventory-store')
 
175
        shutil.rmtree(self.base + '/.bzr/text-store')
 
176
 
 
177
 
 
178
    def _backup_control_dir(self):
 
179
        orig = self.base + '/.bzr'
 
180
        backup = orig + '.backup'
 
181
        shutil.copytree(orig, backup)
 
182
        note('%s has been backed up to %s', orig, backup)
 
183
        note('if conversion fails, you can move this directory back to .bzr')
 
184
        note('if it succeeds, you can remove this directory if you wish')
 
185
 
 
186
 
 
187
    def _convert_working_inv(self):
 
188
        branch = self.branch
 
189
        inv = serializer_v4.read_inventory(branch.controlfile('inventory', 'rb'))
 
190
        serializer_v5.write_inventory(inv, branch.controlfile('inventory', 'wb'))
 
191
 
 
192
 
 
193
 
 
194
    def _write_all_weaves(self):
 
195
        write_a_weave(self.inv_weave, self.base + '/.bzr/inventory.weave')
 
196
        write_a_weave(self.anc_weave, self.base + '/.bzr/ancestry.weave')
 
197
        i = 0
 
198
        try:
 
199
            for file_id, file_weave in self.text_weaves.items():
 
200
                self.pb.update('writing weave', i, len(self.text_weaves))
 
201
                write_a_weave(file_weave, self.base + '/.bzr/weaves/%s.weave' % file_id)
 
202
                i += 1
 
203
        finally:
 
204
            self.pb.clear()
 
205
 
 
206
 
 
207
    def _write_all_revs(self):
 
208
        """Write all revisions out in new form."""
 
209
        shutil.rmtree(self.base + '/.bzr/revision-store')
 
210
        os.mkdir(self.base + '/.bzr/revision-store')
 
211
        try:
 
212
            for i, rev_id in enumerate(self.converted_revs):
 
213
                self.pb.update('write revision', i, len(self.converted_revs))
 
214
                f = file(self.base + '/.bzr/revision-store/%s' % rev_id, 'wb')
 
215
                try:
 
216
                    serializer_v5.write_revision(self.revisions[rev_id], f)
 
217
                finally:
 
218
                    f.close()
 
219
        finally:
 
220
            self.pb.clear()
 
221
 
 
222
            
 
223
    def _load_one_rev(self, rev_id):
 
224
        """Load a revision object into memory.
 
225
 
 
226
        Any parents not either loaded or abandoned get queued to be
 
227
        loaded."""
 
228
        self.pb.update('loading revision',
 
229
                       len(self.revisions),
 
230
                       len(self.known_revisions))
 
231
        if rev_id not in self.branch.revision_store:
 
232
            self.pb.clear()
 
233
            note('revision {%s} not present in branch; '
 
234
                 'will not be converted',
 
235
                 rev_id)
 
236
            self.absent_revisions.add(rev_id)
 
237
        else:
 
238
            rev_xml = self.branch.revision_store[rev_id].read()
 
239
            rev = serializer_v4.read_revision_from_string(rev_xml)
 
240
            for parent_id in rev.parent_ids:
 
241
                self.known_revisions.add(parent_id)
 
242
                self.to_read.append(parent_id)
 
243
            self.revisions[rev_id] = rev
 
244
            old_inv_xml = self.branch.inventory_store[rev_id].read()
 
245
            inv = serializer_v4.read_inventory_from_string(old_inv_xml)
 
246
            assert rev.inventory_sha1 == sha_string(old_inv_xml)
 
247
            self.inventories[rev_id] = inv
 
248
        
 
249
 
 
250
    def _convert_one_rev(self, rev_id):
 
251
        """Convert revision and all referenced objects to new format."""
 
252
        rev = self.revisions[rev_id]
 
253
        inv = self.inventories[rev_id]
 
254
        for parent_id in rev.parent_ids[:]:
 
255
            if parent_id in self.absent_revisions:
 
256
                rev.parent_ids.remove(parent_id)
 
257
                self.pb.clear()
 
258
                note('remove {%s} as parent of {%s}', parent_id, rev_id)
 
259
        self._convert_revision_contents(rev, inv)
 
260
        # the XML is now updated with text versions
 
261
        new_inv_xml = serializer_v5.write_inventory_to_string(inv)
 
262
        new_inv_sha1 = sha_string(new_inv_xml)
 
263
        self.inv_weave.add(rev_id, rev.parent_ids,
 
264
                           new_inv_xml.splitlines(True),
 
265
                           new_inv_sha1)
 
266
        # TODO: Upgrade revision XML and write that out
 
267
        rev.inventory_sha1 = new_inv_sha1
 
268
        self._make_rev_ancestry(rev)
 
269
        self.converted_revs.add(rev_id)
 
270
 
 
271
 
 
272
    def _make_rev_ancestry(self, rev):
 
273
        rev_id = rev.revision_id
 
274
        for parent_id in rev.parent_ids:
 
275
            assert parent_id in self.converted_revs
 
276
        if rev.parent_ids:
 
277
            lines = list(self.anc_weave.mash_iter(rev.parent_ids))
 
278
        else:
 
279
            lines = []
 
280
        lines.append(rev_id + '\n')
 
281
        if __debug__:
 
282
            parent_ancestries = [self.ancestries[p] for p in rev.parent_ids]
 
283
            new_lines = merge_ancestry_lines(rev_id, parent_ancestries)
 
284
            assert set(lines) == set(new_lines)
 
285
            self.ancestries[rev_id] = new_lines
 
286
        self.anc_weave.add(rev_id, rev.parent_ids, lines)
 
287
 
 
288
 
 
289
    def _convert_revision_contents(self, rev, inv):
 
290
        """Convert all the files within a revision.
 
291
 
 
292
        Also upgrade the inventory to refer to the text revision ids."""
 
293
        rev_id = rev.revision_id
 
294
        mutter('converting texts of revision {%s}',
 
295
               rev_id)
 
296
        for file_id in inv:
 
297
            ie = inv[file_id]
 
298
            self._set_name_version(rev, ie)
 
299
            if ie.kind != 'file':
 
300
                continue
 
301
            self._convert_file_version(rev, ie)
 
302
 
 
303
 
 
304
    def _set_name_version(self, rev, ie):
 
305
        """Set name version for a file.
 
306
 
 
307
        Done in a slightly lazy way: if the file is renamed or in a merge revision
 
308
        it gets a new version, otherwise the same as before.
 
309
        """
 
310
        file_id = ie.file_id
 
311
        if len(rev.parent_ids) != 1:
 
312
            ie.name_version = rev.revision_id
 
313
        else:
 
314
            old_inv = self.inventories[rev.parent_ids[0]]
 
315
            if not old_inv.has_id(file_id):
 
316
                ie.name_version = rev.revision_id
 
317
            else:
 
318
                old_ie = old_inv[file_id]
 
319
                if (old_ie.parent_id != ie.parent_id
 
320
                    or old_ie.name != ie.name):
 
321
                    ie.name_version = rev.revision_id
 
322
                else:
 
323
                    ie.name_version = old_ie.name_version
 
324
 
 
325
 
 
326
 
 
327
    def _convert_file_version(self, rev, ie):
 
328
        """Convert one version of one file.
 
329
 
 
330
        The file needs to be added into the weave if it is a merge
 
331
        of >=2 parents or if it's changed from its parent.
 
332
        """
 
333
        file_id = ie.file_id
 
334
        rev_id = rev.revision_id
 
335
        w = self.text_weaves.get(file_id)
 
336
        if w is None:
 
337
            w = Weave(file_id)
 
338
            self.text_weaves[file_id] = w
 
339
        file_lines = self.branch.text_store[ie.text_id].readlines()
 
340
        assert sha_strings(file_lines) == ie.text_sha1
 
341
        assert sum(map(len, file_lines)) == ie.text_size
 
342
        file_parents = []
 
343
        text_changed = False
 
344
        for parent_id in rev.parent_ids:
 
345
            ##if parent_id in self.absent_revisions:
 
346
            ##    continue
 
347
            assert parent_id in self.converted_revs, \
 
348
                   'parent {%s} not converted' % parent_id
 
349
            parent_inv = self.inventories[parent_id]
 
350
            if parent_inv.has_id(file_id):
 
351
                parent_ie = parent_inv[file_id]
 
352
                old_text_version = parent_ie.text_version
 
353
                assert old_text_version in self.converted_revs 
 
354
                if old_text_version not in file_parents:
 
355
                    file_parents.append(old_text_version)
 
356
                if parent_ie.text_sha1 != ie.text_sha1:
 
357
                    text_changed = True
 
358
        if len(file_parents) != 1 or text_changed:
 
359
            w.add(rev_id, file_parents, file_lines, ie.text_sha1)
 
360
            ie.text_version = rev_id
 
361
            self.text_count += 1
 
362
            ##mutter('import text {%s} of {%s}',
 
363
            ##       ie.text_id, file_id)
 
364
        else:
 
365
            ##mutter('text of {%s} unchanged from parent', file_id)
 
366
            ie.text_version = file_parents[0]
 
367
        del ie.text_id
 
368
 
 
369
 
 
370
 
 
371
    def _make_order(self):
 
372
        """Return a suitable order for importing revisions.
 
373
 
 
374
        The order must be such that an revision is imported after all
 
375
        its (present) parents.
 
376
        """
 
377
        todo = set(self.revisions.keys())
 
378
        done = self.absent_revisions.copy()
 
379
        o = []
 
380
        while todo:
 
381
            # scan through looking for a revision whose parents
 
382
            # are all done
 
383
            for rev_id in sorted(list(todo)):
 
384
                rev = self.revisions[rev_id]
 
385
                parent_ids = set(rev.parent_ids)
 
386
                if parent_ids.issubset(done):
 
387
                    # can take this one now
 
388
                    o.append(rev_id)
 
389
                    todo.remove(rev_id)
 
390
                    done.add(rev_id)
 
391
        return o
 
392
 
 
393
 
 
394
def write_a_weave(weave, filename):
 
395
    inv_wf = file(filename, 'wb')
 
396
    try:
 
397
        write_weave(weave, inv_wf)
 
398
    finally:
 
399
        inv_wf.close()
 
400
 
 
401
 
 
402
def upgrade(base_dir):
 
403
    Convert(base_dir)