~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to shelf.py

Merge most of the standalone shelf branch. This brings in a few changes which
make it easier to write a standalone shelf, although not all of them.
There's also a bunch of new features, tests, etc.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python
2
2
 
3
 
from patches import parse_patches
4
3
import os
5
4
import sys
6
 
from bzrlib.commands import Command
7
 
from bzrlib.branch import Branch
8
 
from bzrlib.errors import BzrCommandError
 
5
from errors import CommandError
9
6
from hunk_selector import ShelveHunkSelector, UnshelveHunkSelector
10
7
from diffstat import DiffStat
 
8
from patchsource import PatchSource, FilePatchSource
11
9
 
12
10
class Shelf(object):
13
 
    def __init__(self, location, name='default'):
14
 
        self.branch = Branch.open_containing(location)[0]
15
 
        base = self.branch.controlfilename('x-shelf')
16
 
        self.shelf_dir = os.path.join(base, name)
17
 
 
18
 
        # FIXME surely there's an easier way to do this?
19
 
        t = self.branch._transport
20
 
        for dir in [base, self.shelf_dir]:
21
 
            if not t.has(dir):
22
 
                t.mkdir(dir)
23
 
 
24
 
    def __path(self, idx):
25
 
        return os.path.join(self.shelf_dir, '%.2d' % idx)
26
 
 
27
 
    def next_shelf(self):
28
 
        index = 0
29
 
        while True:
30
 
            name = self.__path(index)
31
 
            if not os.path.exists(name):
32
 
                return name
33
 
            index += 1
34
 
 
35
 
    def last_shelf(self):
36
 
        shelves = os.listdir(self.shelf_dir)
37
 
        indexes = [int(f) for f in shelves]
 
11
    MESSAGE_PREFIX = "# Shelved patch: "
 
12
 
 
13
    _paths = {
 
14
        'base'          : '.shelf',
 
15
        'shelves'       : '.shelf/shelves',
 
16
        'current-shelf' : '.shelf/current-shelf',
 
17
    }
 
18
 
 
19
    def __init__(self, base, name=None):
 
20
        self.base = base
 
21
        self.__setup()
 
22
 
 
23
        if name is None:
 
24
            current = os.path.join(self.base, self._paths['current-shelf'])
 
25
            name = open(current).read().strip()
 
26
 
 
27
        assert '\n' not in name
 
28
        self.name = name
 
29
 
 
30
        self.dir = os.path.join(self.base, self._paths['shelves'], name)
 
31
        if not os.path.isdir(self.dir):
 
32
            os.mkdir(self.dir)
 
33
 
 
34
    def __setup(self):
 
35
        # Create required directories etc.
 
36
        for dir in [self._paths['base'], self._paths['shelves']]:
 
37
            dir = os.path.join(self.base, dir)
 
38
            if not os.path.isdir(dir):
 
39
                os.mkdir(dir)
 
40
 
 
41
        current = os.path.join(self.base, self._paths['current-shelf'])
 
42
        if not os.path.exists(current):
 
43
            f = open(current, 'w')
 
44
            f.write('default')
 
45
            f.close()
 
46
 
 
47
    def make_default(self):
 
48
        f = open(os.path.join(self.base, self._paths['current-shelf']), 'w')
 
49
        f.write(self.name)
 
50
        f.close()
 
51
        self.log("Default shelf is now '%s'\n" % self.name)
 
52
 
 
53
    def log(self, msg):
 
54
        sys.stderr.write(msg)
 
55
 
 
56
    def delete(self, patch):
 
57
        path = self.__path_from_user(patch)
 
58
        os.remove(path)
 
59
 
 
60
    def display(self, patch):
 
61
        path = self.__path_from_user(patch)
 
62
        sys.stdout.write(open(path).read())
 
63
 
 
64
    def list(self):
 
65
        self.log("Patches on shelf '%s':" % self.name)
 
66
        indexes = self.__list()
 
67
        if len(indexes) == 0:
 
68
            self.log(' None\n')
 
69
            return
 
70
        self.log('\n')
 
71
        for index in indexes:
 
72
            msg = self.get_patch_message(self.__path(index))
 
73
            if msg is None:
 
74
                msg = "No message saved with patch."
 
75
            self.log(' %.2d: %s\n' % (index, msg))
 
