~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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#!/usr/bin/python

from patches import parse_patches
import os
import sys
import string
import tty, termios
import glob
from bzrlib.commands import Command

def main(args):
    name = os.path.basename(args.pop(0))

    if name not in ['shelve', 'unshelve']:
        raise Exception("Unknown command name '%s'" % name)

    if len(args) > 0:
        if args[0] == '--bzr-usage':
            print '\n'
            return 0
        elif args[0] == '--bzr-help':
            print 'Shelve a patch, you can get it back later with unshelve.'
            return 0
        else:
            raise Exception("Don't understand args %s" % args)

    if eval(name + "()"):
        return 0

    return 1

def tree_root():
    return run_bzr('root')[0].strip()

def shelf_suffix(index):
    if index == 0:
        return ""
    else:
        return "-%d" % index

def next_shelf():
    def name_sequence():
        i = 0
        while True:
            yield shelf_suffix(i)
            i = i + 1

    stem = os.path.join(tree_root(), '.bzr-shelf')
    for end in name_sequence():
        name = stem + end
        if not os.path.exists(name):
            return name

def last_shelf():
    stem = os.path.join(tree_root(), '.bzr-shelf')
    shelves = glob.glob(stem)
    shelves.extend(glob.glob(stem + '-*'))
    def shelf_index(name):
        if name == stem:
            return 0
        return int(name[len(stem)+1:])
    shelvenums = [shelf_index(f) for f in shelves]
    shelvenums.sort()

    if len(shelvenums) == 0:
        return None
    return stem + shelf_suffix(shelvenums[-1])

def get_shelf_message(shelf):
    prefix = "# shelf: "
    if not shelf.startswith(prefix):
        return None
    return shelf[len(prefix):shelf.index('\n')]

def unshelve():
    shelf = last_shelf()

    if shelf is None:
        raise Exception("No shelf found in '%s'" % tree_root())

    patch = open(shelf, 'r').read()

    print >>sys.stderr, "Reapplying shelved patches",
    message = get_shelf_message(patch)
    if message is not None:
        print >>sys.stderr, ' "%s"' % message
    else:
        print >>sys.stderr, ""
    pipe = os.popen('patch -d %s -s -p0' % tree_root(), 'w')
    pipe.write(patch)
    pipe.flush()

    if pipe.close() is not None:
        raise Exception("Failed running patch!")

    os.remove(shelf)
    print 'Diff status is now:'
    os.system('bzr diff | diffstat')

    return True

class QuitException(Exception):
    pass

def shelve(message = None, revision = None, file_list = None):
    cmd = ['diff']
    if revision is not None:
        cmd.extend(['--revision', str(revision[0])])
    if file_list is not None:
        cmd.extend(file_list)
    patches = parse_patches(run_bzr(cmd))
    try:
        patches = HunkSelector(patches).select()
    except QuitException:
        return False

    if len(patches) == 0:
        print >>sys.stderr, 'Nothing to shelve'
        return True

    shelf = next_shelf()
    print >>sys.stderr, "Saving shelved patches to", shelf
    shelf = open(shelf, 'a')
    if message is not None:
        assert '\n' not in message
        shelf.write("# shelf: %s\n" % message)
    for patch in patches:
        shelf.write(str(patch))

    shelf.flush()
    os.fsync(shelf.fileno())
    shelf.close()

    print >>sys.stderr, "Reverting shelved patches"
    pipe = os.popen('patch -d %s -sR -p0' % tree_root(), 'w')
    for patch in patches:
       pipe.write(str(patch))
    pipe.flush()

    if pipe.close() is not None:
        raise Exception("Failed running patch!")

    print 'Diff status is now:'
    os.system('bzr diff | diffstat')

    return True

def run_bzr(args):
    if type(args) is str:
        args = [ args ]
    pipe = os.popen('bzr %s' % string.join(args, ' '), 'r')
    lines = pipe.readlines()
    if pipe.close() is not None:
        raise Exception("Failed running bzr")
    return lines

class cmd_shelve(Command):
    """Temporarily remove some changes from the current tree.
    Use 'unshelve' to restore these changes.

    If filenames are specified, only changes to those files will be unshelved.
    If a revision is specified, all changes since that revision will may be
    unshelved.
    """
    takes_args = ['file*']
    takes_options = ['message', 'revision']
    def run(self, file_list=None, message=None, revision=None):
        return shelve(message=message, file_list=file_list, revision=revision)

