~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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# Copyright (C) 2005 Aaron Bentley
# <aaron.bentley@utoronto.ca>
#
#    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 sys, os
from subprocess import Popen, PIPE
from bzrlib.transport import get_transport
from urlparse import urlsplit, urlunsplit
from bzrlib.workingtree import WorkingTree
import bzrlib.add

class BzrTagProc:
    """This class handle the additional bazaar diff tags

        TODO:
          error handling
    """
    def __init__(self, tree):
        self.renamed = None
        self.link = None
        self.tree = tree

    def _extractname(self, s):
        x = s[0]
        i = 1
        ls = len(s)

        while i < ls:
            if s[i] == '\\':
                assert(i+1 < ls )
                i += 2
                continue

            if s[i] == x:
                return s[1:i],i+1

            i += 1

        assert(False)

    def extractname(self, s):
        space = s.find(" ",9)    # find the 2nd space
        assert(space)
        return self._extractname(s[space+1:])[0]

    def extractnames(self, s):
        space = s.find(" ",10)    # find the 2nd space
        assert(space)
        s=s[space+1:]
        source, pos = self._extractname(s)
        assert( pos +4 < len(s) )
        dest,  dummy = self._extractname(s[pos+4:])

        return source,dest

    def flush(self):
        self.process( )

    def add(self,name):
        action = bzrlib.add.add_action_add_and_print
        added, ignored = bzrlib.add.smart_add([name], False, action)

    def process(self, cmd = None):
        if self.renamed:
            os.rename(self.renamed[0], self.renamed[1])
            self.renamed = None

        if not cmd: return

        if ( cmd.startswith("removed file") or 
             cmd.startswith("removed symlink") ):

            target = self.extractname(cmd)
            print "removing '%s'"%target
            if not cmd.startswith("removed file"):
                os.unlink(target)
            self.tree.remove([target])

        elif cmd.startswith("removed directory"):

            target = self.extractname(cmd)
            print "removing '%s'"%target
            os.rmdir(target)
            self.tree.remove([target])

        elif cmd.startswith("added file"):
            target = self.extractname(cmd)
            print "adding '%s'"%target
            f = open(target,"w")
            f.close( )
            self.add(target)

        elif cmd.startswith("added directory"):
            target = self.extractname(cmd)
            print "adding '%s'"%target
            os.mkdir(target)
            self.add(target)

        elif cmd.startswith("added symlink"):
            assert(not self.link)
            self.link = self.extractname(cmd)

        elif cmd.startswith("target is"):
            assert(self.link)
            target = self.extractname(cmd)
            print "symlinking '%s' => '%s'"%(target, self.link)
            os.symlink(target, self.link)
            self.link = None
            self.add(self.link)

        elif ( cmd.startswith("renamed symlink") or
               cmd.startswith("renamed file") or
               cmd.startswith("renamed directory") ):

            space = cmd.find(" ",10)    # find the 2nd space
            assert(space)
            source,dest = self.extractnames(cmd[space+1:])
            print "renaming '%s' => '%s'"%(source,dest)

            #os.rename(source,dest)
            self.tree.rename_one(source,dest)

        else:
            sys.stderr.write("Unsupported tag: '%s'\n"%cmd)



def patch(branch, location, strip, legacy):
    """Apply a patch to a branch, using patch(1).  URLs may be used."""
    my_file = None
    if location is None:
        my_file = sys.stdin
    else:
        for prefix in ('http://', 'sftp://', 'file://'):
            if not location.startswith(prefix):
                continue
            (scheme, loc, path, query, fragment) = urlsplit(location)
            loc_start = urlunsplit((scheme, loc, '/', '', ''))
            my_file = get_transport(loc_start).get(path[1:])
        if my_file is None:
            my_file = file(location, 'rb')
    cmd = ['patch', '--directory', branch.base, '--strip', str(strip)]
    r = 0
    if legacy:
        child_proc = Popen(cmd, stdin=PIPE)
        for line in my_file:
            child_proc.stdin.write(line)
        child_proc.stdin.close()
        r = child_proc.wait()
    else:
        bzr_tags_proc = BzrTagProc(WorkingTree.open_containing(u'.')[0])
        child_proc = None
        for line in my_file:
            if line.startswith("=== "):
                if child_proc:
                    child_proc.stdin.close()
                    r = child_proc.wait()
                    child_proc = None
                bzr_tags_proc.process(line[4:])
            else:
                if not child_proc:
                    child_proc = Popen(cmd, stdin=PIPE)
                #sys.stdout.write("# %s"%line)
                child_proc.stdin.write(line)
        if child_proc:
            child_proc.stdin.close()
            r = child_proc.wait()
        bzr_tags_proc.flush( )
    return r