76
 
 
77
    def __path_from_user(self, patch_id):
 
78
        try:
 
79
            patch_index = int(patch_id)
 
80
        except TypeError:
 
81
            raise CommandError("Invalid patch name '%s'" % patch_id)
 
82
 
 
83
        path = self.__path(patch_index)
 
84
 
 
85
        if not os.path.exists(path):
 
86
            raise CommandError("Patch '%s' doesn't exist on shelf %s!" % \
 
87
                        (patch_id, self.name))
 
88
 
 
89
        return path
 
90
 
 
91
    def __path(self, index):
 
92
        return os.path.join(self.dir, '%.2d' % index)
 
93
 
 
94
    def next_patch(self):
 
95
        indexes = self.__list()
 
96
 
 
97
        if len(indexes) == 0:
 
98
            next = 0
 
99
        else:
 
100
            next = indexes[-1] + 1
 
101
        return self.__path(next)
 
102
 
 
103
    def __list(self):
 
104
        patches = os.listdir(self.dir)
 
105
        indexes = [int(f) for f in patches]
38
106
        indexes.sort()
 
107
        return indexes
 
108
 
 
109
    def last_patch(self):
 
110
        indexes = self.__list()
39
111
 
40
112
        if len(indexes) == 0:
41
113
            return None
42
114
 
43
115
        return self.__path(indexes[-1])
44
116
 
45
 
    def get_shelf_message(self, shelf):
46
 
        prefix = "# shelf: "
47
 
        if not shelf.startswith(prefix):
 
117
    def get_patch_message(self, patch_path):
 
118
        patch = open(patch_path, 'r').read()
 
119
 
 
120
        if not patch.startswith(self.MESSAGE_PREFIX):
48
121
            return None
49
 
        return shelf[len(prefix):shelf.index('\n')]
50
 
 
51
 
    def unshelve(self, pick_hunks=False):
52
 
        shelf = self.last_shelf()
53
 
 
54
 
        if shelf is None:
55
 
            raise BzrCommandError("No shelf found in branch '%s'" % \
56
 
                self.branch.base)
57
 
 
58
 
        patches = parse_patches(open(shelf, 'r').readlines())
 
122
        return patch[len(self.MESSAGE_PREFIX):patch.index('\n')]
 
123
 
 
124
    def __show_status(self, source):
 
125
        if source.can_live_update():
 
126
            diff_stat = str(DiffStat(source.readlines()))
 
127
            if len(diff_stat) > 0:
 
128
                self.log('Diff status is now:\n' + diff_stat + '\n')
 
129
            else:
 
130
                self.log('No changes left in working tree.\n')
 
131
 
 
132
    def unshelve(self, patch_source, pick_hunks=False):
 
133
        patch_name = self.last_patch()
 
134
 
 
135
        if patch_name is None:
 
136
            raise CommandError("No patch found on shelf %s" % self.name)
 
137
 
 
138
        hunks = FilePatchSource(patch_name).readhunks()
59
139
        if pick_hunks:
60
 
            to_unshelve, to_remain = UnshelveHunkSelector(patches).select()
 
140
            to_unshelve, to_remain = UnshelveHunkSelector(hunks).select()
61
141
        else:
62
 
            to_unshelve = patches
 
142
            to_unshelve = hunks
63
143
            to_remain = []
64
144
 
65
145
        if len(to_unshelve) == 0:
66
 
            raise BzrCommandError('Nothing to unshelve')
67
 
 
68
 
        print >>sys.stderr, "Reapplying shelved patches",
69
 
        message = self.get_shelf_message(open(shelf, 'r').read())
70
 
        if message is not None:
71
 
            print >>sys.stderr, ' "%s"' % message
72
 
        else:
73
 
            print >>sys.stderr, ""
74
 
 
75
 
        pipe = os.popen('patch -d %s -s -p0' % self.branch.base, 'w')
76
 
        for patch in to_unshelve:
77
 
            pipe.write(str(patch))
 
146
            raise CommandError('Nothing to unshelve')
 
147
 
 
148
        message = self.get_patch_message(patch_name)
 
149
        if message is None:
 
150
            message = ""
 
151
        self.log('Reapplying shelved patches "%s"\n' % message)
 
152
 
 
153
        pipe = os.popen('patch -d %s -s -p0' % self.base, 'w')
 
