~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/changeset.py

  • Committer: Robert Collins
  • Date: 2005-10-11 07:21:00 UTC
  • mto: This revision was merged to the branch mainline in revision 1443.
  • Revision ID: robertc@robertcollins.net-20051011072100-16996b55c43ff24f
move editor into the config file too

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
import errno
18
18
import patch
19
19
import stat
20
 
"""
21
 
Represent and apply a changeset
22
 
"""
 
20
from bzrlib.trace import mutter
 
21
from bzrlib.osutils import rename
 
22
import bzrlib
 
23
 
 
24
# XXX: mbp: I'm not totally convinced that we should handle conflicts
 
25
# as part of changeset application, rather than only in the merge
 
26
# operation.
 
27
 
 
28
"""Represent and apply a changeset
 
29
 
 
30
Conflicts in applying a changeset are represented as exceptions.
 
31
"""
 
32
 
23
33
__docformat__ = "restructuredtext"
24
34
 
25
35
NULL_ID = "!NULL"
26
36
 
27
 
 
 
37
class OldFailedTreeOp(Exception):
 
38
    def __init__(self):
 
39
        Exception.__init__(self, "bzr-tree-change contains files from a"
 
40
                           " previous failed merge operation.")
28
41
def invert_dict(dict):
29
42
    newdict = {}
30
43
    for (key,value) in dict.iteritems():
31
44
        newdict[value] = key
32
45
    return newdict
33
46
 
34
 
 
35
 
class PatchApply(object):
36
 
    """Patch application as a kind of content change"""
37
 
    def __init__(self, contents):
38
 
        """Constructor.
39
 
 
40
 
        :param contents: The text of the patch to apply
41
 
        :type contents: str"""
42
 
        self.contents = contents
43
 
 
44
 
    def __eq__(self, other):
45
 
        if not isinstance(other, PatchApply):
46
 
            return False
47
 
        elif self.contents != other.contents:
48
 
            return False
49
 
        else:
50
 
            return True
51
 
 
52
 
    def __ne__(self, other):
53
 
        return not (self == other)
54
 
 
55
 
    def apply(self, filename, conflict_handler, reverse=False):
56
 
        """Applies the patch to the specified file.
57
 
 
58
 
        :param filename: the file to apply the patch to
59
 
        :type filename: str
60
 
        :param reverse: If true, apply the patch in reverse
61
 
        :type reverse: bool
62
 
        """
63
 
        input_name = filename+".orig"
64
 
        try:
65
 
            os.rename(filename, input_name)
66
 
        except OSError, e:
67
 
            if e.errno != errno.ENOENT:
68
 
                raise
69
 
            if conflict_handler.patch_target_missing(filename, self.contents)\
70
 
                == "skip":
71
 
                return
72
 
            os.rename(filename, input_name)
73
 
            
74
 
 
75
 
        status = patch.patch(self.contents, input_name, filename, 
76
 
                                    reverse)
77
 
        os.chmod(filename, os.stat(input_name).st_mode)
78
 
        if status == 0:
79
 
            os.unlink(input_name)
80
 
        elif status == 1:
81
 
            conflict_handler.failed_hunks(filename)
82
 
 
83
 
        
84
 
class ChangeUnixPermissions(object):
 
47
       
 
48
class ChangeExecFlag(object):
85
49
    """This is two-way change, suitable for file modification, creation,
86
50
    deletion"""
87
 
    def __init__(self, old_mode, new_mode):
88
 
        self.old_mode = old_mode
89
 
        self.new_mode = new_mode
 
51
    def __init__(self, old_exec_flag, new_exec_flag):
 
52
        self.old_exec_flag = old_exec_flag
 
53
        self.new_exec_flag = new_exec_flag
90
54
 
91
55
    def apply(self, filename, conflict_handler, reverse=False):
92
56
        if not reverse:
93
 
            from_mode = self.old_mode
94
 
            to_mode = self.new_mode
 
57
            from_exec_flag = self.old_exec_flag
 
58
            to_exec_flag = self.new_exec_flag
95
59
        else:
96
 
            from_mode = self.new_mode
97
 
            to_mode = self.old_mode
 
60
            from_exec_flag = self.new_exec_flag
 
61
            to_exec_flag = self.old_exec_flag
98
62
        try:
99
 
            current_mode = os.stat(filename).st_mode &0777
 
63
            current_exec_flag = bool(os.stat(filename).st_mode & 0111)
100
64
        except OSError, e:
101
65
            if e.errno == errno.ENOENT:
102
 
                if conflict_handler.missing_for_chmod(filename) == "skip":
 
66
                if conflict_handler.missing_for_exec_flag(filename) == "skip":
103
67
                    return
104
68
                else:
105
 
                    current_mode = from_mode
 
69
                    current_exec_flag = from_exec_flag
106
70
 
107
 
        if from_mode is not None and current_mode != from_mode:
108
 
            if conflict_handler.wrong_old_perms(filename, from_mode, 
109
 
                                                current_mode) != "continue":
 
71
        if from_exec_flag is not None and current_exec_flag != from_exec_flag:
 
72
            if conflict_handler.wrong_old_exec_flag(filename,
 
73
                        from_exec_flag, current_exec_flag) != "continue":
110
74
                return
111
75
 
112
 
        if to_mode is not None:
 
76
        if to_exec_flag is not None:
 
77
            current_mode = os.stat(filename).st_mode
 
78
            if to_exec_flag:
 
79
                umask = os.umask(0)
 
80
                os.umask(umask)
 
81
                to_mode = current_mode | (0100 & ~umask)
 
82
                # Enable x-bit for others only if they can read it.
 
83
                if current_mode & 0004:
 
84
                    to_mode |= 0001 & ~umask
 
85
                if current_mode & 0040:
 
86
                    to_mode |= 0010 & ~umask
 
87
            else:
 
88
                to_mode = current_mode & ~0111
113
89
            try:
114
90
                os.chmod(filename, to_mode)
115
91
            except IOError, e:
116
92
                if e.errno == errno.ENOENT:
117
 
                    conflict_handler.missing_for_chmod(filename)
 
93
                    conflict_handler.missing_for_exec_flag(filename)
118
94
 
119
95
    def __eq__(self, other):
120
 
        if not isinstance(other, ChangeUnixPermissions):
121
 
            return False
122
 
        elif self.old_mode != other.old_mode:
123
 
            return False
124
 
        elif self.new_mode != other.new_mode:
125
 
            return False
126
 
        else:
127
 
            return True
 
96
        return (isinstance(other, ChangeExecFlag) and
 
97
                self.old_exec_flag == other.old_exec_flag and
 
98
                self.new_exec_flag == other.new_exec_flag)
128
99
 
129
100
    def __ne__(self, other):
130
101
        return not (self == other)
131
102
 
 
103
 
132
104
def dir_create(filename, conflict_handler, reverse):
133
105
    """Creates the directory, or deletes it if reverse is true.  Intended to be
134
106
    used with ReplaceContents.
154
126
        try:
155
127
            os.rmdir(filename)
156
128
        except OSError, e:
157
 
            if e.errno != 39:
 
129
            if e.errno != errno.ENOTEMPTY:
158
130
                raise
159
131
            if conflict_handler.rmdir_non_empty(filename) == "skip":
160
132
                return
161
133
            os.rmdir(filename)
162
134
 
163
 
                
164
 
            
165
135
 
166
136
class SymlinkCreate(object):
167
137
    """Creates or deletes a symlink (for use with ReplaceContents)"""
363
333
 
364
334
 
365
335
class Diff3Merge(object):
366
 
    def __init__(self, base_file, other_file):
367
 
        self.base_file = base_file
368
 
        self.other_file = other_file
 
336
    def __init__(self, file_id, base, other):
 
337
        self.file_id = file_id
 
338
        self.base = base
 
339
        self.other = other
369
340
 
370
341
    def __eq__(self, other):
371
342
        if not isinstance(other, Diff3Merge):
372
343
            return False
373
 
        return (self.base_file == other.base_file and 
374
 
                self.other_file == other.other_file)
 
344
        return (self.base == other.base and 
 
345
                self.other == other.other and self.file_id == other.file_id)
375
346
 
376
347
    def __ne__(self, other):
377
348
        return not (self == other)
378
349
 
379
350
    def apply(self, filename, conflict_handler, reverse=False):
380
 
        new_file = filename+".new" 
 
351
        new_file = filename+".new"
 
352
        base_file = self.base.readonly_path(self.file_id)
 
353
        other_file = self.other.readonly_path(self.file_id)
381
354
        if not reverse:
382
 
            base = self.base_file
383
 
            other = self.other_file
 
355
            base = base_file
 
356
            other = other_file
384
357
        else:
385
 
            base = self.other_file
386
 
            other = self.base_file
 
358
            base = other_file
 
359
            other = base_file
387
360
        status = patch.diff3(new_file, filename, base, other)
388
361
        if status == 0:
389
362
            os.chmod(new_file, os.stat(filename).st_mode)
390
 
            os.rename(new_file, filename)
 
363
            rename(new_file, filename)
391
364
            return
392
365
        else:
393
366
            assert(status == 1)
394
 
            conflict_handler.merge_conflict(new_file, filename, base, other)
 
367
            def get_lines(filename):
 
368
                my_file = file(filename, "rb")
 
369
                lines = my_file.readlines()
 
370
                my_file.close()
 
371
                return lines
 
372
            base_lines = get_lines(base)
 
373
            other_lines = get_lines(other)
 
374
            conflict_handler.merge_conflict(new_file, filename, base_lines, 
 
375
                                            other_lines)
395
376
 
396
377
 
397
378
def CreateDir():
653
634
                return None
654
635
            return self.path
655
636
 
656
 
    def summarize_name(self, changeset, reverse=False):
 
637
    def summarize_name(self, reverse=False):
657
638
        """Produce a one-line summary of the filename.  Indicates renames as
