/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.9.2 by Aaron Bentley
Get single-parent comparison working
1
from difflib import SequenceMatcher
0.9.25 by Aaron Bentley
More messy hacking
2
from StringIO import StringIO
0.9.19 by Aaron Bentley
More tweakage
3
import sys
4
0.9.25 by Aaron Bentley
More messy hacking
5
from bzrlib import (
6
    patiencediff,
7
    trace,
8
    ui,
9
    )
10
11
from bzrlib.tuned_gzip import GzipFile
0.9.3 by Aaron Bentley
Get three-parent comparisions under test
12
0.9.1 by Aaron Bentley
Get trivial case passing
13
class MultiParent(object):
14
0.9.2 by Aaron Bentley
Get single-parent comparison working
15
    def __init__(self, hunks=None):
16
        if hunks is not None:
17
            self.hunks = hunks
18
        else:
19
            self.hunks = []
20
21
    def __repr__(self):
22
        return "MultiParent(%r)" % self.hunks
23
24
    def __eq__(self, other):
25
        if self.__class__ is not other.__class__:
26
            return False
27
        return (self.hunks == other.hunks)
0.9.1 by Aaron Bentley
Get trivial case passing
28
29
    @staticmethod
30
    def from_lines(text, parents=()):
0.9.10 by Aaron Bentley
Text reconstruction seems to work
31
        """Produce a MultiParent from a list of lines and parents"""
0.9.2 by Aaron Bentley
Get single-parent comparison working
32
        def compare(parent):
0.9.16 by Aaron Bentley
More control over snapshotting, disable caching for inventory
33
            matcher = patiencediff.PatienceSequenceMatcher(None, parent,
34
                                                           text)
35
            return matcher.get_matching_blocks()
0.9.2 by Aaron Bentley
Get single-parent comparison working
36
        parent_comparisons = [compare(p) for p in parents]
37
        cur_line = 0
38
        new_text = NewText([])
39
        parent_text = []
40
        block_iter = [iter(i) for i in parent_comparisons]
41
        diff = MultiParent([])
42
        def next_block(p):
43
            try:
44
                return block_iter[p].next()
45
            except StopIteration:
46
                return None
47
        cur_block = [next_block(p) for p, i in enumerate(block_iter)]
48
        while cur_line < len(text):
49
            best_match = None
50
            for p, block in enumerate(cur_block):
51
                if block is None:
52
                    continue
53
                i, j, n = block
54
                while j + n < cur_line:
55
                    block = cur_block[p] = next_block(p)
56
                    if block is None:
57
                        break
58
                    i, j, n = block
59
                if block is None:
60
                    continue
61
                if j > cur_line:
62
                    continue
63
                offset = cur_line - j
64
                i += offset
65
                j = cur_line
66
                n -= offset
67
                if n == 0:
68
                    continue
69
                if best_match is None or n > best_match.num_lines:
70
                    best_match = ParentText(p, i, j, n)
71
            if best_match is None:
72
                new_text.lines.append(text[cur_line])
73
                cur_line += 1
74
            else:
75
                if len(new_text.lines) > 0:
76
                    diff.hunks.append(new_text)
77
                    new_text = NewText([])
78
                diff.hunks.append(best_match)
79
                cur_line += best_match.num_lines
80
        if len(new_text.lines) > 0:
81
            diff.hunks.append(new_text)
0.9.1 by Aaron Bentley
Get trivial case passing
82
        return diff
83
84
    @classmethod
85
    def from_texts(cls, text, parents=()):
0.9.10 by Aaron Bentley
Text reconstruction seems to work
86
        """Produce a MultiParent from a text and list of parent text"""
0.9.1 by Aaron Bentley
Get trivial case passing
87
        return cls.from_lines(text.splitlines(True),
88
                              [p.splitlines(True) for p in parents])
89
0.9.4 by Aaron Bentley
Start supporting serialization
90
    def to_patch(self):
0.9.10 by Aaron Bentley
Text reconstruction seems to work
91
        """Yield text lines for a patch"""
0.9.4 by Aaron Bentley
Start supporting serialization
92
        for hunk in self.hunks:
93
            for line in hunk.to_patch():
94
                yield line
95
0.9.25 by Aaron Bentley
More messy hacking
96
    def patch_len(self):
97
        return len(''.join(self.to_patch()))
98
99
    def zipped_patch_len(self):
100
        return len(gzip_string(self.to_patch()))
101
0.9.18 by Aaron Bentley
Implement from_patch
102
    @staticmethod