154
        for hunk in to_unshelve:
 
155
            pipe.write(str(hunk))
78
156
        pipe.flush()
79
157
 
80
158
        if pipe.close() is not None:
81
 
            raise BzrCommandError("Failed running patch!")
 
159
            raise CommandError("Failed running patch!")
82
160
 
83
161
        if len(to_remain) == 0:
84
 
            os.remove(shelf)
 
162
            os.remove(patch_name)
85
163
        else:
86
 
            f = open(shelf, 'w')
87
 
            for patch in to_remain:
88
 
                f.write(str(patch))
 
164
            f = open(patch_name, 'w')
 
165
            for hunk in to_remain:
 
166
                f.write(str(hunk))
89
167
            f.close()
90
168
 
91
 
        diff_stat = DiffStat(self.get_patches(None, None))
92
 
        print 'Diff status is now:\n', diff_stat
93
 
 
94
 
    def get_patches(self, revision, file_list):
95
 
        from StringIO import StringIO
96
 
        from bzrlib.diff import show_diff
97
 
        out = StringIO()
98
 
        show_diff(self.branch, revision, specific_files=file_list, output=out)
99
 
        out.seek(0)
100
 
        return out.readlines()
101
 
 
102
 
    def shelve(self, pick_hunks=False, message=None, revision=None,
103
 
             file_list=None):
104
 
        patches = parse_patches(self.get_patches(revision, file_list))
 
169
        self.__show_status(patch_source)
 
170
 
 
171
    def shelve(self, patch_source, pick_hunks=False, message=None):
 
172
        from datetime import datetime
 
173
 
 
174
        hunks = patch_source.readhunks()
105
175
 
106
176
        if pick_hunks:
107
 
            to_shelve = ShelveHunkSelector(patches).select()[0]
 
177
            to_shelve = ShelveHunkSelector(hunks).select()[0]
108
178
        else:
109
 
            to_shelve = patches
 
179
            to_shelve = hunks
110
180
 
111
181
        if len(to_shelve) == 0:
112
 
            raise BzrCommandError('Nothing to shelve')
113
 
 
114
 
        shelf = self.next_shelf()
115
 
        print >>sys.stderr, "Saving shelved patches to", shelf
116
 
        shelf = open(shelf, 'a')
117
 
        if message is not None:
118
 
            assert '\n' not in message
119
 
            shelf.write("# shelf: %s\n" % message)
120
 
        for patch in to_shelve:
121
 
            shelf.write(str(patch))
122
 
 
123
 
        shelf.flush()
124
 
        os.fsync(shelf.fileno())
125
 
        shelf.close()
126
 
 
127
 
        print >>sys.stderr, "Reverting shelved patches"
128
 
        pipe = os.popen('patch -d %s -sR -p0' % self.branch.base, 'w')
129
 
        for patch in to_shelve:
130
 
            pipe.write(str(patch))
 
182
            raise CommandError('Nothing to shelve')
 
183
 
 
184
        if message is None:
 
185
            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
 
186
            message = "Changes shelved on %s" % timestamp
 
187
 
 
188
        patch_name = self.next_patch()
 
189
        self.log('Shelving to %s/%s: "%s"\n' % \
 
190
                (self.name, os.path.basename(patch_name), message))
 
191
 
 
192
        patch = open(patch_name, 'a')
 
193
 
 
194
        assert '\n' not in message
 
195
        patch.write("%s%s\n" % (self.MESSAGE_PREFIX, message))
 
196
 
 
197
        for hunk in to_shelve:
 
198
            patch.write(str(hunk))
 
199
 
 
200
        patch.flush()
 
201
        os.fsync(patch.fileno())
 
202
        patch.close()
 
203
 
 
204
        pipe = os.popen('patch -d %s -sR -p0' % self.base, 'w')
 
205
        for hunk in to_shelve:
 
206
            pipe.write(str(hunk))
131
207
        pipe.flush()
132
208
 
133
209
        if pipe.close() is not None:
134
 
            raise BzrCommandError("Failed running patch!")
 
210
            raise CommandError("Failed running patch!")
135
211
 
136
 
        diff_stat = DiffStat(self.get_patches(None, None))
137
 
        print 'Diff status is now:\n', diff_stat
 
212
        self.__show_status(patch_source)