658
639
        old => new, indicates creation as None => new, indicates deletion as
659
640
        old => None.
690
671
        :type reverse: bool
691
672
        :rtype: str
692
673
        """
 
674
        mutter("Finding new path for %s" % self.summarize_name())
693
675
        if reverse:
694
676
            parent = self.parent
695
677
            to_dir = self.dir
714
696
        if from_dir == to_dir:
715
697
            dir = os.path.dirname(id_map[self.id])
716
698
        else:
 
699
            mutter("path, new_path: %r %r" % (self.path, self.new_path))
717
700
            parent_entry = changeset.entries[parent]
718
701
            dir = parent_entry.get_new_path(id_map, changeset, reverse)
719
702
        if from_name == to_name:
826
809
    my_sort(target_entries, shortest_to_longest)
827
810
    return (source_entries, target_entries)
828
811
 
829
 
def rename_to_temp_delete(source_entries, inventory, dir, conflict_handler,
830
 
                          reverse):
 
812
def rename_to_temp_delete(source_entries, inventory, dir, temp_dir, 
 
813
                          conflict_handler, reverse):
831
814
    """Delete and rename entries as appropriate.  Entries are renamed to temp
832
 
    names.  A map of id -> temp name is returned.
 
815
    names.  A map of id -> temp name (or None, for deletions) is returned.
833
816
 
834
817
    :param source_entries: The entries to rename and delete
835
818
    :type source_entries: List of `ChangesetEntry`
842
825
    :return: a mapping of id to temporary name
843
826
    :rtype: Dictionary
844
827
    """
845
 
    temp_dir = os.path.join(dir, "temp")
846
828
    temp_name = {}
847
829
    for i in range(len(source_entries)):
848
830
        entry = source_entries[i]
849
831
        if entry.is_deletion(reverse):
850
832
            path = os.path.join(dir, inventory[entry.id])
851
833
            entry.apply(path, conflict_handler, reverse)
 
834
            temp_name[entry.id] = None
852
835
 
853
836
        else:
854
 
            to_name = temp_dir+"/"+str(i)
 
837
            to_name = os.path.join(temp_dir, str(i))
855
838
            src_path = inventory.get(entry.id)
856
839
            if src_path is not None:
857
840
                src_path = os.path.join(dir, src_path)
858
841
                try:
859
 
                    os.rename(src_path, to_name)
 
842
                    rename(src_path, to_name)
860
843
                    temp_name[entry.id] = to_name
861
844
                except OSError, e:
862
845
                    if e.errno != errno.ENOENT:
867
850
    return temp_name
868
851
 
869
852
 
870
 
def rename_to_new_create(temp_name, target_entries, inventory, changeset, dir,
871
 
                         conflict_handler, reverse):
 
853
def rename_to_new_create(changed_inventory, target_entries, inventory, 
 
854
                         changeset, dir, conflict_handler, reverse):
872
855
    """Rename entries with temp names to their final names, create new files.
873
856
 
874
 
    :param temp_name: A mapping of id to temporary name
875
 
    :type temp_name: Dictionary
 
857
    :param changed_inventory: A mapping of id to temporary name
 
858
    :type changed_inventory: Dictionary
876
859
    :param target_entries: The entries to apply changes to
877
860
    :type target_entries: List of `ChangesetEntry`
878
861
    :param changeset: The changeset to apply
883
866
    :type reverse: bool
