~bzr-pqm/bzr/bzr.dev

493 by Martin Pool
- Merge aaron's merge command
1
import changeset
2
from changeset import Inventory, apply_changeset, invert_dict
3
import os.path
4
558 by Martin Pool
- All top-level classes inherit from object
5
class ThreewayInventory(object):
493 by Martin Pool
- Merge aaron's merge command
6
    def __init__(self, this_inventory, base_inventory, other_inventory):
7
        self.this = this_inventory
8
        self.base = base_inventory
9
        self.other = other_inventory
10
def invert_invent(inventory):
11
    invert_invent = {}
12
    for key, value in inventory.iteritems():
13
        invert_invent[value.id] = key
14
    return invert_invent
15
16
def make_inv(inventory):
17
    return Inventory(invert_invent(inventory))
18
        
19
20
def merge_flex(this, base, other, changeset_function, inventory_function,
21
               conflict_handler):
22
    this_inventory = inventory_function(this)
23
    base_inventory = inventory_function(base)
24
    other_inventory = inventory_function(other)
25
    inventory = ThreewayInventory(make_inv(this_inventory),
26
                                  make_inv(base_inventory), 
27
                                  make_inv(other_inventory))
28
    cset = changeset_function(base, other, base_inventory, other_inventory)
29
    new_cset = make_merge_changeset(cset, inventory, this, base, other, 
30
                                    conflict_handler)
622 by Martin Pool
Updated merge patch from Aaron
31
    result = apply_changeset(new_cset, invert_invent(this_inventory),
32
                             this.root, conflict_handler, False)
33
    conflict_handler.finalize()
34
    return result
493 by Martin Pool
- Merge aaron's merge command
35
36
    
37
38
def make_merge_changeset(cset, inventory, this, base, other, 
39
                         conflict_handler=None):
40
    new_cset = changeset.Changeset()
41
    def get_this_contents(id):
42
        path = os.path.join(this.root, inventory.this.get_path(id))
43
        if os.path.isdir(path):
44
            return changeset.dir_create
45
        else:
46
            return changeset.FileCreate(file(path, "rb").read())
47
48
    for entry in cset.entries.itervalues():
49
        if entry.is_boring():
50
            new_cset.add_entry(entry)
51
        else:
850 by Martin Pool
- Merge merge updates from aaron
52
            new_entry = make_merged_entry(entry, inventory, conflict_handler)
53
            new_contents = make_merged_contents(entry, this, base, other,
54
                                                conflict_handler)
55
            new_entry.contents_change = new_contents
56
            new_entry.metadata_change = make_merged_metadata(entry, base, other)
57
            new_cset.add_entry(new_entry)
58
493 by Martin Pool
- Merge aaron's merge command
59
    return new_cset
60
850 by Martin Pool
- Merge merge updates from aaron
61
def make_merged_entry(entry, inventory, conflict_handler):
493 by Martin Pool
- Merge aaron's merge command
62
    this_name = inventory.this.get_name(entry.id)
63
    this_parent = inventory.this.get_parent(entry.id)
64
    this_dir = inventory.this.get_dir(entry.id)
65
    if this_dir is None:
66
        this_dir = ""
67
68
    base_name = inventory.base.get_name(entry.id)
69
    base_parent = inventory.base.get_parent(entry.id)
70
    base_dir = inventory.base.get_dir(entry.id)
71
    if base_dir is None:
72
        base_dir = ""
73
    other_name = inventory.other.get_name(entry.id)
74
    other_parent = inventory.other.get_parent(entry.id)
75
    other_dir = inventory.base.get_dir(entry.id)
76
    if other_dir is None:
77
        other_dir = ""
78
79
    if base_name == other_name:
80
        old_name = this_name
81
        new_name = this_name
82
    else:
83
        if this_name != base_name and this_name != other_name:
84
            conflict_handler.rename_conflict(entry.id, this_name, base_name,
85
                                             other_name)
86
        else:
87
            old_name = this_name
88
            new_name = other_name
