~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
#!/usr/bin/python

from patches import parse_patches
import os
import sys
import string
import tty, termios

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 unshelve():
    root = run_bzr('root')[0].strip()
    shelf = os.path.join(root, '.bzr-shelf')

    if not os.path.exists(shelf):
        raise Exception("No shelf found in '%s'" % shelf)

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

    print >>sys.stderr, "Reapplying shelved patches"
    pipe = os.popen('patch -d %s -s -p0' % 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():
    patches = parse_patches(run_bzr('diff'))
    try:
        patches = HunkSelector(patches).select()
    except QuitException:
        return False

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

    root = run_bzr('root')[0].strip()
    shelf = os.path.join(root, '.bzr-shelf')
    print >>sys.stderr, "Saving shelved patches to", shelf
    shelf = open(shelf, 'a')

    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' % 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