class cmd_unshelve(Command):
    """Restore previously-shelved changes to the current tree.
    See also 'shelve'.
    """
    def run(self):
        return unshelve()

class HunkSelector:
    class Option:
        def __init__(self, char, action, help, default=False):
            self.char = char
            self.action = action
            self.default = default
            self.help = help

    standard_options = [
        Option('n', 'shelve', 'shelve this change for the moment.',
            default=True),
        Option('y', 'keep', 'keep this change in your tree.'),
        Option('d', 'done', 'done, skip to the end.'),
        Option('i', 'invert', 'invert the current selection of all hunks.'),
        Option('s', 'status', 'show status of hunks.'),
        Option('q', 'quit', 'quit')
    ]

    end_options = [
        Option('y', 'continue', 'proceed to shelve selected changes.',
            default=True),
        Option('r', 'restart', 'restart the hunk selection loop.'),
        Option('s', 'status', 'show status of hunks.'),
        Option('i', 'invert', 'invert the current selection of all hunks.'),
        Option('q', 'quit', 'quit')
    ]

    def __init__(self, patches):
        self.patches = patches
        self.total_hunks = 0
        for patch in patches:
            for hunk in patch.hunks:
                # everything's shelved by default
                hunk.selected = True
                self.total_hunks += 1

    def __get_option(self, char):
        for opt in self.standard_options:
            if opt.char == char:
                return opt
        raise Exception('Option "%s" not found!' % char)

    def __select_loop(self):
        j = 0
        for patch in self.patches:
            i = 0
            lasti = -1
            while i < len(patch.hunks):
                hunk = patch.hunks[i]
                if lasti != i:
                    print patch.get_header(), hunk
                    j += 1
                lasti = i

                prompt = 'Keep this change? (%d of %d)' \
                            % (j, self.total_hunks)

                if hunk.selected:
                    self.__get_option('n').default = True
                    self.__get_option('y').default = False
                else:
                    self.__get_option('n').default = False
                    self.__get_option('y').default = True

                action = self.__ask_user(prompt, self.standard_options)

                if action == 'keep':
                    hunk.selected = False
                elif action == 'shelve':
                    hunk.selected = True
                elif action == 'done':
                    return True
                elif action == 'invert':
                    self.__invert_selection()
                    self.__show_status()
                    continue
                elif action == 'status':
                    self.__show_status()
                    continue
                elif action == 'quit':
                    return False

                i += 1
        return True

    def select(self):
        if self.total_hunks == 0:
            return []

        done = False
        while not done:
            if not self.__select_loop():
                return []

            while True:
                self.__show_status()
                prompt = "Shelve these changes, or restart?"
                action = self.__ask_user(prompt, self.end_options)

                if action == 'continue':
                    done = True
                    break
                elif action == 'quit':
                    return []
                elif action == 'status':
                    self.__show_status()
                elif action == 'invert':
                    self.__invert_selection()
                elif action == 'restart':
                    break


        for patch in self.patches:
            tmp = []
            for hunk in patch.hunks:
                if hunk.selected:
                    tmp.append(hunk)
            patch.hunks = tmp

        tmp = []
        for patch in self.patches:
            if len(patch.hunks):
                tmp.append(patch)
        self.patches = tmp

        return self.patches

    def __invert_selection(self):
        for patch in self.patches:
            for hunk in patch.hunks:
                if hunk.__dict__.has_key('selected'):
                    hunk.selected = not hunk.selected
                else:
                    hunk.selected = True

    def __show_status(self):
        print '\nStatus:'
        for patch in self.patches:
            print '  %s' % patch.oldname
            shelve = 0
            keep = 0
            for hunk in patch.hunks:
                if hunk.selected:
                    shelve += 1
                else:
                    keep += 1

            print '    %d hunks to be shelved' % shelve
            print '    %d hunks to be kept' % keep
            print

    def __getchar(self):
        fd = sys.stdin.fileno()
        settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
        return ch

    def __ask_user(self, prompt, options):
        while True:
            sys.stdout.write(prompt)
            sys.stdout.write(' [')
            for opt in options:
                if opt.default:
                    default = opt
                sys.stdout.write(opt.char)
            sys.stdout.write('?] (%s): ' % default.char)

            response = self.__getchar()

            # default, which we see as newline, is 'n'
            if response in ['\n', '\r', '\r\n']:
                response = default.char

            print response # because echo is off

            for opt in options:
                if opt.char == response:
                    return opt.action

            for opt in options:
                print '  %s - %s' % (opt.char, opt.help)