/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
1
#!/usr/bin/env python
2
"""\
3
Read in a changeset output, and process it into a Changeset object.
4
"""
5
6
import bzrlib, bzrlib.changeset
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
7
import pprint
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
8
import common
9
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
10
class BadChangeset(Exception): pass
11
class MalformedHeader(BadChangeset): pass
12
class MalformedPatches(BadChangeset): pass
13
class MalformedFooter(BadChangeset): pass
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
14
0.5.11 by John Arbash Meinel
Working on properly representing renames.
15
def _unescape(name):
16
    """Now we want to find the filename effected.
17
    Unfortunately the filename is written out as
18
    repr(filename), which means that it surrounds
19
    the name with quotes which may be single or double
20
    (single is preferred unless there is a single quote in
21
    the filename). And some characters will be escaped.
22
23
    TODO:   There has to be some pythonic way of undo-ing the
24
            representation of a string rather than using eval.
25
    """
26
    delimiter = name[0]
27
    if name[-1] != delimiter:
28
        raise BadChangeset('Could not properly parse the'
29
                ' filename: %r' % name)
30
    # We need to handle escaped hexadecimals too.
31
    return name[1:-1].replace('\"', '"').replace("\'", "'")
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
32
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
33
class RevisionInfo(object):
34
    """Gets filled out for each revision object that is read.
35
    """
36
    def __init__(self, rev_id):
37
        self.rev_id = rev_id
38
        self.sha1 = None
39
        self.committer = None
0.5.39 by John Arbash Meinel
(broken) Working on changing the processing to use a ChangesetTree.
40
        self.date = None
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
41
        self.timestamp = None
42
        self.timezone = None
43
        self.inventory_id = None
44
        self.inventory_sha1 = None
45
46
        self.parents = None
47
        self.message = None
48
49
    def __str__(self):
50
        return pprint.pformat(self.__dict__)
51
0.5.37 by John Arbash Meinel
Made read_changeset able to spit out 'Revision' entities.
52
    def as_revision(self):
53
        from bzrlib.revision import Revision, RevisionReference
54
        rev = Revision(revision_id=self.rev_id,
55
            committer=self.committer,
56
            timestamp=float(self.timestamp),
57
            timezone=int(self.timezone),
58
            inventory_id=self.inventory_id,
59
            inventory_sha1=self.inventory_sha1,
60
            message='\n'.join(self.message))
61
62
        for parent in self.parents:
63
            rev_id, sha1 = parent.split('\t')
64
            rev.parents.append(RevisionReference(rev_id, sha1))
65
66
        return rev
67
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
68
class ChangesetInfo(object):
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
69
    """This is the intermediate class that gets filled out as
70
    the file is read.
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
71
    """
72
    def __init__(self):
73
        self.committer = None
74
        self.date = None
0.5.17 by John Arbash Meinel
adding apply-changset, plus more meta information.
75
        self.message = None
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
76
        self.base = None
77
        self.base_sha1 = None
78
0.5.39 by John Arbash Meinel
(broken) Working on changing the processing to use a ChangesetTree.
79
        # A list of RevisionInfo objects
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
80
        self.revisions = []
0.5.39 by John Arbash Meinel
(broken) Working on changing the processing to use a ChangesetTree.
81
        # Tuples of (new_file_id, new_file_path)
82
        self.new_file_ids = []
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
83
0.5.39 by John Arbash Meinel
(broken) Working on changing the processing to use a ChangesetTree.
84
        # This is a mapping from file_id to text_id
85
        self.text_ids = {}
0.5.17 by John Arbash Meinel
adding apply-changset, plus more meta information.
86
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
87
        self.tree_root_id = None
88
        self.file_ids = None
0.5.15 by John Arbash Meinel
Created an apply-changeset function, and modified output for better parsing.
89
        self.old_file_ids = None
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
90
91
        self.actions = [] #this is the list of things that happened
0.5.15 by John Arbash Meinel
Created an apply-changeset function, and modified output for better parsing.
92
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
93
    def __str__(self):
94
        return pprint.pformat(self.__dict__)