103
    def from_patch(lines):
0.9.19 by Aaron Bentley
More tweakage
104
        """Produce a MultiParent from a sequence of lines"""
0.9.18 by Aaron Bentley
Implement from_patch
105
        line_iter = iter(lines)
106
        hunks = []
107
        cur_line = None
108
        while(True):
109
            try:
110
                cur_line = line_iter.next()
111
            except StopIteration:
112
                break
113
            if cur_line[0] == 'i':
114
                num_lines = int(cur_line.split(' ')[1])
115
                hunk_lines = [line_iter.next() for x in xrange(num_lines)]
116
                hunk_lines[-1] = hunk_lines[-1][:-1]
117
                hunks.append(NewText(hunk_lines))
118
            elif cur_line[0] == '\n':
119
                hunks[-1].lines[-1] += '\n'
120
            else:
121
                assert cur_line[0] == 'c', cur_line[0]
122
                parent, parent_pos, child_pos, num_lines =\
123
                    [int(v) for v in cur_line.split(' ')[1:]]
124
                hunks.append(ParentText(parent, parent_pos, child_pos,
125
                                        num_lines))
126
        return MultiParent(hunks)
127
0.9.9 by Aaron Bentley
Much progress on non-naive text reconstruction
128
    def range_iterator(self):
0.9.10 by Aaron Bentley
Text reconstruction seems to work
129
        """Iterate through the hunks, with range indicated
130
131
        kind is "new" or "parent".
132
        for "new", data is a list of lines.
133
        for "parent", data is (parent, parent_start, parent_end)
134
        :return: a generator of (start, end, kind, data)
135
        """
0.9.9 by Aaron Bentley
Much progress on non-naive text reconstruction
136
        start = 0
137
        for hunk in self.hunks:
138
            if isinstance(hunk, NewText):
139
                kind = 'new'
140
                end = start + len(hunk.lines)
141
                data = hunk.lines
142
            else:
143
                kind = 'parent'
144
                start = hunk.child_pos
145
                end = start + hunk.num_lines
146
                data = (hunk.parent, hunk.parent_pos, hunk.parent_pos +
147
                        hunk.num_lines)
148
            yield start, end, kind, data
149
            start = end
150
0.9.11 by Aaron Bentley
Implement reconstruct_version, handle all hunks through that
151
    def num_lines(self):
152
        extra_n = 0
153
        for hunk in reversed(self.hunks):
154
            if isinstance(hunk, ParentText):
155
               return hunk.child_pos + hunk.num_lines + extra_n
156
            extra_n += len(hunk.lines)
157
        return extra_n
158
0.9.25 by Aaron Bentley
More messy hacking
159
    def is_snapshot(self):
160
        if len(self.hunks) != 1:
161
            return False
162
        return (isinstance(self.hunks[0], NewText))
163
0.9.1 by Aaron Bentley
Get trivial case passing
164
165
class NewText(object):
0.9.10 by Aaron Bentley
Text reconstruction seems to work
166
    """The contents of text that is introduced by this text"""
0.9.1 by Aaron Bentley
Get trivial case passing
167
168
    def __init__(self, lines):
169
        self.lines = lines
170
171
    def __eq__(self, other):
172
        if self.__class__ is not other.__class__:
173
            return False
174
        return (other.lines == self.lines)
0.9.2 by Aaron Bentley
Get single-parent comparison working
175
176
    def __repr__(self):
177
        return 'NewText(%r)' % self.lines
178
0.9.4 by Aaron Bentley
Start supporting serialization
179
    def to_patch(self):
180
        yield 'i %d\n' % len(self.lines)
181
        for line in self.lines:
182
            yield line
183
        yield '\n'
184
0.9.2 by Aaron Bentley
Get single-parent comparison working
185
186
class ParentText(object):
0.9.10 by Aaron Bentley
Text reconstruction seems to work
187
    """A reference to text present in a parent text"""
0.9.2 by Aaron Bentley
Get single-parent comparison working
188
189
    def __init__(self, parent, parent_pos, child_pos, num_lines):
190
        self.parent = parent
191
        self.parent_pos = parent_pos
192
        self.child_pos = child_pos
193
        self.num_lines = num_lines
194
195
    def __repr__(self):
196
        return 'ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'\
197
            ' %(num_lines)r)' % self.__dict__
198
199
    def __eq__(self, other):
200
        if self.__class__ != other.__class__:
201
            return False
202
        return (self.__dict__ == other.__dict__)
0.9.4 by Aaron Bentley
Start supporting serialization
203
204
    def to_patch(self):
