~bzr-pqm/bzr/bzr.dev

493 by Martin Pool
- Merge aaron's merge command
1
# Copyright (C) 2004 Aaron Bentley <aaron.bentley@utoronto.ca>
2
#
3
#    This program is free software; you can redistribute it and/or modify
4
#    it under the terms of the GNU General Public License as published by
5
#    the Free Software Foundation; either version 2 of the License, or
6
#    (at your option) any later version.
7
#
8
#    This program is distributed in the hope that it will be useful,
9
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
10
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
#    GNU General Public License for more details.
12
#
13
#    You should have received a copy of the GNU General Public License
14
#    along with this program; if not, write to the Free Software
15
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
import os.path
17
import errno
18
import patch
19
import stat
20
"""
21
Represent and apply a changeset
22
"""
23
__docformat__ = "restructuredtext"
24
25
NULL_ID = "!NULL"
26
850 by Martin Pool
- Merge merge updates from aaron
27
class OldFailedTreeOp(Exception):
28
    def __init__(self):
29
        Exception.__init__(self, "bzr-tree-change contains files from a"
30
                           " previous failed merge operation.")
493 by Martin Pool
- Merge aaron's merge command
31
def invert_dict(dict):
32
    newdict = {}
33
    for (key,value) in dict.iteritems():
34
        newdict[value] = key
35
    return newdict
36
37
558 by Martin Pool
- All top-level classes inherit from object
38
class PatchApply(object):
493 by Martin Pool
- Merge aaron's merge command
39
    """Patch application as a kind of content change"""
40
    def __init__(self, contents):
41
        """Constructor.
42
43
        :param contents: The text of the patch to apply
44
        :type contents: str"""
45
        self.contents = contents
46
47
    def __eq__(self, other):
48
        if not isinstance(other, PatchApply):
49
            return False
50
        elif self.contents != other.contents:
51
            return False
52
        else:
53
            return True
54
55
    def __ne__(self, other):
56
        return not (self == other)
57
58
    def apply(self, filename, conflict_handler, reverse=False):
59
        """Applies the patch to the specified file.
60
61
        :param filename: the file to apply the patch to
62
        :type filename: str
63
        :param reverse: If true, apply the patch in reverse
64
        :type reverse: bool
65
        """
66
        input_name = filename+".orig"
67
        try:
68
            os.rename(filename, input_name)
69
        except OSError, e:
70
            if e.errno != errno.ENOENT:
71
                raise
72
            if conflict_handler.patch_target_missing(filename, self.contents)\
73
                == "skip":
74
                return
75
            os.rename(filename, input_name)
76
            
77
78
        status = patch.patch(self.contents, input_name, filename, 
79
                                    reverse)
80
        os.chmod(filename, os.stat(input_name).st_mode)
81
        if status == 0:
82
            os.unlink(input_name)
83
        elif status == 1:
84
            conflict_handler.failed_hunks(filename)
85
86
        
558 by Martin Pool
- All top-level classes inherit from object
87
class ChangeUnixPermissions(object):
493 by Martin Pool
- Merge aaron's merge command
88
    """This is two-way change, suitable for file modification, creation,
89
    deletion"""
90
    def __init__(self, old_mode, new_mode):
91
        self.old_mode = old_mode
92
        self.new_mode = new_mode
93
94
    def apply(self, filename, conflict_handler, reverse=False):
95
        if not reverse:
96
            from_mode = self.old_mode
97
            to_mode = self.new_mode
98
        else:
99
            from_mode = self.new_mode
100
            to_mode = self.old_mode
101
        try:
102
            current_mode = os.stat(filename).st_mode &0777
103
        except OSError, e:
104
            if e.errno == errno.ENOENT:
105
                if conflict_handler.missing_for_chmod(filename) == "skip":
106
                    return
107
                else:
108
                    current_mode = from_mode
109
110
        if from_mode is not None and current_mode != from_mode:
111
            if conflict_handler.wrong_old_perms(filename, from_mode, 
112
                                                current_mode) != "continue":
113
                return
114
115
        if to_mode is not None:
116
            try:
117
                os.chmod(filename, to_mode)
118
            except IOError, e:
119
                if e.errno == errno.ENOENT:
120
                    conflict_handler.missing_for_chmod(filename)
121
122
    def __eq__(self, other):
123
        if not isinstance(other, ChangeUnixPermissions):
124
            return False
125
        elif self.old_mode != other.old_mode:
126
            return False
127
        elif self.new_mode != other.new_mode:
128
            return False
129
        else:
130
            return True
131
132
    def __ne__(self, other):
133
        return not (self == other)
134
135
def dir_create(filename, conflict_handler, reverse):
136
    """Creates the directory, or deletes it if reverse is true.  Intended to be
137
    used with ReplaceContents.
138
139
    :param filename: The name of the directory to create
140
    :type filename: str
141
    :param reverse: If true, delete the directory, instead
142
    :type reverse: bool
143
    """
144
    if not reverse:
145
        try:
146
            os.mkdir(filename)
147
        except OSError, e:
148
            if e.errno != errno.EEXIST:
149
                raise
150
            if conflict_handler.dir_exists(filename) == "continue":
151
                os.mkdir(filename)
152
        except IOError, e:
153
            if e.errno == errno.ENOENT:
154
                if conflict_handler.missing_parent(filename)=="continue":
155
                    file(filename, "wb").write(self.contents)
156
    else:
157
        try:
158
            os.rmdir(filename)
159
        except OSError, e:
160
            if e.errno != 39:
161
                raise
162
            if conflict_handler.rmdir_non_empty(filename) == "skip":
163
                return
164
            os.rmdir(filename)
165
166
                
167
            
168
558 by Martin Pool
- All top-level classes inherit from object
169
class SymlinkCreate(object):
493 by Martin Pool
- Merge aaron's merge command
170
    """Creates or deletes a symlink (for use with ReplaceContents)"""
171
    def __init__(self, contents):
172
        """Constructor.
173
174
        :param contents: The filename of the target the symlink should point to
175
        :type contents: str
176
        """
177
        self.target = contents
178
179
    def __call__(self, filename, conflict_handler, reverse):
180
        """Creates or destroys the symlink.
181
182
        :param filename: The name of the symlink to create
183
        :type filename: str
184
        """
185
        if reverse:
186
            assert(os.readlink(filename) == self.target)
187
            os.unlink(filename)
188
        else:
189
            try:
190
                os.symlink(self.target, filename)
191
            except OSError, e:
192
                if e.errno != errno.EEXIST:
193
                    raise
194
                if conflict_handler.link_name_exists(filename) == "continue":
195
                    os.symlink(self.target, filename)
196
197
    def __eq__(self, other):
198
        if not isinstance(other, SymlinkCreate):
199
            return False
200
        elif self.target != other.target:
201
            return False
202
        else:
203
            return True
204
205
    def __ne__(self, other):
206
        return not (self == other)
207
558 by Martin Pool
- All top-level classes inherit from object
208
class FileCreate(object):
493 by Martin Pool
- Merge aaron's merge command
209
    """Create or delete a file (for use with ReplaceContents)"""
210
    def __init__(self, contents):
211
        """Constructor
212
213
        :param contents: The contents of the file to write
214
        :type contents: str
215
        """
216
        self.contents = contents
217
218
    def __repr__(self):
219
        return "FileCreate(%i b)" % len(self.contents)
220
221
    def __eq__(self, other):
222
        if not isinstance(other, FileCreate):
223
            return False
224
        elif self.contents != other.contents:
225
            return False
226
        else:
227
            return True
228
229
    def __ne__(self, other):
230
        return not (self == other)
231
232
    def __call__(self, filename, conflict_handler, reverse):
233
        """Create or delete a file
234
235
        :param filename: The name of the file to create
236
        :type filename: str
237
        :param reverse: Delete the file instead of creating it
238
        :type reverse: bool
239
        """
240
        if not reverse:
241
            try:
242
                file(filename, "wb").write(self.contents)
243
            except IOError, e:
244
                if e.errno == errno.ENOENT:
245
                    if conflict_handler.missing_parent(filename)=="continue":
246
                        file(filename, "wb").write(self.contents)
247
                else:
248
                    raise
249
250
        else:
251
            try:
252
                if (file(filename, "rb").read() != self.contents):
253
                    direction = conflict_handler.wrong_old_contents(filename,
254
                                                                    self.contents)
255
                    if  direction != "continue":
256
                        return
257
                os.unlink(filename)
258
            except IOError, e:
259
                if e.errno != errno.ENOENT:
260
                    raise
261
                if conflict_handler.missing_for_rm(filename, undo) == "skip":
262
                    return
263
264
                    
265
266
def reversed(sequence):
267
    max = len(sequence) - 1
268
    for i in range(len(sequence)):
269
        yield sequence[max - i]
270
558 by Martin Pool
- All top-level classes inherit from object
271
class ReplaceContents(object):
493 by Martin Pool
- Merge aaron's merge command
272
    """A contents-replacement framework.  It allows a file/directory/symlink to
273
    be created, deleted, or replaced with another file/directory/symlink.
274
    Arguments must be callable with (filename, reverse).
275
    """
276
    def __init__(self, old_contents, new_contents):
277
        """Constructor.
278
279
        :param old_contents: The change to reverse apply (e.g. a deletion), \
280
        when going forwards.
281
        :type old_contents: `dir_create`, `SymlinkCreate`, `FileCreate`, \
282
        NoneType, etc.
283
        :param new_contents: The second change to apply (e.g. a creation), \
284
        when going forwards.
285
        :type new_contents: `dir_create`, `SymlinkCreate`, `FileCreate`, \
286
        NoneType, etc.
287
        """
288
        self.old_contents=old_contents
289
        self.new_contents=new_contents
290
291
    def __repr__(self):
292
        return "ReplaceContents(%r -> %r)" % (self.old_contents,
293
                                              self.new_contents)
294
295
    def __eq__(self, other):
296
        if not isinstance(other, ReplaceContents):
297
            return False
298
        elif self.old_contents != other.old_contents:
299
            return False
300
        elif self.new_contents != other.new_contents:
301
            return False
302
        else:
303
            return True
304
    def __ne__(self, other):
305
        return not (self == other)
306
307
    def apply(self, filename, conflict_handler, reverse=False):
308
        """Applies the FileReplacement to the specified filename
309
310
        :param filename: The name of the file to apply changes to
311
        :type filename: str
312
        :param reverse: If true, apply the change in reverse
313
        :type reverse: bool
314
        """
315
        if not reverse:
316
            undo = self.old_contents
317
            perform = self.new_contents
318
        else:
319
            undo = self.new_contents
320
            perform = self.old_contents
321
        mode = None
322
        if undo is not None:
323
            try:
324
                mode = os.lstat(filename).st_mode
325
                if stat.S_ISLNK(mode):
326
                    mode = None
327
            except OSError, e:
328
                if e.errno != errno.ENOENT:
329
                    raise
330
                if conflict_handler.missing_for_rm(filename, undo) == "skip":
331
                    return
332
            undo(filename, conflict_handler, reverse=True)
333
        if perform is not None:
334
            perform(filename, conflict_handler, reverse=False)
335
            if mode is not None:
336
                os.chmod(filename, mode)
337
558 by Martin Pool
- All top-level classes inherit from object
338
class ApplySequence(object):
493 by Martin Pool
- Merge aaron's merge command
339
    def __init__(self, changes=None):
340
        self.changes = []
341
        if changes is not None:
342
            self.changes.extend(changes)
343
344
    def __eq__(self, other):
345
        if not isinstance(other, ApplySequence):
346
            return False
347
        elif len(other.changes) != len(self.changes):
348
            return False
349
        else:
350
            for i in range(len(self.changes)):
351
                if self.changes[i] != other.changes[i]:
352
                    return False
353
            return True
354
355
    def __ne__(self, other):
356
        return not (self == other)
357
358
    
359
    def apply(self, filename, conflict_handler, reverse=False):
360
        if not reverse:
361
            iter = self.changes
362
        else:
363
            iter = reversed(self.changes)
364
        for change in iter:
365
            change.apply(filename, conflict_handler, reverse)
366
367
558 by Martin Pool
- All top-level classes inherit from object
368
class Diff3Merge(object):
493 by Martin Pool
- Merge aaron's merge command
369
    def __init__(self, base_file, other_file):
370
        self.base_file = base_file
371
        self.other_file = other_file
372
373
    def __eq__(self, other):
374
        if not isinstance(other, Diff3Merge):
375
            return False
376
        return (self.base_file == other.base_file and 
377
                self.other_file == other.other_file)
378
379
    def __ne__(self, other):
380
        return not (self == other)
381
382
    def apply(self, filename, conflict_handler, reverse=False):
383
        new_file = filename+".new" 
384
        if not reverse:
385
            base = self.base_file
386
            other = self.other_file
387
        else:
388
            base = self.other_file
389
            other = self.base_file
390
        status = patch.diff3(new_file, filename, base, other)
391
        if status == 0:
392
            os.chmod(new_file, os.stat(filename).st_mode)
393
            os.rename(new_file, filename)
394
            return
395
        else:
396
            assert(status == 1)
397
            conflict_handler.merge_conflict(new_file, filename, base, other)
398
399
400
def CreateDir():
401
    """Convenience function to create a directory.
402
403
    :return: A ReplaceContents that will create a directory
404
    :rtype: `ReplaceContents`
405
    """
406
    return ReplaceContents(None, dir_create)
407
408
def DeleteDir():
409
    """Convenience function to delete a directory.
410
411
    :return: A ReplaceContents that will delete a directory
412
    :rtype: `ReplaceContents`
413
    """
414
    return ReplaceContents(dir_create, None)
415
416
def CreateFile(contents):
417
    """Convenience fucntion to create a file.
418
    
419
    :param contents: The contents of the file to create 
420
    :type contents: str
421
    :return: A ReplaceContents that will create a file 
422
    :rtype: `ReplaceContents`
423
    """
424
    return ReplaceContents(None, FileCreate(contents))
425
426
def DeleteFile(contents):
427
    """Convenience fucntion to delete a file.
428
    
429
    :param contents: The contents of the file to delete
430
    :type contents: str
431
    :return: A ReplaceContents that will delete a file 
432
    :rtype: `ReplaceContents`
433
    """
434
    return ReplaceContents(FileCreate(contents), None)
435
436
def ReplaceFileContents(old_contents, new_contents):
437
    """Convenience fucntion to replace the contents of a file.
438
    
439
    :param old_contents: The contents of the file to replace 
440
    :type old_contents: str
441
    :param new_contents: The contents to replace the file with
442
    :type new_contents: str
443
    :return: A ReplaceContents that will replace the contents of a file a file 
444
    :rtype: `ReplaceContents`
445
    """
446
    return ReplaceContents(FileCreate(old_contents), FileCreate(new_contents))