95
0.5.39 by John Arbash Meinel
(broken) Working on changing the processing to use a ChangesetTree.
96
    def complete_info(self):
97
        """This makes sure that all information is properly
98
        split up, based on the assumptions that can be made
99
        when information is missing.
100
        """
101
        if self.base is None:
102
            # When we don't have a base, then the real base
103
            # is the first parent of the last revision listed
104
            rev = self.revisions[-1]
105
            self.base = rev.parents[0].revision_id
106
            self.base_sha1 = rev.parents[0].revision_sha1
107
108
        for rev in self.revisions:
0.5.40 by John Arbash Meinel
Added some highres formatting of datestamps.
109
            pass
0.5.39 by John Arbash Meinel
(broken) Working on changing the processing to use a ChangesetTree.
110
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
111
    def create_maps(self):
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
112
        """Go through the individual id sections, and generate the 
113
        id2path and path2id maps.
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
114
        """
0.5.8 by John Arbash Meinel
Added some extra work into changeset, created some dummy files for testing.
115
        # Rather than use an empty path, the changeset code seems 
116
        # to like to use "./." for the tree root.
117
        self.id2path[self.tree_root_id] = './.'
118
        self.path2id['./.'] = self.tree_root_id
119
        self.id2parent[self.tree_root_id] = bzrlib.changeset.NULL_ID
0.5.15 by John Arbash Meinel
Created an apply-changeset function, and modified output for better parsing.
120
        self.old_id2path = self.id2path.copy()
121
        self.old_path2id = self.path2id.copy()
122
        self.old_id2parent = self.id2parent.copy()
123
124
        if self.file_ids:
125
            for info in self.file_ids:
126
                path, f_id, parent_id = info.split('\t')
127
                self.id2path[f_id] = path
128
                self.path2id[path] = f_id
129
                self.id2parent[f_id] = parent_id
130
        if self.old_file_ids:
131
            for info in self.old_file_ids:
132
                path, f_id, parent_id = info.split('\t')
133
                self.old_id2path[f_id] = path
134
                self.old_path2id[path] = f_id
135
                self.old_id2parent[f_id] = parent_id
136
0.5.17 by John Arbash Meinel
adding apply-changset, plus more meta information.
137
    def get_changeset(self):
0.5.15 by John Arbash Meinel
Created an apply-changeset function, and modified output for better parsing.
138
        """Create a changeset from the data contained within."""
139
        from bzrlib.changeset import Changeset, ChangesetEntry, \
140
            PatchApply, ReplaceContents
141
        cset = Changeset()
142
        
0.5.18 by John Arbash Meinel
Some minor fixups
143
        entry = ChangesetEntry(self.tree_root_id, 
144
                bzrlib.changeset.NULL_ID, './.')
145
        cset.add_entry(entry)
0.5.15 by John Arbash Meinel
Created an apply-changeset function, and modified output for better parsing.
146
        for info, lines in self.actions:
147
            parts = info.split(' ')
148
            action = parts[0]
149
            kind = parts[1]
150
            extra = ' '.join(parts[2:])
151
            if action == 'renamed':
152
                old_path, new_path = extra.split(' => ')
153
                old_path = _unescape(old_path)
154
                new_path = _unescape(new_path)
155
156
                new_id = self.path2id[new_path]
157
                old_id = self.old_path2id[old_path]
158
                assert old_id == new_id
159
160
                new_parent = self.id2parent[new_id]
161
                old_parent = self.old_id2parent[old_id]
162
163
                entry = ChangesetEntry(old_id, old_parent, old_path)
164
                entry.new_path = new_path
165
                entry.new_parent = new_parent
166
                if lines:
167
                    entry.contents_change = PatchApply(''.join(lines))
168
            elif action == 'removed':
169
                old_path = _unescape(extra)
170
                old_id = self.old_path2id[old_path]
171
                old_parent = self.old_id2parent[old_id]
172
                entry = ChangesetEntry(old_id, old_parent, old_path)
173
                entry.new_path = None
174
                entry.new_parent = None
175
                if lines:
176
                    # Technically a removed should be a ReplaceContents()
177
                    # Where you need to have the old contents
178
                    # But at most we have a remove style patch.
179
                    #entry.contents_change = ReplaceContents()
180
                    pass
181
            elif action == 'added':
182
                new_path = _unescape(extra)
183
                new_id = self.path2id[new_path]
184
                new_parent = self.id2parent[new_id]
185
                entry = ChangesetEntry(new_id, new_parent, new_path)
186
                entry.path = None
187
                entry.parent = None
188
                if lines:
189
                    # Technically an added should be a ReplaceContents()
190
                    # Where you need to have the old contents
191
                    # But at most we have an add style patch.
192
                    #entry.contents_change = ReplaceContents()
193
                    entry.contents_change = PatchApply(''.join(lines))
194
            elif action == 'modified':
195
                new_path = _unescape(extra)
196
                new_id = self.path2id[new_path]
197
                new_parent = self.id2parent[new_id]
198
                entry = ChangesetEntry(new_id, new_parent, new_path)
199
                entry.path = None
200
                entry.parent = None
201
                if lines:
202
                    # Technically an added should be a ReplaceContents()
203
                    # Where you need to have the old contents
204
                    # But at most we have an add style patch.
205
                    #entry.contents_change = ReplaceContents()
206
                    entry.contents_change = PatchApply(''.join(lines))
207
            else:
208
                raise BadChangeset('Unrecognized action: %r' % action)
209
            cset.add_entry(entry)
210
        return cset
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
211
212
class ChangesetReader(object):
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
213
    """This class reads in a changeset from a file, and returns
214
    a Changeset object, which can then be applied against a tree.
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
215
    """
216
    def __init__(self, from_file):
217
        """Read in the changeset from the file.
218
219
        :param from_file: A file-like object (must have iterator support).
220
        """
221
        object.__init__(self)
222
        self.from_file = from_file
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
223
        self._next_line = None
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
224
        
225
        self.info = ChangesetInfo()
226
        # We put the actual inventory ids in the footer, so that the patch
227
        # is easier to read for humans.
228
        # Unfortunately, that means we need to read everything before we
229
        # can create a proper changeset.
230
        self._read_header()
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
231
        self._read_patches()
232
        self._read_footer()
233
234
    def _next(self):
235
        """yield the next line, but secretly
236
        keep 1 extra line for peeking.
237
        """
238
        for line in self.from_file:
239
            last = self._next_line
240
            self._next_line = line
241
            if last is not None:
242
                yield last
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
243
0.5.17 by John Arbash Meinel
adding apply-changset, plus more meta information.
244
    def get_info(self):
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
245
        """Create the actual changeset object.
246
        """
0.5.39 by John Arbash Meinel
(broken) Working on changing the processing to use a ChangesetTree.
247
        self.info.complete_info()
0.5.17 by John Arbash Meinel
adding apply-changset, plus more meta information.
248
        return self.info
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
249
250
    def _read_header(self):
251
        """Read the bzr header"""
252
        header = common.get_header()
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
253
        found = False
254
        for line in self._next():
255
            if found:
256
                if (line[:2] != '# ' or line[-1:] != '\n'
257
                        or line[2:-1] != header[0]):
258
                    raise MalformedHeader('Found a header, but it'
259
                        ' was improperly formatted')
260
                header.pop(0) # We read this line.
261
                if not header:
262
                    break # We found everything.
263
            elif (line[:1] == '#' and line[-1:] == '\n'):
264
                line = line[1:-1].strip()
265
                if line[:len(common.header_str)] == common.header_str:
266
                    if line == header[0]:
267
                        found = True
268
                    else:
269
                        raise MalformedHeader('Found what looks like'
270
                                ' a header, but did not match')
271
                    header.pop(0)
272
        else:
273
            raise MalformedHeader('Did not find an opening header')
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
274
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
275
        for line in self._next():
276
            # The bzr header is terminated with a blank line
277
            # which does not start with '#'
278
            if line == '\n':
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
279
                break
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
280
            self._handle_next(line)