89
90
    if base_parent == other_parent:
91
        old_parent = this_parent
92
        new_parent = this_parent
93
        old_dir = this_dir
94
        new_dir = this_dir
95
    else:
96
        if this_parent != base_parent and this_parent != other_parent:
97
            conflict_handler.move_conflict(entry.id, inventory)
98
        else:
99
            old_parent = this_parent
100
            old_dir = this_dir
101
            new_parent = other_parent
102
            new_dir = other_dir
850 by Martin Pool
- Merge merge updates from aaron
103
    if old_name is not None and old_parent is not None:
104
        old_path = os.path.join(old_dir, old_name)
105
    else:
106
        old_path = None
493 by Martin Pool
- Merge aaron's merge command
107
    new_entry = changeset.ChangesetEntry(entry.id, old_parent, old_name)
850 by Martin Pool
- Merge merge updates from aaron
108
    if new_name is not None and new_parent is not None:
493 by Martin Pool
- Merge aaron's merge command
109
        new_entry.new_path = os.path.join(new_dir, new_name)
110
    else:
111
        new_entry.new_path = None
112
    new_entry.new_parent = new_parent
850 by Martin Pool
- Merge merge updates from aaron
113
    return new_entry
114
115
116
def make_merged_contents(entry, this, base, other, conflict_handler):
117
    contents = entry.contents_change
118
    if contents is None:
119
        return None
120
    this_path = this.readonly_path(entry.id)
121
    def make_diff3():
122
        if this_path is None:
123
            return conflict_handler.missing_for_merge(entry.id, inventory)
124
        base_path = base.readonly_path(entry.id)
125
        other_path = other.readonly_path(entry.id)    
126
        return changeset.Diff3Merge(base_path, other_path)
127
128
    if isinstance(contents, changeset.PatchApply):
129
        return make_diff3()
130
    if isinstance(contents, changeset.ReplaceContents):
131
        if contents.old_contents is None and contents.new_contents is None:
132
            return None
133
        if contents.new_contents is None:
134
            if this_path is not None and os.path.exists(this_path):
135
                return contents
136
            else:
137
                return None
138
        elif contents.old_contents is None:
139
            if this_path is None or not os.path.exists(this_path):
140
                return contents
141
            else:
142
                this_contents = file(this_path, "rb").read()
143
                if this_contents == contents.new_contents:
144
                    return None
145
                else:
146
                    other_path = other.readonly_path(entry.id)    
147
                    conflict_handler.new_contents_conflict(this_path, 
148
                                                           other_path)
149
        elif isinstance(contents.old_contents, changeset.FileCreate) and \
150
            isinstance(contents.new_contents, changeset.FileCreate):
151
            return make_diff3()
152
        else:
153
            raise Exception("Unhandled merge scenario")
154
155
def make_merged_metadata(entry, base, other):
156
    if entry.metadata_change is not None:
157
        base_path = base.readonly_path(entry.id)
158
        other_path = other.readonly_path(entry.id)    
159
        return PermissionsMerge(base_path, other_path)
493 by Martin Pool
- Merge aaron's merge command
160
    
850 by Martin Pool
- Merge merge updates from aaron
161
def get_merge_entry(entry, inventory, base, other, conflict_handler):
493 by Martin Pool
- Merge aaron's merge command
162
    if entry.contents_change is not None:
163
        new_entry.contents_change = changeset.Diff3Merge(base_path, other_path)
164
    if entry.metadata_change is not None:
165
        new_entry.metadata_change = PermissionsMerge(base_path, other_path)
166
167
    return new_entry
168
558 by Martin Pool
- All top-level classes inherit from object
169
class PermissionsMerge(object):
493 by Martin Pool
- Merge aaron's merge command
170
    def __init__(self, base_path, other_path):
171
        self.base_path = base_path
172
        self.other_path = other_path
173
174
    def apply(self, filename, conflict_handler, reverse=False):
175
        if not reverse:
176
            base = self.base_path
177
            other = self.other_path
178
        else:
179
            base = self.other_path
180
            other = self.base_path
181
        base_stat = os.stat(base).st_mode
182
        other_stat = os.stat(other).st_mode
183
        this_stat = os.stat(filename).st_mode
184
        if base_stat &0777 == other_stat &0777:
185
            return
186
        elif this_stat &0777 == other_stat &0777:
187
            return
188
        elif this_stat &0777 == base_stat &0777:
189
            os.chmod(filename, other_stat)
190
        else:
191
            conflict_handler.permission_conflict(filename, base, other)
192
193
194
import unittest
195
import tempfile
196
import shutil
558 by Martin Pool
- All top-level classes inherit from object
197
class MergeTree(object):
493 by Martin Pool
- Merge aaron's merge command
198
    def __init__(self, dir):
199
        self.dir = dir;
200
        os.mkdir(dir)
201
        self.inventory = {'0': ""}
202
    
203
    def child_path(self, parent, name):
204
        return os.path.join(self.inventory[parent], name)
205
206
    def add_file(self, id, parent, name, contents, mode):
207
        path = self.child_path(parent, name)
208
        full_path = self.abs_path(path)
209
        assert not os.path.exists(full_path)
210
        file(full_path, "wb").write(contents)
211
        os.chmod(self.abs_path(path), mode)
212
        self.inventory[id] = path
213
214
    def add_dir(self, id, parent, name, mode):
215
        path = self.child_path(parent, name)
216
        full_path = self.abs_path(path)
217
        assert not os.path.exists(full_path)
218
        os.mkdir(self.abs_path(path))
219
        os.chmod(self.abs_path(path), mode)
220
        self.inventory[id] = path
221
222
    def abs_path(self, path):
223
        return os.path.join(self.dir, path)
224
225
    def full_path(self, id):
226
        return self.abs_path(self.inventory[id])
227
850 by Martin Pool
- Merge merge updates from aaron
228
    def readonly_path(self, id):
229
        return self.full_path(id)
230
493 by Martin Pool
- Merge aaron's merge command
231
    def change_path(self, id, path):
232
        new = os.path.join(self.dir, self.inventory[id])
233
        os.rename(self.abs_path(self.inventory[id]), self.abs_path(path))
234
        self.inventory[id] = path
235
558 by Martin Pool
- All top-level classes inherit from object
236
class MergeBuilder(object):
493 by Martin Pool
- Merge aaron's merge command
237
    def __init__(self):
238
        self.dir = tempfile.mkdtemp(prefix="BaZing")
239
        self.base = MergeTree(os.path.join(self.dir, "base"))
240
        self.this = MergeTree(os.path.join(self.dir, "this"))
241
        self.other = MergeTree(os.path.join(self.dir, "other"))
242
        
243
        self.cset = changeset.Changeset()
244
        self.cset.add_entry(changeset.ChangesetEntry("0", 
245
                                                     changeset.NULL_ID, "./."))
246
    def get_cset_path(self, parent, name):
247
        if name is None:
248
            assert (parent is None)
249
            return None
250
        return os.path.join(self.cset.entries[parent].path, name)
251
252
    def add_file(self, id, parent, name, contents, mode):
253
        self.base.add_file(id, parent, name, contents, mode)
254
        self.this.add_file(id, parent, name, contents, mode)
255
        self.other.add_file(id, parent, name, contents, mode)
256
        path = self.get_cset_path(parent, name)
257
        self.cset.add_entry(changeset.ChangesetEntry(id, parent, path))
258
259
    def add_dir(self, id, parent, name, mode):
260
        path = self.get_cset_path(parent, name)
261
        self.base.add_dir(id, parent, name, mode)
262
        self.cset.add_entry(changeset.ChangesetEntry(id, parent, path))
263
        self.this.add_dir(id, parent, name, mode)
264
        self.other.add_dir(id, parent, name, mode)
265
266
267
    def change_name(self, id, base=None, this=None, other=None):
268
        if base is not None:
269
            self.change_name_tree(id, self.base, base)