447
448
def CreateSymlink(target):
449
    """Convenience fucntion to create a symlink.
450
    
451
    :param target: The path the link should point to
452
    :type target: str
453
    :return: A ReplaceContents that will delete a file 
454
    :rtype: `ReplaceContents`
455
    """
456
    return ReplaceContents(None, SymlinkCreate(target))
457
458
def DeleteSymlink(target):
459
    """Convenience fucntion to delete a symlink.
460
    
461
    :param target: The path the link should point to
462
    :type target: str
463
    :return: A ReplaceContents that will delete a file 
464
    :rtype: `ReplaceContents`
465
    """
466
    return ReplaceContents(SymlinkCreate(target), None)
467
468
def ChangeTarget(old_target, new_target):
469
    """Convenience fucntion to change the target of a symlink.
470
    
471
    :param old_target: The current link target
472
    :type old_target: str
473
    :param new_target: The new link target to use
474
    :type new_target: str
475
    :return: A ReplaceContents that will delete a file 
476
    :rtype: `ReplaceContents`
477
    """
478
    return ReplaceContents(SymlinkCreate(old_target), SymlinkCreate(new_target))
479
480
481
class InvalidEntry(Exception):
482
    """Raise when a ChangesetEntry is invalid in some way"""
483
    def __init__(self, entry, problem):
484
        """Constructor.
485
486
        :param entry: The invalid ChangesetEntry
487
        :type entry: `ChangesetEntry`
488
        :param problem: The problem with the entry
489
        :type problem: str
490
        """
491
        msg = "Changeset entry for %s (%s) is invalid.\n%s" % (entry.id, 
492
                                                               entry.path, 
493
                                                               problem)
494
        Exception.__init__(self, msg)
495
        self.entry = entry
496
497
498
class SourceRootHasName(InvalidEntry):
499
    """This changeset entry has a name other than "", but its parent is !NULL"""
500
    def __init__(self, entry, name):
501
        """Constructor.
502
503
        :param entry: The invalid ChangesetEntry
504
        :type entry: `ChangesetEntry`
505
        :param name: The name of the entry
506
        :type name: str
507
        """
508
        msg = 'Child of !NULL is named "%s", not "./.".' % name
509
        InvalidEntry.__init__(self, entry, msg)
510
511
class NullIDAssigned(InvalidEntry):
512
    """The id !NULL was assigned to a real entry"""
513
    def __init__(self, entry):
514
        """Constructor.
515
516
        :param entry: The invalid ChangesetEntry
517
        :type entry: `ChangesetEntry`
518
        """
519
        msg = '"!NULL" id assigned to a file "%s".' % entry.path
520
        InvalidEntry.__init__(self, entry, msg)
521
522
class ParentIDIsSelf(InvalidEntry):
523
    """An entry is marked as its own parent"""
524
    def __init__(self, entry):
525
        """Constructor.
526
527
        :param entry: The invalid ChangesetEntry
528
        :type entry: `ChangesetEntry`
529
        """
530
        msg = 'file %s has "%s" id for both self id and parent id.' % \
531
            (entry.path, entry.id)
532
        InvalidEntry.__init__(self, entry, msg)
533
534
class ChangesetEntry(object):
535
    """An entry the changeset"""
536
    def __init__(self, id, parent, path):
537
        """Constructor. Sets parent and name assuming it was not
538
        renamed/created/deleted.
539
        :param id: The id associated with the entry
540
        :param parent: The id of the parent of this entry (or !NULL if no
541
        parent)
542
        :param path: The file path relative to the tree root of this entry
543
        """
544
        self.id = id
545
        self.path = path 
546
        self.new_path = path
547
        self.parent = parent
548
        self.new_parent = parent
549
        self.contents_change = None
550
        self.metadata_change = None
551
        if parent == NULL_ID and path !='./.':
552
            raise SourceRootHasName(self, path)
553
        if self.id == NULL_ID:
554
            raise NullIDAssigned(self)
555
        if self.id  == self.parent:
556
            raise ParentIDIsSelf(self)
557
558
    def __str__(self):
559
        return "ChangesetEntry(%s)" % self.id
560
561
    def __get_dir(self):
562
        if self.path is None:
563
            return None
564
        return os.path.dirname(self.path)
565
566
    def __set_dir(self, dir):
567
        self.path = os.path.join(dir, os.path.basename(self.path))
568
569
    dir = property(__get_dir, __set_dir)
570
    
571
    def __get_name(self):
572
        if self.path is None:
573
            return None
574
        return os.path.basename(self.path)
575
576
    def __set_name(self, name):
577
        self.path = os.path.join(os.path.dirname(self.path), name)
578
579
    name = property(__get_name, __set_name)
580
581
    def __get_new_dir(self):
582
        if self.new_path is None:
583
            return None
584
        return os.path.dirname(self.new_path)
585
586
    def __set_new_dir(self, dir):
587
        self.new_path = os.path.join(dir, os.path.basename(self.new_path))
588
589
    new_dir = property(__get_new_dir, __set_new_dir)
590
591
    def __get_new_name(self):
592
        if self.new_path is None:
593
            return None
594
        return os.path.basename(self.new_path)
595
596
    def __set_new_name(self, name):
597
        self.new_path = os.path.join(os.path.dirname(self.new_path), name)
598
599
    new_name = property(__get_new_name, __set_new_name)
600
601
    def needs_rename(self):
602
        """Determines whether the entry requires renaming.
603
604
        :rtype: bool
605
        """
606
607
        return (self.parent != self.new_parent or self.name != self.new_name)
608
609
    def is_deletion(self, reverse):
610
        """Return true if applying the entry would delete a file/directory.
611
612
        :param reverse: if true, the changeset is being applied in reverse
613
        :rtype: bool
614
        """
615
        return ((self.new_parent is None and not reverse) or 
616
                (self.parent is None and reverse))
617
618
    def is_creation(self, reverse):
619
        """Return true if applying the entry would create a file/directory.
620
621
        :param reverse: if true, the changeset is being applied in reverse
622
        :rtype: bool
623
        """
624
        return ((self.parent is None and not reverse) or 
625
                (self.new_parent is None and reverse))
626
627
    def is_creation_or_deletion(self):
628
        """Return true if applying the entry would create or delete a 
629
        file/directory.
630
631
        :rtype: bool
632
        """
633
        return self.parent is None or self.new_parent is None
634
635
    def get_cset_path(self, mod=False):
636
        """Determine the path of the entry according to the changeset.
637
638
        :param changeset: The changeset to derive the path from
639
        :type changeset: `Changeset`
640
        :param mod: If true, generate the MOD path.  Otherwise, generate the \
641
        ORIG path.
642
        :return: the path of the entry, or None if it did not exist in the \
643
        requested tree.
644
        :rtype: str or NoneType
645
        """
646
        if mod:
647
            if self.new_parent == NULL_ID:
648
                return "./."
649
            elif self.new_parent is None:
650
                return None
651
            return self.new_path
652
        else:
653
            if self.parent == NULL_ID:
654
                return "./."
655
            elif self.parent is None:
656
                return None
657
            return self.path
658
659
    def summarize_name(self, changeset, reverse=False):
660
        """Produce a one-line summary of the filename.  Indicates renames as
661
        old => new, indicates creation as None => new, indicates deletion as
662
        old => None.
663
664
        :param changeset: The changeset to get paths from
665
        :type changeset: `Changeset`
666
        :param reverse: If true, reverse the names in the output
667
        :type reverse: bool
668
        :rtype: str
669
        """
670
        orig_path = self.get_cset_path(False)
671
        mod_path = self.get_cset_path(True)