281
282
    def _read_next_entry(self, line, indent=1):
283
        """Read in a key-value pair
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
284
        """
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
285
        if line[:1] != '#':
286
            raise MalformedHeader('Bzr header did not start with #')
287
        line = line[1:-1] # Remove the '#' and '\n'
288
        if line[:indent] == ' '*indent:
289
            line = line[indent:]
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
290
        if not line:
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
291
            return None, None# Ignore blank lines
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
292
293
        loc = line.find(': ')
294
        if loc != -1:
295
            key = line[:loc]
296
            value = line[loc+2:]
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
297
            if not value:
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
298
                value = self._read_many(indent=indent+3)
299
        elif line[-1:] == ':':
300
            key = line[:-1]
301
            value = self._read_many(indent=indent+3)
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
302
        else:
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
303
            raise MalformedHeader('While looking for key: value pairs,'
304
                    ' did not find the colon %r' % (line))
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
305
306
        key = key.replace(' ', '_')
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
307
        return key, value
308
309
    def _handle_next(self, line):
310
        key, value = self._read_next_entry(line, indent=1)
311
        if key is None:
312
            return
313
314
        if key == 'revision':
315
            self._read_revision(value)
316
        elif hasattr(self.info, key):
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
317
            if getattr(self.info, key) is None:
318
                setattr(self.info, key, value)
319
            else:
320
                raise MalformedHeader('Duplicated Key: %s' % key)
321
        else:
322
            # What do we do with a key we don't recognize
323
            raise MalformedHeader('Unknown Key: %s' % key)
324
        
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
325
    def _read_many(self, indent):
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
326
        """If a line ends with no entry, that means that it should be
327
        followed with multiple lines of values.
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
328
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
329
        This detects the end of the list, because it will be a line that
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
330
        does not start properly indented.
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
331
        """
332
        values = []
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
333
        start = '#' + (' '*indent)
334
335
        if self._next_line[:len(start)] != start:
336
            return values
337
338
        for line in self._next():
339
            values.append(line[len(start):-1])
340
            if self._next_line[:len(start)] != start:
341
                break
342
        return values
343
344
    def _read_one_patch(self):
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
345
        """Read in one patch, return the complete patch, along with
346
        the next line.
347
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
348
        :return: action, lines, do_continue
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
349
        """
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
350
        # Peek and see if there are no patches
351
        if self._next_line[:1] == '#':
352
            return None, [], False
353
354
        line = self._next().next()
355
        if line[:3] != '***':
356
            raise MalformedPatches('The first line of all patches'
357
                ' should be a bzr meta line "***"')
358
        action = line[4:-1]
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
359
360
        lines = []
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
361
        for line in self._next():
362
            lines.append(line)
363
364
            if self._next_line[:3] == '***':
365
                return action, lines, True
366
            elif self._next_line[:1] == '#':
367
                return action, lines, False
368
        return action, lines, False
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
369
            
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
370
    def _read_patches(self):
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
371
        do_continue = True
372
        while do_continue:
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
373
            action, lines, do_continue = self._read_one_patch()
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
374
            if action is not None:
375
                self.info.actions.append((action, lines))
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
376
377
    def _read_revision(self, rev_id):
378
        """Revision entries have extra information associated.
379
        """
380
        rev_info = RevisionInfo(rev_id)
381
        start = '#    '
382
        for line in self._next():
383
            key,value = self._read_next_entry(line, indent=4)
384
            #if key is None:
385
            #    continue
386
            if hasattr(rev_info, key):
387
                if getattr(rev_info, key) is None:
388
                    setattr(rev_info, key, value)
389
                else:
390
                    raise MalformedHeader('Duplicated Key: %s' % key)
391
            else:
392
                # What do we do with a key we don't recognize
393
                raise MalformedHeader('Unknown Key: %s' % key)
394
395
            if self._next_line[:len(start)] != start:
396
                break
397
398
        self.info.revisions.append(rev_info)
399
400
    def _read_footer(self):
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
401
        """Read the rest of the meta information.
402
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
403
        :param first_line:  The previous step iterates past what it
404
                            can handle. That extra line is given here.
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
405
        """
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
406
        line = self._next().next()
