/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 tools/history2weaves.py

  • Committer: Martin Pool
  • Date: 2005-09-19 10:16:36 UTC
  • Revision ID: mbp@sourcefrog.net-20050919101636-a4c0fd80e69edee8
- turn on psyco for testing
- omit absent revisions from file parents

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 True:
 
72
    try:
 
73
        import psyco
 
74
        psyco.full()
 
75
    except ImportError:
 
76
        pass
 
77
 
 
78
 
 
79
import tempfile
 
80
import hotshot, hotshot.stats
 
81
import sys
 
82
import logging
 
83
import time
 
84
 
 
85
from bzrlib.branch import Branch, find_branch
 
86
from bzrlib.revfile import Revfile
 
87
from bzrlib.weave import Weave
 
88
from bzrlib.weavefile import read_weave, write_weave
 
89
from bzrlib.progress import ProgressBar
 
90
from bzrlib.atomicfile import AtomicFile
 
91
from bzrlib.xml4 import serializer_v4
 
92
from bzrlib.xml5 import serializer_v5
 
93
from bzrlib.trace import mutter, note, warning, enable_default_logging
 
94
from bzrlib.osutils import sha_strings
 
95
 
 
96
 
 
97
 
 
98
class Convert(object):
 
99
    def __init__(self):
 
100
        self.converted_revs = set()
 
101
        self.absent_revisions = set()
 
102
        self.text_count = 0
 
103
        self.revisions = {}
 
104
        self.inventories = {}
 
105
        self.convert()
 
106
        
 
107
 
 
108
 
 
109
 
 
110
    def convert(self):
 
111
        enable_default_logging()
 
112
        self.pb = ProgressBar()
 
113
        self.inv_weave = Weave('__inventory')
 
114
        self.anc_weave = Weave('__ancestry')
 
115
 
 
116
        last_text_sha = {}
 
117
 
 
118
        # holds in-memory weaves for all files
 
119
        self.text_weaves = {}
 
120
 
 
121
        b = self.branch = Branch('.', relax_version_check=True)
 
122
 
 
123
        revno = 1
 
124
        rev_history = b.revision_history()
 
125
        last_idx = None
 
126
        inv_parents = []
 
127
 
 
128
        # to_read is a stack holding the revisions we still need to process;
 
129
        # appending to it adds new highest-priority revisions
 
130
        importorder = []
 
131
        self.known_revisions = set(rev_history)
 
132
        self.to_read = [rev_history[-1]]
 
133
        while self.to_read:
 
134
            rev_id = self.to_read.pop()
 
135
            if (rev_id not in self.revisions
 
136
                and rev_id not in self.absent_revisions):
 
137
                self._load_one_rev(rev_id)
 
138
        self.pb.clear()
 
139
        to_import = self._make_order()
 
140
        for i, rev_id in enumerate(to_import):
 
141
            self.pb.update('converting revision', i, len(to_import))
 
142
            self._convert_one_rev(rev_id)
 
143
 
 
144
        print '(not really) upgraded to weaves:'
 
145
        print '  %6d revisions and inventories' % len(self.revisions)
 
146
        print '  %6d absent revisions removed' % len(self.absent_revisions)
 
147
        print '  %6d texts' % self.text_count
 
148
 
 
149
        self._write_all_weaves()
 
150
 
 
151
 
 
152
    def _write_all_weaves(self):
 
153
        i = 0
 
154
        write_atomic_weave(self.inv_weave, 'weaves/inventory.weave')
 
155
        try:
 
156
            for file_id, file_weave in self.text_weaves.items():
 
157
                self.pb.update('writing weave', i, len(self.text_weaves))
 
158
                write_atomic_weave(file_weave, 'weaves/%s.weave' % file_id)
 
159
                i += 1
 
160
        finally:
 
161
            self.pb.clear()
 
162
        ## write_atomic_weave(self.anc_weave, 'weaves/ancestry.weave')
 
163
 
 
164
        
 
165
    def _load_one_rev(self, rev_id):
 
166
        """Load a revision object into memory.
 
167
 
 
168
        Any parents not either loaded or abandoned get queued to be
 
169
        loaded."""
 
170
        self.pb.update('loading revision',
 
171
                       len(self.revisions),
 
172
                       len(self.known_revisions))
 
173
        if rev_id not in self.branch.revision_store:
 
174
            self.pb.clear()
 
175
            note('revision {%s} not present in branch; '
 
176
                 'will not be converted',
 
177
                 rev_id)
 
178
            self.absent_revisions.add(rev_id)
 
179
        else:
 
180
            rev_xml = self.branch.revision_store[rev_id].read()
 
181
            rev = serializer_v4.read_revision_from_string(rev_xml)
 
182
            for parent_id in rev.parent_ids:
 
183
                self.known_revisions.add(parent_id)
 
184
                self.to_read.append(parent_id)
 
185
            self.revisions[rev_id] = rev
 
186
            old_inv_xml = self.branch.inventory_store[rev_id].read()
 
187
            inv = serializer_v4.read_inventory_from_string(old_inv_xml)
 
188
            self.inventories[rev_id] = inv
 
189
        
 
190
 
 
191
    def _convert_one_rev(self, rev_id):
 
192
        """Convert revision and all referenced objects to new format."""
 