672
        if orig_path is not None:
673
            orig_path = orig_path[2:]
674
        if mod_path is not None:
675
            mod_path = mod_path[2:]
676
        if orig_path == mod_path:
677
            return orig_path
678
        else:
679
            if not reverse:
680
                return "%s => %s" % (orig_path, mod_path)
681
            else:
682
                return "%s => %s" % (mod_path, orig_path)
683
684
685
    def get_new_path(self, id_map, changeset, reverse=False):
686
        """Determine the full pathname to rename to
687
688
        :param id_map: The map of ids to filenames for the tree
689
        :type id_map: Dictionary
690
        :param changeset: The changeset to get data from
691
        :type changeset: `Changeset`
692
        :param reverse: If true, we're applying the changeset in reverse
693
        :type reverse: bool
694
        :rtype: str
695
        """
696
        if reverse:
697
            parent = self.parent
698
            to_dir = self.dir
699
            from_dir = self.new_dir
700
            to_name = self.name
701
            from_name = self.new_name
702
        else:
703
            parent = self.new_parent
704
            to_dir = self.new_dir
705
            from_dir = self.dir
706
            to_name = self.new_name
707
            from_name = self.name
708
709
        if to_name is None:
710
            return None
711
712
        if parent == NULL_ID or parent is None:
713
            if to_name != '.':
714
                raise SourceRootHasName(self, to_name)
715
            else:
716
                return '.'
717
        if from_dir == to_dir:
718
            dir = os.path.dirname(id_map[self.id])
719
        else:
720
            parent_entry = changeset.entries[parent]
721
            dir = parent_entry.get_new_path(id_map, changeset, reverse)
722
        if from_name == to_name:
723
            name = os.path.basename(id_map[self.id])
724
        else:
725
            name = to_name
726
            assert(from_name is None or from_name == os.path.basename(id_map[self.id]))
727
        return os.path.join(dir, name)
728
729
    def is_boring(self):
730
        """Determines whether the entry does nothing
731
        
732
        :return: True if the entry does no renames or content changes
733
        :rtype: bool
734
        """
735
        if self.contents_change is not None:
736
            return False
737
        elif self.metadata_change is not None:
738
            return False
739
        elif self.parent != self.new_parent:
740
            return False
741
        elif self.name != self.new_name:
742
            return False
743
        else:
744
            return True
745
746
    def apply(self, filename, conflict_handler, reverse=False):
747
        """Applies the file content and/or metadata changes.
748
749
        :param filename: the filename of the entry
750
        :type filename: str
751
        :param reverse: If true, apply the changes in reverse
752
        :type reverse: bool
753
        """
754
        if self.is_deletion(reverse) and self.metadata_change is not None:
755
            self.metadata_change.apply(filename, conflict_handler, reverse)
756
        if self.contents_change is not None:
757
            self.contents_change.apply(filename, conflict_handler, reverse)
758
        if not self.is_deletion(reverse) and self.metadata_change is not None:
759
            self.metadata_change.apply(filename, conflict_handler, reverse)
760
761
class IDPresent(Exception):
762
    def __init__(self, id):
763
        msg = "Cannot add entry because that id has already been used:\n%s" %\
764
            id
765
        Exception.__init__(self, msg)
766
        self.id = id
767
558 by Martin Pool
- All top-level classes inherit from object
768
class Changeset(object):
493 by Martin Pool
- Merge aaron's merge command
769
    """A set of changes to apply"""
770
    def __init__(self):
771
        self.entries = {}
772
773
    def add_entry(self, entry):
774
        """Add an entry to the list of entries"""
775
        if self.entries.has_key(entry.id):
776
            raise IDPresent(entry.id)
777
        self.entries[entry.id] = entry
778
779
def my_sort(sequence, key, reverse=False):
780
    """A sort function that supports supplying a key for comparison
781
    
782
    :param sequence: The sequence to sort
783
    :param key: A callable object that returns the values to be compared
784
    :param reverse: If true, sort in reverse order
785
    :type reverse: bool
786
    """
787
    def cmp_by_key(entry_a, entry_b):
788
        if reverse:
789
            tmp=entry_a
790
            entry_a = entry_b
791
            entry_b = tmp
792
        return cmp(key(entry_a), key(entry_b))
793
    sequence.sort(cmp_by_key)
794
795
def get_rename_entries(changeset, inventory, reverse):
796
    """Return a list of entries that will be renamed.  Entries are sorted from
797
    longest to shortest source path and from shortest to longest target path.
798
799
    :param changeset: The changeset to look in
800
    :type changeset: `Changeset`
801
    :param inventory: The source of current tree paths for the given ids
802
    :type inventory: Dictionary
803
    :param reverse: If true, the changeset is being applied in reverse
804
    :type reverse: bool
805
    :return: source entries and target entries as a tuple
806
    :rtype: (List, List)
807
    """
808
    source_entries = [x for x in changeset.entries.itervalues() 
809
                      if x.needs_rename()]
810
    # these are done from longest path to shortest, to avoid deleting a
811
    # parent before its children are deleted/renamed 
812
    def longest_to_shortest(entry):
813
        path = inventory.get(entry.id)
814
        if path is None:
815
            return 0
816
        else:
817
            return len(path)
818
    my_sort(source_entries, longest_to_shortest, reverse=True)
819
820
    target_entries = source_entries[:]
821
    # These are done from shortest to longest path, to avoid creating a
822
    # child before its parent has been created/renamed
823
    def shortest_to_longest(entry):
824
        path = entry.get_new_path(inventory, changeset, reverse)
825
        if path is None:
826
            return 0
827
        else:
828
            return len(path)
829
    my_sort(target_entries, shortest_to_longest)
830
    return (source_entries, target_entries)
831
850 by Martin Pool
- Merge merge updates from aaron
832
def rename_to_temp_delete(source_entries, inventory, dir, temp_dir, 
833
                          conflict_handler, reverse):
493 by Martin Pool
- Merge aaron's merge command
834
    """Delete and rename entries as appropriate.  Entries are renamed to temp
850 by Martin Pool
- Merge merge updates from aaron
835
    names.  A map of id -> temp name (or None, for deletions) is returned.
493 by Martin Pool
- Merge aaron's merge command
836
837
    :param source_entries: The entries to rename and delete
838
    :type source_entries: List of `ChangesetEntry`
839
    :param inventory: The map of id -> filename in the current tree
840
    :type inventory: Dictionary
841
    :param dir: The directory to apply changes to
842
    :type dir: str
843
    :param reverse: Apply changes in reverse
844
    :type reverse: bool
845
    :return: a mapping of id to temporary name
846
    :rtype: Dictionary
847
    """
848
    temp_name = {}
849
    for i in range(len(source_entries)):
850
        entry = source_entries[i]
851
        if entry.is_deletion(reverse):
852
            path = os.path.join(dir, inventory[entry.id])
853
            entry.apply(path, conflict_handler, reverse)
850 by Martin Pool
- Merge merge updates from aaron
854
            temp_name[entry.id] = None
493 by Martin Pool
- Merge aaron's merge command
855
856
        else:
850 by Martin Pool
- Merge merge updates from aaron
857
            to_name = os.path.join(temp_dir, str(i))
493 by Martin Pool
- Merge aaron's merge command
858
            src_path = inventory.get(entry.id)
859
            if src_path is not None:
860
                src_path = os.path.join(dir, src_path)
861
                try:
862
                    os.rename(src_path, to_name)
863
                    temp_name[entry.id] = to_name
864
                except OSError, e:
865
                    if e.errno != errno.ENOENT:
866
                        raise
867
                    if conflict_handler.missing_for_rename(src_path) == "skip":
868
                        continue
869
870
    return temp_name
871
872
850 by Martin Pool
- Merge merge updates from aaron
873
def rename_to_new_create(changed_inventory, target_entries, inventory, 
874
                         changeset, dir, conflict_handler, reverse):
493 by Martin Pool
- Merge aaron's merge command
875
    """Rename entries with temp names to their final names, create new files.
876
850 by Martin Pool
- Merge merge updates from aaron
877
    :param changed_inventory: A mapping of id to temporary name
878
    :type changed_inventory: Dictionary
493 by Martin Pool
- Merge aaron's merge command
879
    :param target_entries: The entries to apply changes to
880
    :type target_entries: List of `ChangesetEntry`
881
    :param changeset: The changeset to apply
882
    :type changeset: `Changeset`
883
    :param dir: The directory to apply changes to
884
    :type dir: str
885
    :param reverse: If true, apply changes in reverse
886
    :type reverse: bool
887
    """
888
    for entry in target_entries:
850 by Martin Pool
- Merge merge updates from aaron
889
        new_tree_path = entry.get_new_path(inventory, changeset, reverse)
890
        if new_tree_path is None:
493 by Martin Pool
- Merge aaron's merge command
891
            continue
850 by Martin Pool
- Merge merge updates from aaron
892
        new_path = os.path.join(dir, new_tree_path)
893
        old_path = changed_inventory.get(entry.id)
493 by Martin Pool
- Merge aaron's merge command
894
        if os.path.exists(new_path):
895
            if conflict_handler.target_exists(entry, new_path, old_path) == \
896
                "skip":
897
                continue
898
        if entry.is_creation(reverse):
899
            entry.apply(new_path, conflict_handler, reverse)
850 by Martin Pool
- Merge merge updates from aaron
900
            changed_inventory[entry.id] = new_tree_path
493 by Martin Pool
- Merge aaron's merge command
901
        else:
902
            if old_path is None:
903
                continue
904
            try:
905
                os.rename(old_path, new_path)
850 by Martin Pool
- Merge merge updates from aaron
906
                changed_inventory[entry.id] = new_tree_path
493 by Martin Pool
- Merge aaron's merge command
907
            except OSError, e:
908
                raise Exception ("%s is missing" % new_path)
909
910
class TargetExists(Exception):
911
    def __init__(self, entry, target):
912
        msg = "The path %s already exists" % target
913
        Exception.__init__(self, msg)
914
        self.entry = entry
915
        self.target = target
916
917
class RenameConflict(Exception):
918
    def __init__(self, id, this_name, base_name, other_name):
919
        msg = """Trees all have different names for a file
920
 this: %s
921
 base: %s
922
other: %s
923
   id: %s""" % (this_name, base_name, other_name, id)
924
        Exception.__init__(self, msg)
925
        self.this_name = this_name
926
        self.base_name = base_name
927
        self_other_name = other_name
928
929
class MoveConflict(Exception):
930
    def __init__(self, id, this_parent, base_parent, other_parent):
931
        msg = """The file is in different directories in every tree
932
 this: %s
933
 base: %s
934
other: %s
935
   id: %s""" % (this_parent, base_parent, other_parent, id)
936
        Exception.__init__(self, msg)
937
        self.this_parent = this_parent
938
        self.base_parent = base_parent
939
        self_other_parent = other_parent
940
941
class MergeConflict(Exception):
942
    def __init__(self, this_path):
943
        Exception.__init__(self, "Conflict applying changes to %s" % this_path)
944
        self.this_path = this_path
945
946
class MergePermissionConflict(Exception):
947
    def __init__(self, this_path, base_path, other_path):
948
        this_perms = os.stat(this_path).st_mode & 0755
949
        base_perms = os.stat(base_path).st_mode & 0755
950
        other_perms = os.stat(other_path).st_mode & 0755
951
        msg = """Conflicting permission for %s
952
this: %o
953
base: %o
954
other: %o
955
        """ % (this_path, this_perms, base_perms, other_perms)
956
        self.this_path = this_path
957
        self.base_path = base_path
958
        self.other_path = other_path
959
        Exception.__init__(self, msg)
960
961
class WrongOldContents(Exception):
962
    def __init__(self, filename):
963
        msg = "Contents mismatch deleting %s" % filename
964
        self.filename = filename
965
        Exception.__init__(self, msg)
966
967
class WrongOldPermissions(Exception):
968
    def __init__(self, filename, old_perms, new_perms):
969
        msg = "Permission missmatch on %s:\n" \
970
        "Expected 0%o, got 0%o." % (filename, old_perms, new_perms)
971
        self.filename = filename
972
        Exception.__init__(self, msg)
973
974
class RemoveContentsConflict(Exception):
975
    def __init__(self, filename):
976
        msg = "Conflict deleting %s, which has different contents in BASE"\
977
            " and THIS" % filename
978
        self.filename = filename
979
        Exception.__init__(self, msg)
980
981
class DeletingNonEmptyDirectory(Exception):
982
    def __init__(self, filename):
983
        msg = "Trying to remove dir %s while it still had files" % filename
984
        self.filename = filename
985
        Exception.__init__(self, msg)
986
987
988
class PatchTargetMissing(Exception):
989
    def __init__(self, filename):
990
        msg = "Attempt to patch %s, which does not exist" % filename
991
        Exception.__init__(self, msg)
992
        self.filename = filename
993
994
class MissingPermsFile(Exception):
995
    def __init__(self, filename):
996
        msg = "Attempt to change permissions on  %s, which does not exist" %\
997
            filename
998
        Exception.__init__(self, msg)
999
        self.filename = filename
1000
1001
class MissingForRm(Exception):
1002
    def __init__(self, filename):
1003
        msg = "Attempt to remove missing path %s" % filename
1004
        Exception.__init__(self, msg)
1005
        self.filename = filename
1006
1007
1008
class MissingForRename(Exception):
1009
    def __init__(self, filename):
1010
        msg = "Attempt to move missing path %s" % (filename)
1011
        Exception.__init__(self, msg)
1012
        self.filename = filename
1013
850 by Martin Pool
- Merge merge updates from aaron
1014
class NewContentsConflict(Exception):
1015
    def __init__(self, filename):
1016
        msg = "Conflicting contents for new file %s" % (filename)
1017
        Exception.__init__(self, msg)
1018
1019
1020
class MissingForMerge(Exception):
1021
    def __init__(self, filename):
1022
        msg = "The file %s was modified, but does not exist in this tree"\
1023
            % (filename)
1024
        Exception.__init__(self, msg)
1025
1026
558 by Martin Pool
- All top-level classes inherit from object
1027
class ExceptionConflictHandler(object):
493 by Martin Pool
- Merge aaron's merge command
1028
    def __init__(self, dir):
1029
        self.dir = dir
1030
    
1031
    def missing_parent(self, pathname):
1032
        parent = os.path.dirname(pathname)
1033
        raise Exception("Parent directory missing for %s" % pathname)
1034
1035
    def dir_exists(self, pathname):
1036
        raise Exception("Directory already exists for %s" % pathname)
1037
1038
    def failed_hunks(self, pathname):
1039
        raise Exception("Failed to apply some hunks for %s" % pathname)
1040
1041
    def target_exists(self, entry, target, old_path):
1042
        raise TargetExists(entry, target)
1043
1044
    def rename_conflict(self, id, this_name, base_name, other_name):