407
        if line != '# BEGIN BZR FOOTER\n':
408
            raise MalformedFooter('Footer did not begin with BEGIN BZR FOOTER')
409
410
        for line in self._next():
411
            if line == '# END BZR FOOTER\n':
0.5.9 by John Arbash Meinel
Now adding the patch information to the ChangesetInfo
412
                return
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
413
            self._handle_next(line)
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
414
415
def read_changeset(from_file):
416
    """Read in a changeset from a filelike object (must have "readline" support), and
417
    parse it into a Changeset object.
418
    """
419
    cr = ChangesetReader(from_file)
0.5.17 by John Arbash Meinel
adding apply-changset, plus more meta information.
420
    info = cr.get_info()
421
    return info
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
422
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
423
424
class ChangesetTree:
425
    def __init__(self, base_tree):
426
        self.base_tree = base_tree
427
        self._renamed = {}
428
        self._renamed_r = {}
429
        self._new_id = {}
430
        self._new_id_r = {}
431
        self.patches = {}
432
433
    def note_rename(self, old_path, new_path):
434
        assert not self._renamed.has_key(old_path)
435
        assert not self._renamed_r.has_key(new_path)
436
        self._renamed[new_path] = old_path
437
        self._renamed_r[old_path] = new_path
438
0.5.43 by aaron.bentley at utoronto
Handled moves and adds properly
439
    def note_id(self, new_id, new_path):
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
440
        self._new_id[new_path] = new_id
441
        self._new_id_r[new_id] = new_path
442
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
443
    def note_patch(self, new_path, patch):
444
        self.patches[new_path] = patch
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
445
446
    def old_path(self, new_path):
447
        import os.path
448
        old_path = self._renamed.get(new_path)
449
        if old_path is not None:
450
            return old_path
451
        dirname,basename = os.path.split(new_path)
0.5.42 by aaron.bentley at utoronto
Improved rename handling
452
        if dirname is not '':
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
453
            old_dir = self.old_path(dirname)
454
            if old_dir is None:
0.5.42 by aaron.bentley at utoronto
Improved rename handling
455
                old_path = None
456
            else:
457
                old_path = os.path.join(old_dir, basename)
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
458
        else:
0.5.42 by aaron.bentley at utoronto
Improved rename handling
459
            old_path = new_path
460
        #If the new path wasn't in renamed, the old one shouldn't be in
461
        #renamed_r
462
        if self._renamed_r.has_key(old_path):
463
            return None
464
        return old_path 
465
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
466
467
    def new_path(self, old_path):
468
        import os.path
469
        new_path = self._renamed_r.get(old_path)
470
        if new_path is not None:
471
            return new_path
472
        if self._renamed.has_key(new_path):
473
            return None
474
        dirname,basename = os.path.split(old_path)
475
        if dirname is not '':
476
            new_dir = self.new_path(dirname)
477
            if new_dir is None:
0.5.42 by aaron.bentley at utoronto
Improved rename handling
478
                new_path = None
479
            else:
480
                new_path = os.path.join(new_dir, basename)
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
481
        else:
0.5.42 by aaron.bentley at utoronto
Improved rename handling
482
            new_path = old_path
483
        #If the old path wasn't in renamed, the new one shouldn't be in
484
        #renamed_r
485
        if self._renamed.has_key(new_path):
486
            return None
487
        return new_path 
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
488
489
    def path2id(self, path):
490
        file_id = self._new_id.get(path)
491
        if file_id is not None:
492
            return file_id
0.5.43 by aaron.bentley at utoronto
Handled moves and adds properly
493
        old_path = self.old_path(path)
494
        if old_path is None:
495
            return None
496
        return self.base_tree.path2id(old_path)
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
497
498
    def id2path(self, file_id):
499
        path = self._new_id_r.get(file_id)
500
        if path is not None:
501
            return path
0.5.43 by aaron.bentley at utoronto
Handled moves and adds properly
502
        old_path = self.base_tree.id2path(file_id)