205
        yield 'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'\
206
            % self.__dict__
0.9.8 by Aaron Bentley
get add_version working
207
208
209
class MultiVersionedFile(object):
0.9.10 by Aaron Bentley
Text reconstruction seems to work
210
    """VersionedFile skeleton for MultiParent"""
0.9.8 by Aaron Bentley
get add_version working
211
0.9.16 by Aaron Bentley
More control over snapshotting, disable caching for inventory
212
    def __init__(self, snapshot_interval=25, max_snapshots=None):
0.9.8 by Aaron Bentley
get add_version working
213
        self._diffs = {}
214
        self._lines = {}
215
        self._parents = {}
0.9.16 by Aaron Bentley
More control over snapshotting, disable caching for inventory
216
        self._snapshots = set()
0.9.12 by Aaron Bentley
Make benchmarks for mp
217
        self.snapshot_interval = snapshot_interval
0.9.16 by Aaron Bentley
More control over snapshotting, disable caching for inventory
218
        self.max_snapshots = max_snapshots
0.9.12 by Aaron Bentley
Make benchmarks for mp
219
220
    def do_snapshot(self, version_id, parent_ids):
0.9.16 by Aaron Bentley
More control over snapshotting, disable caching for inventory
221
        if self.snapshot_interval is None:
222
            return False
223
        if self.max_snapshots is not None and\
224
            len(self._snapshots) == self.max_snapshots:
0.9.14 by Aaron Bentley
Temporarily force snapshots to 44
225
            return False
0.9.12 by Aaron Bentley
Make benchmarks for mp
226
        if len(parent_ids) == 0:
0.9.16 by Aaron Bentley
More control over snapshotting, disable caching for inventory
227
            return True
228
        for ignored in xrange(self.snapshot_interval):
0.9.12 by Aaron Bentley
Make benchmarks for mp
229
            if len(parent_ids) == 0:
230
                return False
0.9.17 by Aaron Bentley
Dynamically select snapshots based on all parents
231
            version_ids = parent_ids
232
            parent_ids = []
233
            for version_id in version_ids:
234
                if version_id not in self._snapshots:
235
                    parent_ids.extend(self._parents[version_id])
0.9.16 by Aaron Bentley
More control over snapshotting, disable caching for inventory
236
        else:
237
            return True
0.9.8 by Aaron Bentley
get add_version working
238
0.9.16 by Aaron Bentley
More control over snapshotting, disable caching for inventory
239
    def add_version(self, lines, version_id, parent_ids,
0.9.20 by Aaron Bentley
Convert to a plugin
240
                    force_snapshot=None, single_parent=False):
0.9.16 by Aaron Bentley
More control over snapshotting, disable caching for inventory
241
        if force_snapshot is None:
242
            do_snapshot = self.do_snapshot(version_id, parent_ids)
243
        else:
244
            do_snapshot = force_snapshot
245
        if do_snapshot:
246
            self._snapshots.add(version_id)
0.9.12 by Aaron Bentley
Make benchmarks for mp
247
            diff = MultiParent([NewText(lines)])
248
        else:
0.9.20 by Aaron Bentley
Convert to a plugin
249
            if single_parent:
250
                parent_lines = self.get_line_list(parent_ids[:1])
251
            else:
252
                parent_lines = self.get_line_list(parent_ids)
0.9.12 by Aaron Bentley
Make benchmarks for mp
253
            diff = MultiParent.from_lines(lines, parent_lines)
0.9.25 by Aaron Bentley
More messy hacking
254
            snapdiff = MultiParent([NewText(lines)])
255
            if diff.is_snapshot():
256
                self._snapshots.add(version_id)
257
            elif diff.patch_len() >= snapdiff.patch_len():
258
                trace.note("Forcing snapshot")
259
                self._snapshots.add(version_id)
0.9.8 by Aaron Bentley
get add_version working
260
        self.add_diff(diff, version_id, parent_ids)
261
        self._lines[version_id] = lines
262
263
    def add_diff(self, diff, version_id, parent_ids):
264
        self._diffs[version_id] = diff
265
        self._parents[version_id] = parent_ids
266
0.9.20 by Aaron Bentley
Convert to a plugin
267
    def import_versionedfile(self, vf, snapshots, no_cache=True,
0.9.22 by Aaron Bentley
Fix restoration bug
268
                             single_parent=False, verify=False):