884
867
    """
885
868
    for entry in target_entries:
886
 
        new_path = entry.get_new_path(inventory, changeset, reverse)
887
 
        if new_path is None:
 
869
        new_tree_path = entry.get_new_path(inventory, changeset, reverse)
 
870
        if new_tree_path is None:
888
871
            continue
889
 
        new_path = os.path.join(dir, new_path)
890
 
        old_path = temp_name.get(entry.id)
891
 
        if os.path.exists(new_path):
 
872
        new_path = os.path.join(dir, new_tree_path)
 
873
        old_path = changed_inventory.get(entry.id)
 
874
        if bzrlib.osutils.lexists(new_path):
892
875
            if conflict_handler.target_exists(entry, new_path, old_path) == \
893
876
                "skip":
894
877
                continue
895
878
        if entry.is_creation(reverse):
896
879
            entry.apply(new_path, conflict_handler, reverse)
 
880
            changed_inventory[entry.id] = new_tree_path
897
881
        else:
898
882
            if old_path is None:
899
883
                continue
900
884
            try:
901
 
                os.rename(old_path, new_path)
 
885
                rename(old_path, new_path)
 
886
                changed_inventory[entry.id] = new_tree_path
902
887
            except OSError, e:
903
888
                raise Exception ("%s is missing" % new_path)
904
889
 
938
923
        Exception.__init__(self, "Conflict applying changes to %s" % this_path)
939
924
        self.this_path = this_path
940
925
 
941
 
class MergePermissionConflict(Exception):
942
 
    def __init__(self, this_path, base_path, other_path):
943
 
        this_perms = os.stat(this_path).st_mode & 0755
944
 
        base_perms = os.stat(base_path).st_mode & 0755
945
 
        other_perms = os.stat(other_path).st_mode & 0755
946
 
        msg = """Conflicting permission for %s
947
 
this: %o
948
 
base: %o
949
 
other: %o
950
 
        """ % (this_path, this_perms, base_perms, other_perms)
951
 
        self.this_path = this_path
952
 
        self.base_path = base_path
953
 
        self.other_path = other_path
954
 
        Exception.__init__(self, msg)
955
 
 
956
926
class WrongOldContents(Exception):
957
927
    def __init__(self, filename):
958
928
        msg = "Contents mismatch deleting %s" % filename
959
929
        self.filename = filename
960
930
        Exception.__init__(self, msg)
961
931
 
962
 
class WrongOldPermissions(Exception):
963
 
    def __init__(self, filename, old_perms, new_perms):
964
 
        msg = "Permission missmatch on %s:\n" \
965
 
        "Expected 0%o, got 0%o." % (filename, old_perms, new_perms)
 
932
class WrongOldExecFlag(Exception):
 
933
    def __init__(self, filename, old_exec_flag, new_exec_flag):
 
934
        msg = "Executable flag missmatch on %s:\n" \
 
935
        "Expected %s, got %s." % (filename, old_exec_flag, new_exec_flag)
966
936
        self.filename = filename
967
937
        Exception.__init__(self, msg)
968
938
 
986
956
        Exception.__init__(self, msg)
987
957
        self.filename = filename
988
958
 
989
 
class MissingPermsFile(Exception):
 
959
class MissingForSetExec(Exception):
990
960
    def __init__(self, filename):
991
961
        msg = "Attempt to change permissions on  %s, which does not exist" %\
992
962
            filename
1006
976
        Exception.__init__(self, msg)
1007
977
        self.filename = filename
1008
978
 
 
979
class NewContentsConflict(Exception):
 
980
    def __init__(self, filename):
 
981
        msg = "Conflicting contents for new file %s" % (filename)
 
982
        Exception.__init__(self, msg)
 
983
 
 
984
 
 
985
class MissingForMerge(Exception):
 
986
    def __init__(self, filename):
 
987
        msg = "The file %s was modified, but does not exist in this tree"\
 
988
            % (filename)
 
989
        Exception.__init__(self, msg)
 
990
 
 
991
 
1009
992
class ExceptionConflictHandler(object):
1010
 
    def __init__(self, dir):
1011
 
        self.dir = dir
1012
 
    
 
993
    """Default handler for merge exceptions.
 
994
 
 
995
    This throws an error on any kind of conflict.  Conflict handlers can
 
996
    descend from this class if they have a better way to handle some or
 
997
    all types of conflict.
 