270
            self.cset.entries[id].name = base
271
272
        if this is not None:
273
            self.change_name_tree(id, self.this, this)
274
275
        if other is not None:
276
            self.change_name_tree(id, self.other, other)
277
            self.cset.entries[id].new_name = other
278
279
    def change_parent(self, id, base=None, this=None, other=None):
280
        if base is not None:
281
            self.change_parent_tree(id, self.base, base)
282
            self.cset.entries[id].parent = base
283
            self.cset.entries[id].dir = self.cset.entries[base].path
284
285
        if this is not None:
286
            self.change_parent_tree(id, self.this, this)
287
288
        if other is not None:
289
            self.change_parent_tree(id, self.other, other)
290
            self.cset.entries[id].new_parent = other
291
            self.cset.entries[id].new_dir = \
292
                self.cset.entries[other].new_path
293
294
    def change_contents(self, id, base=None, this=None, other=None):
295
        if base is not None:
296
            self.change_contents_tree(id, self.base, base)
297
298
        if this is not None:
299
            self.change_contents_tree(id, self.this, this)
300
301
        if other is not None:
302
            self.change_contents_tree(id, self.other, other)
303
304
        if base is not None or other is not None:
305
            old_contents = file(self.base.full_path(id)).read()
306
            new_contents = file(self.other.full_path(id)).read()
307
            contents = changeset.ReplaceFileContents(old_contents, 
308
                                                     new_contents)
309
            self.cset.entries[id].contents_change = contents
310
311
    def change_perms(self, id, base=None, this=None, other=None):
312
        if base is not None:
313
            self.change_perms_tree(id, self.base, base)
314
315
        if this is not None:
316
            self.change_perms_tree(id, self.this, this)
317
318
        if other is not None:
319
            self.change_perms_tree(id, self.other, other)
320
321
        if base is not None or other is not None:
322
            old_perms = os.stat(self.base.full_path(id)).st_mode &077
323
            new_perms = os.stat(self.other.full_path(id)).st_mode &077
324
            contents = changeset.ChangeUnixPermissions(old_perms, 
325
                                                       new_perms)
326
            self.cset.entries[id].metadata_change = contents
327
328
    def change_name_tree(self, id, tree, name):
329
        new_path = tree.child_path(self.cset.entries[id].parent, name)
330
        tree.change_path(id, new_path)
331
332
    def change_parent_tree(self, id, tree, parent):
333
        new_path = tree.child_path(parent, self.cset.entries[id].name)
334
        tree.change_path(id, new_path)
335
336
    def change_contents_tree(self, id, tree, contents):
337
        path = tree.full_path(id)
338
        mode = os.stat(path).st_mode
339
        file(path, "w").write(contents)
340
        os.chmod(path, mode)
341
342
    def change_perms_tree(self, id, tree, mode):
343
        os.chmod(tree.full_path(id), mode)
344
345
    def merge_changeset(self):
346
        all_inventory = ThreewayInventory(Inventory(self.this.inventory),
347
                                          Inventory(self.base.inventory), 
348
                                          Inventory(self.other.inventory))
349
        conflict_handler = changeset.ExceptionConflictHandler(self.this.dir)
850 by Martin Pool
- Merge merge updates from aaron
350
        return make_merge_changeset(self.cset, all_inventory, self.this,
351
                                    self.base, self.other, conflict_handler)
352
353
    def apply_inv_change(self, inventory_change, orig_inventory):
354
        orig_inventory_by_path = {}
355
        for file_id, path in orig_inventory.iteritems():
356
            orig_inventory_by_path[path] = file_id
357
358
        def parent_id(file_id):
359
            try:
360
                parent_dir = os.path.dirname(orig_inventory[file_id])
361
            except:
362
                print file_id
363
                raise
364
            if parent_dir == "":
365
                return None
366
            return orig_inventory_by_path[parent_dir]
367
        
368
        def new_path(file_id):
369
            if inventory_change.has_key(file_id):
370
                return inventory_change[file_id]
371
            else:
372
                parent = parent_id(file_id)
373
                if parent is None:
374
                    return orig_inventory[file_id]
375
                dirname = new_path(parent)
376
                return os.path.join(dirname, orig_inventory[file_id])
377
378
        new_inventory = {}
379
        for file_id in orig_inventory.iterkeys():
380
            path = new_path(file_id)
381
            if path is None:
382
                continue
383
            new_inventory[file_id] = path
384
385
        for file_id, path in inventory_change.iteritems():
386
            if orig_inventory.has_key(file_id):
387
                continue
388
            new_inventory[file_id] = path
389
        return new_inventory
390
391
        
392
493 by Martin Pool
- Merge aaron's merge command
393
    def apply_changeset(self, cset, conflict_handler=None, reverse=False):
850 by Martin Pool
- Merge merge updates from aaron
394
        inventory_change = changeset.apply_changeset(cset,
395
                                                     self.this.inventory,
396
                                                     self.this.dir,
397
                                                     conflict_handler, reverse)
398
        self.this.inventory =  self.apply_inv_change(inventory_change, 
399
                                                     self.this.inventory)
400
401
                    
402
        
403
493 by Martin Pool
- Merge aaron's merge command
404
        
405
    def cleanup(self):
406
        shutil.rmtree(self.dir)
407
408
409
class MergeTest(unittest.TestCase):
410
    def test_change_name(self):
411
        """Test renames"""
412
        builder = MergeBuilder()
413
        builder.add_file("1", "0", "name1", "hello1", 0755)
414
        builder.change_name("1", other="name2")
415
        builder.add_file("2", "0", "name3", "hello2", 0755)
416
        builder.change_name("2", base="name4")
417
        builder.add_file("3", "0", "name5", "hello3", 0755)
418
        builder.change_name("3", this="name6")
419
        cset = builder.merge_changeset()
420
        assert(cset.entries["2"].is_boring())
421
        assert(cset.entries["1"].name == "name1")
422
        assert(cset.entries["1"].new_name == "name2")
423
        assert(cset.entries["3"].is_boring())
424
        for tree in (builder.this, builder.other, builder.base):
425
            assert(tree.dir != builder.dir and 
426
                   tree.dir.startswith(builder.dir))
427
            for path in tree.inventory.itervalues():
428
                fullpath = tree.abs_path(path)
429
                assert(fullpath.startswith(tree.dir))
430
                assert(not path.startswith(tree.dir))
431
                assert os.path.exists(fullpath)
432
        builder.apply_changeset(cset)
433
        builder.cleanup()
434
        builder = MergeBuilder()
435
        builder.add_file("1", "0", "name1", "hello1", 0644)
436
        builder.change_name("1", other="name2", this="name3")
437
        self.assertRaises(changeset.RenameConflict, 
438
                          builder.merge_changeset)
439
        builder.cleanup()
440
        
441
    def test_file_moves(self):
442
        """Test moves"""
443
        builder = MergeBuilder()
444
        builder.add_dir("1", "0", "dir1", 0755)
445
        builder.add_dir("2", "0", "dir2", 0755)
446
        builder.add_file("3", "1", "file1", "hello1", 0644)
447
        builder.add_file("4", "1", "file2", "hello2", 0644)
448
        builder.add_file("5", "1", "file3", "hello3", 0644)
449
        builder.change_parent("3", other="2")
450
        assert(Inventory(builder.other.inventory).get_parent("3") == "2")
451
        builder.change_parent("4", this="2")
452
        assert(Inventory(builder.this.inventory).get_parent("4") == "2")
453
        builder.change_parent("5", base="2")
454
        assert(Inventory(builder.base.inventory).get_parent("5") == "2")
455
        cset = builder.merge_changeset()
456
        for id in ("1", "2", "4", "5"):
457
            assert(cset.entries[id].is_boring())
458
        assert(cset.entries["3"].parent == "1")
459
        assert(cset.entries["3"].new_parent == "2")
460
        builder.apply_changeset(cset)
