~abentley/bzrtools/bzrtools.dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Copyright (C) 2009 Aaron Bentley <aaron@aaronbentley.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


import errno

from bzrlib.diff import internal_diff
from bzrlib.workingtree import WorkingTree
from bzrlib.plugins.bzrtools import errors


def conflict_diff(output, filename, direction):
    """Perform a diff for a file with conflicts."""
    old_path = filename + '.BASE'
    old_lines = get_old_lines(filename, old_path)
    new_path_extension = {
        'other': '.OTHER',
        'this': '.THIS'}[direction]
    new_path = filename + new_path_extension
    newlines = open(new_path).readlines()
    internal_diff(old_path, old_lines, new_path, newlines, output)


def get_old_lines(filename, base_path):
    """"Return the lines from before the conflicting changes were made."""
    try:
        old_lines = open(base_path).readlines()
    except IOError, e:
        if e.errno != errno.ENOENT:
            raise
        tree, path = WorkingTree.open_containing(filename)
        tree.lock_read()
        try:
            file_id = tree.path2id(path)
            graph = tree.branch.repository.get_graph()
            parent_ids = tree.get_parent_ids()
            if len(parent_ids) < 2:
                raise errors.NoConflictFiles(base_path)
            lca = graph.find_unique_lca(*parent_ids)
            oldtree = tree.branch.repository.revision_tree(lca)
            old_lines = oldtree.get_file_lines(file_id)
        finally:
            tree.unlock()
    return old_lines