1045
        raise RenameConflict(id, this_name, base_name, other_name)
1046
1047
    def move_conflict(self, id, inventory):
1048
        this_dir = inventory.this.get_dir(id)
1049
        base_dir = inventory.base.get_dir(id)
1050
        other_dir = inventory.other.get_dir(id)
1051
        raise MoveConflict(id, this_dir, base_dir, other_dir)
1052
1053
    def merge_conflict(self, new_file, this_path, base_path, other_path):
1054
        os.unlink(new_file)
1055
        raise MergeConflict(this_path)
1056
1057
    def permission_conflict(self, this_path, base_path, other_path):
1058
        raise MergePermissionConflict(this_path, base_path, other_path)
1059
1060
    def wrong_old_contents(self, filename, expected_contents):
1061
        raise WrongOldContents(filename)
1062
1063
    def rem_contents_conflict(self, filename, this_contents, base_contents):
1064
        raise RemoveContentsConflict(filename)
1065
1066
    def wrong_old_perms(self, filename, old_perms, new_perms):
1067
        raise WrongOldPermissions(filename, old_perms, new_perms)
1068
1069
    def rmdir_non_empty(self, filename):
1070
        raise DeletingNonEmptyDirectory(filename)
1071
1072
    def link_name_exists(self, filename):
1073
        raise TargetExists(filename)
1074
1075
    def patch_target_missing(self, filename, contents):
1076
        raise PatchTargetMissing(filename)
1077
1078
    def missing_for_chmod(self, filename):
1079
        raise MissingPermsFile(filename)
1080
1081
    def missing_for_rm(self, filename, change):
1082
        raise MissingForRm(filename)
1083
1084
    def missing_for_rename(self, filename):
1085
        raise MissingForRename(filename)
1086
850 by Martin Pool
- Merge merge updates from aaron
1087
    def missing_for_merge(self, file_id, inventory):
1088
        raise MissingForMerge(inventory.other.get_path(file_id))
1089
1090
    def new_contents_conflict(self, filename, other_contents):
1091
        raise NewContentsConflict(filename)
1092
622 by Martin Pool
Updated merge patch from Aaron
1093
    def finalize():
1094
        pass
1095
493 by Martin Pool
- Merge aaron's merge command
1096
def apply_changeset(changeset, inventory, dir, conflict_handler=None, 
1097
                    reverse=False):
1098
    """Apply a changeset to a directory.
1099
1100
    :param changeset: The changes to perform
1101
    :type changeset: `Changeset`
1102
    :param inventory: The mapping of id to filename for the directory
1103
    :type inventory: Dictionary
1104
    :param dir: The path of the directory to apply the changes to
1105
    :type dir: str
1106
    :param reverse: If true, apply the changes in reverse
1107
    :type reverse: bool
1108
    :return: The mapping of the changed entries
1109
    :rtype: Dictionary
1110
    """
1111
    if conflict_handler is None:
1112
        conflict_handler = ExceptionConflictHandler(dir)
850 by Martin Pool
- Merge merge updates from aaron
1113
    temp_dir = os.path.join(dir, "bzr-tree-change")
1114
    try:
1115
        os.mkdir(temp_dir)
1116
    except OSError, e:
1117
        if e.errno == errno.EEXIST:
1118
            try:
1119
                os.rmdir(temp_dir)
1120
            except OSError, e:
1121
                if e.errno == errno.ENOTEMPTY:
1122
                    raise OldFailedTreeOp()
1123
            os.mkdir(temp_dir)
1124
        else:
1125
            raise
493 by Martin Pool
- Merge aaron's merge command
1126
    
1127
    #apply changes that don't affect filenames
1128
    for entry in changeset.entries.itervalues():
1129
        if not entry.is_creation_or_deletion():
1130
            path = os.path.join(dir, inventory[entry.id])
1131
            entry.apply(path, conflict_handler, reverse)
1132
1133
    # Apply renames in stages, to minimize conflicts:
1134
    # Only files whose name or parent change are interesting, because their
1135
    # target name may exist in the source tree.  If a directory's name changes,
1136
    # that doesn't make its children interesting.
1137
    (source_entries, target_entries) = get_rename_entries(changeset, inventory,
1138
                                                          reverse)
1139
850 by Martin Pool
- Merge merge updates from aaron
1140
    changed_inventory = rename_to_temp_delete(source_entries, inventory, dir,
1141
                                              temp_dir, conflict_handler,
1142
                                              reverse)
493 by Martin Pool
- Merge aaron's merge command
1143
850 by Martin Pool
- Merge merge updates from aaron
1144
    rename_to_new_create(changed_inventory, target_entries, inventory,
1145
                         changeset, dir, conflict_handler, reverse)
493 by Martin Pool
- Merge aaron's merge command
1146
    os.rmdir(temp_dir)
850 by Martin Pool
- Merge merge updates from aaron
1147
    return changed_inventory
493 by Martin Pool
- Merge aaron's merge command
1148
1149
1150
def apply_changeset_tree(cset, tree, reverse=False):
1151
    r_inventory = {}
1152
    for entry in tree.source_inventory().itervalues():
1153
        inventory[entry.id] = entry.path
1154
    new_inventory = apply_changeset(cset, r_inventory, tree.root,
1155
                                    reverse=reverse)
1156
    new_entries, remove_entries = \
1157
        get_inventory_change(inventory, new_inventory, cset, reverse)
1158
    tree.update_source_inventory(new_entries, remove_entries)
1159
1160
1161
def get_inventory_change(inventory, new_inventory, cset, reverse=False):
1162
    new_entries = {}
1163
    remove_entries = []
1164
    for entry in cset.entries.itervalues():
1165
        if entry.needs_rename():
850 by Martin Pool
- Merge merge updates from aaron
1166
            new_path = entry.get_new_path(inventory, cset)
1167
            if new_path is None:
1168
                remove_entries.append(entry.id)
493 by Martin Pool
- Merge aaron's merge command
1169
            else:
850 by Martin Pool
- Merge merge updates from aaron
1170
                new_entries[new_path] = entry.id
493 by Martin Pool
- Merge aaron's merge command
1171
    return new_entries, remove_entries
1172
1173
1174
def print_changeset(cset):
1175
    """Print all non-boring changeset entries
1176
    
1177
    :param cset: The changeset to print
1178
    :type cset: `Changeset`
1179
    """
1180
    for entry in cset.entries.itervalues():
1181
        if entry.is_boring():
1182
            continue
1183
        print entry.id
1184
        print entry.summarize_name(cset)
1185
1186
class CompositionFailure(Exception):
1187
    def __init__(self, old_entry, new_entry, problem):
1188
        msg = "Unable to conpose entries.\n %s" % problem
1189
        Exception.__init__(self, msg)
1190
1191
class IDMismatch(CompositionFailure):
1192
    def __init__(self, old_entry, new_entry):
1193
        problem = "Attempt to compose entries with different ids: %s and %s" %\
1194
            (old_entry.id, new_entry.id)
1195
        CompositionFailure.__init__(self, old_entry, new_entry, problem)
1196
1197
def compose_changesets(old_cset, new_cset):
1198
    """Combine two changesets into one.  This works well for exact patching.
1199
    Otherwise, not so well.
1200
1201
    :param old_cset: The first changeset that would be applied
1202
    :type old_cset: `Changeset`
1203
    :param new_cset: The second changeset that would be applied
1204
    :type new_cset: `Changeset`
1205
    :return: A changeset that combines the changes in both changesets
1206
    :rtype: `Changeset`
1207
    """