503
        if old_path is None:
504
            return None
505
        return self.new_path(old_path)
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
506
507
    def get_file(self, file_id):
508
        if self.base_tree.has_id(file_id):
509
            patch_original = self.base_tree.get_file(file_id)
510
        else:
511
            patch_original = None
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
512
        file_patch = self.patches.get(self.id2path(file_id))
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
513
        if file_patch is None:
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
514
            return patch_original
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
515
        return patched_file(file_patch, patch_original)
516
517
def patched_file(file_patch, original):
518
    from bzrlib.patch import patch
519
    from tempfile import mkdtemp
520
    from shutil import rmtree
521
    from StringIO import StringIO
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
522
    from bzrlib.osutils import pumpfile
523
    import os.path
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
524
    temp_dir = mkdtemp()
525
    try:
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
526
        original_path = os.path.join(temp_dir, "originalfile")
527
        temp_original = file(original_path, "wb")
528
        if original is not None:
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
529
            pumpfile(original, temp_original)
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
530
        temp_original.close()
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
531
        patched_path = os.path.join(temp_dir, "patchfile")
532
        patch(file_patch, original_path, patched_path)
533
        result = StringIO()
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
534
        temp_patched = file(patched_path, "rb")
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
535
        pumpfile(temp_patched, result)
536
        temp_patched.close()
537
        result.seek(0,0)
538
539
    finally:
540
        rmtree(temp_dir)
541
542
    return result
543
544
def test():
545
    import unittest
546
    from StringIO import StringIO
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
547
    from bzrlib.diff import internal_diff
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
548
    class MockTree(object):
549
        def __init__(self):
550
            object.__init__(self)
551
            self.paths = {}
552
            self.ids = {}
553
            self.contents = {}
554
555
        def add_dir(self, file_id, path):
556
            self.paths[file_id] = path
557
            self.ids[path] = file_id
558
        
559
        def add_file(self, file_id, path, contents):
560
            self.add_dir(file_id, path)
561
            self.contents[file_id] = contents
562
563
        def path2id(self, path):
564
            return self.ids.get(path)
565
566
        def id2path(self, file_id):
567
            return self.paths.get(file_id)
568
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
569
        def has_id(self, file_id):
570
            return self.id2path(file_id) is not None
571
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
572
        def get_file(file_id):
573
            result = StringIO()
574
            result.write(self.contents[file_id])
575
            result.seek(0,0)
576
            return result
577
578
    class CTreeTester(unittest.TestCase):
0.5.43 by aaron.bentley at utoronto
Handled moves and adds properly
579
580
        def make_tree_1(self):
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
581
            mtree = MockTree()
582
            mtree.add_dir("a", "grandparent")
583
            mtree.add_dir("b", "grandparent/parent")
584
            mtree.add_file("c", "grandparent/parent/file", "Hello")
0.5.43 by aaron.bentley at utoronto
Handled moves and adds properly
585
            mtree.add_dir("d", "grandparent/alt_parent")
586
            return ChangesetTree(mtree), mtree
587
            
588
        def testRenames(self):
589
            """Ensure that file renames have the proper effect on children"""
590
            ctree = self.make_tree_1()[0]
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
591
            assert ctree.old_path("grandparent") == "grandparent"
592
            assert ctree.old_path("grandparent/parent") == "grandparent/parent"
593
            assert ctree.old_path("grandparent/parent/file") ==\
594
                "grandparent/parent/file"
595
596
            assert ctree.id2path("a") == "grandparent"
597
            assert ctree.id2path("b") == "grandparent/parent"
598
            assert ctree.id2path("c") == "grandparent/parent/file"
599
600
            assert ctree.path2id("grandparent") == "a"
601
            assert ctree.path2id("grandparent/parent") == "b"
602
            assert ctree.path2id("grandparent/parent/file") == "c"
603
604
            assert ctree.path2id("grandparent2") is None
605
            assert ctree.path2id("grandparent2/parent") is None
606
            assert ctree.path2id("grandparent2/parent/file") is None