461
        builder.cleanup()
462
463
        builder = MergeBuilder()
464
        builder.add_dir("1", "0", "dir1", 0755)
465
        builder.add_dir("2", "0", "dir2", 0755)
466
        builder.add_dir("3", "0", "dir3", 0755)
467
        builder.add_file("4", "1", "file1", "hello1", 0644)
468
        builder.change_parent("4", other="2", this="3")
469
        self.assertRaises(changeset.MoveConflict, 
470
                          builder.merge_changeset)
471
        builder.cleanup()
472
473
    def test_contents_merge(self):
474
        """Test diff3 merging"""
475
        builder = MergeBuilder()
476
        builder.add_file("1", "0", "name1", "text1", 0755)
477
        builder.change_contents("1", other="text4")
478
        builder.add_file("2", "0", "name3", "text2", 0655)
479
        builder.change_contents("2", base="text5")
480
        builder.add_file("3", "0", "name5", "text3", 0744)
481
        builder.change_contents("3", this="text6")
482
        cset = builder.merge_changeset()
483
        assert(cset.entries["1"].contents_change is not None)
484
        assert(isinstance(cset.entries["1"].contents_change,
485
                          changeset.Diff3Merge))
486
        assert(isinstance(cset.entries["2"].contents_change,
487
                          changeset.Diff3Merge))
488
        assert(cset.entries["3"].is_boring())
489
        builder.apply_changeset(cset)
490
        assert(file(builder.this.full_path("1"), "rb").read() == "text4" )
491
        assert(file(builder.this.full_path("2"), "rb").read() == "text2" )
492
        assert(os.stat(builder.this.full_path("1")).st_mode &0777 == 0755)
493
        assert(os.stat(builder.this.full_path("2")).st_mode &0777 == 0655)
494
        assert(os.stat(builder.this.full_path("3")).st_mode &0777 == 0744)
495
        builder.cleanup()
496
497
        builder = MergeBuilder()
498
        builder.add_file("1", "0", "name1", "text1", 0755)
499
        builder.change_contents("1", other="text4", this="text3")
500
        cset = builder.merge_changeset()
501
        self.assertRaises(changeset.MergeConflict, builder.apply_changeset,
502
                          cset)
503
        builder.cleanup()
504
505
    def test_perms_merge(self):
506
        builder = MergeBuilder()
507
        builder.add_file("1", "0", "name1", "text1", 0755)
508
        builder.change_perms("1", other=0655)
509
        builder.add_file("2", "0", "name2", "text2", 0755)
510
        builder.change_perms("2", base=0655)
511
        builder.add_file("3", "0", "name3", "text3", 0755)
512
        builder.change_perms("3", this=0655)
513
        cset = builder.merge_changeset()
514
        assert(cset.entries["1"].metadata_change is not None)
515
        assert(isinstance(cset.entries["1"].metadata_change,
516
                          PermissionsMerge))
517
        assert(isinstance(cset.entries["2"].metadata_change,
518
                          PermissionsMerge))
519
        assert(cset.entries["3"].is_boring())
520
        builder.apply_changeset(cset)
521
        assert(os.stat(builder.this.full_path("1")).st_mode &0777 == 0655)
522
        assert(os.stat(builder.this.full_path("2")).st_mode &0777 == 0755)
523
        assert(os.stat(builder.this.full_path("3")).st_mode &0777 == 0655)
524
        builder.cleanup();
525
        builder = MergeBuilder()
526
        builder.add_file("1", "0", "name1", "text1", 0755)
527
        builder.change_perms("1", other=0655, base=0555)
528
        cset = builder.merge_changeset()
529
        self.assertRaises(changeset.MergePermissionConflict, 
530
                     builder.apply_changeset, cset)
531
        builder.cleanup()
532
533
def test():        
534
    changeset_suite = unittest.makeSuite(MergeTest, 'test_')
535
    runner = unittest.TextTestRunner()
536
    runner.run(changeset_suite)
537
        
538
if __name__ == "__main__":
539
    test()