1208
    composed = Changeset()
1209
    for old_entry in old_cset.entries.itervalues():
1210
        new_entry = new_cset.entries.get(old_entry.id)
1211
        if new_entry is None:
1212
            composed.add_entry(old_entry)
1213
        else:
1214
            composed_entry = compose_entries(old_entry, new_entry)
1215
            if composed_entry.parent is not None or\
1216
                composed_entry.new_parent is not None:
1217
                composed.add_entry(composed_entry)
1218
    for new_entry in new_cset.entries.itervalues():
1219
        if not old_cset.entries.has_key(new_entry.id):
1220
            composed.add_entry(new_entry)
1221
    return composed
1222
1223
def compose_entries(old_entry, new_entry):
1224
    """Combine two entries into one.
1225
1226
    :param old_entry: The first entry that would be applied
1227
    :type old_entry: ChangesetEntry
1228
    :param old_entry: The second entry that would be applied
1229
    :type old_entry: ChangesetEntry
1230
    :return: A changeset entry combining both entries
1231
    :rtype: `ChangesetEntry`
1232
    """
1233
    if old_entry.id != new_entry.id:
1234
        raise IDMismatch(old_entry, new_entry)
1235
    output = ChangesetEntry(old_entry.id, old_entry.parent, old_entry.path)
1236
1237
    if (old_entry.parent != old_entry.new_parent or 
1238
        new_entry.parent != new_entry.new_parent):
1239
        output.new_parent = new_entry.new_parent
1240
1241
    if (old_entry.path != old_entry.new_path or 
1242
        new_entry.path != new_entry.new_path):
1243
        output.new_path = new_entry.new_path
1244
1245
    output.contents_change = compose_contents(old_entry, new_entry)
1246
    output.metadata_change = compose_metadata(old_entry, new_entry)
1247
    return output
1248
1249
def compose_contents(old_entry, new_entry):
1250
    """Combine the contents of two changeset entries.  Entries are combined
1251
    intelligently where possible, but the fallback behavior returns an 
1252
    ApplySequence.
1253
1254
    :param old_entry: The first entry that would be applied
1255
    :type old_entry: `ChangesetEntry`
1256
    :param new_entry: The second entry that would be applied
1257
    :type new_entry: `ChangesetEntry`
1258
    :return: A combined contents change
1259
    :rtype: anything supporting the apply(reverse=False) method
1260
    """
1261
    old_contents = old_entry.contents_change
1262
    new_contents = new_entry.contents_change
1263
    if old_entry.contents_change is None:
1264
        return new_entry.contents_change
1265
    elif new_entry.contents_change is None:
1266
        return old_entry.contents_change
1267
    elif isinstance(old_contents, ReplaceContents) and \
1268
        isinstance(new_contents, ReplaceContents):
1269
        if old_contents.old_contents == new_contents.new_contents:
1270
            return None
1271
        else:
1272
            return ReplaceContents(old_contents.old_contents,
1273
                                   new_contents.new_contents)
1274
    elif isinstance(old_contents, ApplySequence):
1275
        output = ApplySequence(old_contents.changes)
1276
        if isinstance(new_contents, ApplySequence):
1277
            output.changes.extend(new_contents.changes)
1278
        else:
1279
            output.changes.append(new_contents)
1280
        return output
1281
    elif isinstance(new_contents, ApplySequence):
1282
        output = ApplySequence((old_contents.changes,))
1283
        output.extend(new_contents.changes)
1284
        return output
1285
    else:
1286
        return ApplySequence((old_contents, new_contents))
1287
1288
def compose_metadata(old_entry, new_entry):
1289
    old_meta = old_entry.metadata_change
1290
    new_meta = new_entry.metadata_change
1291
    if old_meta is None:
1292
        return new_meta
1293
    elif new_meta is None:
1294
        return old_meta
1295
    elif isinstance(old_meta, ChangeUnixPermissions) and \
1296
        isinstance(new_meta, ChangeUnixPermissions):
1297
        return ChangeUnixPermissions(old_meta.old_mode, new_meta.new_mode)
1298
    else:
1299
        return ApplySequence(old_meta, new_meta)
1300
1301
1302
def changeset_is_null(changeset):
1303
    for entry in changeset.entries.itervalues():
1304
        if not entry.is_boring():
1305
            return False
1306
    return True
1307
1308
class UnsuppportedFiletype(Exception):
1309
    def __init__(self, full_path, stat_result):
1310
        msg = "The file \"%s\" is not a supported filetype." % full_path
1311
        Exception.__init__(self, msg)
1312
        self.full_path = full_path
1313
        self.stat_result = stat_result
1314
1315
def generate_changeset(tree_a, tree_b, inventory_a=None, inventory_b=None):
1316
    return ChangesetGenerator(tree_a, tree_b, inventory_a, inventory_b)()
1317
1318
class ChangesetGenerator(object):
1319
    def __init__(self, tree_a, tree_b, inventory_a=None, inventory_b=None):
1320
        object.__init__(self)
1321
        self.tree_a = tree_a
1322
        self.tree_b = tree_b
1323
        if inventory_a is not None:
1324
            self.inventory_a = inventory_a
1325
        else:
1326
            self.inventory_a = tree_a.inventory()
1327
        if inventory_b is not None:
1328
            self.inventory_b = inventory_b
1329
        else:
1330
            self.inventory_b = tree_b.inventory()
1331
        self.r_inventory_a = self.reverse_inventory(self.inventory_a)
1332
        self.r_inventory_b = self.reverse_inventory(self.inventory_b)
1333
1334
    def reverse_inventory(self, inventory):
1335
        r_inventory = {}
1336
        for entry in inventory.itervalues():
1337
            if entry.id is None:
1338
                continue
1339
            r_inventory[entry.id] = entry
1340
        return r_inventory
1341
1342
    def __call__(self):
1343
        cset = Changeset()
1344
        for entry in self.inventory_a.itervalues():
1345
            if entry.id is None:
1346
                continue
1347
            cs_entry = self.make_entry(entry.id)
1348
            if cs_entry is not None and not cs_entry.is_boring():
1349
                cset.add_entry(cs_entry)
1350
1351
        for entry in self.inventory_b.itervalues():
1352
            if entry.id is None:
1353
                continue
1354
            if not self.r_inventory_a.has_key(entry.id):
1355
                cs_entry = self.make_entry(entry.id)
1356
                if cs_entry is not None and not cs_entry.is_boring():
1357
                    cset.add_entry(cs_entry)
1358
        for entry in list(cset.entries.itervalues()):
1359
            if entry.parent != entry.new_parent:
1360
                if not cset.entries.has_key(entry.parent) and\
1361
                    entry.parent != NULL_ID and entry.parent is not None:
1362
                    parent_entry = self.make_boring_entry(entry.parent)
1363
                    cset.add_entry(parent_entry)
1364
                if not cset.entries.has_key(entry.new_parent) and\
1365
                    entry.new_parent != NULL_ID and \
1366
                    entry.new_parent is not None:
1367
                    parent_entry = self.make_boring_entry(entry.new_parent)
1368
                    cset.add_entry(parent_entry)
1369
        return cset
1370
1371
    def get_entry_parent(self, entry, inventory):
1372
        if entry is None:
1373
            return None
1374
        if entry.path == "./.":
1375
            return NULL_ID
1376
        dirname = os.path.dirname(entry.path)
1377
        if dirname == ".":
1378
            dirname = "./."
1379
        parent = inventory[dirname]
1380
        return parent.id
1381
1382
    def get_paths(self, entry, tree):