998
    """
1013
999
    def missing_parent(self, pathname):
1014
1000
        parent = os.path.dirname(pathname)
1015
1001
        raise Exception("Parent directory missing for %s" % pathname)
1026
1012
    def rename_conflict(self, id, this_name, base_name, other_name):
1027
1013
        raise RenameConflict(id, this_name, base_name, other_name)
1028
1014
 
1029
 
    def move_conflict(self, id, inventory):
1030
 
        this_dir = inventory.this.get_dir(id)
1031
 
        base_dir = inventory.base.get_dir(id)
1032
 
        other_dir = inventory.other.get_dir(id)
 
1015
    def move_conflict(self, id, this_dir, base_dir, other_dir):
1033
1016
        raise MoveConflict(id, this_dir, base_dir, other_dir)
1034
1017
 
1035
 
    def merge_conflict(self, new_file, this_path, base_path, other_path):
 
1018
    def merge_conflict(self, new_file, this_path, base_lines, other_lines):
1036
1019
        os.unlink(new_file)
1037
1020
        raise MergeConflict(this_path)
1038
1021
 
1039
 
    def permission_conflict(self, this_path, base_path, other_path):
1040
 
        raise MergePermissionConflict(this_path, base_path, other_path)
1041
 
 
1042
1022
    def wrong_old_contents(self, filename, expected_contents):
1043
1023
        raise WrongOldContents(filename)
1044
1024
 
1045
1025
    def rem_contents_conflict(self, filename, this_contents, base_contents):
1046
1026
        raise RemoveContentsConflict(filename)
1047
1027
 
1048
 
    def wrong_old_perms(self, filename, old_perms, new_perms):
1049
 
        raise WrongOldPermissions(filename, old_perms, new_perms)
 
1028
    def wrong_old_exec_flag(self, filename, old_exec_flag, new_exec_flag):
 
1029
        raise WrongOldExecFlag(filename, old_exec_flag, new_exec_flag)
1050
1030
 
1051
1031
    def rmdir_non_empty(self, filename):
1052
1032
        raise DeletingNonEmptyDirectory(filename)
1057
1037
    def patch_target_missing(self, filename, contents):
1058
1038
        raise PatchTargetMissing(filename)
1059
1039
 
1060
 
    def missing_for_chmod(self, filename):
1061
 
        raise MissingPermsFile(filename)
 
1040
    def missing_for_exec_flag(self, filename):
 
1041
        raise MissingForExecFlag(filename)
1062
1042
 
1063
1043
    def missing_for_rm(self, filename, change):
1064
1044
        raise MissingForRm(filename)
1066
1046
    def missing_for_rename(self, filename):
1067
1047
        raise MissingForRename(filename)
1068
1048
 
 
1049
    def missing_for_merge(self, file_id, other_path):
 
1050
        raise MissingForMerge(other_path)
 
1051
 
 
1052
    def new_contents_conflict(self, filename, other_contents):
 
1053
        raise NewContentsConflict(filename)
 
1054
 
 
1055
    def finalize(self):
 
1056
        pass
 
1057
 
1069
1058
def apply_changeset(changeset, inventory, dir, conflict_handler=None, 
1070
1059
                    reverse=False):
1071
1060
    """Apply a changeset to a directory.
1082
1071
    :rtype: Dictionary