193
        rev = self.revisions[rev_id]
 
194
        inv = self.inventories[rev_id]
 
195
        self._convert_revision_contents(rev, inv)
 
196
        # the XML is now updated with text versions
 
197
        new_inv_xml = serializer_v5.write_inventory_to_string(inv)
 
198
        inv_parents = [x for x in self.revisions[rev_id].parent_ids
 
199
                       if x not in self.absent_revisions]
 
200
        self.inv_weave.add(rev_id, inv_parents,
 
201
                           new_inv_xml.splitlines(True))
 
202
        # TODO: Upgrade revision XML and write that out
 
203
        self.converted_revs.add(rev_id)
 
204
 
 
205
 
 
206
    def _convert_revision_contents(self, rev, inv):
 
207
        """Convert all the files within a revision.
 
208
 
 
209
        Also upgrade the inventory to refer to the text revision ids."""
 
210
        rev_id = rev.revision_id
 
211
        mutter('converting texts of revision {%s}',
 
212
               rev_id)
 
213
        for path, ie in inv.iter_entries():
 
214
            if ie.kind != 'file':
 
215
                continue
 
216
            self._convert_file_version(rev, ie)
 
217
            # TODO: Check and convert name versions
 
218
 
 
219
 
 
220
    def _convert_file_version(self, rev, ie):
 
221
        """Convert one version of one file.
 
222
 
 
223
        The file needs to be added into the weave if it is a merge
 
224
        of >=2 parents or if it's changed from its parent.
 
225
        """
 
226
        file_id = ie.file_id
 
227
        rev_id = rev.revision_id
 
228
        w = self.text_weaves.get(file_id)
 
229
        if w is None:
 
230
            w = Weave(file_id)
 
231
            self.text_weaves[file_id] = w
 
232
        file_lines = self.branch.text_store[ie.text_id].readlines()
 
233
        assert sha_strings(file_lines) == ie.text_sha1
 
234
        assert sum(map(len, file_lines)) == ie.text_size
 
235
        file_parents = []
 
236
        text_changed = False
 
237
        for parent_id in rev.parent_ids:
 
238
            if parent_id in self.absent_revisions:
 
239
                continue
 
240
            assert parent_id in self.converted_revs
 
241
            parent_inv = self.inventories[parent_id]
 
242
            if parent_inv.has_id(file_id):
 
243
                parent_ie = parent_inv[file_id]
 
244
                old_text_version = parent_ie.text_version
 
245
                assert old_text_version in self.converted_revs 
 
246
                if old_text_version not in file_parents:
 
247
                    file_parents.append(old_text_version)
 
248
                if parent_ie.text_sha1 != ie.text_sha1:
 
249
                    text_changed = True
 
250
        if len(file_parents) != 1 or text_changed:
 
251
            w.add(rev_id, file_parents, file_lines)
 
252
            ie.name_version = ie.text_version = rev_id
 
253
            mutter('import text {%s} of {%s}',
 
254
                   ie.text_id, file_id)
 
255
        else:
 
256
            mutter('text of {%s} unchanged from parent', file_id)            
 
257
            ie.text_version = file_parents[0]
 
258
            ie.name_version = file_parents[0]
 
259
        del ie.text_id
 
260
                   
 
261
 
 
262
 
 
263
    def _make_order(self):
 
264
        """Return a suitable order for importing revisions.
 
265
 
 
266
        The order must be such that an revision is imported after all
 
267
        its (present) parents.
 
268
        """
 
269
        todo = set(self.revisions.keys())
 
270
        done = self.absent_revisions.copy()
 
271
        o = []
 
272
        while todo:
 
273
            # scan through looking for a revision whose parents
 
274
            # are all done
 
275
            for rev_id in sorted(list(todo)):
 
276
                rev = self.revisions[rev_id]
 
277
                parent_ids = set(rev.parent_ids)
 
278
                if parent_ids.issubset(done):
 
279
                    # can take this one now
 
280
                    o.append(rev_id)
 
281
                    todo.remove(rev_id)
 
282
                    done.add(rev_id)
 
283
        return o
 
284
                
 
285
 
 
286
def write_atomic_weave(weave, filename):
 
287
    inv_wf = AtomicFile(filename)
 
288
    try:
 
289
        write_weave(weave, inv_wf)
 
290
        inv_wf.commit()
 
291
    finally:
 
292
        inv_wf.close()
 
293
 
 
294
    
 
295
 
 
296
 
 
297
def profile_convert(): 
 
298
    prof_f = tempfile.NamedTemporaryFile()
 
299
 
 
300
    prof = hotshot.Profile(prof_f.name)
 
301
 
 
302
    prof.runcall(Convert) 
 
303
    prof.close()
 
304
 
 
305
    stats = hotshot.stats.load(prof_f.name)
 
306
    ##stats.strip_dirs()
 
307
    stats.sort_stats('time')
 
308
    # XXX: Might like to write to stderr or the trace file instead but
 
309
    # print_stats seems hardcoded to stdout
 
310
    stats.print_stats(20)
 
311
 
 
312
 
 
313
enable_default_logging()
 
314
 
 
315
if '-p' in sys.argv[1:]:
 
316
    profile_convert()
 
317
else:
 
318
    Convert()
 
319