~bzr-pqm/bzr/bzr.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# (C) 2005 Matt Mackall
# (C) 2005 Canonical Ltd

# based on code by Matt Mackall, hacked by Martin Pool

# mm's code works line-by-line; this just works on byte strings.
# Possibly slower; possibly gives better results for code not
# regularly separated by newlines and anyhow a bit simpler.


# 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


# TODO: maybe work on files not strings?


import difflib, sys, struct
from cStringIO import StringIO

def diff(a, b):
    d = difflib.SequenceMatcher(None, a, b)
    
    ## sys.stderr.write('  ~ real_quick_ratio: %.4f\n' % d.real_quick_ratio())
    
    for o, m, n, s, t in d.get_opcodes():
        if o == 'equal': continue
        # a[m:n] should be replaced by b[s:t]
        if s == t:
            yield m, n, ''
        else:
            yield m, n, b[s:t]


def tobinary(ops):
    b = StringIO()
    for f in ops:
        b.write(struct.pack(">III", f[0], f[1], len(f[2])))
        b.write(f[2])
    return b.getvalue()


def bdiff(a, b):
    return tobinary(diff(a, b))


def patch(t, ops):
    last = 0
    b = StringIO()

    for m, n, r in ops:
        b.write(t[last:m])
        if r:
            b.write(r)
        last = n
        
    b.write(t[last:])
    return b.getvalue()


def frombinary(b):
    bin = StringIO(b)
    while True:
        p = bin.read(12)
        if not p:
            break

        m, n, l = struct.unpack(">III", p)
        
        if l == 0:
            r = ''
        else:
            r = bin.read(l)
            if len(r) != l:
                raise Exception("truncated patch data")
            
        yield m, n, r


def bpatch(t, b):
    return patch(t, frombinary(b))