1083
1072
    """
1084
1073
    if conflict_handler is None:
1085
 
        conflict_handler = ExceptionConflictHandler(dir)
1086
 
    temp_dir = dir+"/temp"
1087
 
    os.mkdir(temp_dir)
 
1074
        conflict_handler = ExceptionConflictHandler()
 
1075
    temp_dir = os.path.join(dir, "bzr-tree-change")
 
1076
    try:
 
1077
        os.mkdir(temp_dir)
 
1078
    except OSError, e:
 
1079
        if e.errno == errno.EEXIST:
 
1080
            try:
 
1081
                os.rmdir(temp_dir)
 
1082
            except OSError, e:
 
1083
                if e.errno == errno.ENOTEMPTY:
 
1084
                    raise OldFailedTreeOp()
 
1085
            os.mkdir(temp_dir)
 
1086
        else:
 
1087
            raise
1088
1088
    
1089
1089
    #apply changes that don't affect filenames
1090
1090
    for entry in changeset.entries.itervalues():
1099
1099
    (source_entries, target_entries) = get_rename_entries(changeset, inventory,
1100
1100
                                                          reverse)
1101
1101
 
1102
 
    temp_name = rename_to_temp_delete(source_entries, inventory, dir,
1103
 
                                      conflict_handler, reverse)
 
1102
    changed_inventory = rename_to_temp_delete(source_entries, inventory, dir,
 
1103
                                              temp_dir, conflict_handler,
 
1104
                                              reverse)
1104
1105
 
1105
 
    rename_to_new_create(temp_name, target_entries, inventory, changeset, dir,
1106
 
                         conflict_handler, reverse)
 
1106
    rename_to_new_create(changed_inventory, target_entries, inventory,
 
1107
                         changeset, dir, conflict_handler, reverse)
1107
1108
    os.rmdir(temp_dir)
1108
 
    r_inventory = invert_dict(inventory)
1109
 
    new_entries, removed_entries = get_inventory_change(inventory,
1110
 
    r_inventory, changeset, reverse)
1111
 
    new_inventory = {}
1112
 
    for path, file_id in new_entries.iteritems():
1113
 
        new_inventory[file_id] = path
1114
 
    for file_id in removed_entries:
1115
 
        new_inventory[file_id] = None
1116
 
    return new_inventory
 
1109
    return changed_inventory
1117
1110
 
1118
1111
 
1119
1112
def apply_changeset_tree(cset, tree, reverse=False):
1130
1123
def get_inventory_change(inventory, new_inventory, cset, reverse=False):
1131
1124
    new_entries = {}
1132
1125
    remove_entries = []
1133
 
    r_inventory = invert_dict(inventory)
1134
 
    r_new_inventory = invert_dict(new_inventory)
1135
1126
    for entry in cset.entries.itervalues():
1136
1127
        if entry.needs_rename():
1137
 
            old_path = r_inventory.get(entry.id)
1138
 
            if old_path is not None:
1139
 
                remove_entries.append(old_path)
 
1128
            new_path = entry.get_new_path(inventory, cset)
 
1129
            if new_path is None:
 
1130
                remove_entries.append(entry.id)
1140
1131
            else:
1141
 
                new_path = entry.get_new_path(inventory, cset)
1142
 
                if new_path is not None:
1143
 
                    new_entries[new_path] = entry.id
 
1132
                new_entries[new_path] = entry.id
1144
1133
    return new_entries, remove_entries
1145
1134
 
1146
1135
 
1265
1254
        return new_meta
1266
1255
    elif new_meta is None:
1267
1256
        return old_meta
1268
 
    elif isinstance(old_meta, ChangeUnixPermissions) and \
1269
 
        isinstance(new_meta, ChangeUnixPermissions):
1270
 
        return ChangeUnixPermissions(old_meta.old_mode, new_meta.new_mode)
 
1257
    elif (isinstance(old_meta, ChangeExecFlag) and
 
1258
          isinstance(new_meta, ChangeExecFlag)):
 
1259
        return ChangeExecFlag(old_meta.old_exec_flag, new_meta.new_exec_flag)
1271
1260
    else:
1272
1261
        return ApplySequence(old_meta, new_meta)
1273
1262
 
1285
1274
        self.full_path = full_path
1286
1275
        self.stat_result = stat_result
1287
1276
 
1288
 
def generate_changeset(tree_a, tree_b, inventory_a=None, inventory_b=None):
1289
 
    return ChangesetGenerator(tree_a, tree_b, inventory_a, inventory_b)()
 
1277
def generate_changeset(tree_a, tree_b, interesting_ids=None):
 
1278
    return ChangesetGenerator(tree_a, tree_b, interesting_ids)()
1290
1279
 
1291
1280
class ChangesetGenerator(object):
1292
 
    def __init__(self, tree_a, tree_b, inventory_a=None, inventory_b=None):
 
1281
    def __init__(self, tree_a, tree_b, interesting_ids=None):
1293
1282
        object.__init__(self)
1294
1283
        self.tree_a = tree_a
1295
1284
        self.tree_b = tree_b
1296
 
        if inventory_a is not None:
1297
 
            self.inventory_a = inventory_a
1298
 
        else:
1299
 
            self.inventory_a = tree_a.inventory()
1300
 
        if inventory_b is not None:
1301
 
            self.inventory_b = inventory_b
1302
 
        else:
1303
 
            self.inventory_b = tree_b.inventory()
1304
 
        self.r_inventory_a = self.reverse_inventory(self.inventory_a)
1305
 
        self.r_inventory_b = self.reverse_inventory(self.inventory_b)
 
1285
        self._interesting_ids = interesting_ids
1306
1286
 
1307
 
    def reverse_inventory(self, inventory):
1308
 
        r_inventory = {}
1309
 
        for entry in inventory.itervalues():
1310
 
            if entry.id is None:
1311
 
                continue
1312
 
            r_inventory[entry.id] = entry
1313
 
        return r_inventory
 
1287
    def iter_both_tree_ids(self):
 
1288
        for file_id in self.tree_a:
 
1289
            yield file_id
 
1290
        for file_id in self.tree_b:
 
1291
            if file_id not in self.tree_a:
 
1292
                yield file_id
1314
1293
 
1315
1294
    def __call__(self):
1316
1295
        cset = Changeset()
1317
 
        for entry in self.inventory_a.itervalues():
1318
 
            if entry.id is None:
1319
 
                continue
1320
 
            cs_entry = self.make_entry(entry.id)
 
1296
        for file_id in self.iter_both_tree_ids():
 
1297
            cs_entry = self.make_entry(file_id)
1321
1298
            if cs_entry is not None and not cs_entry.is_boring():
1322
1299
                cset.add_entry(cs_entry)
1323
1300
 
1324
 
        for entry in self.inventory_b.itervalues():
1325
 
            if entry.id is None:
1326
 
                continue
1327
 
            if not self.r_inventory_a.has_key(entry.id):
1328
 
                cs_entry = self.make_entry(entry.id)
1329
 
                if cs_entry is not None and not cs_entry.is_boring():
1330
 
                    cset.add_entry(cs_entry)
1331
1301
        for entry in list(cset.entries.itervalues()):
1332
1302
            if entry.parent != entry.new_parent:
1333
1303
                if not cset.entries.has_key(entry.parent) and\
1341
1311
                    cset.add_entry(parent_entry)
1342
1312
        return cset
1343
1313
 
1344
 
    def get_entry_parent(self, entry, inventory):
1345
 
        if entry is None:
1346
 
            return None
1347
 
        if entry.path == "./.":
1348
 
            return NULL_ID
1349
 
        dirname = os.path.dirname(entry.path)
1350
 
        if dirname == ".":
1351
 
            dirname = "./."
1352
 
        parent = inventory[dirname]
1353
 
        return parent.id
1354
 
 
1355
 
    def get_paths(self, entry, tree):
1356
 
        if entry is None:
1357
 
            return (None, None)
1358
 
        full_path = tree.readonly_path(entry.id)
1359
 
        if entry.path == ".":
1360
 
            return ("", full_path)
1361
 
        return (entry.path, full_path)
1362
 
 
1363
 
    def make_basic_entry(self, id, only_interesting):
1364
 
        entry_a = self.r_inventory_a.get(id)
1365
 
        entry_b = self.r_inventory_b.get(id)
 
1314
    def iter_inventory(self, tree):
 
1315
        for file_id in tree:
 
1316
            yield self.get_entry(file_id, tree)
 
1317
 
 
1318
    def get_entry(self, file_id, tree):
 
1319
        if not tree.has_or_had_id(file_id):
 
1320
            return None
 
1321
        return tree.tree.inventory[file_id]
 
1322
 
 
1323
    def get_entry_parent(self, entry):
 
1324
        if entry is None:
 
1325
            return None
 
1326
        return entry.parent_id
 
1327
 
 
1328
    def get_path(self, file_id, tree):
 
1329
        if not tree.has_or_had_id(file_id):
 
1330
            return None
 
1331
        path = tree.id2path(file_id)
 
1332
        if path == '':
 
1333
            return './.'
 
1334
        else:
 
1335
            return path
 
1336
 
 
1337
    def make_basic_entry(self, file_id, only_interesting):
 
1338
        entry_a = self.get_entry(file_id, self.tree_a)
 
1339
        entry_b = self.get_entry(file_id, self.tree_b)
1366
1340
        if only_interesting and not self.is_interesting(entry_a, entry_b):
1367
 
            return (None, None, None)
1368
 
        parent = self.get_entry_parent(entry_a, self.inventory_a)
1369
 
        (path, full_path_a) = self.get_paths(entry_a, self.tree_a)
1370
 
        cs_entry = ChangesetEntry(id, parent, path)
1371
 
        new_parent = self.get_entry_parent(entry_b, self.inventory_b)
1372
 
 
1373
 
 
1374
 
        (new_path, full_path_b) = self.get_paths(entry_b, self.tree_b)
 
1341
            return None
 
1342
        parent = self.get_entry_parent(entry_a)
 
1343
        path = self.get_path(file_id, self.tree_a)
 
1344
        cs_entry = ChangesetEntry(file_id, parent, path)
 
1345
        new_parent = self.get_entry_parent(entry_b)
 
1346
 
 
1347
        new_path = self.get_path(file_id, self.tree_b)
1375
1348
 
1376
1349
        cs_entry.new_path = new_path
1377
1350
        cs_entry.new_parent = new_parent
1378
 
        return (cs_entry, full_path_a, full_path_b)
 
1351
        return cs_entry
1379
1352
 
1380
1353
    def is_interesting(self, entry_a, entry_b):
 
1354
        if self._interesting_ids is None:
 
1355
            return True
1381
1356
        if entry_a is not None:
1382
 
            if entry_a.interesting:
1383
 
                return True
1384
 
        if entry_b is not None:
1385
 
            if entry_b.interesting:
1386
 
                return True
1387
 
        return False
 
1357
            file_id = entry_a.file_id
 
1358
        elif entry_b is not None:
 
1359
            file_id = entry_b.file_id
 
1360
        else:
 
1361
            return False
 
1362
        return file_id in self._interesting_ids
1388
1363
 
1389
1364
    def make_boring_entry(self, id):
1390
 
        (cs_entry, full_path_a, full_path_b) = \
1391
 
            self.make_basic_entry(id, only_interesting=False)
 
1365
        cs_entry = self.make_basic_entry(id, only_interesting=False)
1392
1366
        if cs_entry.is_creation_or_deletion():
1393
1367
            return self.make_entry(id, only_interesting=False)
1394
1368
        else:
1396
1370
        
1397
1371
 
1398
1372
    def make_entry(self, id, only_interesting=True):
1399
 
        (cs_entry, full_path_a, full_path_b) = \
1400
 
            self.make_basic_entry(id, only_interesting)
 
1373
        cs_entry = self.make_basic_entry(id, only_interesting)
1401
1374
 
1402
1375
        if cs_entry is None:
1403
1376
            return None
1404
 
       
 
1377
 
 
1378
        full_path_a = self.tree_a.readonly_path(id)
 
1379
        full_path_b = self.tree_b.readonly_path(id)
1405
1380
        stat_a = self.lstat(full_path_a)
1406
1381
        stat_b = self.lstat(full_path_b)
1407
 
        if stat_b is None:
1408
 
            cs_entry.new_parent = None
1409
 
            cs_entry.new_path = None
1410
 
        
1411
 
        cs_entry.metadata_change = self.make_mode_change(stat_a, stat_b)
 
1382
 
 
1383
        cs_entry.metadata_change = self.make_exec_flag_change(stat_a, stat_b)
 
1384
 
 
1385
        if id in self.tree_a and id in self.tree_b:
 
1386
            a_sha1 = self.tree_a.get_file_sha1(id)
 
1387
            b_sha1 = self.tree_b.get_file_sha1(id)
 
1388
            if None not in (a_sha1, b_sha1) and a_sha1 == b_sha1:
 
1389
                return cs_entry
 
1390
 
1412
1391
        cs_entry.contents_change = self.make_contents_change(full_path_a,
1413
1392
                                                             stat_a, 
1414
1393
                                                             full_path_b, 
1415
1394
                                                             stat_b)
1416
1395
        return cs_entry
1417
1396
 
1418
 
    def make_mode_change(self, stat_a, stat_b):
1419
 
        mode_a = None
 
1397
    def make_exec_flag_change(self, stat_a, stat_b):
 
1398
        exec_flag_a = exec_flag_b = None
1420
1399
        if stat_a is not None and not stat.S_ISLNK(stat_a.st_mode):
1421
 
            mode_a = stat_a.st_mode & 0777
1422
 
        mode_b = None
 
1400
            exec_flag_a = bool(stat_a.st_mode & 0111)
1423
1401
        if stat_b is not None and not stat.S_ISLNK(stat_b.st_mode):
1424
 
            mode_b = stat_b.st_mode & 0777
1425
 
        if mode_a == mode_b:
 
1402
            exec_flag_b = bool(stat_b.st_mode & 0111)
 
1403
        if exec_flag_a == exec_flag_b:
1426
1404
            return None
1427
 
        return ChangeUnixPermissions(mode_a, mode_b)
 
1405
        return ChangeExecFlag(exec_flag_a, exec_flag_b)
1428
1406
 
1429
1407
    def make_contents_change(self, full_path_a, stat_a, full_path_b, stat_b):
1430
1408
        if stat_a is None and stat_b is None:
1437
1415
            if stat_a.st_ino == stat_b.st_ino and \
1438
1416
                stat_a.st_dev == stat_b.st_dev:
1439
1417
                return None
1440
 
            if file(full_path_a, "rb").read() == \
1441
 
                file(full_path_b, "rb").read():
1442
 
                return None
1443
 
 
1444
 
            patch_contents = patch.diff(full_path_a, 
1445
 
                                        file(full_path_b, "rb").read())
1446
 
            if patch_contents is None:
1447
 
                return None
1448
 
            return PatchApply(patch_contents)
1449
1418
 
1450
1419
        a_contents = self.get_contents(stat_a, full_path_a)
1451
1420
        b_contents = self.get_contents(stat_b, full_path_b)
1499
1468
 
1500
1469
 
1501
1470
        
1502
 
    
 
1471
# XXX: Can't we unify this with the regular inventory object
1503
1472
class Inventory(object):
1504
1473
    def __init__(self, inventory):
1505
1474
        self.inventory = inventory
1514
1483
        return self.inventory.get(id)
1515
1484
 
1516
1485
    def get_name(self, id):
1517
 
        return os.path.basename(self.get_path(id))
 
1486
        path = self.get_path(id)
 
1487
        if path is None:
 
1488
            return None
 
1489
        else:
 
1490
            return os.path.basename(path)
1518
1491
 
1519
1492
    def get_dir(self, id):
1520
1493
        path = self.get_path(id)
1521
1494
        if path == "":
1522
1495
            return None
 
1496
        if path is None:
 
1497
            return None
1523
1498
        return os.path.dirname(path)
1524
1499
 
1525
1500
    def get_parent(self, id):
 
1501
        if self.get_path(id) is None:
 
1502
            return None
1526
1503
        directory = self.get_dir(id)
1527
1504
        if directory == '.':
1528
1505
            directory = './.'