1383
        if entry is None:
1384
            return (None, None)
1385
        full_path = tree.readonly_path(entry.id)
1386
        if entry.path == ".":
1387
            return ("", full_path)
1388
        return (entry.path, full_path)
1389
1390
    def make_basic_entry(self, id, only_interesting):
1391
        entry_a = self.r_inventory_a.get(id)
1392
        entry_b = self.r_inventory_b.get(id)
1393
        if only_interesting and not self.is_interesting(entry_a, entry_b):
1394
            return (None, None, None)
1395
        parent = self.get_entry_parent(entry_a, self.inventory_a)
1396
        (path, full_path_a) = self.get_paths(entry_a, self.tree_a)
1397
        cs_entry = ChangesetEntry(id, parent, path)
1398
        new_parent = self.get_entry_parent(entry_b, self.inventory_b)
1399
1400
1401
        (new_path, full_path_b) = self.get_paths(entry_b, self.tree_b)
1402
1403
        cs_entry.new_path = new_path
1404
        cs_entry.new_parent = new_parent
1405
        return (cs_entry, full_path_a, full_path_b)
1406
1407
    def is_interesting(self, entry_a, entry_b):
1408
        if entry_a is not None:
1409
            if entry_a.interesting:
1410
                return True
1411
        if entry_b is not None:
1412
            if entry_b.interesting:
1413
                return True
1414
        return False
1415
1416
    def make_boring_entry(self, id):
1417
        (cs_entry, full_path_a, full_path_b) = \
1418
            self.make_basic_entry(id, only_interesting=False)
1419
        if cs_entry.is_creation_or_deletion():
1420
            return self.make_entry(id, only_interesting=False)
1421
        else:
1422
            return cs_entry
1423
        
1424
1425
    def make_entry(self, id, only_interesting=True):
1426
        (cs_entry, full_path_a, full_path_b) = \
1427
            self.make_basic_entry(id, only_interesting)
1428
1429
        if cs_entry is None:
1430
            return None
1431
       
1432
        stat_a = self.lstat(full_path_a)
1433
        stat_b = self.lstat(full_path_b)
1434
        if stat_b is None:
1435
            cs_entry.new_parent = None
1436
            cs_entry.new_path = None
1437
        
1438
        cs_entry.metadata_change = self.make_mode_change(stat_a, stat_b)
1439
        cs_entry.contents_change = self.make_contents_change(full_path_a,
1440
                                                             stat_a, 
1441
                                                             full_path_b, 
1442
                                                             stat_b)
1443
        return cs_entry
1444
1445
    def make_mode_change(self, stat_a, stat_b):
1446
        mode_a = None
1447
        if stat_a is not None and not stat.S_ISLNK(stat_a.st_mode):
1448
            mode_a = stat_a.st_mode & 0777
1449
        mode_b = None
1450
        if stat_b is not None and not stat.S_ISLNK(stat_b.st_mode):
1451
            mode_b = stat_b.st_mode & 0777
1452
        if mode_a == mode_b:
1453
            return None
1454
        return ChangeUnixPermissions(mode_a, mode_b)
1455
1456
    def make_contents_change(self, full_path_a, stat_a, full_path_b, stat_b):
1457
        if stat_a is None and stat_b is None:
1458
            return None
1459
        if None not in (stat_a, stat_b) and stat.S_ISDIR(stat_a.st_mode) and\
1460
            stat.S_ISDIR(stat_b.st_mode):
1461
            return None
1462
        if None not in (stat_a, stat_b) and stat.S_ISREG(stat_a.st_mode) and\
1463
            stat.S_ISREG(stat_b.st_mode):
1464
            if stat_a.st_ino == stat_b.st_ino and \
1465
                stat_a.st_dev == stat_b.st_dev:
1466
                return None
1467
            if file(full_path_a, "rb").read() == \
1468
                file(full_path_b, "rb").read():
1469
                return None
1470
1471
            patch_contents = patch.diff(full_path_a, 
1472
                                        file(full_path_b, "rb").read())
1473
            if patch_contents is None:
1474
                return None
1475
            return PatchApply(patch_contents)
1476
1477
        a_contents = self.get_contents(stat_a, full_path_a)
1478
        b_contents = self.get_contents(stat_b, full_path_b)
1479
        if a_contents == b_contents:
1480
            return None
1481
        return ReplaceContents(a_contents, b_contents)
1482
1483
    def get_contents(self, stat_result, full_path):
1484
        if stat_result is None:
1485
            return None
1486
        elif stat.S_ISREG(stat_result.st_mode):
1487
            return FileCreate(file(full_path, "rb").read())
1488
        elif stat.S_ISDIR(stat_result.st_mode):
1489
            return dir_create
1490
        elif stat.S_ISLNK(stat_result.st_mode):
1491
            return SymlinkCreate(os.readlink(full_path))
1492
        else:
1493
            raise UnsupportedFiletype(full_path, stat_result)
1494
1495
    def lstat(self, full_path):
1496
        stat_result = None
1497
        if full_path is not None:
1498
            try:
1499
                stat_result = os.lstat(full_path)
1500
            except OSError, e:
1501
                if e.errno != errno.ENOENT:
1502
                    raise
1503
        return stat_result
1504
1505
1506
def full_path(entry, tree):
1507
    return os.path.join(tree.root, entry.path)
1508
1509
def new_delete_entry(entry, tree, inventory, delete):
1510
    if entry.path == "":
1511
        parent = NULL_ID
1512
    else:
1513
        parent = inventory[dirname(entry.path)].id
1514
    cs_entry = ChangesetEntry(parent, entry.path)
1515
    if delete:
1516
        cs_entry.new_path = None
1517
        cs_entry.new_parent = None
1518
    else:
1519
        cs_entry.path = None
1520
        cs_entry.parent = None
1521
    full_path = full_path(entry, tree)
1522
    status = os.lstat(full_path)
1523
    if stat.S_ISDIR(file_stat.st_mode):
1524
        action = dir_create
1525
    
1526
1527
1528
        
1529
    
558 by Martin Pool
- All top-level classes inherit from object
1530
class Inventory(object):
493 by Martin Pool
- Merge aaron's merge command
1531
    def __init__(self, inventory):
1532
        self.inventory = inventory
1533
        self.rinventory = None
1534
1535
    def get_rinventory(self):
1536
        if self.rinventory is None:
1537
            self.rinventory  = invert_dict(self.inventory)
1538
        return self.rinventory
1539
1540
    def get_path(self, id):
1541
        return self.inventory.get(id)
1542
1543
    def get_name(self, id):
850 by Martin Pool
- Merge merge updates from aaron
1544
        path = self.get_path(id)
1545
        if path is None:
1546
            return None
1547
        else:
1548
            return os.path.basename(path)
493 by Martin Pool
- Merge aaron's merge command
1549
1550
    def get_dir(self, id):
1551
        path = self.get_path(id)
1552
        if path == "":
1553
            return None
850 by Martin Pool
- Merge merge updates from aaron
1554
        if path is None:
1555
            return None
493 by Martin Pool
- Merge aaron's merge command
1556
        return os.path.dirname(path)
1557
1558
    def get_parent(self, id):
850 by Martin Pool
- Merge merge updates from aaron
1559
        if self.get_path(id) is None:
1560
            return None
493 by Martin Pool
- Merge aaron's merge command
1561
        directory = self.get_dir(id)
1562
        if directory == '.':
1563
            directory = './.'
1564
        if directory is None:
1565
            return NULL_ID
1566
        return self.get_rinventory().get(directory)