607
608
            ctree.note_rename("grandparent", "grandparent2")
609
            assert ctree.old_path("grandparent") is None 
610
            assert ctree.old_path("grandparent/parent") is None 
611
            assert ctree.old_path("grandparent/parent/file") is None 
612
613
            assert ctree.id2path("a") == "grandparent2"
614
            assert ctree.id2path("b") == "grandparent2/parent"
615
            assert ctree.id2path("c") == "grandparent2/parent/file"
616
617
            assert ctree.path2id("grandparent2") == "a"
618
            assert ctree.path2id("grandparent2/parent") == "b"
619
            assert ctree.path2id("grandparent2/parent/file") == "c"
620
621
            assert ctree.path2id("grandparent") is None
622
            assert ctree.path2id("grandparent/parent") is None
623
            assert ctree.path2id("grandparent/parent/file") is None
624
625
            ctree.note_rename("grandparent/parent", "grandparent2/parent2")
626
            assert ctree.id2path("a") == "grandparent2"
627
            assert ctree.id2path("b") == "grandparent2/parent2"
628
            assert ctree.id2path("c") == "grandparent2/parent2/file"
629
630
            assert ctree.path2id("grandparent2") == "a"
631
            assert ctree.path2id("grandparent2/parent2") == "b"
632
            assert ctree.path2id("grandparent2/parent2/file") == "c"
633
634
            assert ctree.path2id("grandparent2/parent") is None
635
            assert ctree.path2id("grandparent2/parent/file") is None
0.5.43 by aaron.bentley at utoronto
Handled moves and adds properly
636
637
            ctree.note_rename("grandparent/parent/file", 
638
                              "grandparent2/parent2/file2")
639
            assert ctree.id2path("a") == "grandparent2"
640
            assert ctree.id2path("b") == "grandparent2/parent2"
641
            assert ctree.id2path("c") == "grandparent2/parent2/file2"
642
643
            assert ctree.path2id("grandparent2") == "a"
644
            assert ctree.path2id("grandparent2/parent2") == "b"
645
            assert ctree.path2id("grandparent2/parent2/file2") == "c"
646
647
            assert ctree.path2id("grandparent2/parent2/file") is None
648
649
        def testMoves(self):
650
            """Ensure that file moves have the proper effect on children"""
651
            ctree = self.make_tree_1()[0]
652
            ctree.note_rename("grandparent/parent/file", 
653
                              "grandparent/alt_parent/file")
654
            assert ctree.id2path("c") == "grandparent/alt_parent/file"
655
            assert ctree.path2id("grandparent/alt_parent/file") == "c"
656
            assert ctree.path2id("grandparent/parent/file") == None
657
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
658
        def unified_diff(self, old, new):
659
            out = StringIO()
660
            internal_diff("old", old, "new", new, out)
661
            out.seek(0,0)
662
            return out.read()
663
0.5.43 by aaron.bentley at utoronto
Handled moves and adds properly
664
        def testAdds(self):
665
            """Ensure that inventory adds work"""
666
            ctree = self.make_tree_1()[0]
667
            ctree.note_rename("grandparent/parent/file", 
668
                              "grandparent/alt_parent/file")
669
            assert ctree.id2path("e") is None
670
            assert ctree.path2id("grandparent/parent/file") is None
671
            ctree.note_id("e", "grandparent/parent/file")
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
672
            add_patch = self.unified_diff([], ["Extra cheese"])
673
            ctree.note_patch("grandparent/parent/file", add_patch)
674
0.5.43 by aaron.bentley at utoronto
Handled moves and adds properly
675
            assert ctree.id2path("e") == "grandparent/parent/file"
676
            assert ctree.path2id("grandparent/parent/file") == "e"
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
677
            assert ctree.get_file("e").read() == "Extra cheese"
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
678
        
679
    patchesTestSuite = unittest.makeSuite(CTreeTester,'test')
680
    runner = unittest.TextTestRunner()
681
    runner.run(patchesTestSuite)
682
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
683
if __name__ == '__main__':
684
    import sys
685
    print read_changeset(sys.stdin)