0.9.20 by Aaron Bentley
Convert to a plugin
269
        """Import all revisions of a versionedfile
270
271
        :param vf: The versionedfile to import
272
        :param snapshots: If provided, the revisions to make snapshots of.
273
            Otherwise, this will be auto-determined
274
        :param no_cache: If true, clear the cache after every add.
275
        :param single_parent: If true, omit all but one parent text, (but
276
            retain parent metadata).
277
        """
0.9.22 by Aaron Bentley
Fix restoration bug
278
        assert no_cache or not verify
0.9.19 by Aaron Bentley
More tweakage
279
        revisions = set(vf.versions())
280
        total = len(revisions)
0.9.20 by Aaron Bentley
Convert to a plugin
281
        pb = ui.ui_factory.nested_progress_bar()
282
        try:
283
            while len(revisions) > 0:
284
                added = set()
285
                for revision in revisions:
286
                    parents = vf.get_parents(revision)
287
                    if [p for p in parents if p not in self._diffs] != []:
288
                        continue
289
                    lines = [a + ' ' + l for a, l in
290
                             vf.annotate_iter(revision)]
0.9.21 by Aaron Bentley
finish converting ft_ to snapshots
291
                    if snapshots is None:
0.9.20 by Aaron Bentley
Convert to a plugin
292
                        force_snapshot = None
293
                    else:
0.9.21 by Aaron Bentley
finish converting ft_ to snapshots
294
                        force_snapshot = (revision in snapshots)
0.9.20 by Aaron Bentley
Convert to a plugin
295
                    self.add_version(lines, revision, parents, force_snapshot,
296
                                     single_parent)
297
                    added.add(revision)
298
                    if no_cache:
299
                        self.clear_cache()
0.9.25 by Aaron Bentley
More messy hacking
300
                        vf.clear_cache()
0.9.22 by Aaron Bentley
Fix restoration bug
301
                        if verify:
302
                            assert lines == self.get_line_list([revision])[0]
303
                            self.clear_cache()
0.9.20 by Aaron Bentley
Convert to a plugin
304
                    pb.update('Importing revisions',
305
                              (total - len(revisions)) + len(added), total)
306
                revisions = [r for r in revisions if r not in added]
307
        finally:
308
            pb.finished()
0.9.19 by Aaron Bentley
More tweakage
309
0.9.23 by Aaron Bentley
handle snapshots all at once
310
    def select_snapshots(self, vf):
311
        distances = {}
312
        descendants = {}
313
        snapshots = set()
314
        for version_id in vf.versions():
315
            for parent_id in vf.get_parents(version_id):
316
                descendants.setdefault(parent_id, []).append(version_id)
317
        cur = [v for v in vf.versions() if len(vf.get_parents(v)) == 0]
318
        while len(cur) > 0:
319
            next = []
320
            for version_id in cur:
321
                if version_id in distances:
322
                    continue
323
                parents = vf.get_parents(version_id)
324
                p_distances = [distances.get(p) for p in parents]
325
                if None in p_distances:
326
                    continue
327
                next.extend(descendants.get(version_id, []))
328
                if len(p_distances) == 0:
329
                    snapshots.add(version_id)
330
                    distances[version_id] = 0
331
                else:
332
                    max_distance = max(p_distances)
333
                    if max_distance + 1 > self.snapshot_interval:
334
                        snapshots.add(version_id)
335
                        distances[version_id] = 0
0.9.24 by Aaron Bentley
Add some snapshot-selection crack
336
                    elif len(descendants) > 1 and max_distance > \
337
                        self.snapshot_interval -4 and False:
338
                        snapshots.add(version_id)
339
                        distances[version_id] = 0
0.9.23 by Aaron Bentley
handle snapshots all at once
340
                    else:
341
                        distances[version_id] = max_distance + 1
342
            cur = next
343
        return snapshots
344
345
0.9.8 by Aaron Bentley
get add_version working
346
    def clear_cache(self):
347
        self._lines.clear()
0.9.9 by Aaron Bentley
Much progress on non-naive text reconstruction
348
349
    def get_line_list(self, version_ids):
350
        return [self.cache_version(v) for v in version_ids]
351
352
    def cache_version(self, version_id):
353
        try:
354
            return self._lines[version_id]
355
        except KeyError:
356
            pass
357
        diff = self._diffs[version_id]
358
        lines = []
0.9.17 by Aaron Bentley
Dynamically select snapshots based on all parents
359
        reconstructor = _Reconstructor(self._diffs, self._lines,
360
                                       self._parents)
0.9.11 by Aaron Bentley
Implement reconstruct_version, handle all hunks through that
361
        reconstructor.reconstruct_version(lines, version_id)
0.9.25 by Aaron Bentley
More messy hacking
362
        #self._lines[version_id] = lines
0.9.9 by Aaron Bentley
Much progress on non-naive text reconstruction
363
        return lines
364
365
366
class _Reconstructor(object):
0.9.10 by Aaron Bentley
Text reconstruction seems to work
367
    """Build a text from the diffs, ancestry graph and cached lines"""
0.9.9 by Aaron Bentley
Much progress on non-naive text reconstruction
368
369
    def __init__(self, diffs, lines, parents):
370
        self.diffs = diffs
371
        self.lines = lines
372
        self.parents = parents
373
        self.cursor = {}
374
375
    def reconstruct(self, lines, parent_text, version_id):
0.9.10 by Aaron Bentley
Text reconstruction seems to work
376
        """Append the lines referred to by a ParentText to lines"""
0.9.9 by Aaron Bentley
Much progress on non-naive text reconstruction
377
        parent_id = self.parents[version_id][parent_text.parent]
378
        end = parent_text.parent_pos + parent_text.num_lines
0.9.17 by Aaron Bentley
Dynamically select snapshots based on all parents
379
        return self._reconstruct(lines, parent_id, parent_text.parent_pos,
380
                                 end)
0.9.9 by Aaron Bentley
Much progress on non-naive text reconstruction
381
382
    def _reconstruct(self, lines, req_version_id, req_start, req_end):
0.9.10 by Aaron Bentley
Text reconstruction seems to work
383
        """Append lines for the requested version_id range"""
384
        # stack of pending range requests
0.9.9 by Aaron Bentley
Much progress on non-naive text reconstruction
385
        pending_reqs = [(req_version_id, req_start, req_end)]
386
        while len(pending_reqs) > 0:
387
            req_version_id, req_start, req_end = pending_reqs.pop()
0.9.10 by Aaron Bentley
Text reconstruction seems to work
388
            # lazily allocate cursors for versions
0.9.9 by Aaron Bentley
Much progress on non-naive text reconstruction
389
            try:
390
                start, end, kind, data, iterator = self.cursor[req_version_id]
391
            except KeyError:
392
                iterator = self.diffs[req_version_id].range_iterator()
393
                start, end, kind, data = iterator.next()
0.9.22 by Aaron Bentley
Fix restoration bug
394
            if start > req_start:
395
                iterator = self.diffs[req_version_id].range_iterator()
396
                start, end, kind, data = iterator.next()
397
0.9.10 by Aaron Bentley
Text reconstruction seems to work
398
            # find the first hunk relevant to the request
399
            while end <= req_start:
0.9.9 by Aaron Bentley
Much progress on non-naive text reconstruction
400
                start, end, kind, data = iterator.next()
401
            self.cursor[req_version_id] = start, end, kind, data, iterator
0.9.10 by Aaron Bentley
Text reconstruction seems to work
402
            # if the hunk can't satisfy the whole request, split it in two,
403
            # and leave the second half for later.
404
            if req_end > end:
405
                pending_reqs.append((req_version_id, end, req_end))
406
                req_end = end
0.9.9 by Aaron Bentley
Much progress on non-naive text reconstruction
407
            if kind == 'new':
408
                lines.extend(data[req_start - start: (req_end - start)])
409
            else:
0.9.10 by Aaron Bentley
Text reconstruction seems to work
410
                # If the hunk is a ParentText, rewrite it as a range request
411
                # for the parent, and make it the next pending request.
0.9.9 by Aaron Bentley
Much progress on non-naive text reconstruction
412
                parent, parent_start, parent_end = data
0.9.10 by Aaron Bentley
Text reconstruction seems to work
413
                new_version_id = self.parents[req_version_id][parent]
414
                new_start = parent_start + req_start - start
415
                new_end = parent_end + req_end - end
416
                pending_reqs.append((new_version_id, new_start, new_end))
0.9.11 by Aaron Bentley
Implement reconstruct_version, handle all hunks through that
417
418
    def reconstruct_version(self, lines, version_id):
419
        length = self.diffs[version_id].num_lines()
420
        return self._reconstruct(lines, version_id, 0, length)
0.9.25 by Aaron Bentley
More messy hacking
421
422
def gzip_string(lines):
423
    sio = StringIO()
424
    data_file = GzipFile(None, mode='wb', fileobj=sio)
425
    data_file.writelines(lines)
426
    data_file.close()
427
    return sio.getvalue()